diff --git a/rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/merge_verify.py b/rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/merge_verify.py new file mode 100644 index 0000000000000000000000000000000000000000..99447b748fddf5a1c3ed10c1fd01f5218b806cac --- /dev/null +++ b/rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/merge_verify.py @@ -0,0 +1,60 @@ +"""Merge the per-task replay-verification shards into one success mask. + +Output: keep[i] over cache episode indices. An episode stays in the success pool only +if it is a demo (ground truth, never replayed), or a rollout whose logged success +REPRODUCED when its actions were re-executed from the logged sim_state. Episodes that +could not be resolved (source parquet missing) are dropped from the success pool rather +than trusted -- the whole point is that an unverified success is not a success. +""" +import argparse, glob, numpy as np + +ap = argparse.ArgumentParser() +ap.add_argument("--cache", required=True) +ap.add_argument("--shards", required=True, help="REPLAY shards (reproducibility)") +ap.add_argument("--goal-shards", default="", + help="GOAL-AUDIT shards (goal predicate at the logged final state). " + "DIAGNOSTIC ONLY -- do NOT filter on this. It answers 'was the label " + "honest about the state the episode reached', which is not the " + "admissibility question. Admissibility is REPRODUCIBILITY in the eval " + "environment; see --shards.") +ap.add_argument("--out", required=True) +ap.add_argument("--keep-unresolvable", type=int, default=0) +a = ap.parse_args() + +m = np.load(f"{a.cache}/meta.npz", allow_pickle=True) +demo, succ = m["ep_demo"].astype(bool), m["ep_success"].astype(bool) +keep = demo.copy() # demos always kept +seen = np.zeros(len(demo), bool) +rep = unres = 0 +# ADMISSIBILITY RULE: a trajectory may train an offline learner only if its reward +# labels REPRODUCE in the environment we evaluate in. A label that was honest about the +# state its own run reached is still inadmissible if replaying those actions here does +# not get there -- those (s,a,r) tuples describe different dynamics than the ones the +# policy will be scored against, which is exactly what breaks offline RL. +src, mode = a.shards, "REPLAY in the eval environment (admissibility)" +if a.goal_shards: + print("[merge] NOTE: goal-audit shards given but NOT used as the filter; " + "they are diagnostic. Filtering on reproducibility.") +print(f"[merge] filtering on: {mode}") +for f in sorted(glob.glob(f"{src}/task*.npz")): + z = np.load(f, allow_pickle=True) + if a.goal_shards: + r = z["rows"]; idx, ver = r[:, 0], r[:, 1] + else: + idx, ver = z["ep_index"], z["verified"] + for e, v in zip(idx, ver): + seen[e] = True + if v == 1: keep[e] = True; rep += 1 + elif v < 0: + unres += 1 + if a.keep_unresolvable: keep[e] = True +n_succ = int((succ & ~demo).sum()) +missing = int((succ & ~demo & ~seen).sum()) +np.savez(a.out, keep=keep, n_checked=int(seen.sum()), n_reproduced=rep) +print(f"[merge] rollout successes in cache : {n_succ}") +print(f"[merge] checked : {int(seen.sum())} (missing shards: {missing})") +print(f"[merge] reproduced : {rep} ({rep/max(seen.sum(),1):.1%})") +print(f"[merge] unresolvable : {unres} " + f"({'kept' if a.keep_unresolvable else 'DROPPED'})") +print(f"[merge] success pool: {int((succ).sum())} -> {int(keep.sum())} episodes") +print(f"[merge] wrote {a.out}") diff --git a/rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/mislabel_report.py b/rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/mislabel_report.py new file mode 100644 index 0000000000000000000000000000000000000000..f27a0ca4e7bfa2b8c0ab16399f9ceefb8c4070a7 --- /dev/null +++ b/rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/mislabel_report.py @@ -0,0 +1,41 @@ +"""Per-task mislabelling breakdown: episodes AND reward-frames affected. + +An episode's success bit is one label, but the reward is per-frame and derived from +it, so a single mislabelled episode corrupts every frame it occupies. Both counts are +reported because they answer different questions: how much of the success POOL is +fake (episodes), and how much of the reward SIGNAL is wrong (frames).""" +import glob, sys, numpy as np +V = sys.argv[1] if len(sys.argv) > 1 else "/data/pulkitag/users/rli14/rsm_libero_runs/verify" +C = "/data/pulkitag/users/rli14/rsm_libero_cache/full_demo" +m = np.load(f"{C}/meta.npz", allow_pickle=True) +elen = (m["ep_to"] - m["ep_from"]).astype(int) +tn = [str(t) for t in m["tasks"]] +d, s = m["ep_demo"].astype(bool), m["ep_success"].astype(bool) +rows, TE, TB, TF, TFB = [], 0, 0, 0, 0 +for f in sorted(glob.glob(f"{V}/task*.npz")): + z = np.load(f); t = int(z["task"]) + idx, ver = z["ep_index"], z["verified"] + ok = ver >= 0; idx, ver = idx[ok], ver[ok] + if len(idx) == 0: + rows.append((t, 0, 0, 0, 0)); continue + bad = idx[ver == 0] + nf, nfb = int(elen[idx].sum()), int(elen[bad].sum()) + rows.append((t, len(idx), len(bad), nf, nfb)) + TE += len(idx); TB += len(bad); TF += nf; TFB += nfb +print(f"{'task':4s} {'name':36s} {'checked':>8s} {'MISLAB':>7s} {'rate':>6s} " + f"{'frames':>9s} {'bad frames':>11s} {'%':>6s}") +for t, n, b, nf, nfb in sorted(rows): + if n == 0: + print(f" {t:<3d} {tn[t][:36]:36s} {'--':>8s} {'--':>7s} {'--':>6s}" + f" {'--':>9s} {'--':>11s} {'--':>6s} (no logged successes)") + continue + print(f" {t:<3d} {tn[t][:36]:36s} {n:8d} {b:7d} {b/n:6.1%} " + f"{nf:9,d} {nfb:11,d} {nfb/nf:6.1%}") +nd = sum(1 for r in rows if r[1] > 0) +print(f"\n TOTAL over {nd} tasks with successes: {TE} checked, " + f"{TB} mislabelled ({TB/max(TE,1):.1%})") +print(f" reward frames: {TF:,} in verified episodes, {TFB:,} carry a wrong label " + f"({TFB/max(TF,1):.1%})") +npool = int((s & ~d).sum()) +print(f" rollout successes in cache: {npool}; checked {TE} ({TE/npool:.0%})" + f" -> projected ~{round(npool*TB/max(TE,1))} mislabelled at the pooled rate") diff --git a/rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/model.py b/rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/model.py new file mode 100644 index 0000000000000000000000000000000000000000..c6cf68df73b39203ed50016da17e3c5e986ad4f9 --- /dev/null +++ b/rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/model.py @@ -0,0 +1,528 @@ +"""Nets for RSM on the LIBERO-10 pi0.5 rollout corpus. + +Design follows the unified-RSM recipe on gen_q `main` (ogbench_unified_rsm/RECIPE.md, +notes/COLLAPSE_ANALYSIS.md), adapted from goal-ball OGBench to sparse-success LIBERO: + + * beta BAND training, not a single discount (RECIPE "train beta [0.8,0.98]") + * Fourier features on log(-log beta) (RECIPE "fourier_unit, n_fourier=6") + * residual successor z' = z + delta, with delta divided by the per-dimension + dataset RMS of (z_fut - z_now) (RECIPE v6.1 "horizon-normalize + then per-dimension divide by rms((s'-s)_i)") + * EMA target encoder supplies the future target, stop-grad, plus a per-coordinate + variance floor (RECIPE "variance floor keeps the + embedding from collapsing"; smolvla_rsm METHOD.md) + * action chunk conditions the occupancy on an equal footing with the task + embedding, via concat + FiLM (RECIPE v6 "condition on g and a equally") + +What is deliberately NOT ported: the goal-ball arrival likelihood (`q_readout=lik`, +`p = exp(-d^2/2 tol^2)` on privileged xy/xyz). LIBERO has no privileged success ball +in this latent, so the read-out is a learned reward decoder over the same latent, as +the image branch of CLAUDE.md requires. + +COLLAPSE_ANALYSIS lesson carried over: a value that scores STATES but cannot rank +ACTIONS produces flat batch metrics and a closed-loop cliff. The occupancy here is +action-conditioned for exactly that reason, and action ranking is the headline +diagnostic rather than state ranking. +""" +from __future__ import annotations +import numpy as np +import torch +import torch.nn as nn +import torch.nn.functional as F + + +def beta_fourier(beta: torch.Tensor, n: int = 6) -> torch.Tensor: + """Fourier features on the log-horizon of a discount in (0,1).""" + x = torch.log(-torch.log(beta.clamp(1e-6, 1 - 1e-6))) + fr = torch.arange(1, n + 1, device=beta.device, dtype=beta.dtype) + a = x[:, None] * fr[None] + return torch.cat([a.sin(), a.cos(), x[:, None]], -1) # 2n+1 + + +def time_embed(t: torch.Tensor, dim: int = 64) -> torch.Tensor: + half = dim // 2 + fr = torch.exp(-np.log(10000.0) * torch.arange(half, device=t.device, + dtype=t.dtype) / half) + a = t[:, None] * fr[None] * 1000.0 + return torch.cat([a.sin(), a.cos()], -1) + + +def mlp(sizes, act=nn.SiLU, out_act=False, norm=False): + layers = [] + for i in range(len(sizes) - 1): + layers.append(nn.Linear(sizes[i], sizes[i + 1])) + if i < len(sizes) - 2 or out_act: + if norm: + layers.append(nn.LayerNorm(sizes[i + 1])) + layers.append(act()) + return nn.Sequential(*layers) + + + +class TaskCond(nn.Module): + """Task conditioning: a frozen T5 sentence embedding, projected. + + The alternative -- nn.Embedding(n_task, d_task) -- conditions on an INDEX. It carries + nothing about what the task is, cannot transfer to a held-out instruction, and gives + the network a shortcut that removes any pressure on the visual latent to represent + the instruction. Passing t5_path swaps in the frozen sentence embedding; omitting it + keeps the index embedding so old checkpoints still load. + """ + + def __init__(self, n_task: int, d_task: int = 64, t5_path: str = ""): + super().__init__() + self.t5 = bool(t5_path) + if self.t5: + import numpy as _np + emb = _np.load(t5_path)["emb"].astype("float32") + emb = emb / (_np.linalg.norm(emb, axis=1, keepdims=True) + 1e-6) + self.register_buffer("E", torch.tensor(emb), persistent=True) + self.proj = nn.Linear(emb.shape[1], d_task) + else: + # hold the table as `weight` and look it up with F.embedding, so the + # state_dict key stays `.task.weight` -- exactly what + # nn.Embedding produced. Wrapping it as a submodule would rename the + # key and break every checkpoint written before this change. + self.weight = nn.Parameter(torch.randn(n_task, d_task) * 0.02) + + def forward(self, task): + if self.t5: + return self.proj(self.E[task]) + return F.embedding(task, self.weight) + + +class Encoder(nn.Module): + """OGPO 4096-d -> compact reward-predictive latent.""" + + def __init__(self, d_in: int, d_z: int = 256, width: int = 1024, depth: int = 3): + super().__init__() + self.net = mlp([d_in] + [width] * depth + [d_z], norm=True) + self.d_z = d_z + + def forward(self, x): + return self.net(x) + + +class IdentityEncoder(nn.Module): + """`--enc identity`: the (z-scored) input feature IS the latent. No parameters, so the + EMA target, the variance floor and the reward warm-up are all no-ops. Used when the + feature is a frozen foundation-model embedding modelled directly (rsm_rise: DINOv2 + CLS|GeM per camera + proprio, 1545-d), as the OCBench visual recipe did.""" + + def __init__(self, d_in: int): + super().__init__() + self.d_z = int(d_in) + + def forward(self, x): + return x + + +class PCAEncoder(nn.Module): + """`--pca-dim k`: a FIXED linear map fitted once on training frames (not a learned encoder). + z = (x - mean) @ W with W [d_in, k] orthonormal columns (top-k right singular vectors), so the + pseudo-inverse is W^T: back(z) = z @ W^T + mean. mean/W are persistent buffers, saved in the + checkpoint's `enc` state_dict and reloaded by is_ope.load_critic.""" + + def __init__(self, d_in: int, k: int): + super().__init__() + self.d_z = int(k) + self.register_buffer("mean", torch.zeros(int(d_in))) + self.register_buffer("W", torch.zeros(int(d_in), int(k))) + + @torch.no_grad() + def fit(self, X): + """X [n, d_in] float tensor of (z-scored) training states. Returns explained-variance ratio.""" + self.mean.copy_(X.mean(0)) + _u, S, Vh = torch.linalg.svd(X - self.mean, full_matrices=False) + self.W.copy_(Vh[: self.d_z].T) + var = S.pow(2) + return float(var[: self.d_z].sum() / var.sum()) + + def forward(self, x): + return (x - self.mean) @ self.W + + def back(self, z): + return z @ self.W.T + self.mean + + +class RewardHead(nn.Module): + """Goal-conditioned reward decoder R(z, task) -> logit of 'task complete here'.""" + + def __init__(self, d_z: int, n_task: int, d_task: int = 64, width: int = 512, t5_path: str = ""): + super().__init__() + self.task = TaskCond(n_task, d_task, t5_path) + self.net = mlp([d_z + d_task, width, width, 1]) + + def forward(self, z, task): + return self.net(torch.cat([z, self.task(task)], -1)).squeeze(-1) + + +class GoalLikelihood(nn.Module): + """Dense two-tower goal likelihood -- the recipe's `q_readout=lik`. + + `l = sigmoid( / tau)` with phi, psi unit-norm MLPs. Asymmetric + on purpose (phi != psi), because "z is at goal g" is not "g is at goal z". + + Why this replaces a binary success head: the success head is SPARSE -- terminal + labels are ~0.5% of frames, so almost every sampled future reads ~0 and Q is + near-constant in the action, leaving nothing to rank. This gives EVERY (z, g) + pair a probability, which is what makes the read-out able to separate actions. + + Trained by in-batch InfoNCE: positive is (z + eps, z), negatives are the other + goals in the batch. Recipe knobs: goal_feat_dim 256, towers (512,)x3, + goal_nce_tau 0.2, nce_noise 0.1. The scorer is STOP-GRAD in the Q path -- NCE + is the only gradient into the towers. + """ + + def __init__(self, d_z: int, d_feat: int = 256, width: int = 512, depth: int = 3, + tau: float = 0.2, noise: float = 0.1): + super().__init__() + self.phi = mlp([d_z] + [width] * depth + [d_feat], norm=True) + self.psi = mlp([d_z] + [width] * depth + [d_feat], norm=True) + self.tau = tau + self.noise = noise + + def _emb(self, net, z): + e = net(z) + return e / e.norm(dim=-1, keepdim=True).clamp_min(1e-6) + + def logit(self, z, g): + return (self._emb(self.phi, z) * self._emb(self.psi, g)).sum(-1) / self.tau + + def forward(self, z, g): + return torch.sigmoid(self.logit(z, g)) + + def nce_loss(self, z): + """In-batch InfoNCE. Positive (z+eps, z); negatives are other batch rows.""" + zp = z + self.noise * torch.randn_like(z) + a = self._emb(self.phi, zp) + b = self._emb(self.psi, z) + logits = (a @ b.t()) / self.tau + tgt = torch.arange(z.shape[0], device=z.device) + return F.cross_entropy(logits, tgt) + + +class FiLM(nn.Module): + def __init__(self, d_cond, d_h): + super().__init__() + self.to_gb = nn.Linear(d_cond, 2 * d_h) + + def forward(self, h, c): + g, b = self.to_gb(c).chunk(2, -1) + return h * (1 + g) + b + + +class OccFlow(nn.Module): + """Conditional flow-matching velocity for the beta-discounted successor. + + Predicts the velocity of the RESIDUAL delta = (z_fut - z_now) / rms, so the + network never has to re-encode z_now's own coordinates. + """ + + def __init__(self, d_z: int, d_act: int, n_task: int, d_task: int = 64, + width: int = 1024, depth: int = 4, n_fourier: int = 6, t5_path: str = "", + norm: bool = False, dropout: float = 0.0, 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) diff --git a/rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/pack.py b/rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/pack.py new file mode 100644 index 0000000000000000000000000000000000000000..dc899ff8fb29c3fb0408514dc528de8ffb203541 --- /dev/null +++ b/rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/pack.py @@ -0,0 +1,278 @@ +"""Pack the LIBERO-10 pi0.5 OGPO rollout corpus into a flat memmap cache. + +Source layout (one npz per episode, 43,135 episodes over 10 task dirs): + /ep_t{T}_b{B}_i{id}_{epidx:06d}.npz + z [F,4096] float16 OGPO latent (agentview | wrist) + (task_index is NOT read -- see the guard in main()) + proprio [F,8] float32 + actions [F,7] float32 + success () bool + prompt () str + +Cache layout (written atomically into /): + z.f16 memmap [N,D] latents, frame-major, episodes contiguous + act.f32 memmap [N,7] executed action at that frame + meta.npz ep_from/ep_to/ep_len/ep_task/ep_success/ep_src, tasks, dim + +LEAKAGE NOTE recorded here because it shapes every downstream label choice: +failed episodes are ALL exactly 520 frames (the timeout) while successful ones +terminate early (mean ~263). Episode LENGTH therefore predicts success almost +perfectly. Any label built from "frames remaining" leaks the outcome, so the +reward label is defined on terminal states of successful episodes only, and the +headline diagnostic is action ranking at a FIXED state, never state ranking. +""" +from __future__ import annotations +import argparse, io, json, os, time, zipfile +from concurrent.futures import ThreadPoolExecutor +from pathlib import Path +import numpy as np + + +def read_header(path, assume_success=None): + """(n_frames, success) without reading the arrays. + + `np.load(f)["z"].shape` materialises the whole 2.3 MB latent block, which for + 43k episodes is ~99 GB of pointless NFS traffic. npz is a zip of .npy members, + so the shape lives in the member's own header: parse that and stop. + """ + with zipfile.ZipFile(path) as zf: + with zf.open("z.npy") as f: + ver = np.lib.format.read_magic(f) + shape, _fortran, _dt = np.lib.format._read_array_header(f, ver) + if assume_success is None or "success.npy" in zf.namelist(): + # rollouts always carry it; REPLAYED demo caches (rerender_rollouts.py + # --pool demos_replay) carry it too, and a demo whose live replay did not + # end in success is inadmissible exactly like a non-reproducing rollout + with zf.open("success.npy") as f: + succ = bool(np.load(io.BytesIO(f.read()), allow_pickle=False)) + else: + succ = assume_success # legacy demo caches carry no success field + return int(shape[0]), succ + + +def episode_files(root: Path): + """-> list of (task_name, path, is_demo). Task id comes from the directory name. + + Rollout dirs hold ep_*.npz and carry a `success` flag. The demo cache uses the + same task name with a `_demo` suffix, holds demo_*.npz, and has no success + field because every demonstration succeeds.""" + out = [] + for d in sorted(p for p in root.iterdir() if p.is_dir()): + demo = d.name.endswith("_demo") + name = d.name[:-5] if demo else d.name + for f in sorted(d.glob("demo_*.npz" if demo else "ep_*.npz")): + out.append((name, f, demo)) + return out + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--src", required=True) + ap.add_argument("--out", required=True) + ap.add_argument("--demos", default="", help="optional demo cache root to union in") + ap.add_argument("--max-eps", type=int, default=0, help="0 = all") + ap.add_argument("--stride", type=int, default=1) + ap.add_argument("--seed", type=int, default=0) + ap.add_argument("--workers", type=int, default=32, + help="threads for the header scan (NFS latency-bound)") + ap.add_argument("--header-cache", default="", + help="npz to cache/reuse the (success,length) scan") + ap.add_argument("--tasks-file", default="/data/pulkitag/hamer_diffusion_policy_project/projects/continual_learning_for_manipulation/logs/09052026_lib10_tasks.txt", + help="canonical LIBERO benchmark-id task order; task ids are " + "assigned from THIS list, never from directory sort order " + "and never from the npz `task_index` field.") + ap.add_argument("--keep-all-demos", action="store_true", + help="always include EVERY demo episode, then fill the rest " + "with rollouts. Balanced sampling kept only 94 of 500 " + "demos, which starves a BC-on-demos baseline.") + ap.add_argument("--episode-list", default="", + help="text file, one '/.npz' per line: pack EXACTLY these " + "rollouts in this order. Two clusters packing from the same list produce " + "index-identical caches, so per-episode artefacts (subgoal labels, " + "admissibility mask) transfer by index.") + ap.add_argument("--encoder", default="pi05_base_pytorch", + help="feature-encoder tag (basename of OGPO_PI05_BASE the latents were encoded " + "with). Written to PACK.json/RENDER.json; the evaluator refuses a mismatch.") + ap.add_argument("--cam-res", default="", + help="render resolution the SOURCE latents were encoded from (e.g. 256). " + "Written to PACK.json and RENDER.json; the evaluator refuses a cache " + "whose cam_res is undeclared or differs from its own --cam-res.") + ap.add_argument("--balance", action="store_true", + help="equalize success/failure count within each task") + args = ap.parse_args() + + rng = np.random.default_rng(args.seed) + src, out = Path(args.src), Path(args.out) + out.mkdir(parents=True, exist_ok=True) + files = episode_files(src) + if args.episode_list: + _want = [l.strip() for l in open(args.episode_list) if l.strip()] + _by = {f"{f.parent.name}/{f.name}": (n, f, dm) for n, f, dm in files if not dm} + _missing = [w for w in _want if w not in _by] + if _missing: + raise SystemExit(f"--episode-list: {len(_missing)} listed episodes absent under --src, e.g. {_missing[:3]}") + files = [_by[w] for w in _want] + [t for t in files if t[2]] # rollouts in list order, then demos + print(f"[pack] episode list: {len(_want)} rollouts pinned from {args.episode_list}", flush=True) + if args.demos: + files += episode_files(Path(args.demos)) + print(f"[pack] found {len(files)} episodes in {len(set(t for t, *_ in files))} tasks", + flush=True) + + # ---- pass 1: read headers (success + length), pick the subset ---- + hc = Path(args.header_cache) if args.header_cache else out / "headers.npz" + if hc.exists(): + c = np.load(hc, allow_pickle=True) + if len(c["paths"]) == len(files) and set(map(str, c["paths"])) == {str(f[1]) for f in files}: + dm_col = c["demo"] if "demo" in c.files else np.zeros(len(c["paths"]), bool) + hdr = [(t, Path(p), bool(s), int(L), bool(dm)) for t, p, s, L, dm in + zip(c["tasknames"], c["paths"], c["succ"], c["lens"], dm_col)] + print(f"[pack] header scan reused from {hc}", flush=True) + else: + hc.unlink() + if not hc.exists(): + def rd(tf): + task, f, demo = tf + L, succ = read_header(f, assume_success=True if demo else None) + return (task, f, succ, L, demo) + t_scan = time.time() + with ThreadPoolExecutor(max_workers=args.workers) as ex: + hdr = list(ex.map(rd, files, chunksize=16)) + print(f"[pack] header scan {len(hdr)} files in {time.time()-t_scan:.0f}s", + flush=True) + hc.parent.mkdir(parents=True, exist_ok=True) + np.savez(hc, tasknames=np.array([h[0] for h in hdr]), + paths=np.array([str(h[1]) for h in hdr]), + succ=np.array([h[2] for h in hdr]), + lens=np.array([h[3] for h in hdr]), + demo=np.array([h[4] for h in hdr])) + + # Task ids come from the canonical benchmark-id list so they agree with every + # other trainer in this lane. Two things are deliberately NOT used: directory + # sort order (incidental, and disagrees with benchmark id), and the npz + # `task_index` field (0 in every episode of this corpus). + canon = [n.strip() for n in + Path(args.tasks_file).read_text().replace("\n", ",").split(",") if n.strip()] + tid = {t: i for i, t in enumerate(canon)} + present = sorted(set(t for t, *_ in hdr)) + unknown = [t for t in present if t not in tid] + if unknown: + raise SystemExit(f"[pack] refusing: task dir(s) not in {args.tasks_file}: {unknown}") + tasks = canon + chosen = [] + unbalanced = [] + forced = [] + if args.keep_all_demos: + forced = [h for h in hdr if h[4]] + hdr = [h for h in hdr if not h[4]] + print(f"[pack] forcing all {len(forced)} demo episodes into the cache", flush=True) + if args.max_eps and args.max_eps < len(hdr): + per_task = args.max_eps // len(tasks) + for t in tasks: + pool = [h for h in hdr if h[0] == t] + if args.balance: + s = [h for h in pool if h[2]] + f_ = [h for h in pool if not h[2]] + k = min(per_task // 2, len(s), len(f_)) + pick = ([s[i] for i in rng.choice(len(s), k, replace=False)] + + [f_[i] for i in rng.choice(len(f_), k, replace=False)]) + if k == 0 and pool: + # A task can be entirely one-sided: STUDY_SCENE1 has 0 + # successes in 2,962 rollouts, so 50/50 balancing would drop + # it silently. Keep it at natural composition and record that + # it could not be balanced -- a task the behaviour policy + # never solves is a result, not a reason to hide the task. + kk = min(per_task, len(pool)) + pick = [pool[i] for i in rng.choice(len(pool), kk, replace=False)] + unbalanced.append((t, len(s), len(f_))) + else: + k = min(per_task, len(pool)) + pick = [pool[i] for i in rng.choice(len(pool), k, replace=False)] + chosen += pick + else: + chosen = hdr + chosen = forced + chosen + rng.shuffle(chosen) + sel_task = np.array([tid[h[0]] for h in chosen]) + n_per = np.bincount(sel_task, minlength=len(tasks)) + missing = [tasks[i] for i, n in enumerate(n_per) if n == 0 and + any(h[0] == tasks[i] for h in hdr)] + if missing: + raise SystemExit(f"[pack] refusing: task(s) present in source but absent " + f"from the selection: {missing}") + print(f"[pack] packing {len(chosen)} episodes " + f"(success {np.mean([h[2] for h in chosen]):.3f}) " + f"per-task {n_per.tolist()}", flush=True) + if unbalanced: + print(f"[pack] NOT balanceable (kept at natural composition): " + f"{[(u[0][:28], u[1], u[2]) for u in unbalanced]}", flush=True) + + # ---- pass 2: sizes, allocate, fill ---- + lens = np.array([1 + (h[3] - 1) // args.stride for h in chosen], dtype=np.int64) + ep_demo = np.array([h[4] for h in chosen], bool) + ep_to = np.cumsum(lens); ep_from = ep_to - lens + N = int(ep_to[-1]) + with np.load(chosen[0][1], allow_pickle=True) as n: + D = int(n["z"].shape[1]); A = int(n["actions"].shape[1]) + print(f"[pack] N={N} frames D={D} A={A} " + f"({N*D*2/1e9:.1f} GB latents)", flush=True) + + zmm = np.lib.format.open_memmap(out / "z.f16.npy", mode="w+", + dtype=np.float16, shape=(N, D)) + # proprio is cheap (8 floats/frame) and the lane's closed-loop policy head + # consumes it alongside the latent, so pack it for interoperability even + # though the occupancy critic here does not use it. + pmm = np.lib.format.open_memmap(out / "proprio.f32.npy", mode="w+", + dtype=np.float32, shape=(N, 8)) + amm = np.lib.format.open_memmap(out / "act.f32.npy", mode="w+", + dtype=np.float32, shape=(N, A)) + ep_task = np.zeros(len(chosen), np.int64) + ep_succ = np.zeros(len(chosen), bool) + ep_src = [] + for i, (task, f, succ, _L, _dm) in enumerate(chosen): + with np.load(f, allow_pickle=True) as n: + z = n["z"][::args.stride] + a = n["actions"][::args.stride] + pr = n["proprio"][::args.stride] if "proprio" in n.files else None + s, e = int(ep_from[i]), int(ep_to[i]) + zmm[s:e] = z[: e - s] + amm[s:e] = a[: e - s] + if pr is not None: + pmm[s:e] = pr[: e - s] + ep_task[i] = tid[task]; ep_succ[i] = succ + ep_src.append(str(f)) + if (i + 1) % 250 == 0: + # Bound dirty-page accumulation: without periodic flushes the whole + # written cache sits dirty in page cache and the box is reported as + # out of memory (it killed this job and the concurrent upload once). + zmm.flush(); amm.flush(); pmm.flush() + print(f"[pack] {i+1}/{len(chosen)} episodes", flush=True) + zmm.flush(); amm.flush(); pmm.flush() + + np.savez(out / "meta.npz", ep_from=ep_from, ep_to=ep_to, ep_len=lens, + ep_task=ep_task, ep_success=ep_succ, ep_demo=ep_demo, + tasks=np.array(tasks), + dim=D, adim=A, stride=args.stride, n_frames=N, + ep_src=np.array(ep_src)) + _cam = int(args.cam_res) if str(args.cam_res).isdigit() else (args.cam_res or "UNKNOWN") + (out / "RENDER.json").write_text(json.dumps({ + "cam_res": _cam, "encoder": args.encoder, "flip": "[::-1,::-1] to serving orientation", + "resize": "-> 224 bilinear, uint8", + "encoder": "08312026_1110pm_ogpo_latent_cache.py PaliGemma base||wrist", + "proprio": "eef_pos(3)+axis_angle(3)+gripper(2)"}, indent=1)) + (out / "PACK.json").write_text(json.dumps({ + "cam_res": _cam, "encoder": args.encoder, + "src": str(src), "episodes": len(chosen), "frames": N, "dim": D, + "adim": A, "stride": args.stride, + "success_rate": float(ep_succ.mean()), + "n_demo": int(ep_demo.sum()), + "tasks": tasks, + "task_id_source": f"canonical benchmark order from {args.tasks_file} " + f"(dir sort order and the npz task_index field are both ignored)", + "episodes_per_task": n_per.tolist(), + "tasks_not_balanceable": [[u[0], int(u[1]), int(u[2])] for u in unbalanced], + }, indent=2)) + print(f"[pack] DONE -> {out}", flush=True) + + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/paired_test.py b/rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/paired_test.py new file mode 100644 index 0000000000000000000000000000000000000000..e1b441c5581e64006461e0c581f253bb9b3664c8 --- /dev/null +++ b/rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/paired_test.py @@ -0,0 +1,55 @@ +"""Paired comparison of two closed-loop evals. + +Arms are paired by construction: the env seed depends only on (seed, tid, k), so two +arms run at the same SEED see identical initial conditions. This verifies that from the +recorded init_sha256 and then runs McNemar's exact test on the discordant pairs, which +is the correct test for paired binary outcomes. The unpaired two-proportion z-test used +elsewhere is conservative here and understates real differences. +""" +import json, sys +from math import comb + +def load(p): + """Key on (task, episode index), NOT on init_sha256. + + The env seed is a pure function of (seed, tid, k), so episode k is the same + initial condition in every arm run at the same SEED. init_sha256 hashes raw + float64 sim-state bytes and therefore differs between compute nodes for a + logically identical state, which made it useless as a join key.""" + r = json.load(open(p)) + out, sha = {}, {} + for task, eps in r["episodes_detail"].items(): + for e in eps: + out[(task, e["episode"])] = bool(e["success"]) + sha[(task, e["episode"])] = e.get("init_sha256") + return out, r["pooled_SR"], sha + +def mcnemar(b, c): + """two-sided exact binomial on the discordant pairs""" + n = b + c + if n == 0: + return 1.0 + k = min(b, c) + tail = sum(comb(n, i) for i in range(0, k + 1)) / (2 ** n) + return min(1.0, 2 * tail) + +A, srA, shA = load(sys.argv[1]) +B, srB, shB = load(sys.argv[2]) +shared = set(A) & set(B) +print(f" {sys.argv[1].split('/')[-1][:-5]:26s} SR {srA:.3f} n={len(A)}") +print(f" {sys.argv[2].split('/')[-1][:-5]:26s} SR {srB:.3f} n={len(B)}") +nsha = sum(1 for k in shared if shA.get(k) and shA[k] == shB.get(k)) +print(f" matched episodes: {len(shared)}/{min(len(A),len(B))}" + f" ({'PAIRED' if len(shared)==min(len(A),len(B)) else 'PARTIAL'})" + f" [identical init hash on {nsha}/{len(shared)}" + f"{'' if nsha==len(shared) else ' — rest differ only in float bits across nodes'}]") +if not shared: + print(" no shared inits; arms used different seeds"); raise SystemExit +b = sum(1 for k in shared if A[k] and not B[k]) +c = sum(1 for k in shared if B[k] and not A[k]) +agree = len(shared) - b - c +p = mcnemar(b, c) +d = srA - srB +print(f" concordant {agree} A-only {b} B-only {c}") +print(f" diff {d:+.3f} McNemar exact p = {p:.4g}" + f" {'SIGNIFICANT' if p < 0.05 else 'not significant'} at 0.05") diff --git a/rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/parl_rsm.py b/rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/parl_rsm.py new file mode 100644 index 0000000000000000000000000000000000000000..4eb1a34c8995c9acbf5d00fb91e0404d42f98a42 --- /dev/null +++ b/rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/parl_rsm.py @@ -0,0 +1,305 @@ +"""PARL with the RSM occupancy value: rank proposal samples by Q, distill the argmax. + +Faithful to the lane's PARL recipe (MaxSobolMark/PolicyAgnosticRL action +optimisation): sample N action chunks from a base proposal policy, rank them by +Q, keep the best, and distill those into a fresh head with the ordinary flow +loss. Our Q is the RSM occupancy read-out rather than a TD value. + +Why this is different from the Q-filtering already tried, and why that one was +handicapped: PARL's own note is that it "only helps if the proposal policy's N +samples are DIVERSE -- an overtrained flow collapses to the mean, so there is +nothing to rank". Our behaviour clones are trained 120k steps and then the +checkpoint is selected by BEST held-out sampled reconstruction MSE, which selects +precisely the most mean-collapsed checkpoint. Measured here as `proposal_std`, +which is reported before any distillation so a collapsed proposal is visible +rather than silently wasting the run. + +Selection uses depth 1 by default so the recursion never has to re-draw an action +in a latent the flow only imagined, which a raw-feature policy cannot be queried +for. +""" +from __future__ import annotations +import sys as _sys, os as _os +_sys.path.insert(0, _os.path.dirname(_os.path.abspath(__file__))) +import argparse, json +from pathlib import Path +import numpy as np +import torch + +from data import LiberoRSMData +from is_ope import load_critic, make_policy, policy_nll, policy_features, \ + q_recursive, sampled_action_mse +from awr import offline_score + + +@torch.no_grad() +def proposal_diversity(pol, pfeat, d, rng, device, n_states=256, n_samp=16, + temp=1.0, sde=0.0): + """Mean per-dimension std across N samples at a FIXED state. + + This is the quantity PARL lives or dies on. A collapsed proposal gives the + ranker N copies of the same action and the argmax is then meaningless. + """ + b = d.sample_frames(n_states, rng, "val", device) + z = pfeat(b["x"]) + acts = torch.stack([pol.sample(z, b["task"], temp=temp, sde=sde) + for _ in range(n_samp)]) + return float(acts.std(0).mean()), float(b["a"].std()) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--cache", required=True) + ap.add_argument("--critic", required=True) + ap.add_argument("--proposal", required=True, help="base policy checkpoint") + ap.add_argument("--out", required=True) + ap.add_argument("--chunk", type=int, default=10) + ap.add_argument("--proposal-sde", type=float, default=0.0, + help="noise injected during integration. Unlike temp it " + "follows the learned drift, so candidates stay near " + "the manifold instead of being thrown off it.") + ap.add_argument("--proposal-temp", type=float, default=1.0, + help="scales the proposal's initial noise; >1 widens the " + "candidate set the value ranks over") + ap.add_argument("--n-actions", type=int, default=32, + help="candidates per state (PARL repo default 32)") + ap.add_argument("--select-pool", default="demos", + choices=["demos", "succ", "demos_succ", "all"], + help="states the distillation set is drawn from") + ap.add_argument("--qf-ckpt", default="", + help="rank with the SUPERVISED student Q from rsm_main.py " + "instead of the counterfactual-conditioned occupancy " + "read-out. The student is fit on real (s,a,s') " + "transitions and is the only reader measured to rank " + "actions correctly on this corpus.") + ap.add_argument("--num-keep", type=int, default=4, + help="keep the top-k candidates, not only the arg-max. " + "Distilling a single arg-max concentrates all of the " + "estimator's error into the target.") + ap.add_argument("--margin-quantile", type=float, default=0.7, + help="confidence GATE. Keep only states whose critic margin " + "(best minus median candidate) is above this quantile; " + "apply selection only where the value actually separates " + "candidates, and leave the rest to the anchor. 0 = off.") + ap.add_argument("--include-demos", type=int, default=1, + help="anchor the distillation set on (state, LOGGED demo " + "action) pairs alongside the selected ones. PA-RL's " + "distil set is selected pairs PLUS demonstrations; " + "without the anchor the student has nothing holding it " + "on the demonstration manifold.") + ap.add_argument("--distill-states", type=int, default=200000) + ap.add_argument("--distill-steps", type=int, default=60000) + ap.add_argument("--batch", type=int, default=1024) + ap.add_argument("--lr", type=float, default=3e-4) + ap.add_argument("--beta-q", type=float, default=0.90) + ap.add_argument("--gamma", type=float, default=0.99) + ap.add_argument("--depth", type=int, default=1) + ap.add_argument("--particles", type=int, default=8) + ap.add_argument("--q-pessimism", type=float, default=2.0) + ap.add_argument("--policy-features", default="raw", choices=["raw", "latent"]) + ap.add_argument("--feat-scale", default="center", choices=["zscore", "center"]) + ap.add_argument("--policy-family", default="concat", + choices=["concat", "flow", "gauss"]) + ap.add_argument("--norm-pool", default="demos", choices=["all", "demos"]) + ap.add_argument("--reward-mode", default="dense", choices=["dense", "terminal", "subgoal", "soft"]) + ap.add_argument("--in-ram", type=int, default=1) + ap.add_argument("--seed", type=int, default=0) + ap.add_argument("--proposal-sde-anneal", type=int, default=0, + help="1 = anneal --proposal-sde to zero by the last integration step") + ap.add_argument("--rank", default="critic", choices=["critic", "random"], + help="random = keep --num-keep random candidates (critic-free control)") + ap.add_argument("--hop-policy", default="", + help="latent-feature BC checkpoint for hops >= 2 (required if --depth > 1)") + ap.add_argument("--crn", type=int, default=1, + help="common random numbers across candidates when scoring") + ap.add_argument("--save-every", type=int, default=10000, + help="save policy_s.pt during distillation; policy_last.pt is always saved") + args = ap.parse_args() + + torch.manual_seed(args.seed) + dev = "cuda" if torch.cuda.is_available() else "cpu" + out = Path(args.out); out.mkdir(parents=True, exist_ok=True) + d = LiberoRSMData(args.cache, chunk=args.chunk, seed=args.seed, + in_ram=bool(args.in_ram), reward_mode=args.reward_mode, + norm_pool=args.norm_pool) + enc, rew, flow, rms, cfg = load_critic(args.critic, d.feat_dim, d.n_task, + dev, data=d) + args.d_z = cfg["d_z"] + qstud = qenc = None + if args.qf_ckpt: + from model import Encoder as _Enc + from rsm_main import QStudent + _ck = torch.load(args.qf_ckpt, map_location=dev, weights_only=False) + _c = _ck["config"] + qenc = _Enc(d.feat_dim, _c["d_z"], _c["enc_width"]).to(dev) + qenc.load_state_dict(_ck["enc"]); qenc.eval() + qstud = QStudent(_c["d_z"], _ck["d_act"], d.n_task).to(dev) + qstud.load_state_dict(_ck["qf"]); qstud.eval() + print(f"[parl] ranking with the SUPERVISED student Q " + f"(arrival AUC {_ck.get('arrival_auc', float('nan')):.4f})", flush=True) + pfeat, d_pol = policy_features(args, enc, d, cfg, dev) + hop = None + if args.depth > 1: + if not args.hop_policy: + raise SystemExit("--depth > 1 needs --hop-policy") + _hk = torch.load(args.hop_policy, map_location=dev, weights_only=False) + class _HA: pass + _ha = _HA(); [setattr(_ha, k, v) for k, v in _hk["config"].items()] + hop = make_policy(_ha, d, dev, d_z=cfg["d_z"]); hop.load_state_dict(_hk["pol"]); hop.eval() + print(f"[parl] hop policy loaded for depth {args.depth}", flush=True) + + pk = torch.load(args.proposal, map_location=dev, weights_only=False) + # the distilled head inherits the proposal's architecture (width/depth) + args.pol_width = int(pk["config"].get("pol_width", 1024) or 1024) + args.pol_depth = int(pk["config"].get("pol_depth", 4) or 4) + base = make_policy(args, d, dev, d_z=d_pol) + base.load_state_dict(pk["pol"]); base.eval() + + rng = np.random.default_rng(args.seed + 31) + std_a, std_data = proposal_diversity(base, pfeat, d, rng, dev, + temp=args.proposal_temp, + sde=args.proposal_sde) + print(f"[parl] proposal action std {std_a:.5f} vs data action std {std_data:.5f} " + f"(ratio {std_a / max(std_data, 1e-9):.3f})", flush=True) + if std_a < 0.02 * std_data: + print("[parl] WARNING: the proposal has collapsed to the mean; ranking " + "N copies of one action cannot improve anything", flush=True) + + ok = {"demos": d.ep_demo, "succ": d.ep_success, + "demos_succ": d.ep_demo | d.ep_success, + "all": np.ones(d.n_ep, bool)}[args.select_pool] + pool = np.array([e for e in d.train_eps if ok[e]], dtype=np.int64) + + # ---- build the distillation set: argmax_a Q(z, a) over N proposal draws ---- + xs, acts, tasks, margins = [], [], [], [] + got, bs = 0, 256 + sel = np.random.default_rng(args.seed + 41) + t_report = 0 + while got < args.distill_states: + w = d.ep_len[pool].astype(np.float64); w /= w.sum() + e = sel.choice(pool, size=bs, p=w) + t = d.ep_from[e] + (sel.random(bs) * (d.ep_to[e] - d.ep_from[e])).astype(np.int64) + x = torch.from_numpy(d._feat(t)).to(dev) + tk = torch.from_numpy(d.ep_task[e]).long().to(dev) + with torch.no_grad(): + zc = enc(x) # critic latent for scoring + zp = pfeat(x) # policy features for proposing + cand = torch.stack([base.sample(zp, tk, temp=args.proposal_temp, + sde=args.proposal_sde, + sde_anneal=bool(args.proposal_sde_anneal)) + for _ in range(args.n_actions)]) + N, B, A = cand.shape + qs = [] + zq = qenc(x) if qstud is not None else None + _seed_i = int(args.seed * 1000003 + got) + for i in range(N): + if args.crn: + torch.manual_seed(_seed_i) # same MC noise for every candidate of this batch + if qstud is not None: + q = qstud(zq, cand[i], tk) + else: + q, _ = q_recursive(zc, cand[i], tk, rew=rew, flow=flow, rms=rms, + pol=hop, wend=None, beta=args.beta_q, + gamma=args.gamma, depth=args.depth, + n_particles=args.particles, use_is=False, + pessimism=args.q_pessimism) + qs.append(q) + Q = torch.stack(qs) # [N, B] + k = max(1, min(args.num_keep, Q.shape[0])) + if args.rank == "random": + topk = torch.stack([torch.randperm(N, device=dev)[:k] for _ in range(B)], 1) # [k, B] + else: + topk = Q.topk(k, dim=0).indices # [k, B] + # margin: how far the best candidate stands above the typical one. + # Small margin means the value does not separate the candidates here. + margin = Q.max(0).values - Q.median(0).values # [B] + ar = torch.arange(B, device=dev) + for j in range(k): + xs.append(x.cpu()); acts.append(cand[topk[j], ar].cpu()) + tasks.append(tk.cpu()); margins.append(margin.cpu()) + got += bs + if got - t_report >= 25600: + t_report = got + print(f"[parl] selected {got}/{args.distill_states}", flush=True) + X = torch.cat(xs); A_ = torch.cat(acts); T = torch.cat(tasks) + Mg = torch.cat(margins) + if args.margin_quantile > 0: + thr = torch.quantile(Mg, args.margin_quantile) + keep = Mg >= thr + print(f"[parl] margin gate q={args.margin_quantile} thr={float(thr):.4f} " + f"keeps {int(keep.sum())}/{len(keep)}", flush=True) + X, A_, T = X[keep], A_[keep], T[keep] + n_sel = len(X) + if args.include_demos: + # the anchor: raw (state, LOGGED action) pairs from demonstrations + dm = np.array([e for e in d.train_eps if d.ep_demo[e]], dtype=np.int64) + ax, aa, at = [], [], [] + need, dr = max(n_sel, 1), np.random.default_rng(args.seed + 51) + while sum(len(t) for t in ax) < need: + w = d.ep_len[dm].astype(np.float64); w /= w.sum() + e = dr.choice(dm, size=1024, p=w) + t = d.ep_from[e] + (dr.random(1024) * (d.ep_to[e] - d.ep_from[e])).astype(np.int64) + ax.append(torch.from_numpy(d._feat(t))) + aa.append(torch.from_numpy(d._chunk_at(t, e))) + at.append(torch.from_numpy(d.ep_task[e]).long()) + X = torch.cat([X] + ax); A_ = torch.cat([A_] + aa); T = torch.cat([T] + at) + print(f"[parl] demo anchor: {len(X) - n_sel} demo pairs + {n_sel} selected " + f"= {len(X)} ({100.0 * (len(X) - n_sel) / len(X):.1f}% demo share)", + flush=True) + print(f"[parl] distillation set {tuple(X.shape)} from {args.select_pool}", flush=True) + + # ---- distill a FRESH head onto the selected actions ---- + new = make_policy(args, d, dev, d_z=d_pol) + opt = torch.optim.Adam(new.parameters(), lr=args.lr) + ev = np.random.default_rng(args.seed + 77) + best_mse, best_sd, best_step = float("inf"), None, 0 + for step in range(1, args.distill_steps + 1): + idx = torch.randint(0, len(X), (args.batch,)) + xb = X[idx].to(dev); ab = A_[idx].to(dev); tb = T[idx].to(dev) + loss = policy_nll(new, pfeat(xb), tb, ab) + opt.zero_grad(); loss.backward() + torch.nn.utils.clip_grad_norm_(new.parameters(), 1.0); opt.step() + if step % max(1, args.distill_steps // 20) == 0 or step == args.distill_steps: + new.eval() + m = sampled_action_mse(new, d, pfeat, ev, dev, ok) + new.train() + tag = "" + if m == m and m < best_mse: + best_mse, best_step = m, step + best_sd = {k: v.detach().clone() for k, v in new.state_dict().items()} + tag = " <- best" + print(f"[parl] distill {step} loss={float(loss):.4f} " + f"sampled_mse_vs_LOGGED={m:.5f}{tag}", flush=True) + if args.save_every and step % args.save_every == 0: + torch.save({"pol": new.state_dict(), "round": 1, "step": step, "config": vars(args), + "cam_res": getattr(d, "cam_res", "UNKNOWN"), "encoder": getattr(d, "encoder", "pi05_base_pytorch")}, out / f"policy_s{step}.pt") + # The LAST distilled head is the deployable one: the logged-action MSE proxy selects + # AGAINST the Q-preferred actions PARL is supposed to move toward (and picked a + # checkpoint 0.10 SR below the last one for plain BC). policy_r1.pt keeps the + # proxy-best for comparison; select between them on validation inits. + torch.save({"pol": new.state_dict(), "round": 1, "step": args.distill_steps, "config": vars(args), + "cam_res": getattr(d, "cam_res", "UNKNOWN"), "encoder": getattr(d, "encoder", "pi05_base_pytorch"), + "note": "LAST distilled checkpoint"}, out / "policy_last.pt") + if best_sd is not None: + new.load_state_dict(best_sd) + new.eval() + + torch.save({"pol": new.state_dict(), "round": 1, "config": vars(args), + "cam_res": getattr(d, "cam_res", "UNKNOWN"), "encoder": getattr(d, "encoder", "pi05_base_pytorch")}, + out / "policy_r1.pt") + sc = offline_score(d, enc, new, np.random.default_rng(args.seed + 23), dev, + pfeat=pfeat) + sc["proposal_action_std"] = std_a + sc["data_action_std"] = std_data + # NOTE: sampled_mse against the LOGGED action is not the objective here -- a + # working PARL run should move AWAY from the logged action toward the + # Q-preferred one, so a higher value is expected and is not a failure. + (out / "parl.json").write_text(json.dumps( + {"config": vars(args), "score": sc, "best_distill_step": best_step}, + indent=2)) + print(f"[parl] {sc}", flush=True) + print("[parl] DONE", flush=True) + + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/pooled_test.py b/rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/pooled_test.py new file mode 100644 index 0000000000000000000000000000000000000000..d065243928d079355e8e9c12b1f8c7406992d23b --- /dev/null +++ b/rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/pooled_test.py @@ -0,0 +1,25 @@ +"""Pool paired McNemar counts across seeds. Each seed is an independent draw of +500 initial conditions on protocol B, so discordant pairs add.""" +import json, sys +from math import comb, sqrt, erfc +def counts(pa, pb): + def load(p): + r=json.load(open(p)); o={} + for t,eps in r["episodes_detail"].items(): + for e in eps: o[(t,e["episode"])]=bool(e["success"]) + return o, r["pooled_SR"] + A,sa=load(pa); B,sb=load(pb); sh=set(A)&set(B) + return (sum(1 for k in sh if A[k] and not B[k]), + sum(1 for k in sh if B[k] and not A[k]), len(sh), sa, sb) +B=C=N=0; srs=[] +for i in range(1,len(sys.argv),2): + b,c,n,sa,sb = counts(sys.argv[i], sys.argv[i+1]) + B+=b; C+=c; N+=n; srs.append((sa,sb)) + print(f" seed pair {i//2}: SR {sa:.3f} vs {sb:.3f} b={b} c={c} diff {sa-sb:+.3f}") +z=(B-C)/sqrt(B+C) if B+C else 0.0 +p=erfc(abs(z)/sqrt(2)) +msr=sum(a for a,_ in srs)/len(srs); mbs=sum(b for _,b in srs)/len(srs) +print(f"\n POOLED over {len(srs)} seeds, {N} paired episodes") +print(f" mean SR {msr:.3f} vs {mbs:.3f} diff {msr-mbs:+.3f}") +print(f" discordant b={B} c={C} z={z:.2f} p={p:.4f} " + f"{'SIGNIFICANT' if p<0.05 else 'NOT significant'} at 0.05") diff --git a/rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/probe_actcon.py b/rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/probe_actcon.py new file mode 100644 index 0000000000000000000000000000000000000000..f355db89470063931af07e049ed7548d0204881e --- /dev/null +++ b/rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/probe_actcon.py @@ -0,0 +1,95 @@ +"""Which negative does the action-contrast term actually need? + +Two candidate negatives for the flow-matching error at a state z: + (A) shuffle the ACTION only (s, a_rand, s') <- what we implement + (B) shuffle the action AND the target (s, a_rand, s'_rand) + +(B) is the intuitive reading, but it confounds two effects. Its error is large +partly because the conditioning action is wrong and partly because the TARGET is +an unrelated future. A successor that ignores the action entirely still scores +well on (B), because predicting the true future from z is easy and predicting an +unrelated one is hard -- which is exactly the failure the term exists to prevent. + +This measures the decomposition on a trained critic: + e_pos true action, true target + e_act shuffled action, TRUE target -> isolates the action + e_both shuffled action, shuffled target -> action + target confounded + e_tgt TRUE action, shuffled target -> isolates the target +If (e_both - e_pos) is dominated by (e_tgt - e_pos), then (B) is mostly a +target-mismatch test and says little about action sensitivity. +""" +from __future__ import annotations +import sys as _sys, os as _os +_sys.path.insert(0, _os.path.dirname(_os.path.abspath(__file__))) +import argparse +import numpy as np +import torch + +from data import LiberoRSMData +from is_ope import load_critic + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--cache", required=True) + ap.add_argument("--critic", required=True) + ap.add_argument("--chunk", type=int, default=10) + ap.add_argument("--beta", type=float, default=0.90) + ap.add_argument("--batch", type=int, default=4096) + ap.add_argument("--reps", type=int, default=8) + ap.add_argument("--norm-pool", default="demos", choices=["all", "demos"]) + ap.add_argument("--in-ram", type=int, default=1) + ap.add_argument("--seed", type=int, default=0) + args = ap.parse_args() + torch.manual_seed(args.seed) + dev = "cuda" + d = LiberoRSMData(args.cache, chunk=args.chunk, seed=args.seed, + in_ram=bool(args.in_ram), reward_mode="dense", + norm_pool=args.norm_pool) + enc, rew, flow, rms, cfg = load_critic(args.critic, d.feat_dim, d.n_task, + dev, data=d) + rng = np.random.default_rng(args.seed + 13) + acc = {k: 0.0 for k in ("pos", "act", "both", "tgt")} + with torch.no_grad(): + for _ in range(args.reps): + b = d.sample(args.batch, rng, args.beta, args.beta, "val", dev) + z = enc(b["x_now"]); zf = enc(b["x_fut"]) + y = (zf - z) / rms # true normalised residual + k = torch.rand(args.batch, device=dev) + noise = torch.randn_like(y) + x_k = (1 - k)[:, None] * y + k[:, None] * noise + u = y - noise + p = torch.randperm(args.batch, device=dev) + a_t, a_r = b["a_now"], b["a_now"][p] + # shuffled TARGET: rebuild the path from the permuted residual + y_r = y[p]; n_r = noise[p] + x_k_r = (1 - k)[:, None] * y_r + k[:, None] * n_r + u_r = y_r - n_r + + def err(a, xk, tgt): + return (flow(z, a, b["task"], b["beta"], xk, k) + - tgt).pow(2).mean(-1).mean() + acc["pos"] += float(err(a_t, x_k, u)) + acc["act"] += float(err(a_r, x_k, u)) # action only + acc["both"] += float(err(a_r, x_k_r, u_r)) # action + target + acc["tgt"] += float(err(a_t, x_k_r, u_r)) # target only + for kk in acc: + acc[kk] /= args.reps + print(f"\n{'negative':<34s} {'flow-matching error':>20s} {'gap vs true':>13s}") + print(f"{'(true action, true target)':<34s} {acc['pos']:20.5f} {0.0:13.5f}") + print(f"{'A: shuffled ACTION, true target':<34s} {acc['act']:20.5f} " + f"{acc['act'] - acc['pos']:+13.5f}") + print(f"{' true action, shuffled target':<34s} {acc['tgt']:20.5f} " + f"{acc['tgt'] - acc['pos']:+13.5f}") + print(f"{'B: shuffled action AND target':<34s} {acc['both']:20.5f} " + f"{acc['both'] - acc['pos']:+13.5f}") + ga, gb = acc["act"] - acc["pos"], acc["both"] - acc["pos"] + gt = acc["tgt"] - acc["pos"] + print(f"\naction-only gap as a share of the both-shuffled gap: " + f"{100.0 * ga / gb:.1f}%" if gb else "") + print(f"target-only gap as a share of the both-shuffled gap: " + f"{100.0 * gt / gb:.1f}%" if gb else "") + + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/probe_action_info.py b/rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/probe_action_info.py new file mode 100644 index 0000000000000000000000000000000000000000..e2ed7896cb7a8e9a74f36919134390950265a6f4 --- /dev/null +++ b/rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/probe_action_info.py @@ -0,0 +1,97 @@ +"""Does the ACTION carry outcome information beyond the state, in this corpus? + +Everything in this lane hinges on it. The RSM Q takes its action dependence from +the occupancy model extrapolating to actions never observed at that state, which +is unsupervised in the action direction, and was measured to have arbitrary sign. +A directly supervised head has that dependence SUPERVISED by real outcomes. + +Two heads, same latent, same data, same budget, held-out AUC against episode +success: + V(z) state only + Q(z, a) state and the logged action chunk +If Q does not beat V, the action carries nothing beyond the state at this +granularity and NO critic of any kind can rank actions here -- the ceiling is the +data, not the model. If Q does beat V, the action signal exists and the defect is +the occupancy model's extrapolation, which is fixable. + +Reported on rollouts (which contain failures); demonstrations alone are almost +all successes and cannot answer the question. +""" +from __future__ import annotations +import sys as _sys, os as _os +_sys.path.insert(0, _os.path.dirname(_os.path.abspath(__file__))) +import argparse +import numpy as np +import torch +import torch.nn.functional as F + +from data import LiberoRSMData +from is_ope import load_critic +from model import mlp +from train_rsm import auc + + +def train_head(d, enc, dev, use_action, steps, batch, lr, seed, tag): + torch.manual_seed(seed) + d_act = d.chunk * d.adim + din = 264 + (d_act if use_action else 0) + net = mlp([din, 1024, 1024, 1], norm=True).to(dev) + emb = torch.nn.Embedding(d.n_task, 0).to(dev) # task enters via the latent + opt = torch.optim.Adam(net.parameters(), lr=lr) + rng = np.random.default_rng(seed + 3) + for step in range(1, steps + 1): + b = d.sample_frames(batch, rng, "train", dev) + with torch.no_grad(): + z = enc(b["x"]) + x = torch.cat([z, b["a"]], -1) if use_action else z + loss = F.binary_cross_entropy_with_logits(net(x).squeeze(-1), b["succ"]) + opt.zero_grad(); loss.backward(); opt.step() + if step % max(1, steps // 5) == 0: + print(f" [{tag}] {step} bce={float(loss):.4f}", flush=True) + # held-out AUC against EPISODE success + net.eval() + ev = np.random.default_rng(seed + 77) + P, Y = [], [] + with torch.no_grad(): + for _ in range(8): + b = d.sample_frames(2048, ev, "val", dev) + z = enc(b["x"]) + x = torch.cat([z, b["a"]], -1) if use_action else z + P.append(torch.sigmoid(net(x).squeeze(-1)).cpu().numpy()) + Y.append(b["succ"].cpu().numpy()) + return float(auc(np.concatenate(P), np.concatenate(Y))) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--cache", required=True) + ap.add_argument("--critic", required=True) + ap.add_argument("--chunk", type=int, default=10) + ap.add_argument("--steps", type=int, default=20000) + ap.add_argument("--batch", type=int, default=1024) + ap.add_argument("--lr", type=float, default=3e-4) + ap.add_argument("--norm-pool", default="demos", choices=["all", "demos"]) + ap.add_argument("--in-ram", type=int, default=1) + ap.add_argument("--seed", type=int, default=0) + args = ap.parse_args() + dev = "cuda" + d = LiberoRSMData(args.cache, chunk=args.chunk, seed=args.seed, + in_ram=bool(args.in_ram), reward_mode="dense", + norm_pool=args.norm_pool) + enc, _r, _f, _rms, cfg = load_critic(args.critic, d.feat_dim, d.n_task, + dev, data=d) + print(f"[probe] corpus success rate {float(d.ep_success.mean()):.3f}", flush=True) + a_v = train_head(d, enc, dev, False, args.steps, args.batch, args.lr, + args.seed, "V(z)") + a_q = train_head(d, enc, dev, True, args.steps, args.batch, args.lr, + args.seed, "Q(z,a)") + print(f"\nheld-out AUC vs episode success") + print(f" V(z) state only {a_v:.4f}") + print(f" Q(z,a) state and action {a_q:.4f}") + print(f" delta {a_q - a_v:+.4f}") + print("\ndelta ~ 0 means the action adds nothing beyond the state at this " + "granularity, and no critic can rank actions on this corpus.", flush=True) + + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/probe_crn.py b/rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/probe_crn.py new file mode 100644 index 0000000000000000000000000000000000000000..085b28516f2b3b3b5f36c991953ae86653062de2 --- /dev/null +++ b/rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/probe_crn.py @@ -0,0 +1,105 @@ +"""Is Q blind to the action, or is its ESTIMATOR too noisy to see the action? + +q_recursive draws fresh flow noise on every call, so comparing Q(a1) with Q(a2) +compares two noisy Monte-Carlo estimates. If the per-call noise is larger than the +effect an action has, the comparison is pure coin-flip -- which is exactly what +probe_perturb saw (expert wins 0.483-0.508, mean Q moving 1% when the action is +destroyed). That is equally consistent with "Q ignores the action" and with "the +estimator cannot resolve the action". + +This separates them: + repeat noise |Q(a) - Q'(a)| same action, INDEPENDENT noise + paired effect |Q(a) - Q(a+e)| different action, COMMON noise (CRN) +If the paired effect is comparable to or larger than the repeat noise, the signal +is there and was being drowned; common random numbers recover it. If the paired +effect is ~0 under CRN, the model genuinely ignores the action. +""" +from __future__ import annotations +import sys as _sys, os as _os +_sys.path.insert(0, _os.path.dirname(_os.path.abspath(__file__))) +import argparse +import numpy as np +import torch + +from data import LiberoRSMData +from is_ope import load_critic +from train_rsm import sample_future + + +def q_fixed_noise(enc_z, a, tk, *, rew, flow, rms, beta, gamma, n_particles, + flow_steps, noise): + """Q with the flow's initial noise SUPPLIED, so candidates share it.""" + B, D = enc_z.shape + z = enc_z.repeat_interleave(n_particles, 0) + aa = a.repeat_interleave(n_particles, 0) + t = tk.repeat_interleave(n_particles, 0) + bq = torch.full((z.shape[0],), beta, device=z.device) + x = noise.clone() + for s in range(flow_steps): + k = torch.full((z.shape[0],), 1.0 - s / flow_steps, device=z.device) + x = x + flow(z, aa, t, bq, x, k) / flow_steps + z_end = z + x * rms + r = torch.sigmoid(rew(z_end, t)).view(B, n_particles) + return r.mean(1) / (1 - gamma) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--cache", required=True) + ap.add_argument("--critic", required=True) + ap.add_argument("--chunk", type=int, default=10) + ap.add_argument("--beta-q", type=float, default=0.90) + ap.add_argument("--gamma", type=float, default=0.99) + ap.add_argument("--particles", type=int, default=16) + ap.add_argument("--flow-steps", type=int, default=8) + ap.add_argument("--n", type=int, default=1024) + ap.add_argument("--norm-pool", default="demos", choices=["all", "demos"]) + ap.add_argument("--in-ram", type=int, default=1) + ap.add_argument("--seed", type=int, default=0) + args = ap.parse_args() + + torch.manual_seed(args.seed) + dev = "cuda" + d = LiberoRSMData(args.cache, chunk=args.chunk, seed=args.seed, + in_ram=bool(args.in_ram), reward_mode="dense", + norm_pool=args.norm_pool) + enc, rew, flow, rms, cfg = load_critic(args.critic, d.feat_dim, d.n_task, + dev, data=d) + pool = np.array([e for e in d.val_eps if d.ep_demo[e]], dtype=np.int64) + if not len(pool): + pool = np.array([e for e in d.train_eps if d.ep_demo[e]], dtype=np.int64) + rng = np.random.default_rng(args.seed + 9) + w = d.ep_len[pool].astype(np.float64); w /= w.sum() + e = rng.choice(pool, size=args.n, p=w) + t = d.ep_from[e] + (rng.random(args.n) * (d.ep_to[e] - d.ep_from[e])).astype(np.int64) + x = torch.from_numpy(d._feat(t)).to(dev) + a0 = torch.from_numpy(d._chunk_at(t, e)).to(dev) + tk = torch.from_numpy(d.ep_task[e]).long().to(dev) + + with torch.no_grad(): + z = enc(x) + D = z.shape[1] + kw = dict(rew=rew, flow=flow, rms=rms, beta=args.beta_q, gamma=args.gamma, + n_particles=args.particles, flow_steps=args.flow_steps) + n1 = torch.randn(args.n * args.particles, D, device=dev) + n2 = torch.randn(args.n * args.particles, D, device=dev) + q_a = q_fixed_noise(z, a0, tk, noise=n1, **kw) + q_b = q_fixed_noise(z, a0, tk, noise=n2, **kw) + repeat = (q_a - q_b).abs().mean() + print(f"repeat noise, same action different noise : {float(repeat):.5f}") + print(f"{'noise':>7s} {'|dQ| CRN':>10s} {'expert wins CRN':>16s} " + f"{'|dQ|/repeat':>12s}") + for sig in (0.1, 0.2, 0.4, 0.8): + q_p = q_fixed_noise(z, a0 + sig * torch.randn_like(a0), tk, + noise=n1, **kw) # COMMON noise + dq = (q_a - q_p) + win = float((dq > 0).float().mean()) + print(f"{sig:7.2f} {float(dq.abs().mean()):10.5f} {win:16.3f} " + f"{float(dq.abs().mean() / repeat.clamp_min(1e-9)):12.2f}", + flush=True) + print("\nexpert wins CRN > 0.5 means the model DOES prefer the expert action " + "once the shared noise is removed.", flush=True) + + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/probe_inits.py b/rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/probe_inits.py new file mode 100644 index 0000000000000000000000000000000000000000..fdf86c1210f2a7a2f284d115f6b748adcb17496c --- /dev/null +++ b/rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/probe_inits.py @@ -0,0 +1,46 @@ +"""Characterise the two initial-condition distributions the evaluator can use. + +Protocol A replays LIBERO's 50 stored init states; protocol B lets the task's BDDL +placement region resample. Both are full sim-state vectors, so they are directly +comparable. Reports, per task, how much each distribution actually spreads and +whether A's 50 states are a subset of B's support. +""" +import os, sys, numpy as np +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from libero.libero import benchmark, get_libero_path +from libero.libero.envs import OffScreenRenderEnv +from pathlib import Path + +bench = benchmark.get_benchmark_dict()["libero_10"]() +rows = [] +for tid in range(10): + task = bench.get_task(tid) + env = OffScreenRenderEnv( + bddl_file_name=str(Path(get_libero_path("bddl_files")) + / task.problem_folder / task.bddl_file), + camera_heights=128, camera_widths=128) + inits = np.asarray(bench.get_task_init_states(tid)) # protocol A + fresh = [] + for k in range(50): # protocol B, eval seeds + env.seed(0 * 100003 + tid * 1009 + k) + env.reset() + fresh.append(np.asarray(env.env.sim.get_state().flatten())) + fresh = np.stack(fresh) + n = min(inits.shape[1], fresh.shape[1]) + A, B = inits[:, :n], fresh[:, :n] + # dims that actually vary in either protocol = the randomised object DoF + var = (A.std(0) > 1e-6) | (B.std(0) > 1e-6) + sa, sb = A[:, var].std(0), B[:, var].std(0) + # is every stock state inside the fresh support? + lo, hi = B[:, var].min(0), B[:, var].max(0) + inside = ((A[:, var] >= lo - 1e-6) & (A[:, var] <= hi + 1e-6)).all(1).mean() + rows.append((tid, task.name[:34], int(var.sum()), sa.mean(), sb.mean(), inside)) + print(f"t{tid} {task.name[:34]:34s} varying_dof={int(var.sum()):3d} " + f"std_stock={sa.mean():.4f} std_fresh={sb.mean():.4f} " + f"stock_inside_fresh_support={inside:.2f}", flush=True) + env.close() +print() +print(f"MEAN std_stock={np.mean([r[3] for r in rows]):.4f} " + f"std_fresh={np.mean([r[4] for r in rows]):.4f} " + f"ratio={np.mean([r[4] for r in rows])/max(np.mean([r[3] for r in rows]),1e-9):.2f}x " + f"stock_inside={np.mean([r[5] for r in rows]):.2f}") diff --git a/rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/probe_inits2.py b/rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/probe_inits2.py new file mode 100644 index 0000000000000000000000000000000000000000..a75d29fe0353eb974d93872c4bd35f92ff6135d6 --- /dev/null +++ b/rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/probe_inits2.py @@ -0,0 +1,39 @@ +"""Exactly what each protocol randomises: per-DoF comparison + the sampler ranges.""" +import os, sys, numpy as np +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from libero.libero import benchmark, get_libero_path +from libero.libero.envs import OffScreenRenderEnv +from pathlib import Path + +bench = benchmark.get_benchmark_dict()["libero_10"]() +for tid in [0, 3]: + task = bench.get_task(tid) + env = OffScreenRenderEnv( + bddl_file_name=str(Path(get_libero_path("bddl_files")) + / task.problem_folder / task.bddl_file), + camera_heights=128, camera_widths=128) + print(f"\n===== t{tid} {task.name} =====") + pi = env.env.placement_initializer + for smp in getattr(pi, "samplers", {}).values() if hasattr(pi, "samplers") else []: + xr = getattr(smp, "x_range", None); yr = getattr(smp, "y_range", None) + rot = getattr(smp, "rotation", None) + if xr is None: continue + xs = float(np.ptp(np.asarray(xr))); ys = float(np.ptp(np.asarray(yr))) + print(f" sampler {smp.name[:38]:38s} x-span {xs*100:6.2f} cm y-span {ys*100:6.2f} cm rot {rot}") + inits = np.asarray(bench.get_task_init_states(tid)) + fresh = [] + for k in range(50): + env.seed(tid*1009 + k); env.reset() + fresh.append(np.asarray(env.env.sim.get_state().flatten())) + fresh = np.stack(fresh) + n = min(inits.shape[1], fresh.shape[1]); A, B = inits[:, :n], fresh[:, :n] + va, vb = A.std(0) > 1e-6, B.std(0) > 1e-6 + both, only_a, only_b = va & vb, va & ~vb, vb & ~va + print(f" DoF varying in BOTH: {both.sum():3d} stdA {A[:,both].std(0).mean():.4f} " + f"stdB {B[:,both].std(0).mean():.4f}") + print(f" DoF varying in STOCK ONLY (A randomises, B holds fixed): {only_a.sum():3d}" + f" stdA {A[:,only_a].std(0).mean() if only_a.any() else 0:.4f}") + print(f" DoF varying in FRESH ONLY: {only_b.sum():3d}") + nq = env.env.sim.model.nq + print(f" (nq={nq}; robot joints are the first ~7-9 dims, objects are free joints after)") + env.close() diff --git a/rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/probe_perturb.py b/rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/probe_perturb.py new file mode 100644 index 0000000000000000000000000000000000000000..cc8552cafa865f8bb464f69f537cacbd8654bbbb --- /dev/null +++ b/rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/probe_perturb.py @@ -0,0 +1,81 @@ +"""Does Q prefer the EXPERT action over noisy perturbations of it? + +This is the question PARL actually asks, and it has unambiguous ground truth: on +a demonstration frame the logged chunk IS the good action, and adding noise can +only make it worse. The earlier action-gap probe compared the logged action +against a DIFFERENT episode's action, which is dominated by on-support versus +off-support and says little about ranking candidates near the mode. + +Reports, per noise scale: the fraction of states where Q ranks the expert action +above the perturbed one, and mean Q as a function of noise. If mean Q RISES with +noise the critic is inverted, and the fix is a sign, not more training. +""" +from __future__ import annotations +import sys as _sys, os as _os +_sys.path.insert(0, _os.path.dirname(_os.path.abspath(__file__))) +import argparse +import numpy as np +import torch + +from data import LiberoRSMData +from is_ope import load_critic, q_recursive + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--cache", required=True) + ap.add_argument("--critic", required=True) + ap.add_argument("--chunk", type=int, default=10) + ap.add_argument("--beta-q", type=float, default=0.90) + ap.add_argument("--gamma", type=float, default=0.99) + ap.add_argument("--depth", type=int, default=1) + ap.add_argument("--particles", type=int, default=16) + ap.add_argument("--n", type=int, default=1024) + ap.add_argument("--pool", default="demos", choices=["demos", "succ", "all"]) + ap.add_argument("--norm-pool", default="demos", choices=["all", "demos"]) + ap.add_argument("--pessimism", type=float, default=0.0) + ap.add_argument("--in-ram", type=int, default=1) + ap.add_argument("--seed", type=int, default=0) + args = ap.parse_args() + + torch.manual_seed(args.seed) + dev = "cuda" + d = LiberoRSMData(args.cache, chunk=args.chunk, seed=args.seed, + in_ram=bool(args.in_ram), reward_mode="dense", + norm_pool=args.norm_pool) + enc, rew, flow, rms, cfg = load_critic(args.critic, d.feat_dim, d.n_task, + dev, data=d) + ok = {"demos": d.ep_demo, "succ": d.ep_success, + "all": np.ones(d.n_ep, bool)}[args.pool] + pool = np.array([e for e in d.val_eps if ok[e]], dtype=np.int64) + if not len(pool): + pool = np.array([e for e in d.train_eps if ok[e]], dtype=np.int64) + rng = np.random.default_rng(args.seed + 9) + w = d.ep_len[pool].astype(np.float64); w /= w.sum() + e = rng.choice(pool, size=args.n, p=w) + t = d.ep_from[e] + (rng.random(args.n) * (d.ep_to[e] - d.ep_from[e])).astype(np.int64) + x = torch.from_numpy(d._feat(t)).to(dev) + a0 = torch.from_numpy(d._chunk_at(t, e)).to(dev) + tk = torch.from_numpy(d.ep_task[e]).long().to(dev) + + def Q(a): + q, _ = q_recursive(enc(x), a, tk, rew=rew, flow=flow, rms=rms, pol=None, + wend=None, beta=args.beta_q, gamma=args.gamma, + depth=args.depth, n_particles=args.particles, + use_is=False, pessimism=args.pessimism) + return q + + with torch.no_grad(): + q0 = Q(a0) + print(f"expert action: mean Q {float(q0.mean()):+.5f}", flush=True) + print(f"{'noise':>7s} {'mean Q':>10s} {'expert wins':>12s}") + for sig in (0.05, 0.1, 0.2, 0.4, 0.8): + qn = Q(a0 + sig * torch.randn_like(a0)) + win = float((q0 > qn).float().mean()) + print(f"{sig:7.2f} {float(qn.mean()):+10.5f} {win:12.3f}", flush=True) + print("\nexpert wins > 0.5 = the critic prefers the expert action.", flush=True) + print("mean Q RISING with noise = the critic is inverted.", flush=True) + + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/probe_pessimism.py b/rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/probe_pessimism.py new file mode 100644 index 0000000000000000000000000000000000000000..13a8593b4e34a92bacaea1502954a2f7fda91059 --- /dev/null +++ b/rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/probe_pessimism.py @@ -0,0 +1,73 @@ +"""Does a disagreement penalty fix the critic's inverted action ranking? + +Measures the held-out action win rate -- how often Q ranks the action actually +taken above a different action taken in the SAME task -- as a function of the +pessimism coefficient. Within-task negatives on purpose: cross-task negatives +measure support violation, not preference. +""" +from __future__ import annotations +import sys as _sys, os as _os +_sys.path.insert(0, _os.path.dirname(_os.path.abspath(__file__))) +import argparse +import numpy as np +import torch + +from data import LiberoRSMData +from is_ope import load_critic, q_recursive, train_bc, policy_features + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--cache", required=True) + ap.add_argument("--critic", required=True) + ap.add_argument("--chunk", type=int, default=10) + ap.add_argument("--beta-q", type=float, default=0.90) + ap.add_argument("--gamma", type=float, default=0.99) + ap.add_argument("--depth", type=int, default=3) + ap.add_argument("--particles", type=int, default=16) + ap.add_argument("--n", type=int, default=1024) + ap.add_argument("--batch", type=int, default=256) + ap.add_argument("--bc-steps", type=int, default=4000) + ap.add_argument("--in-ram", type=int, default=1) + ap.add_argument("--seed", type=int, default=0) + ap.add_argument("--policy-family", default="concat") + args = ap.parse_args() + torch.manual_seed(args.seed) + dev = "cuda" + d = LiberoRSMData(args.cache, chunk=args.chunk, seed=args.seed, + in_ram=bool(args.in_ram), reward_mode="dense") + enc, rew, flow, rms, cfg = load_critic(args.critic, d.feat_dim, d.n_task, dev, data=d) + args.d_z = cfg["d_z"] + # continuation policy in the critic's latent space, as the recursion needs + cont = train_bc(d, enc, args, dev, only_success=True, steps=args.bc_steps) + + rng = np.random.default_rng(args.seed + 5) + b = d.sample_frames(args.n, rng, "val", dev) + # within-task negative: another frame's action chunk from the SAME task + task = b["task"].cpu().numpy() + perm = np.arange(len(task)) + for t in np.unique(task): + idx = np.where(task == t)[0] + perm[idx] = rng.permutation(idx) + a_neg = b["a"][torch.from_numpy(perm).to(dev)] + + with torch.no_grad(): + z = enc(b["x"]) + print(f"{'pessimism':>10s} {'win rate':>9s} {'gap':>10s}") + for pe in (0.0, 0.5, 1.0, 2.0, 4.0): + qp, _ = q_recursive(z, b["a"], b["task"], rew=rew, flow=flow, rms=rms, + pol=cont, wend=None, beta=args.beta_q, + gamma=args.gamma, depth=args.depth, + n_particles=args.particles, use_is=False, + pessimism=pe) + qn, _ = q_recursive(z, a_neg, b["task"], rew=rew, flow=flow, rms=rms, + pol=cont, wend=None, beta=args.beta_q, + gamma=args.gamma, depth=args.depth, + n_particles=args.particles, use_is=False, + pessimism=pe) + win = float((qp > qn).float().mean()) + print(f"{pe:10.1f} {win:9.3f} {float((qp - qn).mean()):+10.5f}", flush=True) + + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/probe_qf.py b/rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/probe_qf.py new file mode 100644 index 0000000000000000000000000000000000000000..a8dc50e5a32e27c176decf45a7882b480d8707e5 --- /dev/null +++ b/rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/probe_qf.py @@ -0,0 +1,76 @@ +"""Does main's SUPERVISED student Q rank actions where our counterfactual Q cannot? + +Same test as probe_perturb/probe_crn, applied to qf(z,a) from rsm_main.py. qf is +fit by regression onto r + gamma(1-done)V(s') using the REAL logged s', so its +action dependence is supervised rather than extrapolated. It is also +deterministic, so there is no sampling noise to cancel -- the comparison is exact. + +expert wins > 0.5 means it prefers the expert chunk over a perturbation of it. +""" +from __future__ import annotations +import sys as _sys, os as _os +_sys.path.insert(0, _os.path.dirname(_os.path.abspath(__file__))) +import argparse +import numpy as np +import torch + +from data import LiberoRSMData +from model import Encoder +from rsm_main import QStudent + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--cache", required=True) + ap.add_argument("--ckpt", required=True) + ap.add_argument("--n", type=int, default=2048) + ap.add_argument("--pool", default="demos", choices=["demos", "succ", "all"]) + ap.add_argument("--in-ram", type=int, default=1) + ap.add_argument("--seed", type=int, default=0) + args = ap.parse_args() + dev = "cuda" + ck = torch.load(args.ckpt, map_location=dev, weights_only=False) + c = ck["config"] + d = LiberoRSMData(args.cache, chunk=c["chunk"], k_success=c["k_success"], + seed=args.seed, in_ram=bool(args.in_ram), + reward_mode="terminal", norm_pool=c["norm_pool"]) + enc = Encoder(d.feat_dim, c["d_z"], c["enc_width"]).to(dev) + enc.load_state_dict(ck["enc"]); enc.eval() + qf = QStudent(c["d_z"], ck["d_act"], d.n_task).to(dev) + qf.load_state_dict(ck["qf"]); qf.eval() + + ok = {"demos": d.ep_demo, "succ": d.ep_success, + "all": np.ones(d.n_ep, bool)}[args.pool] + pool = np.array([e for e in d.val_eps if ok[e]], dtype=np.int64) + if not len(pool): + pool = np.array([e for e in d.train_eps if ok[e]], dtype=np.int64) + rng = np.random.default_rng(args.seed + 9) + w = d.ep_len[pool].astype(np.float64); w /= w.sum() + e = rng.choice(pool, size=args.n, p=w) + t = d.ep_from[e] + (rng.random(args.n) * (d.ep_to[e] - d.ep_from[e])).astype(np.int64) + x = torch.from_numpy(d._feat(t)).to(dev) + a0 = torch.from_numpy(d._chunk_at(t, e)).to(dev) + tk = torch.from_numpy(d.ep_task[e]).long().to(dev) + + with torch.no_grad(): + z = enc(x) + q0 = qf(z, a0, tk) + print(f"expert chunk: mean Q {float(q0.mean()):+.4f} sd {float(q0.std()):.4f}") + print(f"{'noise':>7s} {'mean Q':>10s} {'expert wins':>12s} {'mean dQ':>10s}") + for sig in (0.05, 0.1, 0.2, 0.4, 0.8): + qn = qf(z, a0 + sig * torch.randn_like(a0), tk) + print(f"{sig:7.2f} {float(qn.mean()):+10.4f} " + f"{float((q0 > qn).float().mean()):12.3f} " + f"{float((q0 - qn).mean()):+10.4f}", flush=True) + # in-support control: a real chunk from a DIFFERENT frame of the same task + tt = tk.cpu().numpy(); perm = np.arange(len(tt)) + for task in np.unique(tt): + idx = np.where(tt == task)[0] + perm[idx] = rng.permutation(idx) + qo = qf(z, a0[torch.from_numpy(perm).to(dev)], tk) + print(f"\nwithin-task other real chunk: expert wins " + f"{float((q0 > qo).float().mean()):.3f}", flush=True) + + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/proposer_bias_diag.py b/rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/proposer_bias_diag.py new file mode 100644 index 0000000000000000000000000000000000000000..b1a52ecbfa1ec085e54a8bf0e78f470754e547b0 --- /dev/null +++ b/rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/proposer_bias_diag.py @@ -0,0 +1,105 @@ +"""Does the critic prefer one PROPOSER's action style regardless of state? + +At held-out frames, grouped by where they come from (demo episodes, successful +rollouts, failed rollouts), draw N chunks from the BC-demos policy and N from the +BC-successes policy and score every chunk with the same recursive Q the closed-loop +mixed arms use. Reports, per frame source: mean Q by proposer, how often the +arg-max over the 2N pool lands on a successes chunk, and the Q of the logged action. + +A critic that evaluates ACTIONS should prefer neither proposer on the demo frames +(where the demos policy is at home) in particular. A critic that identifies the +POLICY from the action style prefers the successes proposer everywhere, because the +demos are <1% of the frames it was fit on. + +usage: proposer_bias_diag.py --cache ... --critic ... --hop-policy ... --pol1 + --pol2 [--n 8 --frames 512 --beta 0.95 --depth 3 --particles 16] +""" +from __future__ import annotations +import sys as _sys, os as _os +_sys.path.insert(0, _os.path.dirname(_os.path.abspath(__file__))) +import argparse, json +import numpy as np +import torch +from data import LiberoRSMData +from is_ope import load_critic, make_policy, policy_features, q_recursive + + +def load_pol(path, d, dev, d_pol): + pk = torch.load(path, map_location=dev, weights_only=False) + class _A: pass + a = _A(); [setattr(a, k, v) for k, v in pk["config"].items()] + a.pol_width = int(pk["config"].get("pol_width", 1024) or 1024) + a.pol_depth = int(pk["config"].get("pol_depth", 4) or 4) + pol = make_policy(a, d, dev, d_z=d_pol); pol.load_state_dict(pk["pol"]); pol.eval() + return pol + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--cache", required=True); ap.add_argument("--critic", required=True) + ap.add_argument("--hop-policy", default=""); ap.add_argument("--pol1", required=True) + ap.add_argument("--pol2", required=True); ap.add_argument("--out", required=True) + ap.add_argument("--n", type=int, default=8); ap.add_argument("--frames", type=int, default=512) + ap.add_argument("--beta", type=float, default=0.95); ap.add_argument("--gamma", type=float, default=0.98) + ap.add_argument("--depth", type=int, default=3); ap.add_argument("--particles", type=int, default=16) + ap.add_argument("--norm-pool", default="all"); ap.add_argument("--reward-mode", default="dense") + ap.add_argument("--seed", type=int, default=0) + args = ap.parse_args() + torch.manual_seed(args.seed) + dev = "cuda" + d = LiberoRSMData(args.cache, chunk=10, seed=0, in_ram=False, reward_mode=args.reward_mode, + norm_pool=args.norm_pool) + enc, rew, flow, rms, cfg = load_critic(args.critic, d.feat_dim, d.n_task, dev, data=d) + enc.eval() + class _P: pass + _p = _P(); _p.policy_features = "raw" + pfeat, d_pol = policy_features(_p, enc, d, cfg, dev) + hop = None + if args.hop_policy: + hop = load_pol(args.hop_policy, d, dev, cfg["d_z"]) + pol1 = load_pol(args.pol1, d, dev, d_pol); pol2 = load_pol(args.pol2, d, dev, d_pol) + rng = np.random.default_rng(args.seed) + val = d.val_eps + groups = {"demo": val[d.ep_demo[val]], + "roll_succ": val[d.ep_success[val] & ~d.ep_demo[val]], + "roll_fail": val[~d.ep_success[val] & ~d.ep_demo[val]]} + res = {} + for g, eps in groups.items(): + if len(eps) == 0: + continue + e = rng.choice(eps, size=args.frames, replace=True) + t = d.ep_from[e] + (rng.random(args.frames) * np.maximum(d.ep_to[e] - d.ep_from[e] - 10, 1)).astype(np.int64) + x = torch.from_numpy(d._feat(t)).to(dev); tk = torch.from_numpy(d.ep_task[e]).long().to(dev) + a_log = torch.from_numpy(d._chunk_at(t, e)).to(dev).view(args.frames, -1) + with torch.no_grad(): + zc = enc(x); zp = pfeat(x) + c1 = torch.stack([pol1.sample(zp, tk) for _ in range(args.n)]) + c2 = torch.stack([pol2.sample(zp, tk) for _ in range(args.n)]) + cand = torch.cat([c1, c2, a_log[None]], 0) # [2N+1, B, A] + qs = [] + for i in range(cand.shape[0]): + torch.manual_seed(args.seed * 7919 + 1) # CRN across candidates + q, _ = q_recursive(zc, cand[i], tk, rew=rew, flow=flow, rms=rms, pol=hop, + wend=None, beta=args.beta, gamma=args.gamma, depth=args.depth, + n_particles=args.particles, use_is=False, pessimism=0.0) + qs.append(q) + Q = torch.stack(qs).cpu().numpy() # [2N+1, B] + q1, q2, ql = Q[:args.n], Q[args.n:2 * args.n], Q[-1] + am = Q[:2 * args.n].argmax(0) + # action-style distance: how far each proposer's chunks sit from the logged one + d1 = (c1 - a_log[None]).pow(2).mean(-1).sqrt().mean().item() + d2 = (c2 - a_log[None]).pow(2).mean(-1).sqrt().mean().item() + r = {"frames": int(args.frames), "mean_q_demoBC": float(q1.mean()), "mean_q_succBC": float(q2.mean()), + "mean_q_logged": float(ql.mean()), "argmax_is_succBC": float((am >= args.n).mean()), + "frac_frames_succ_mean_higher": float((q2.mean(0) > q1.mean(0)).mean()), + "within_demoBC_std": float(q1.std(0).mean()), "within_succBC_std": float(q2.std(0).mean()), + "rms_dist_to_logged_demoBC": d1, "rms_dist_to_logged_succBC": d2, + "mean_r_at_frame": float(d.r[t].mean())} + res[g] = r + print(f"[bias] {g:10s} " + " ".join(f"{k}={v:.3f}" for k, v in r.items() if isinstance(v, float)), flush=True) + json.dump({"args": vars(args), "res": res}, open(args.out, "w"), indent=1) + print("[bias] DONE", flush=True) + + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/q_vs_return_diag.py b/rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/q_vs_return_diag.py new file mode 100644 index 0000000000000000000000000000000000000000..0c6ade5b3d36fb8c578d79b66bd86c85367d5a33 --- /dev/null +++ b/rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/q_vs_return_diag.py @@ -0,0 +1,85 @@ +"""Policy-evaluation quality of the critics on HELD-OUT logged (state, action) pairs: +Spearman / Pearson between each estimated Q(s,a) and the logged discounted return G_t. + G_sub = (1-g) * sum_k g^k r_{t+k} r = per-frame BDDL subgoal fraction (dense) + G_succ = g^(steps to success) if the episode succeeds else 0 (sparse, terminal) +Arms: RSM restart-Q at depth 1 and 3 (16 particles, shared noise), RSM depth 1 with 256 +particles, the IQL Q trained on the same latent, the reward head alone r_hat(z_t) (no +future), and the per-task constant (the null every pooled correlation has to beat). +Pooled AND within-task (mean of per-task Spearman) are reported: pooled rank correlation +is dominated by task identity (tasks differ in mean subgoal fraction). +usage: q_vs_return_diag.py --cache C --critic ckpt --subgoal-dir D --mask M [--iql iql_q.pt] [--hop hop.pt]""" +import argparse, os, sys, numpy as np, torch +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from data import LiberoRSMData +from is_ope import load_critic, q_recursive, make_policy +from scipy.stats import spearmanr, pearsonr + +ap = argparse.ArgumentParser() +ap.add_argument("--cache", required=True); ap.add_argument("--critic", required=True) +ap.add_argument("--subgoal-dir", default=""); ap.add_argument("--mask", default="") +ap.add_argument("--iql", default=""); ap.add_argument("--hop", default="") +ap.add_argument("--n", type=int, default=6000); ap.add_argument("--gamma", type=float, default=0.99) +ap.add_argument("--beta", type=float, default=0.98) +a = ap.parse_args() +dev = "cuda" if torch.cuda.is_available() else "cpu" +d = LiberoRSMData(a.cache, chunk=10, seed=0, in_ram=False, reward_mode="subgoal", subgoal_dir=a.subgoal_dir, + success_mask=a.mask, norm_pool="demos") +enc, rew, flow, rms, cfg = load_critic(a.critic, d.feat_dim, d.n_task, dev, data=d) +hop = None +if a.hop: + hk = torch.load(a.hop, map_location=dev, weights_only=False) + class _A: pass + ha = _A(); [setattr(ha, k, v) for k, v in hk["config"].items()] + hop = make_policy(ha, d, dev, d_z=cfg["d_z"]); hop.load_state_dict(hk["pol"]); hop.eval() +qnet = None +if a.iql: + from iql import QNet + ck = torch.load(a.iql, map_location=dev, weights_only=False) + qnet = QNet(ck["d_z"], ck["d_act"], ck["n_task"]).to(dev); qnet.load_state_dict(ck["q"]); qnet.eval() +rng = np.random.default_rng(0) +g = a.gamma +# ---- sample held-out frames with their logged action chunk and compute logged returns +eps = d.val_eps; w = d.ep_len[eps].astype(np.float64); w /= w.sum() +e = rng.choice(eps, size=a.n, p=w) +t = d.ep_from[e] + (rng.random(a.n) * np.maximum(d.ep_to[e] - d.ep_from[e] - 10, 1)).astype(np.int64) +G_sub = np.zeros(a.n); G_succ = np.zeros(a.n); to_end = np.zeros(a.n) +for i in range(a.n): + lo, hi = int(t[i]), int(d.ep_to[e[i]]) + rr = np.asarray(d.r[lo:hi], np.float64); k = np.arange(len(rr)) + G_sub[i] = (1 - g) * float((g ** k * rr).sum()) + G_succ[i] = (g ** (hi - lo)) if bool(d.ep_success[e[i]]) else 0.0 + to_end[i] = hi - lo +x = torch.from_numpy(d._feat(t)).to(dev); tk = torch.from_numpy(d.ep_task[e]).long().to(dev) +act = torch.from_numpy(d._chunk_at(t, e)).to(dev).view(a.n, -1) +res = {} +with torch.no_grad(): + z = enc(x) + res["reward head r_hat(z_t) (no future)"] = torch.sigmoid(rew(z, tk)).cpu().numpy() + def rsm(depth, part, crn=True): + out = [] + for i in range(0, a.n, 256): + q, _ = q_recursive(z[i:i+256], act[i:i+256], tk[i:i+256], rew=rew, flow=flow, rms=rms, pol=hop, wend=None, + beta=a.beta, gamma=g, depth=depth, n_particles=part, use_is=False, crn=crn) + out.append(q.cpu()) + return torch.cat(out).numpy() + res["RSM depth 1, 16 particles"] = rsm(1, 16) + res["RSM depth 1, 256 particles"] = rsm(1, 256) + if hop is not None: + res["RSM depth 3, 16 particles"] = rsm(3, 16) + res["RSM depth 3, 256 particles"] = rsm(3, 256) + if qnet is not None: + res["IQL Q(z,a)"] = qnet(z, act, tk).squeeze(-1).cpu().numpy() +tk_np = tk.cpu().numpy() +res["per-task constant (null)"] = np.array([G_sub[tk_np == tt].mean() for tt in tk_np]) +def report(name, q): + rows = [] + for gname, G in (("G_sub", G_sub), ("G_succ", G_succ)): + sp = spearmanr(q, G).correlation; pe = pearsonr(q, G)[0] + wt = [spearmanr(q[tk_np == tt], G[tk_np == tt]).correlation for tt in range(d.n_task) if (tk_np == tt).sum() > 30] + wt = [v for v in wt if v == v] + rows.append(f"{gname}: spearman {sp:+.3f} pearson {pe:+.3f} within-task spearman {np.mean(wt):+.3f}") + print(f"{name:36} | " + " | ".join(rows), flush=True) +print(f"held-out frames n={a.n} from {len(eps)} val episodes; mean G_sub={G_sub.mean():.3f} mean G_succ={G_succ.mean():.3f}") +for k, v in res.items(): + report(k, np.asarray(v, np.float64)) +print("[diag] DONE") diff --git a/rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/recheck_encoding.py b/rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/recheck_encoding.py new file mode 100644 index 0000000000000000000000000000000000000000..80d1cb52af890616d1ea25d6a38b82afb8816021 --- /dev/null +++ b/rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/recheck_encoding.py @@ -0,0 +1,157 @@ +"""Was the ROLLOUT cache built with the same image preprocessing as the evaluator? + +Hypothesis 2 of williamd4112/gen_q#251. The demo cache and the rollout cache have +different producers, and demo frames sit 48.7-61.5 from the nearest rollout frame +against 7.5-9.2 within the rollout cloud. `to224`'s own docstring records that uint8 +quantisation alone moves the latent 3 sigma on the dimensions that matter and cost a +working policy 0.46 -> 0/50, with cosine similarity 0.999898 hiding it completely. + +So: take a rollout episode's OWN raw frames (the parquets carry `image` and +`wrist_image`), push them through the EVALUATOR's exact path, and compare against that +frame's cached latent. Agreement means the rollout cache matches the evaluator and the +support gap is real scene difference. Disagreement means every rollout latent is in a +space the evaluator never produces, and no policy or critic trained on them can be read +online. + +Reports L2 in z-scored feature units, so the numbers are directly comparable to the +48.7-61.5 / 7.5-9.2 gap measured in #251 -- cosine similarity is deliberately NOT the +headline for the reason above. +""" +from __future__ import annotations +import argparse, importlib.util, io, os, re, sys +from pathlib import Path +import numpy as np +import torch + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE)) +from eval_closed_loop import to224, BUILDER + +_spec = importlib.util.spec_from_file_location("ogpo_rc", BUILDER) +ogpo = importlib.util.module_from_spec(_spec) +sys.modules["ogpo_rc"] = ogpo +_spec.loader.exec_module(ogpo) + +PAT = re.compile(r"ep_t(\d+)_b(\d+)_i(\d+)_(\d+)\.npz$") +PQ_ROOT = "/data/pulkitag/users/rli14/pi05_lib10_sde_v1" + + +def decode(cell): + """Parquet image cell -> HxWx3 uint8. LeRobot stores either raw bytes (PNG/JPEG) + or a nested list; handle both rather than guessing.""" + v = cell.as_py() if hasattr(cell, "as_py") else cell + if isinstance(v, dict) and "bytes" in v: + v = v["bytes"] + if isinstance(v, (bytes, bytearray)): + from PIL import Image + return np.asarray(Image.open(io.BytesIO(v)).convert("RGB"), np.uint8) + a = np.asarray(v) + if a.dtype != np.uint8: + a = (a * 255).round().clip(0, 255).astype(np.uint8) if a.max() <= 1.001 else a.astype(np.uint8) + if a.ndim == 1: + n = int(round((a.size / 3) ** 0.5)); a = a.reshape(n, n, 3) + if a.ndim == 3 and a.shape[0] == 3: + a = a.transpose(1, 2, 0) + return a + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--cache", required=True) + ap.add_argument("--n-ep", type=int, default=6) + ap.add_argument("--frames", type=int, default=4, help="frames checked per episode") + ap.add_argument("--pool", default="rollsucc", choices=["rollsucc", "demos"], + help="demos re-encodes from the LIBERO hdf5 (agentview_rgb / " + "eye_in_hand_rgb); the demo cache's npz holds no images") + ap.add_argument("--src-res", type=int, default=0, + help="resize the source image to this square resolution BEFORE " + "to224, emulating a camera that renders at that size. The " + "rollout parquets are 256x256; the evaluator renders at 128.") + ap.add_argument("--flips", default="both,none,ud,lr", + help="flip conventions to try; the evaluator uses img[::-1,::-1] = both") + args = ap.parse_args() + + import pyarrow.parquet as pq + dev = "cuda" if torch.cuda.is_available() else "cpu" + print(f"[rc] device {dev}", flush=True) + tower = ogpo.build_paligemma(dev) + from libero.libero import benchmark + bench = benchmark.get_benchmark_dict()["libero_10"]() + + C = Path(args.cache) + m = np.load(C / "meta.npz", allow_pickle=True) + fr, to = m["ep_from"].astype(int), m["ep_to"].astype(int) + dem = m["ep_demo"].astype(bool); suc = m["ep_success"].astype(bool) + tk = m["ep_task"]; dim = int(m["dim"]) + Z = np.load(C / "z.f16.npy", mmap_mode="r").reshape(-1, dim) + st = np.load(C / "feat_stats_demos.npz") + sd_vis = st["sd"][:dim] # visual block only + + flips = {"both": (slice(None, None, -1), slice(None, None, -1)), + "none": (slice(None), slice(None)), + "ud": (slice(None, None, -1), slice(None)), + "lr": (slice(None), slice(None, None, -1))} + want = [f for f in args.flips.split(",") if f in flips] + + def frames_of(e): + """(n_frames, getter(r) -> (agentview, wrist)) for episode e, from the raw + image source that produced its cached latents.""" + if args.pool == "rollsucc": + g = PAT.search(str(m["ep_src"][e])) + t, b, i, idx = g.groups() + p = (f"{PQ_ROOT}/task{int(t)}_block{int(b)}/rank_0/id_{int(i)}" + f"/data/chunk-000/episode_{int(idx):06d}.parquet") + if not os.path.exists(p): + return 0, None + tb = pq.read_table(p, columns=["image", "wrist_image"]) + return tb.num_rows, (lambda r: (decode(tb["image"][int(r)]), + decode(tb["wrist_image"][int(r)]))) + import h5py + sp = str(m["ep_src"][e]) # .../_demo/demo_7.npz + tdir = Path(sp).parent.name # _demo + k = Path(sp).stem # demo_7 + H = h5py.File(f"/data/pulkitag/users/rli14/libero_datasets/libero_10/{tdir}.hdf5", "r") + ob = H["data"][k]["obs"] + return ob["agentview_rgb"].shape[0], (lambda r: (np.asarray(ob["agentview_rgb"][int(r)]), + np.asarray(ob["eye_in_hand_rgb"][int(r)]))) + + eps = np.where((suc & ~dem) if args.pool == "rollsucc" else dem)[0][:args.n_ep] + print(f"[rc] pool={args.pool}: {len(eps)} episodes, {args.frames} frames each\n", flush=True) + agg = {f: [] for f in want} + for e in eps: + t = int(tk[e]) + n_src, get = frames_of(e) + if get is None: + print(f" ep {e}: source missing"); continue + ids = ogpo.tokenize_prompt(bench.get_task(t).language) + n = min(n_src, int(to[e] - fr[e])) + rows = np.linspace(0, n - 1, args.frames).astype(int) + for r in rows: + im0, im1 = get(r) + if args.src_res and im0.shape[0] != args.src_res: + from PIL import Image + _rs = lambda a: np.asarray(Image.fromarray(a).resize( + (args.src_res, args.src_res), Image.BILINEAR), np.uint8) + im0, im1 = _rs(im0), _rs(im1) + z_cache = np.asarray(Z[fr[e] + int(r)], np.float32) + for f in want: + a, bb = flips[f] + cams = [to224(im0[a, bb])[None], to224(im1[a, bb])[None]] + z = np.concatenate( + [ogpo.encode_frames(tower, c, ids, dev, 2) for c in cams], axis=1)[0] + # L2 in z-scored units: comparable to the #251 support-gap numbers + agg[f].append(float(np.linalg.norm((z - z_cache) / sd_vis))) + print(f" ep {e} t{t} done " + " ".join( + f"{f}={np.mean(agg[f][-args.frames:]):.2f}" for f in want), flush=True) + + print(f"\n=== pool={args.pool}: re-encode vs cached latent, L2 in z-scored units ===") + print("(reference from #251: rollout->nearest rollout 7.5-9.2, demo->nearest rollout 48.7-61.5)") + for f in want: + v = np.array(agg[f]) + print(f" flip={f:<5} n={len(v):<4} mean={v.mean():>8.2f} min={v.min():>8.2f} max={v.max():>8.2f}") + best = min(want, key=lambda f: np.mean(agg[f])) + print(f"\nbest convention: {best} (evaluator uses 'both')") + + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/reencode_rollouts.py b/rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/reencode_rollouts.py new file mode 100644 index 0000000000000000000000000000000000000000..32b31d495e4fb47d84528ba37d581a35876404d7 --- /dev/null +++ b/rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/reencode_rollouts.py @@ -0,0 +1,121 @@ +"""Re-encode the rollout corpus at the resolution the evaluator actually renders. + +Finding (williamd4112/gen_q#251): the rollout latents in `pi05_lib10_ogpo_fl15_v1` +were encoded from the collector's 256x256 renders. The closed-loop evaluator renders +at 128x128 (`camera_heights=128`), and so does the demo hdf5. Re-encoding a rollout +frame through the evaluator's own path puts it 74.97 z-scored units from its cached +latent (within-cloud scale 7.5-9.2; demo cache re-encoded the same way: 4.27). Every +rollout latent is therefore off the manifold the evaluator produces -- which is why +BC on rollout successes is 0/500 with held-out action MSE 0.0008, and why a critic +trained on a 90%-rollout corpus is read off-support online. + +This rebuilds the rollout npz tree with latents from: parquet image (256, stored +upright) -> 128 (PIL bilinear, emulating the 128 camera) -> 224 (PIL bilinear, the +builder's own step) -> the SAME encoder. No flip: the parquet images are already in +the serving orientation (verified visually and by L2: flip=none matches at 4.26). +proprio / actions / success / prompt / task_index are copied from the original npz, +which are bit-identical to the parquet fields. + +Output tree mirrors the input so pack.py runs unchanged with --src . +""" +from __future__ import annotations +import argparse, importlib.util, io, os, re, sys, time +from pathlib import Path +import numpy as np +import torch + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE)) +from eval_closed_loop import BUILDER +from recheck_encoding import decode, PAT, PQ_ROOT + +_spec = importlib.util.spec_from_file_location("ogpo_re", BUILDER) +ogpo = importlib.util.module_from_spec(_spec) +sys.modules["ogpo_re"] = ogpo +_spec.loader.exec_module(ogpo) + + +def prep(img, cam_res): + """uint8 HxWx3 (upright) -> uint8 224x224x3 via the camera resolution.""" + from PIL import Image + im = Image.fromarray(img) + if im.size != (cam_res, cam_res): + im = im.resize((cam_res, cam_res), Image.BILINEAR) + if im.size != (224, 224): + im = im.resize((224, 224), Image.BILINEAR) # builder's own step + return np.asarray(im, np.uint8) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--src", default="/data/pulkitag/users/rli14/pi05_lib10_ogpo_fl15_v1") + ap.add_argument("--out", required=True) + ap.add_argument("--cam-res", type=int, default=128) + ap.add_argument("--shard", type=int, default=0) + ap.add_argument("--num-shards", type=int, default=1) + ap.add_argument("--only-cache", default="", + help="meta.npz of a cache: re-encode only the episodes it uses " + "(the 4,500-rollout subset first, the full corpus after)") + ap.add_argument("--batch", type=int, default=128) + ap.add_argument("--limit", type=int, default=0, help="smoke: stop after N episodes") + args = ap.parse_args() + + import pyarrow.parquet as pq + dev = "cuda" if torch.cuda.is_available() else "cpu" + tower = ogpo.build_paligemma(dev) + + if args.only_cache: + m = np.load(args.only_cache, allow_pickle=True) + srcs = [str(s) for s, d in zip(m["ep_src"], m["ep_demo"]) if not d] + else: + srcs = sorted(str(p) for p in Path(args.src).glob("*/ep_*.npz")) + srcs = srcs[args.shard::args.num_shards] + if args.limit: + srcs = srcs[:args.limit] + print(f"[re] shard {args.shard}/{args.num_shards}: {len(srcs)} episodes -> {args.out} " + f"(cam_res={args.cam_res}, device={dev})", flush=True) + + t0 = time.time(); n_done = n_skip = 0 + for k, sp in enumerate(srcs): + rel = Path(sp).relative_to(args.src) + op = Path(args.out) / rel + if op.exists(): + n_skip += 1; continue + g = PAT.search(sp) + t, b, i, idx = g.groups() + pp = (f"{PQ_ROOT}/task{int(t)}_block{int(b)}/rank_0/id_{int(i)}" + f"/data/chunk-000/episode_{int(idx):06d}.parquet") + if not os.path.exists(pp): + print(f"[re] MISSING parquet for {rel}", flush=True); continue + z0 = np.load(sp, allow_pickle=True) + T = int(z0["z"].shape[0]) + tb = pq.read_table(pp, columns=["image", "wrist_image"]) + if tb.num_rows < T: + print(f"[re] {rel}: parquet has {tb.num_rows} rows < npz {T}; truncating", + flush=True); T = tb.num_rows + ids = ogpo.tokenize_prompt(str(z0["prompt"])) + zs = [] + for cam in ("image", "wrist_image"): + frames = np.stack([prep(decode(tb[cam][j]), args.cam_res) for j in range(T)]) + outs = [] + for s in range(0, T, args.batch): + outs.append(ogpo.encode_frames(tower, frames[s:s + args.batch], ids, dev, + args.batch)) + zs.append(np.concatenate(outs, 0)) + z = np.concatenate(zs, 1).astype(np.float16) # [T, 4096] base||wrist + assert z.shape == (T, z0["z"].shape[1]), (z.shape, z0["z"].shape) + op.parent.mkdir(parents=True, exist_ok=True) + tmp = str(op) + ".tmp.npz" + np.savez(tmp, z=z, proprio=z0["proprio"][:T], actions=z0["actions"][:T], + success=z0["success"], prompt=z0["prompt"], task_index=z0["task_index"]) + os.replace(tmp, op) + n_done += 1 + if n_done % 25 == 0: + el = time.time() - t0 + print(f"[re] {k+1}/{len(srcs)} done={n_done} skip={n_skip} " + f"{el/n_done:.1f}s/ep eta {(len(srcs)-k-1)*el/n_done/60:.0f} min", flush=True) + print(f"[re] DONE shard {args.shard}: {n_done} written, {n_skip} existed", flush=True) + + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/report.py b/rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/report.py new file mode 100644 index 0000000000000000000000000000000000000000..e3beba245705a8fdeaaa97408d4bdeb020329fd2 --- /dev/null +++ b/rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/report.py @@ -0,0 +1,96 @@ +"""Collect run artifacts into one honest table. + +Reports what was actually measured and labels what was NOT. In particular the +offline metrics here are NOT closed-loop LIBERO success, so they cannot by +themselves support a claim of beating behaviour cloning; that requires the lane's +per-task closed-loop eval. This script prints the distinction rather than hiding it. +""" +from __future__ import annotations +import argparse, json +from pathlib import Path + + +def row(k, v, w=34): + print(f" {k:<{w}} {v}") + + +def winrate_ci(win, n, z=1.96): + """Wilson interval for a win rate. The action gap is a heavy-tailed mean and + swings between evals (+0.045 / +0.063 / +0.018 on consecutive checkpoints); + the win rate over the same pairs is the stable statistic, so report it with + an interval rather than quoting a point estimate.""" + if not n: + return (float("nan"), float("nan")) + p = win + d = 1 + z * z / n + c = (p + z * z / (2 * n)) / d + h = z * ((p * (1 - p) / n + z * z / (4 * n * n)) ** 0.5) / d + return (c - h, c + h) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--critic", default="") + ap.add_argument("--ope-signal", default="") + ap.add_argument("--ope-null", default="") + ap.add_argument("--awr", default="") + a = ap.parse_args() + + if a.critic: + h = json.loads((Path(a.critic) / "history.json").read_text()) + last, best = h[-1], max(h, key=lambda r: r["q_action_gap"]) + print("\n== CRITIC (occupancy + reward latent) ==") + row("reward AUC (held-out)", f"{last['reward_auc']:.4f}") + row("occupancy CFM val loss", f"{last['cfm_val']:.4f}") + row("latent std min (collapse guard)", f"{last['latent_std_min']:.4f}") + lo, hi = winrate_ci(last["q_action_winrate"], 1024) + row("ACTION gap (headline)", f"{last['q_action_gap']:+.5f} " + f"(win {last['q_action_winrate']:.3f}, 95% CI [{lo:.3f},{hi:.3f}])") + bh = last.get("by_horizon", {}) + for k, v in bh.items(): + blo, bhi = winrate_ci(v["action_winrate"], v["n"]) + sig = "" if blo <= 0.5 <= bhi else " <-- excludes chance" + row(f" frames-to-end {k}", + f"gap {v['action_gap']:+.5f} win {v['action_winrate']:.3f} " + f"[{blo:.3f},{bhi:.3f}] n={v['n']}{sig}") + row(" best over training", f"{best['q_action_gap']:+.5f} @ step {best['step']}") + row("state success AUC", f"{last['q_success_auc']:.4f}") + print(" NOTE action gap is the metric that matters: COLLAPSE_ANALYSIS shows a") + print(" state-ranking value with a flat action gap dies in closed loop.") + + for tag, path in (("SIGNAL pi=BC(successes)", a.ope_signal), + ("NULL pi=BC(all)~mu", a.ope_null)): + if not path: + continue + r = json.loads((Path(path) / "report.json").read_text()) + c, v = r["calibration"], r["value"] + print(f"\n== OPE GATE :: {tag} ==") + row("E_mu[w] after calibration", f"{c['E_mu[w_endpoint]']:.4f} (target 1.000)") + row("calibration factor applied", f"{c['calib_scale']:.3f}") + row("E_mu[W] raw chunk product", f"{c['E_mu[W_chunk]']:.4f} (target 1.000)") + row("corr(endpoint w, chunk W)", f"{c['corr_w_vs_W']:.4f}") + row("weight ESS fraction", f"{c['ess_frac']:.3f}") + row("particle ESS fraction", f"{v['ess_particles']:.3f}") + row("success AUC with IS", f"{v['auc_success_IS']:.4f}") + row("success AUC without IS", f"{v['auc_success_noIS']:.4f}") + row("relative |dQ| from IS", f"{v['rel_shift_IS_vs_noIS']:.4f}") + row("expectation", v["gate_expectation"]) + + if a.awr: + L = json.loads((Path(a.awr) / "loop.json").read_text()) + print("\n== AWR LOOP ==") + row("pi_0 offline score", json.dumps(L["pi_0"])) + for r in L["rounds"]: + adv = r["awr"][-1] if r["awr"] else {} + row(f"round {r['round']} mean|adv|", + f"{adv.get('mean_abs_adv', float('nan')):.4f} " + f"(smolvla null result was 0.0190)") + row(f"round {r['round']} score", json.dumps(r["score"])) + + print("\nNOT MEASURED HERE: closed-loop LIBERO success. Every number above is") + print("offline. Beating BC on demos (0.584 +- 0.025 step-matched in this lane)") + print("requires the per-task closed-loop harness and is not claimed by this table.") + + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/report_arms.py b/rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/report_arms.py new file mode 100644 index 0000000000000000000000000000000000000000..5dcd3bdd892113d594ffe67080fcee9a606002f8 --- /dev/null +++ b/rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/report_arms.py @@ -0,0 +1,95 @@ +"""The headline table: closed-loop LIBERO-10 success and throughput, four arms. + +Throughput = pooled_SR * max_steps / mean_steps, reported two ways because they +answer different questions: + succ : mean steps over SUCCESSFUL episodes -- how fast it is when it works + all : mean steps over ALL episodes -- a failure burns the full horizon, so + this penalises failing twice (once in SR, once in wasted time) + +Success rates are pooled over all task-episodes and carry a Wilson interval. +Arms are compared against A_bc_demos, the BC-on-demonstrations bar an RSM recipe +has to clear; a difference is only called a win when the intervals separate. +""" +from __future__ import annotations +import argparse, json +from pathlib import Path + +ARMS = [("LANE_CONTROL", "lane bcdemos (reference bar)"), + ("A_bc_demos", "BC on demos, our pipeline"), + ("B_bc_succ", "behaviour-policy extraction"), + ("C_iql", "IQL critic + AWR"), + ("D_rsm", "RSM critic + AWR (ours)")] + + +def wilson(k, n, z=1.96): + if not n: + return float("nan"), float("nan") + p = k / n + d = 1 + z * z / n + c = (p + z * z / (2 * n)) / d + h = z * ((p * (1 - p) / n + z * z / (4 * n * n)) ** 0.5) / d + return c - h, c + h + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--eval-dir", default="/data/pulkitag/users/rli14/rsm_libero_runs/eval") + a = ap.parse_args() + d = Path(a.eval_dir) + + got = {} + for tag, _ in ARMS: + f = d / f"{tag}.json" + if f.exists(): + got[tag] = json.loads(f.read_text()) + + print("\n== CLOSED-LOOP LIBERO-10 (10 tasks x 10 inits, max 520 steps) ==") + print(f" {'arm':<12} {'what it is':<30} {'succ/n':>9} {'pooled SR':>10} " + f"{'95% CI':>16} {'thr_succ':>9} {'thr_all':>8}") + for tag, what in ARMS: + r = got.get(tag) + if r is None: + print(f" {tag:<12} {what:<30} {'--':>9} {'not yet run':>10}") + continue + k, n = r["successes"], r["episodes"] + lo, hi = wilson(k, n) + print(f" {tag:<12} {what:<30} {f'{k}/{n}':>9} {r['pooled_SR']:>10.3f} " + f"{f'[{lo:.3f},{hi:.3f}]':>16} {r['throughput_succ']:>9.3f} " + f"{r['throughput_all']:>8.3f}") + + # The bar is the REFERENCE policy when we have it: comparing our arms + # against our own broken BC would let a 0.02 arm look like a "win". + base = got.get("LANE_CONTROL") or got.get("A_bc_demos") + if base: + blo, bhi = wilson(base["successes"], base["episodes"]) + print(f"\n== vs the BC-on-demos bar ({base['pooled_SR']:.3f}) ==") + for tag, what in ARMS: + if got.get(tag) is base: + continue + r = got.get(tag) + if r is None: + continue + lo, hi = wilson(r["successes"], r["episodes"]) + if lo > bhi: + v = "WIN (intervals separate)" + elif hi < blo: + v = "LOSS (intervals separate)" + else: + v = "no separation at 95%" + print(f" {tag:<12} {r['pooled_SR'] - base['pooled_SR']:+.3f} {v}") + + if got: + print("\n== per-task pooled SR ==") + tasks = sorted({t for r in got.values() for t in r["per_task"]}) + print(f" {'task':<52}" + "".join(f"{t:>12}" for t, _ in ARMS if t in got)) + for tk in tasks: + print(f" {tk[:50]:<52}" + + "".join(f"{got[t]['per_task'].get(tk, float('nan')):>12.2f}" + for t, _ in ARMS if t in got)) + missing = [t for t, _ in ARMS if t not in got] + if missing: + print(f"\n NOT YET MEASURED: {', '.join(missing)} -- the table above is incomplete.") + + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/rerender_rollouts.py b/rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/rerender_rollouts.py new file mode 100644 index 0000000000000000000000000000000000000000..0b752e30d6a1025e0356829db4739fb70798fbae --- /dev/null +++ b/rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/rerender_rollouts.py @@ -0,0 +1,318 @@ +"""Re-render every rollout frame INSIDE the evaluator's environment, then encode. + +Why not resize the collector's 256x256 pixels (reencode_rollouts.py)? Measured: a +256->128 bilinear downsample lands in a THIRD region -- 63.7 from the live evaluator +feature, 71.5 from the demo cloud, 81.5 from the old rollout cloud -- no closer to the +evaluator than the cache it was meant to fix. SigLIP features do not survive an +approximate raster (to224's docstring: uint8 rounding alone is 3 sigma). + +So do the only thing that is evaluator-consistent BY CONSTRUCTION: the parquets log +`sim_state` for every frame; set it in the evaluator's own OffScreenRenderEnv +(camera_heights=128, EGL), read both cameras exactly as eval_closed_loop does +([::-1, ::-1], to224), encode with the evaluator's encoder. This is the admissibility +rule applied to features: a latent is admissible only if the eval environment can +produce it. + +Built-in validation (--validate-demos N): the demo hdf5 stores `states`; re-rendering +those through this path must land ~4 z-scored units from the demo cache (which was +built from the hdf5's own recorded images). If it does not, the path is wrong and no +rollout output should be trusted. + +Output mirrors the input npz tree so pack.py runs unchanged. Idempotent (skips +existing), atomic writes, requeue-safe. +""" +from __future__ import annotations +import argparse, importlib.util, os, re, sys, time +from pathlib import Path +import numpy as np +import torch + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE)) +from eval_closed_loop import BUILDER, to224, _eef_ori +from recheck_encoding import PAT, PQ_ROOT + +_spec = importlib.util.spec_from_file_location("ogpo_rr", BUILDER) +ogpo = importlib.util.module_from_spec(_spec) +sys.modules["ogpo_rr"] = ogpo +_spec.loader.exec_module(ogpo) + +DEMO_H5 = os.environ.get("RSM_DEMO_H5", "/data/pulkitag/users/rli14/libero_datasets/libero_10") + + +class Renderer: + """One evaluator env per task, reused across episodes.""" + def __init__(self, cam_res=128): + self.cam_res = cam_res + from libero.libero import benchmark, get_libero_path + from libero.libero.envs import OffScreenRenderEnv + self.bench = benchmark.get_benchmark_dict()["libero_10"]() + self.get_libero_path = get_libero_path; self.Env = OffScreenRenderEnv + self.envs, self.ids = {}, {} + + def env(self, tid): + # ONE live env at a time. robosuite's offscreen EGL context is shared across + # OffScreenRenderEnv instances in a process: with several alive, a render can + # come from whichever model last touched the context (measured: a task-0 state + # rendered as task-4's mugs and plates; one frame came back black). The + # evaluator builds one env per task and closes it; do the same. + if tid not in self.envs: + for _k in list(self.envs): + try: + self.envs[_k].close() + except Exception: + pass + self.envs.pop(_k, None) + t = self.bench.get_task(tid) + e = self.Env(bddl_file_name=str(Path(self.get_libero_path("bddl_files")) + / t.problem_folder / t.bddl_file), + camera_heights=self.cam_res, camera_widths=self.cam_res) + e.reset(); e.step(np.zeros(7)) + self.envs[tid] = e; self.ids[tid] = ogpo.tokenize_prompt(t.language) + return self.envs[tid], self.ids[tid] + + def frames(self, tid, states): + """states [T, nq+nv] -> (agent [T,224,224,3], wrist [T,224,224,3], proprio [T,8])""" + env, _ = self.env(tid) + sim = env.env.sim + A, W, P = [], [], [] + for st in states: + sim.set_state_from_flattened(np.asarray(st, np.float64)); sim.forward() + # Python-side visuals are NOT in the MuJoCo state: the stove burner is a + # site_rgba alpha in sim.model toggled by set_visualization() from + # turn_on(qpos), which the env runs inside step() via _check_success -> + # _post_process. Replay that update or a mid-episode kitchen frame renders + # with the burner off while the logged image has it on (measured: kitchen + # tasks drift 10-37, living-room tasks 3-4). + try: + env.env._check_success() + except Exception: + pass + if hasattr(env.env, "set_visualization"): + env.env.set_visualization() + sim.forward() + obs = env.env._get_observations(force_update=True) + A.append(to224(obs["agentview_image"][::-1, ::-1])) + W.append(to224(obs["robot0_eye_in_hand_image"][::-1, ::-1])) + P.append(np.concatenate([obs["robot0_eef_pos"], _eef_ori(obs), + obs["robot0_gripper_qpos"]]).astype(np.float32)) + return np.stack(A), np.stack(W), np.stack(P) + + +def encode(tower, ids, A, W, dev, bs): + za = ogpo.encode_frames(tower, A, ids, dev, bs) + zw = ogpo.encode_frames(tower, W, ids, dev, bs) + return np.concatenate([za, zw], 1).astype(np.float16) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--src", default="/data/pulkitag/users/rli14/pi05_lib10_ogpo_fl15_v1") + ap.add_argument("--out", required=True) + ap.add_argument("--shard", type=int, default=0) + ap.add_argument("--num-shards", type=int, default=1) + ap.add_argument("--only-cache", default="") + ap.add_argument("--limit", type=int, default=0) + ap.add_argument("--batch", type=int, default=128) + ap.add_argument("--cam-res", type=int, default=256, + help="256 = RLinf libero_10 env (lane evaluator + collector); 128 = demo hdf5") + ap.add_argument("--pool", default="rollouts", choices=["rollouts", "demos", "demos_replay"], + help="demos: re-render the 500 demo episodes from hdf5 `states` into a " + "new demo cache tree (/_demo/demo_k.npz)") + ap.add_argument("--validate-rollouts", type=int, default=0, + help="re-render N rollout episodes (4 frames each) and report L2 to the " + "CACHED rollout latent. ~4 at --cam-res 256 means our evaluator at 256 " + "reproduces the collector, and the 43k latents are on-manifold as-is.") + ap.add_argument("--validate-demos", type=int, default=0, + help="re-render N demo episodes' hdf5 states and report L2 to the " + "demo cache (z-scored, demo stats). Run BEFORE trusting output.") + ap.add_argument("--demo-cache", default="/data/pulkitag/users/rli14/libero10_demo_ogpo_cache_cam128") + ap.add_argument("--stats", default="/data/pulkitag/users/rli14/rsm_libero_cache/full_demo_cam256/feat_stats_demos.npz") + args = ap.parse_args() + + dev = "cuda" if torch.cuda.is_available() else "cpu" + tower = ogpo.build_paligemma(dev) + R = Renderer(args.cam_res) + print(f"[rr] cam_res={args.cam_res} pool={args.pool}", flush=True) + + if args.validate_demos: + import h5py, glob + st = np.load(args.stats); mu, sd = st["mu"][:4096], st["sd"][:4096] + dists = [] + h5s = sorted(glob.glob(f"{DEMO_H5}/*.hdf5")) + for tid, h5 in enumerate(h5s[:args.validate_demos]): + tname = Path(h5).stem[:-5] # strip _demo + tids = [i for i in range(10) if R.bench.get_task(i).name == tname] + if not tids: print(f"[rr] validate: no task for {tname}"); continue + tid = tids[0] + with h5py.File(h5, "r") as H: + states = np.asarray(H["data"]["demo_0"]["states"][:]) + rows = np.linspace(0, len(states) - 1, 4).astype(int) + A, W, _ = R.frames(tid, states[rows]) + _, ids = R.env(tid) + z = encode(tower, ids, A, W, dev, args.batch).astype(np.float32) + zc = np.load(f"{args.demo_cache}/{tname}_demo/demo_0.npz")["z"][rows].astype(np.float32) + print(f"[rr] validate demo task {tid}: comparing against {args.demo_cache}", flush=True) + dd = np.linalg.norm((z - zc) / sd, axis=1) + dists += dd.tolist() + print(f"[rr] validate demo task {tid} ({tname[:30]}): L2 to demo cache " + f"{np.round(dd, 2).tolist()}", flush=True) + print(f"[rr] VALIDATE demos: mean {np.mean(dists):.2f} max {np.max(dists):.2f} " + f"(demo cache re-encoded from its own hdf5 images: 3.7-4.3; " + f"anything >10 means this path is NOT the evaluator's)", flush=True) + + import pyarrow.parquet as pq + if args.validate_rollouts: + st = np.load(args.stats); sd = st["sd"][:4096] + m = np.load(args.only_cache, allow_pickle=True) if args.only_cache else None + cand = [str(s) for s, d in zip(m["ep_src"], m["ep_demo"]) if not d] if m is not None \ + else sorted(str(p) for p in Path(args.src).glob("*/ep_*.npz")) + dists = [] + for sp in cand[:args.validate_rollouts]: + g = PAT.search(sp); t, b, i, idx = g.groups() + pp = (f"{PQ_ROOT}/task{int(t)}_block{int(b)}/rank_0/id_{int(i)}" + f"/data/chunk-000/episode_{int(idx):06d}.parquet") + z0 = np.load(sp, allow_pickle=True); T = int(z0["z"].shape[0]) + tb = pq.read_table(pp, columns=["sim_state"]) + rows = np.linspace(0, min(T, tb.num_rows) - 1, 4).astype(int) + states = np.stack([np.asarray(tb["sim_state"][int(r)].as_py(), np.float64) for r in rows]) + tid = int(t) # from the FILENAME: the npz task_index field is wrong in the raw corpus (#234) + A, W, P = R.frames(tid, states); _, ids = R.env(tid) + z = encode(tower, ids, A, W, dev, args.batch).astype(np.float32) + dd = np.linalg.norm((z - z0["z"][rows].astype(np.float32)) / sd, axis=1) + dists += dd.tolist() + # Is the LOGGED image the same scene as the LOGGED sim_state? Compare the + # re-rendered proprio to the logged proprio (consistency of sim_state with + # state/actions), and save frame-0 side by side for the eye. + dp = float(np.abs(P - z0["proprio"][rows]).mean()) + print(f"[rr] validate rollout t{t} {Path(sp).name}: L2 to cached " + f"{np.round(dd, 2).tolist()} |rerendered proprio - logged| = {dp:.4f}", flush=True) + try: + from PIL import Image + from recheck_encoding import decode + tbi = pq.read_table(pp, columns=["image"]) + logged = Image.fromarray(decode(tbi["image"][int(rows[0])])).resize((224, 224)) + pair = Image.new("RGB", (448, 224)); pair.paste(logged, (0, 0)); pair.paste(Image.fromarray(A[0]), (224, 0)) + od = Path(args.out) / "validate_pairs"; od.mkdir(parents=True, exist_ok=True) + pair.save(od / f"{Path(sp).stem}_L2_{dd[0]:.0f}.png") + except Exception as e: + print(f"[rr] (pair save failed: {e})", flush=True) + print(f"[rr] VALIDATE rollouts @{args.cam_res}: mean {np.mean(dists):.2f} " + f"max {np.max(dists):.2f} (cache re-encoded from its own 256 pixels: 4.0-4.3)", + flush=True) + + if args.pool == "demos_replay": + # REPLAY the demonstration's logged actions live in the evaluator env from its + # logged initial state, recording what the env actually renders. Re-rendering + # from per-frame sim_state cannot reproduce a live render on the kitchen/study + # scenes (two fresh renders of the same state differ by 10-37 z-scored units; + # living rooms 3-4), so the only demo frames that are guaranteed to be in the + # evaluator's space are ones the evaluator itself produced along a trajectory. + # A demo whose replay does not end in success is inadmissible (same rule as + # rollouts) and is written with success=False so pack/BC can drop it. + import h5py, glob + n_done = n_ok = 0 + for h5 in sorted(glob.glob(f"{DEMO_H5}/*.hdf5")): + tname = Path(h5).stem[:-5] + tids = [i for i in range(10) if R.bench.get_task(i).name == tname] + if not tids: print(f"[rr] no task for {tname}"); continue + tid = tids[0]; env, ids = R.env(tid) + src_npz = sorted(glob.glob(f"{args.demo_cache}/{tname}_demo/demo_*.npz")) + with h5py.File(h5, "r") as H: + for sp in src_npz: + k = Path(sp).stem; op = Path(args.out) / f"{tname}_demo" / f"{k}.npz" + if op.exists(): continue + z0 = np.load(sp, allow_pickle=True) + acts = np.asarray(H["data"][k]["actions"][:], np.float32) + st0 = np.asarray(H["data"][k]["states"][0], np.float64) + env.reset(); env.env.sim.set_state_from_flattened(st0); env.env.sim.forward() + obs, _, _, _ = env.step(np.zeros(7)) + A, W, P = [], [], []; done = False + for a in acts: + A.append(to224(obs["agentview_image"][::-1, ::-1])) + W.append(to224(obs["robot0_eye_in_hand_image"][::-1, ::-1])) + P.append(np.concatenate([obs["robot0_eef_pos"], _eef_ori(obs), + obs["robot0_gripper_qpos"]]).astype(np.float32)) + obs, _, done, _ = env.step(a) + if done: break + T = len(A) + z = encode(tower, ids, np.stack(A), np.stack(W), dev, args.batch) + op.parent.mkdir(parents=True, exist_ok=True) + tmp = str(op) + ".tmp.npz" + np.savez(tmp, z=z, proprio=np.stack(P), actions=acts[:T], prompt=z0["prompt"], + success=bool(done), replayed=True) + os.replace(tmp, op); n_done += 1; n_ok += int(bool(done)) + print(f"[rr] demos_replay task {tid}: {len(src_npz)} episodes, replay success so far " + f"{n_ok}/{n_done}", flush=True) + print(f"[rr] DONE demos_replay: {n_done} episodes, {n_ok} reproduce success " + f"({n_ok / max(n_done, 1):.3f}) at cam_res={args.cam_res}", flush=True) + return + + if args.pool == "demos": + import h5py, glob + n_done = 0 + for h5 in sorted(glob.glob(f"{DEMO_H5}/*.hdf5")): + tname = Path(h5).stem[:-5] + tids = [i for i in range(10) if R.bench.get_task(i).name == tname] + if not tids: print(f"[rr] no task for {tname}"); continue + tid = tids[0]; _, ids = R.env(tid) + src_npz = sorted(glob.glob(f"{args.demo_cache}/{tname}_demo/demo_*.npz")) + with h5py.File(h5, "r") as H: + for sp in src_npz: + k = Path(sp).stem; op = Path(args.out) / f"{tname}_demo" / f"{k}.npz" + if op.exists(): continue + z0 = np.load(sp, allow_pickle=True) + states = np.asarray(H["data"][k]["states"][:]) + T = min(len(states), int(z0["z"].shape[0])) + A, W, P = R.frames(tid, states[:T]) + z = encode(tower, ids, A, W, dev, args.batch) + op.parent.mkdir(parents=True, exist_ok=True) + tmp = str(op) + ".tmp.npz" + np.savez(tmp, z=z, proprio=P, actions=z0["actions"][:T], prompt=z0["prompt"]) + os.replace(tmp, op); n_done += 1 + print(f"[rr] demos task {tid}: {len(src_npz)} episodes -> {args.out}/{tname}_demo " + f"(total written {n_done})", flush=True) + print(f"[rr] DONE demos: {n_done} episodes at cam_res={args.cam_res}", flush=True) + return + + if args.only_cache: + m = np.load(args.only_cache, allow_pickle=True) + srcs = [str(s) for s, d in zip(m["ep_src"], m["ep_demo"]) if not d] + else: + srcs = sorted(str(p) for p in Path(args.src).glob("*/ep_*.npz")) + srcs = srcs[args.shard::args.num_shards] + if args.limit: srcs = srcs[:args.limit] + print(f"[rr] shard {args.shard}/{args.num_shards}: {len(srcs)} episodes -> {args.out}", flush=True) + + t0 = time.time(); n_done = n_skip = 0 + for k, sp in enumerate(srcs): + rel = Path(sp).relative_to(args.src); op = Path(args.out) / rel + if op.exists(): n_skip += 1; continue + g = PAT.search(sp); t, b, i, idx = g.groups() + pp = (f"{PQ_ROOT}/task{int(t)}_block{int(b)}/rank_0/id_{int(i)}" + f"/data/chunk-000/episode_{int(idx):06d}.parquet") + if not os.path.exists(pp): print(f"[rr] MISSING parquet {rel}", flush=True); continue + z0 = np.load(sp, allow_pickle=True); T = int(z0["z"].shape[0]) + tb = pq.read_table(pp, columns=["sim_state"]) + T = min(T, tb.num_rows) + states = np.stack([np.asarray(tb["sim_state"][j].as_py(), np.float64) for j in range(T)]) + tid = int(t) # from the FILENAME: the npz task_index field is wrong in the raw corpus (#234) + A, W, P = R.frames(tid, states) + _, ids = R.env(tid) + z = encode(tower, ids, A, W, dev, args.batch) + # proprio: the re-rendered observation, which is what the evaluator would feed; + # agrees with the logged `state` to float precision (checked: mean |d| = 0.0) + op.parent.mkdir(parents=True, exist_ok=True) + tmp = str(op) + ".tmp.npz" + np.savez(tmp, z=z, proprio=P, actions=z0["actions"][:T], success=z0["success"], + prompt=z0["prompt"], task_index=z0["task_index"]) + os.replace(tmp, op); n_done += 1 + if n_done % 25 == 0: + el = time.time() - t0 + print(f"[rr] {k+1}/{len(srcs)} done={n_done} skip={n_skip} {el/n_done:.1f}s/ep " + f"eta {(len(srcs)-k-1)*el/n_done/60:.0f} min", flush=True) + print(f"[rr] DONE shard {args.shard}: {n_done} written, {n_skip} existed", flush=True) + + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/reward_diag.py b/rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/reward_diag.py new file mode 100644 index 0000000000000000000000000000000000000000..d6783a88e07eeb815acc9cb124bf3ffc4588d40f --- /dev/null +++ b/rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/reward_diag.py @@ -0,0 +1,56 @@ +"""How good is the RSM reward head, really? Held-out (val-split) frames, per task, plus the +two failure modes that matter for ranking: (a) goal-mismatch (right state, wrong task id), +(b) imagined endpoints (flow samples) vs. the true future subgoal fraction. +usage: reward_diag.py --cache C --critic ckpt [--subgoal-dir D] [--mask M]""" +import argparse, os, sys, numpy as np, torch +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from data import LiberoRSMData +from is_ope import load_critic +from train_rsm import sample_future, auc + +ap = argparse.ArgumentParser() +ap.add_argument("--cache", required=True); ap.add_argument("--critic", required=True) +ap.add_argument("--subgoal-dir", default=""); ap.add_argument("--mask", default="") +ap.add_argument("--n", type=int, default=20000); ap.add_argument("--beta", type=float, default=0.98) +a = ap.parse_args() +dev = "cuda" if torch.cuda.is_available() else "cpu" +d = LiberoRSMData(a.cache, chunk=10, seed=0, in_ram=False, reward_mode="subgoal", subgoal_dir=a.subgoal_dir, + success_mask=a.mask, norm_pool="demos") +enc, rew, flow, rms, cfg = load_critic(a.critic, d.feat_dim, d.n_task, dev, data=d) +lat = enc # load_critic already wraps the encoder with the proprio append (same as the evaluator) +rng = np.random.default_rng(0) +with torch.no_grad(): + fb = d.sample_frames(a.n, rng, "val", dev) + x, tk, r = fb["x"], fb["task"], fb["r"].float() + z = lat(x); rh = torch.sigmoid(rew(z, tk)) + e = (rh - r); print(f"VAL frames n={a.n}: MSE={float(e.pow(2).mean()):.4f} (const-null MSE={float((r-r.mean()).pow(2).mean()):.4f}) " + f"Pearson={float(np.corrcoef(rh.cpu(), r.cpu())[0,1]):.3f} mean r={float(r.mean()):.3f} mean r_hat={float(rh.mean()):.3f}") + print(f" AUC(all subgoals satisfied, r==1): {auc(rh.cpu().numpy(), (r.cpu().numpy()>=0.999).astype(float)):.3f} " + f"AUC(any progress, r>0): {auc(rh.cpu().numpy(), (r.cpu().numpy()>0.001).astype(float)):.3f}") + # calibration by true fraction + for lo, hi in ((0, 0.001), (0.001, 0.4), (0.4, 0.7), (0.7, 0.999), (0.999, 1.01)): + m = (r >= lo) & (r < hi) + if m.any(): print(f" true r in [{lo:.2f},{hi:.2f}): n={int(m.sum()):6d} mean r_hat={float(rh[m].mean()):.3f} std={float(rh[m].std()):.3f}") + # per task + for t in range(d.n_task): + m = tk == t + if m.sum() > 50: + print(f" task {t}: n={int(m.sum()):5d} Pearson={float(np.corrcoef(rh[m].cpu(), r[m].cpu())[0,1]):.3f} MSE={float(e[m].pow(2).mean()):.4f} mean r={float(r[m].mean()):.3f}") + # (a) goal mismatch: same latent, wrong task id + tk2 = (tk + torch.randint(1, d.n_task, tk.shape, device=dev)) % d.n_task + rh2 = torch.sigmoid(rew(z, tk2)) + print(f"GOAL-MISMATCH (wrong task id): mean r_hat={float(rh2.mean()):.3f} vs correct-task {float(rh.mean()):.3f}; " + f"fraction where wrong-task r_hat > correct-task r_hat: {float((rh2 > rh).float().mean()):.3f}") + # (b) imagined endpoints: flow sample at beta vs true future subgoal fraction + vb = d.sample(min(a.n, 8192), rng, a.beta, a.beta, "val", dev) + zc = lat(vb["x_now"]); zf_true = lat(vb["x_fut"]) + zf_imag = sample_future(flow, zc, vb["a_now"], vb["task"], vb["beta"], rms, 8, n=1) + r_true_fut = torch.sigmoid(rew(zf_true, vb["task"])) + r_imag = torch.sigmoid(rew(zf_imag, vb["task"])) + print(f"IMAGINED ENDPOINTS (beta={a.beta}): r_hat(true future latent) mean={float(r_true_fut.mean()):.3f}, r_hat(flow sample) mean={float(r_imag.mean()):.3f}, " + f"Pearson(imagined, true-future r_hat)={float(np.corrcoef(r_imag.cpu(), r_true_fut.cpu())[0,1]):.3f}, " + f"Pearson(imagined, TRUE future subgoal fraction)={float(np.corrcoef(r_imag.cpu(), vb['r_fut'].float().cpu())[0,1]) if 'r_fut' in vb else float('nan'):.3f}") + # (c) random latents: gaussian noise in latent space -> base-rate drift? + zr = torch.randn_like(z) * z.std(0, keepdim=True) + z.mean(0, keepdim=True) + print(f"RANDOM LATENTS (matched moments): mean r_hat={float(torch.sigmoid(rew(zr, tk)).mean()):.3f}") +print("[diag] DONE") diff --git a/rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/rsm_main.py b/rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/rsm_main.py new file mode 100644 index 0000000000000000000000000000000000000000..0e4a18bd041b51cf2b7467d577da05157cb535f4 --- /dev/null +++ b/rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/rsm_main.py @@ -0,0 +1,325 @@ +"""origin/main's MIMICGEN RSM port, applied to the LIBERO-10 latent corpus. + +SCOPE CORRECTION. This file ports mimicgen_rsm/rsm_mimicgen/rsm.py, which is +ONE variant on main and not the main RSM recipe. The headline recipe in +ogbench_unified_rsm IS action-conditioned: its flow trains on (s, a, g) -> +s_{t+K} pairs and hop 1 uses the queried action. Only the mimicgen port drops +that, stating "NOT goal-conditioned ... d_beta(s'|s), reward(s), qf(s,a)". +Both are worth running here; do not read this file as "what main does". + +Our own recipe differs from main's in four ways that matter, and this file adopts +all four. See notes/rsm_formula_comparison.pdf for the derivation side. + +1. REWARD IS AN ARRIVAL DETECTOR, NOT AN OUTCOME PREDICTOR. + main: a classifier with a CALIBRATED threshold, hard-thresholded to + r_hat(s) = 1[logit > thr] - 1 in {0, -1}; the threshold is fit on held-out + episodes because "the classifier's scores are well ordered but not centred on + 0". ours (until now): r = 1 on EVERY frame of a successful episode, i.e. + P(this episode succeeds | s). Measured consequence of ours: a directly + supervised Q(z,a) beats a state-only V(z) by AUC 0.9550 vs 0.9539, delta + +0.0012 -- the action adds nothing, because whether an episode succeeds is a + property of the state, not of the next 10 frames. + +2. THE OCCUPANCY IS STATE-ONLY in THIS port: d_beta(s'|s). The ogbench recipe + conditions on the action instead; that variant is the action-conditioned + critic this lane already has. + +3. THE ACTION ENTERS BY SUPERVISED REGRESSION, NOT BY CONDITIONING A GENERATIVE + MODEL ON A COUNTERFACTUAL. main distils a student + qf(s,a) <- r + gamma * (1-done) * V(s'), s' the REAL logged next state, + with V from the frozen occupancy and, in their words, "no TD bootstrap off + qf". Ours conditioned the flow on a candidate action, which is unsupervised in + the action direction; probe_crn measured the result to have the right + magnitude and an arbitrary sign. + +4. ARRIVAL ABSORBS AND STOPPING IS GEOMETRIC OVER MANY HOPS. + p_stop = beta(1-gamma)/(gamma(1-beta)); a rollout stops on the coin OR on + reaching the goal, over max_hops (expected ~11 at beta=0.9, gamma=0.99). Ours + read the reward once at a fixed depth of 2-3. The reduction is an optimistic + hop-weighted expectile, not a plain mean. +""" +from __future__ import annotations +import sys as _sys, os as _os +_sys.path.insert(0, _os.path.dirname(_os.path.abspath(__file__))) +import argparse, json +from pathlib import Path +import numpy as np +import torch +import torch.nn.functional as F + +from data import LiberoRSMData +from model import Encoder, RewardHead, OccFlow, mlp, ema_update +from train_rsm import auc + + +# --------------------------------------------------------------------------- # +def p_stop_of(beta: float, gamma: float) -> float: + """main's geometric stopping probability. beta <= gamma is required.""" + assert beta <= gamma, f"need beta <= gamma, got {beta} > {gamma}" + return beta * (1.0 - gamma) / (gamma * (1.0 - beta)) if beta < gamma else 1.0 + + +def hop_weighted_value(r, absorb_hop, tau, rho, gamma, gain=1.0): + """main's speed-weighted upper expectile over per-rollout returns in {0,-1}.""" + A = 1.0 / (2.0 * (1.0 - tau)) + is_goal = r == 0.0 + w = torch.where(is_goal, + 1.0 + (A - 1.0) * gain * rho ** (absorb_hop.clamp_min(1) - 1).float(), + torch.ones_like(r)) + return ((w * r).sum(1) / w.sum(1).clamp_min(1e-12)) / (1.0 - gamma) + + +def value_from_at_goal_prob(q, tau, gamma): + if tau == 0.5: + m = q - 1.0 + else: + num = (1.0 - tau) * (1.0 - q) + den = tau * q + (1.0 - tau) * (1.0 - q) + m = -num / den.clamp_min(1e-12) + return m / (1.0 - gamma) + + +class MainRSM(torch.nn.Module): + """State-only occupancy + thresholded arrival reward + geometric-stop value.""" + + def __init__(self, d_lat, n_task, width=1024, depth=4): + super().__init__() + # d_act=1 with a zero action: the occupancy is state-only by construction, + # while reusing the same FiLM/Fourier successor the rest of the lane uses. + self.flow = OccFlow(d_lat, 1, n_task, width=width, depth=depth) + self.rew = RewardHead(d_lat, n_task) + self.register_buffer("rms", torch.ones(d_lat)) + self.threshold = 0.0 + + def flow_v(self, z, task, beta, x_k, k): + a0 = torch.zeros(z.shape[0], 1, device=z.device) + return self.flow(z, a0, task, beta, x_k, k) + + @torch.no_grad() + def hop(self, z, task, beta, steps=8): + x = torch.randn_like(z) + for s in range(steps): + k = torch.full((z.shape[0],), 1.0 - s / steps, device=z.device) + x = x + self.flow_v(z, task, beta, x, k) / steps + return z + x * self.rms + + @torch.no_grad() + def r_hat(self, z, task): + """Hard arrival reward in {0, -1} at the CALIBRATED threshold.""" + return (self.rew(z, task) > self.threshold).float() - 1.0 + + @torch.no_grad() + def estimate_value(self, z, task, *, beta, gamma, n_samples=16, max_hops=20, + tau=0.5, rho=0.9, gain=1.0, mode="hop", flow_steps=8): + B = z.shape[0] + p_stop = p_stop_of(beta, gamma) + s = z.repeat_interleave(n_samples, 0) + tk = task.repeat_interleave(n_samples, 0) + bq = torch.full((s.shape[0],), beta, device=z.device) + M = s.shape[0] + active = torch.ones(M, dtype=torch.bool, device=z.device) + stopped = s.clone() + absorb = torch.zeros(M, dtype=torch.long, device=z.device) + for h in range(1, max_hops + 1): + s_next = self.hop(s, tk, bq, steps=flow_steps) + s = torch.where(active.unsqueeze(-1), s_next, s) + at_goal = self.r_hat(s, tk) == 0.0 + coin = torch.rand(M, device=z.device) < p_stop + just = active & (coin | at_goal) + absorb = torch.where(just & at_goal, torch.full_like(absorb, h), absorb) + stopped = torch.where(just.unsqueeze(-1), s, stopped) + active = active & ~just + if not active.any(): + break + stopped = torch.where(active.unsqueeze(-1), s, stopped) + r = self.r_hat(stopped, tk).reshape(B, n_samples) + ah = absorb.reshape(B, n_samples) + if mode == "hop": + return hop_weighted_value(r, ah, tau, rho, gamma, gain) + q = (r == 0.0).float().mean(1) + return value_from_at_goal_prob(q, tau, gamma) + + +class QStudent(torch.nn.Module): + def __init__(self, d_lat, d_act, n_task, d_task=64, width=1024, depth=3): + super().__init__() + self.task = torch.nn.Embedding(n_task, d_task) + self.net = mlp([d_lat + d_act + d_task] + [width] * depth + [1], norm=True) + + def forward(self, z, a, task): + return self.net(torch.cat([z, a, self.task(task)], -1)).squeeze(-1) + + +def calibrate_threshold(model, d, enc, dev, rng, n=8192): + """Fit the cutoff on HELD-OUT frames, as main does. + + Chosen to match the positive base rate rather than at logit 0: main's note is + that the scores are well ordered but not centred, and estimate_value + thresholds hard, so an uncentred cutoff silently changes the arrival rate. + """ + P, Y = [], [] + with torch.no_grad(): + for _ in range(max(1, n // 2048)): + b = d.sample_frames(2048, rng, "val", dev) + z = enc(b["x"]) + P.append(model.rew(z, b["task"]).cpu().numpy()) + Y.append(b["r"].cpu().numpy()) + P = np.concatenate(P); Y = np.concatenate(Y) + pos = float(Y.mean()) + thr = float(np.quantile(P, 1.0 - pos)) if 0 < pos < 1 else 0.0 + a = auc(P, Y) + at_rate = float((P > thr).mean()) + return thr, a, pos, at_rate + + +# --------------------------------------------------------------------------- # +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--cache", required=True) + ap.add_argument("--out", required=True) + ap.add_argument("--chunk", type=int, default=10) + ap.add_argument("--d-z", type=int, default=256) + ap.add_argument("--enc-width", type=int, default=1024) + ap.add_argument("--flow-width", type=int, default=1024) + ap.add_argument("--flow-depth", type=int, default=4) + ap.add_argument("--beta", type=float, default=0.90) + ap.add_argument("--gamma", type=float, default=0.99) + ap.add_argument("--k-success", type=int, default=10, + help="frames at the END of a successful episode counted as " + "AT GOAL. This is main's arrival convention; the dense " + "whole-episode label is an outcome predictor and was " + "measured to carry no action information.") + ap.add_argument("--n-value-samples", type=int, default=16) + ap.add_argument("--max-hops", type=int, default=20) + ap.add_argument("--value-expectile", type=float, default=0.7) + ap.add_argument("--expectile-mode", default="hop", choices=["hop", "reward"]) + ap.add_argument("--hop-rho", type=float, default=0.9) + ap.add_argument("--occ-steps", type=int, default=20000) + ap.add_argument("--qf-steps", type=int, default=40000) + ap.add_argument("--distill-states", type=int, default=153600, + help="transitions in the distillation buffer; V is " + "computed once per transition, not per batch") + ap.add_argument("--batch", type=int, default=512) + ap.add_argument("--qf-batch", type=int, default=256) + ap.add_argument("--lr", type=float, default=3e-4) + ap.add_argument("--ema", type=float, default=0.005) + ap.add_argument("--norm-pool", default="demos", choices=["all", "demos"]) + ap.add_argument("--in-ram", type=int, default=1) + ap.add_argument("--seed", type=int, default=0) + args = ap.parse_args() + + torch.manual_seed(args.seed) + dev = "cuda" if torch.cuda.is_available() else "cpu" + out = Path(args.out); out.mkdir(parents=True, exist_ok=True) + # ARRIVAL labels, not outcome labels + d = LiberoRSMData(args.cache, chunk=args.chunk, k_success=args.k_success, + seed=args.seed, in_ram=bool(args.in_ram), + reward_mode="terminal", norm_pool=args.norm_pool) + print(f"[main-rsm] {d.n_ep} eps, at-goal frames {float(d.r.mean()):.4f} " + f"(main's arrival convention), p_stop " + f"{p_stop_of(args.beta, args.gamma):.4f}, E[hops] " + f"{1.0 / max(p_stop_of(args.beta, args.gamma), 1e-9):.1f}", flush=True) + + enc = Encoder(d.feat_dim, args.d_z, args.enc_width).to(dev) + enc_t = Encoder(d.feat_dim, args.d_z, args.enc_width).to(dev) + enc_t.load_state_dict(enc.state_dict()) + for p in enc_t.parameters(): + p.requires_grad_(False) + m = MainRSM(args.d_z, d.n_task, args.flow_width, args.flow_depth).to(dev) + opt = torch.optim.AdamW(list(enc.parameters()) + list(m.flow.parameters()) + + list(m.rew.parameters()), lr=args.lr, weight_decay=0.01) + rng = np.random.default_rng(args.seed) + pos_w = torch.tensor(max((1 - d.r.mean()) / max(d.r.mean(), 1e-6), 1.0), device=dev) + + # ---- stage 1: state-only occupancy + arrival classifier ---- + for step in range(1, args.occ_steps + 1): + b = d.sample(args.batch, rng, args.beta, args.beta, "train", dev) + z = enc(b["x_now"]) + with torch.no_grad(): + z_fut = enc_t(b["x_fut"]) + l_rew = F.binary_cross_entropy_with_logits( + m.rew(z, b["task"]), b["r_now"], pos_weight=pos_w) + delta = z_fut - (z.detach() if step <= 2000 else z) + with torch.no_grad(): + m.rms.mul_(0.99).add_(delta.pow(2).mean(0).sqrt().clamp_min(1e-3), alpha=0.01) + y = delta / m.rms + k = torch.rand(args.batch, device=dev) + noise = torch.randn_like(y) + x_k = (1 - k)[:, None] * y + k[:, None] * noise + v = m.flow_v(z if step > 2000 else z.detach(), b["task"], b["beta"], x_k, k) + l_cfm = (v - (y - noise)).pow(2).mean() + std = z.std(0) + loss = l_rew + l_cfm + 10.0 * F.relu(0.1 - std).mean() + opt.zero_grad(); loss.backward() + torch.nn.utils.clip_grad_norm_( + list(enc.parameters()) + list(m.flow.parameters()) + + list(m.rew.parameters()), 1.0) + opt.step(); ema_update(enc_t, enc, args.ema) + if step % 2000 == 0: + print(f"[occ] {step} rew={float(l_rew):.4f} cfm={float(l_cfm):.4f}", + flush=True) + + enc.eval(); m.eval() + torch.save({"enc": enc.state_dict(), "flow": m.flow.state_dict(), + "rew": m.rew.state_dict(), "rms": m.rms.cpu(), + "config": vars(args)}, out / "stage1.pt") + thr, a_r, pos, at_rate = calibrate_threshold(m, d, enc, dev, + np.random.default_rng(args.seed + 5)) + m.threshold = thr + print(f"[main-rsm] arrival classifier AUC {a_r:.4f}; threshold {thr:+.3f} " + f"calibrated to base rate {pos:.4f} (at-goal rate {at_rate:.4f})", + flush=True) + + # ---- stage 2: distil qf(z,a) <- r + gamma (1-done) V(z'), REAL z' ---- + # Build the distillation BUFFER once. Recomputing V per batch means a fresh + # 16-rollout, 20-hop expansion every step (<1.7 steps/s measured); the target + # does not change during stage 2, so it is computed once and regressed on. + rq = np.random.default_rng(args.seed + 11) + Z, ZA, TK, TG = [], [], [], [] + got, bs = 0, 512 + while got < args.distill_states: + b = d.sample_frames(bs, rq, "train", dev) + t_next = np.minimum(b["t_idx"] + d.chunk, d.ep_to[b["ep"]] - 1) + done = torch.from_numpy( + (t_next >= d.ep_to[b["ep"]] - 1).astype(np.float32)).to(dev) + with torch.no_grad(): + z = enc(b["x"]) + zn = enc(torch.from_numpy(d._feat(t_next)).to(dev)) + r_now = m.r_hat(z, b["task"]) + v_next = m.estimate_value( + zn, b["task"], beta=args.beta, gamma=args.gamma, + n_samples=args.n_value_samples, max_hops=args.max_hops, + tau=args.value_expectile, rho=args.hop_rho, + mode=args.expectile_mode) + target = r_now + args.gamma * (1 - done) * v_next + Z.append(z.cpu()); ZA.append(b["a"].cpu()) + TK.append(b["task"].cpu()); TG.append(target.cpu()) + got += bs + if got % 25600 == 0: + print(f"[buf] {got}/{args.distill_states} " + f"target_mean={float(target.mean()):.3f}", flush=True) + Z = torch.cat(Z); ZA = torch.cat(ZA); TK = torch.cat(TK); TG = torch.cat(TG) + print(f"[buf] done {tuple(Z.shape)} target mean {float(TG.mean()):.3f} " + f"sd {float(TG.std()):.3f}", flush=True) + + qf = QStudent(args.d_z, d.chunk * d.adim, d.n_task).to(dev) + qopt = torch.optim.Adam(qf.parameters(), lr=args.lr) + for step in range(1, args.qf_steps + 1): + idx = torch.randint(0, len(Z), (args.qf_batch,)) + loss = F.mse_loss(qf(Z[idx].to(dev), ZA[idx].to(dev), TK[idx].to(dev)), + TG[idx].to(dev)) + qopt.zero_grad(); loss.backward() + torch.nn.utils.clip_grad_norm_(qf.parameters(), 1.0); qopt.step() + if step % 4000 == 0: + print(f"[qf] {step} loss={float(loss):.4f}", flush=True) + + torch.save({"enc": enc.state_dict(), "flow": m.flow.state_dict(), + "rew": m.rew.state_dict(), "rms": m.rms.cpu(), + "threshold": thr, "qf": qf.state_dict(), + "config": vars(args), "d_act": d.chunk * d.adim, + "tasks": d.tasks, "arrival_auc": a_r}, out / "main_rsm.pt") + print("[main-rsm] DONE", flush=True) + + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/run_ope.py b/rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/run_ope.py new file mode 100644 index 0000000000000000000000000000000000000000..d3d6a6167bd9d645022263ab0b9416d13a150d09 --- /dev/null +++ b/rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/run_ope.py @@ -0,0 +1,171 @@ +"""Driver: pi_0 -> ratio -> endpoint weight -> IS-corrected Q, with the gate. + +Order of operations is deliberate. The IS machinery is validated BEFORE any +policy is trained on it, because a critic that is never checked is how the +smolvla line shipped an advantage of 0.019 and a null AWR result. +""" +from __future__ import annotations +import sys as _sys, os as _os +_sys.path.insert(0, _os.path.dirname(_os.path.abspath(__file__))) +import argparse, json +from pathlib import Path +import numpy as np +import torch + +from data import LiberoRSMData +from is_ope import (load_critic, train_bc, train_ratio, train_endpoint_ratio, + train_likelihood_ratio, + q_recursive, precompute_decision_logratio, chunk_logW_fast, + effective_horizon) +from train_rsm import auc + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--cache", required=True) + ap.add_argument("--critic", required=True) + ap.add_argument("--out", required=True) + ap.add_argument("--batch", type=int, default=512) + ap.add_argument("--beta-q", type=float, default=0.98) + ap.add_argument("--gamma", type=float, default=0.99) + ap.add_argument("--depth", type=int, default=2) + ap.add_argument("--particles", type=int, default=16) + ap.add_argument("--bc-steps", type=int, default=8000) + ap.add_argument("--ratio-steps", type=int, default=6000) + ap.add_argument("--wend-steps", type=int, default=6000) + ap.add_argument("--pi-mode", default="succ", choices=["succ", "all"], + help="succ = BC on successful rollouts (a genuinely better " + "target policy); all = BC on everything, which approximates " + "the behaviour policy and is the NULL control: with pi ~= mu " + "the weights must be ~1 and IS must not move Q.") + ap.add_argument("--chunk", type=int, default=10, + help="MUST match the critic's training chunk; the action\n dim is chunk*7 and a mismatch silently breaks loading") + ap.add_argument("--ratio-mode", default="classifier", + choices=["classifier", "likelihood"], + help="classifier = discriminative density ratio (SHOWN BROKEN: " + "an identity control puts two same-data policies at 0.945-" + "0.977 separability, so the logit reads network identity). " + "likelihood = genuine pi/mu_hat with tractable Gaussians.") + ap.add_argument("--ratio-chunk", type=int, default=0, + help="action length the IS ratio scores; 0 = same as --chunk. " + "Set to the BEHAVIOUR POLICY decision period (10 for pi0.5). " + "The occupancy may condition on a much longer window; the " + "ratio is a product over DECISIONS and must not.") + ap.add_argument("--reward-mode", default="dense", choices=["dense","terminal"], + help="dense = P(task succeeds|z), every frame of a success is a " + "positive (~50%%). terminal = last k frames only (~0.5%%), which " + "leaves Q near-constant in the action.") + ap.add_argument("--seed", type=int, default=0) + ap.add_argument("--in-ram", type=int, default=1) + ap.add_argument("--policy-family", default="flow", choices=["flow", "gauss"]) + ap.add_argument("--ratio-smooth", type=float, default=0.0, + help="Gaussian kernel width applied to BOTH action classes before " + "the ratio classifier; buys overlap at the cost of a blurred ratio") + args = ap.parse_args() + + # Seed torch too, not just numpy: the policy head init and the + # flow-matching noise are torch RNG. Without this two arms meant to + # differ in ONE flag start from different policies -- observed as + # pi_0 separation gaps of 0.0170 (IS on) vs 0.0089 (IS off). + torch.manual_seed(args.seed) + dev = "cuda" if torch.cuda.is_available() else "cpu" + out = Path(args.out); out.mkdir(parents=True, exist_ok=True) + d = LiberoRSMData(args.cache, chunk=args.chunk, seed=args.seed, + in_ram=bool(args.in_ram), reward_mode=args.reward_mode) + enc, rew, flow, rms, cfg = load_critic(args.critic, d.feat_dim, d.n_task, dev, data=d) + args.d_z = cfg["d_z"] + rng = np.random.default_rng(args.seed + 7) + report = {"config": vars(args)} + + only_succ = (args.pi_mode == "succ") + print(f"=== pi_0: behaviour cloning ({'successes only' if only_succ else 'ALL data (null control)'}) ===", + flush=True) + pol = train_bc(d, enc, args, dev, only_success=only_succ, steps=args.bc_steps) + + print("=== step 1: per-decision density ratio by classification ===", flush=True) + rc = args.ratio_chunk or d.chunk + if args.ratio_mode == "likelihood": + ratio, pol_dec = train_likelihood_ratio( + d, enc, args, dev, steps=args.ratio_steps, + only_success=only_succ, chunk_len=rc) + elif rc != d.chunk: + print(f"=== fitting a DECISION-level policy (chunk {rc}) for the ratio ===", + flush=True) + print(f"=== fitting a DECISION-level policy (chunk {rc}) for the ratio ===", + flush=True) + pol_dec = train_bc(d, enc, args, dev, only_success=only_succ, + steps=args.bc_steps, chunk_len=rc) + ratio = train_ratio(d, enc, pol_dec, args, dev, steps=args.ratio_steps) + else: + pol_dec = pol + ratio = train_ratio(d, enc, pol_dec, args, dev, steps=args.ratio_steps) + + print("=== step 2/3: endpoint weight (Rao-Blackwellized) ===", flush=True) + wend = train_endpoint_ratio(d, enc, ratio, args, dev, steps=args.wend_steps) + + # ---------------- calibration: E_mu[w] should be ~1 ---------------- + b = d.sample(4096, rng, args.beta_q, args.beta_q, "val", dev) + with torch.no_grad(): + z = enc(b["x_now"]); zf = enc(b["x_fut"]) + w = wend(z, b["a_now"], zf, b["task"]) * getattr(wend, "calib", 1.0) + pre = precompute_decision_logratio(d, enc, ratio, dev, rc=rc) + W = torch.from_numpy(chunk_logW_fast(pre, b["t_idx"], b["fut_idx"])).to(dev) + W = W.clamp(-4, 4).exp() + ess = float((w.sum() ** 2) / (w.pow(2).sum() * len(w))) + report["calibration"] = { + "calib_scale": float(getattr(wend, "calib", 1.0)), + "E_mu[W_chunk]": float(W.mean()), "E_mu[w_endpoint]": float(w.mean()), + "w_p05": float(w.quantile(0.05)), "w_p50": float(w.quantile(0.5)), + "w_p95": float(w.quantile(0.95)), "ess_frac": ess, + "corr_w_vs_W": float(np.corrcoef(w.cpu().numpy(), W.cpu().numpy())[0, 1]), + } + print(f"[gate] E_mu[w]={w.mean():.3f} (target 1.0) ESS={ess:.3f} " + f"corr(what,W)={report['calibration']['corr_w_vs_W']:.3f}", flush=True) + + # ---------------- the falsifiable gate ---------------- + # pi_synth := mu restricted to successful episodes. Its occupancy is directly + # estimable, so the IS-corrected value can be checked against a reference + # rather than merely asserted. + fb = d.sample_frames(2048, rng, "val", dev) + with torch.no_grad(): + zq = enc(fb["x"]) + q_is, ess_q = q_recursive(zq, fb["a"], fb["task"], rew=rew, flow=flow, rms=rms, + pol=pol, wend=wend, beta=args.beta_q, gamma=args.gamma, + depth=args.depth, n_particles=args.particles, + use_is=True) + q_no, _ = q_recursive(zq, fb["a"], fb["task"], rew=rew, flow=flow, rms=rms, + pol=pol, wend=wend, beta=args.beta_q, gamma=args.gamma, + depth=args.depth, n_particles=args.particles, + use_is=False) + succ = fb["succ"].cpu().numpy() + dq = float((q_is - q_no).abs().mean() / q_no.abs().mean().clamp_min(1e-6)) + report["horizon"] = effective_horizon(args.beta_q, args.gamma, args.depth) + print(f"[horizon] depth={args.depth} -> {report['horizon']['mean_hops']:.2f} hops, " + f"~{report['horizon']['effective_frames']:.0f} frames, " + f"gamma_eff={report['horizon']['gamma_effective']:.4f} " + f"(nominal {args.gamma}); truncated mass " + f"{report['horizon']['truncation_mass']:.3f}", flush=True) + report["value"] = { + "pi_mode": args.pi_mode, + "rel_shift_IS_vs_noIS": dq, + "gate_expectation": ("null: weights ~1 and rel_shift should be SMALL" + if args.pi_mode == "all" else + "signal: pi is better than mu, Q should move UP"), + "auc_success_IS": auc(q_is.cpu().numpy(), succ), + "auc_success_noIS": auc(q_no.cpu().numpy(), succ), + "q_mean_IS": float(q_is.mean()), "q_mean_noIS": float(q_no.mean()), + "ess_particles": float(ess_q.mean()), + "depth": args.depth, "beta": args.beta_q, "gamma": args.gamma, + } + print(f"[gate] pi_mode={args.pi_mode} success-AUC IS={report['value']['auc_success_IS']:.4f} " + f"noIS={report['value']['auc_success_noIS']:.4f} " + f"rel|dQ|={dq:.4f} particle ESS={float(ess_q.mean()):.3f}", flush=True) + + torch.save({"pol": pol.state_dict(), "ratio": ratio.state_dict(), + "wend": wend.state_dict(), "config": vars(args)}, out / "is_stack.pt") + (out / "report.json").write_text(json.dumps(report, indent=2)) + print(json.dumps(report, indent=2), flush=True) + + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/subgoals_from_npz.py b/rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/subgoals_from_npz.py new file mode 100644 index 0000000000000000000000000000000000000000..6259dfde2adb9be1c774aa4c1d98775c9c65a7e1 --- /dev/null +++ b/rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/subgoals_from_npz.py @@ -0,0 +1,24 @@ +"""Subgoal labels for a pack whose per-episode npz already carry a per-frame `subgoals` +count (written by eval_closed_loop.py --collect from the live BDDL predicates). Emits the +/task{t}.npz (ep, vals, K) layout that data.py reward_mode=subgoal reads. + +usage: subgoals_from_npz.py --cache --out +""" +import argparse, numpy as np +from pathlib import Path +ap = argparse.ArgumentParser(); ap.add_argument("--cache", required=True); ap.add_argument("--out", required=True) +a = ap.parse_args() +m = np.load(f"{a.cache}/meta.npz", allow_pickle=True) +out = Path(a.out); out.mkdir(parents=True, exist_ok=True) +for t in range(len(m["tasks"])): + eps, vals, K = [], [], None + for e in np.where((m["ep_task"] == t) & ~m["ep_demo"].astype(bool))[0]: + z = np.load(str(m["ep_src"][e]), allow_pickle=True) + v = np.asarray(z["subgoals"], np.int8)[::int(m["stride"])] + n = int(m["ep_to"][e] - m["ep_from"][e]) + if len(v) < n: v = np.concatenate([v, np.full(n - len(v), v[-1] if len(v) else 0, np.int8)]) + eps.append(int(e)); vals.append(v[:n]); K = int(z["K"]) + if eps: + np.savez_compressed(out / f"task{t}.npz", ep=np.array(eps), vals=np.array(vals, dtype=object), K=K) + f = np.concatenate(vals); print(f"[sg] task {t}: {len(eps)} eps, K={K}, mean subgoal frac {f.mean()/K:.3f}", flush=True) +print("[sg] DONE") diff --git a/rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/sweep_horizon.py b/rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/sweep_horizon.py new file mode 100644 index 0000000000000000000000000000000000000000..d9e46709ded09c6920c3f42519508c350c6ac774 --- /dev/null +++ b/rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/sweep_horizon.py @@ -0,0 +1,140 @@ +"""Sweep query discount x recursion depth on a TRAINED critic. No retraining. + +The critic is fit on a beta BAND, so one checkpoint can be read at any query +beta. That makes the central tradeoff cheap to map: + + short hops -> the action still determines where you land, but the read is + myopic and never reaches the terminal reward + long hops -> the read reaches further, but the successor tends to ignore + the action chunk entirely + +Reports the action gap bucketed by time-to-episode-end, because a pooled number +averages the signal away: at beta=0.98 depth=1 the gap is +0.063 within 50 +frames of the end and ~0 beyond it, while the pooled value is +0.008. +""" +from __future__ import annotations +import sys as _sys, os as _os +_sys.path.insert(0, _os.path.dirname(_os.path.abspath(__file__))) +import argparse, json +from pathlib import Path +import numpy as np +import torch + +from data import LiberoRSMData +from is_ope import load_critic, q_recursive, effective_horizon, train_bc +from model import BCHead +from train_rsm import auc + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--cache", required=True) + ap.add_argument("--critic", required=True) + ap.add_argument("--out", required=True) + ap.add_argument("--betas", default="0.96,0.98,0.99,0.995") + ap.add_argument("--depths", default="1,2,3") + ap.add_argument("--gamma", type=float, default=0.99) + ap.add_argument("--particles", type=int, default=16) + ap.add_argument("--n", type=int, default=2048) + ap.add_argument("--chunk", type=int, default=10, + help="MUST match the critic's training chunk; the action\n dim is chunk*7 and a mismatch silently breaks loading") + ap.add_argument("--reward-mode", default="dense", choices=["dense","terminal"], + help="dense = P(task succeeds|z), every frame of a success is a " + "positive (~50%%). terminal = last k frames only (~0.5%%), which " + "leaves Q near-constant in the action.") + ap.add_argument("--seed", type=int, default=0) + ap.add_argument("--in-ram", type=int, default=1) + ap.add_argument("--policy-family", default="flow", choices=["flow", "gauss"]) + ap.add_argument("--bc-steps", type=int, default=3000) + ap.add_argument("--batch", type=int, default=512) + args = ap.parse_args() + + # Seed torch too, not just numpy: the policy head init and the + # flow-matching noise are torch RNG. Without this two arms meant to + # differ in ONE flag start from different policies -- observed as + # pi_0 separation gaps of 0.0170 (IS on) vs 0.0089 (IS off). + torch.manual_seed(args.seed) + dev = "cuda" if torch.cuda.is_available() else "cpu" + d = LiberoRSMData(args.cache, chunk=args.chunk, seed=args.seed, + in_ram=bool(args.in_ram), reward_mode=args.reward_mode) + enc, rew, flow, rms, cfg = load_critic(args.critic, d.feat_dim, d.n_task, dev, data=d) + rng = np.random.default_rng(args.seed + 5) + # Continuation policy for the recursion boundary. This MUST be on-support: an + # untrained head emits off-manifold action chunks at every hop, and the frozen + # reward decoder then scores the resulting latents arbitrarily -- the same + # support-exploitation artifact that turned the cross-task action gap + # negative. A quick behaviour clone keeps the boundary actions in + # distribution so the depth>1 numbers mean something. + args.d_z = cfg["d_z"] + args.seed = args.seed + pol = train_bc(d, enc, args, dev, only_success=False, steps=args.bc_steps) + + fb = d.sample_frames(args.n, rng, "val", dev) + with torch.no_grad(): + z = enc(fb["x"]) + te = fb["to_end"].cpu().numpy() + succ = fb["succ"].cpu().numpy() + # Two negatives, deliberately: + # within-task -- an on-support alternative; the fair action-ranking test + # cross-task -- the old batch-wide permutation, kept as a CONTROL. Once + # the flow is genuinely action-conditioned, an off-support + # action yields an off-manifold latent that the frozen + # reward decoder scores arbitrarily, so a "preference" for + # it measures support violation, not action quality. + tk_np_all = fb["task"].cpu().numpy() + perm_cross = torch.randperm(args.n, device=dev) + pw = np.arange(args.n) + for ti in np.unique(tk_np_all): + idx = np.nonzero(tk_np_all == ti)[0] + if len(idx) > 1: + pw[idx] = rng.permutation(idx) + perm_within = torch.from_numpy(pw).to(dev) + rows = [] + for beta in [float(b) for b in args.betas.split(",")]: + for depth in [int(x) for x in args.depths.split(",")]: + if beta >= args.gamma and depth > 1: + continue + with torch.no_grad(): + q_log, ess = q_recursive(z, fb["a"], fb["task"], rew=rew, flow=flow, + rms=rms, pol=pol, wend=None, beta=beta, + gamma=args.gamma, depth=depth, + n_particles=args.particles, use_is=False) + q_win, _ = q_recursive(z, fb["a"][perm_within], fb["task"], rew=rew, + flow=flow, rms=rms, pol=pol, wend=None, + beta=beta, gamma=args.gamma, depth=depth, + n_particles=args.particles, use_is=False) + q_crs, _ = q_recursive(z, fb["a"][perm_cross], fb["task"], rew=rew, + flow=flow, rms=rms, pol=pol, wend=None, + beta=beta, gamma=args.gamma, depth=depth, + n_particles=args.particles, use_is=False) + gl = (q_log - q_win).cpu().numpy() + gc = (q_log - q_crs).cpu().numpy() + ql = q_log.cpu().numpy() + h = effective_horizon(beta, args.gamma, depth) + row = {"beta": beta, "depth": depth, + "eff_frames": h["effective_frames"], + "gamma_eff": h["gamma_effective"], + "gap_pooled": float(gl.mean()), + "win_pooled": float((gl > 0).mean()), + "gap_pooled_crosstask": float(gc.mean()), + "win_pooled_crosstask": float((gc > 0).mean()), + "state_auc": auc(ql, succ)} + for name, lo_, hi_ in (("0-50", 0, 50), ("50-100", 50, 100), + ("100-200", 100, 200), ("200+", 200, 1e9)): + m = (te >= lo_) & (te < hi_) + if m.sum() >= 16: + row[f"gap_{name}"] = float(gl[m].mean()) + row[f"win_{name}"] = float((gl[m] > 0).mean()) + rows.append(row) + print(f"beta={beta:<6} depth={depth} eff={h['effective_frames']:5.0f}f " + f"pooled gap={row['gap_pooled']:+.5f} win={row['win_pooled']:.3f} " + f"auc={row['state_auc']:.3f} " + f"0-50 win={row.get('win_0-50', float('nan')):.2f} " + f"| xtask win={row['win_pooled_crosstask']:.3f}", flush=True) + out = Path(args.out); out.mkdir(parents=True, exist_ok=True) + (out / "horizon_sweep.json").write_text(json.dumps(rows, indent=2)) + print(f"\nwrote {out/'horizon_sweep.json'}", flush=True) + + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/test_dwm.py b/rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/test_dwm.py new file mode 100644 index 0000000000000000000000000000000000000000..0b0cd2105e0a9f8f68a306c47978e8a543c87e96 --- /dev/null +++ b/rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/test_dwm.py @@ -0,0 +1,262 @@ +"""CPU unit tests for the DWM successor model (synthetic token cache, tiny ViT). + + cd rsm_libero && python3 -m pytest -x -q test_dwm.py +""" +from __future__ import annotations +import json, os, subprocess, sys +from pathlib import Path +import numpy as np +import pytest +import torch + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE)) +from dwm_model import (DWM, DWMReward, Normalizer, TokenRSMData, make_synthetic_cache, + pool_tokens, sample_future_dwm, N_TOK, D_TOK) +from dwm_readout import load_critic_dwm, verify_pooling + +TINY = dict(depth=1, heads=2, dim_head=8, mlp_dim=32, dropout=0.0, emb_dropout=0.0) +TINY_FLAGS = ["--depth", "1", "--heads", "2", "--dim-head", "8", "--mlp", "32", "--dropout", "0"] + + +@pytest.fixture(scope="module") +def cache(tmp_path_factory): + root = tmp_path_factory.mktemp("syncache") + make_synthetic_cache(root, n_ep=6, ep_len=(20, 28), seed=0) + return root + + +@pytest.fixture(scope="module") +def data(cache): + return TokenRSMData(cache, chunk=8, seed=0) + + +def test_cache_layout(cache, data): + tok = np.load(cache / "tokens" / "tok.f16.npy", mmap_mode="r") + assert tok.shape[1:] == (N_TOK, D_TOK) and tok.dtype == np.float16 + info = json.loads((cache / "tokens" / "TOKENS.json").read_text()) + assert info["shape"] == list(tok.shape) + assert data.n_pr == 9 and data.adim == 7 + assert data.stats["mu"].shape == (N_TOK, D_TOK) + + +def test_pooling_matches_pooled_cache(cache): + r = verify_pooling(cache, n=64) + assert r["dim"] == 1545, r + assert r["fp16_ok"], r + + +def test_shapes(data): + m = DWM(N_TOK, D_TOK, 9, 56, **TINY) + r = DWMReward(N_TOK, D_TOK, 9) + assert m.dim == 424 and m.n_seq == N_TOK + 1 + rng = np.random.default_rng(0) + b = data.sample(3, rng, 0.9, 0.99, "train") + norm = Normalizer(data.stats) + tn, pn = norm.tok(b["tok_now"]), norm.pr(b["pr_now"]) + assert tn.shape == (3, N_TOK, D_TOK) and pn.shape == (3, 9) and b["a_now"].shape == (3, 56) + xk, xp, k = torch.randn_like(tn), torch.randn_like(pn), torch.rand(3) + v_tok, v_pr = m(tn, pn, b["a_now"], b["beta"], xk, xp, k) + assert v_tok.shape == (3, N_TOK, D_TOK) and v_pr.shape == (3, 9) + assert torch.isfinite(v_tok).all() and torch.isfinite(v_pr).all() + assert r(tn, pn).shape == (3,) + # the geometric future never leaves the episode and beta is in the band + assert (b["fut_idx"] >= b["t_idx"]).all() and (b["fut_idx"] < data.ep_to[b["ep"]]).all() + assert (b["beta"] >= 0.9).all() and (b["beta"] <= 0.99).all() + # full-size configuration: ~20 M as the plan states + full = DWM(N_TOK, D_TOK, 9, 56) + n = sum(p.numel() for p in full.parameters()) + assert 18e6 < n < 24e6, n + + +def test_flow_loss_decreases(data): + torch.manual_seed(0) + m = DWM(N_TOK, D_TOK, 9, 56, **TINY) + norm = Normalizer(data.stats) + opt = torch.optim.AdamW(m.parameters(), lr=1e-3) + rng = np.random.default_rng(1) + b = data.sample(6, rng, 0.9, 0.99, "train") # one fixed batch: the loss must fall + tn, tf = norm.tok(b["tok_now"]), norm.tok(b["tok_fut"]) + pn, pf = norm.pr(b["pr_now"]), norm.pr(b["pr_fut"]) + y_tok = (tf - tn) / 1.0; y_pr = (pf - pn) + g = torch.Generator().manual_seed(0) + k = torch.rand(6, generator=g); nt = torch.randn(y_tok.shape, generator=g); npr = torch.randn(y_pr.shape, generator=g) + xk = (1 - k)[:, None, None] * y_tok + k[:, None, None] * nt + xp = (1 - k)[:, None] * y_pr + k[:, None] * npr + losses = [] + for it in range(40): + v_tok, v_pr = m(tn, pn, b["a_now"], b["beta"], xk, xp, k) + loss = (v_tok - (y_tok - nt)).pow(2).mean() + (v_pr - (y_pr - npr)).pow(2).mean() + opt.zero_grad(); loss.backward(); opt.step() + losses.append(float(loss)) + assert losses[-1] < 0.7 * losses[0], losses[::10] + + +def test_sample_future_runs(data): + torch.manual_seed(0) + m = DWM(N_TOK, D_TOK, 9, 56, **TINY).eval() + norm = Normalizer(data.stats) + rng = np.random.default_rng(2) + b = data.sample(2, rng, 0.9, 0.99, "val") + tn, pn = norm.tok(b["tok_now"]), norm.pr(b["pr_now"]) + rms_tok = torch.ones(N_TOK, D_TOK); rms_pr = torch.ones(9) + xt, xp = sample_future_dwm(m, tn, pn, b["a_now"], b["beta"], rms_tok, rms_pr, n_steps=3, n=4, micro=3) + assert xt.shape == (8, N_TOK, D_TOK) and xp.shape == (8, 9) + assert torch.isfinite(xt).all() + # common random numbers: same x0 -> identical samples + x0 = (torch.randn(8, N_TOK, D_TOK), torch.randn(8, 9)) + a1, _ = sample_future_dwm(m, tn, pn, b["a_now"], b["beta"], rms_tok, rms_pr, 3, n=4, x0=x0) + a2, _ = sample_future_dwm(m, tn, pn, b["a_now"], b["beta"], rms_tok, rms_pr, 3, n=4, x0=x0) + assert torch.equal(a1, a2) + + +def n_particles_is_one(n): + return n == 1 + + +def _run_trainer(cache, out, steps, nproc=1, extra=()): + cmd = [sys.executable, "-m", "torch.distributed.run", "--standalone", f"--nproc_per_node={nproc}", + str(HERE / "train_rsm_dwm.py"), "--cache", str(cache), "--out", str(out), + "--batch", "8", "--micro", "4", "--steps", str(steps), "--eval-every", "3", + "--eval-rows", "8", "--eval-frames", "8", "--eval-minmse-n", "2", "--flow-steps", "2", + "--save-every", "3", "--warm-cache", "0", "--wandb-mode", "disabled", "--print-every", "1", + *TINY_FLAGS, *extra] + env = dict(os.environ, OMP_NUM_THREADS="2", CUDA_VISIBLE_DEVICES="") + p = subprocess.run(cmd, capture_output=True, text=True, env=env, timeout=900) + assert p.returncode == 0, p.stdout[-3000:] + "\n" + p.stderr[-3000:] + return p.stdout + + +HIST_KEYS = {"step", "reward_auc", "cfm_val", "per_task", "by_horizon", "q_action_gap", "q_action_winrate", + "q_success_auc", "q_mean", "identity", "minmse_train", "minmse_val", "meanmse_train", + "meanmse_val", "staymse_train", "staymse_val", "meanmse", "staymse"} + + +def test_ddp_launch_and_resume(cache, tmp_path): + out = tmp_path / "run" + log = _run_trainer(cache, out, steps=6, nproc=1) + assert "[dwm] params:" in log and "[dwm] EVAL 3:" in log and "[dwm] DONE" in log + hist = json.loads((out / "history.json").read_text()) + assert [h["step"] for h in hist] == [3, 6] + assert HIST_KEYS <= set(hist[-1]), HIST_KEYS - set(hist[-1]) + for f in ("ckpt.pt", "ckpt_s3.pt", "ckpt_s6.pt", "ckpt_best.pt"): + assert (out / f).exists(), f + assert all(np.isfinite(hist[-1][k]) for k in ("cfm_val", "minmse_val", "staymse_val", "q_action_winrate")) + # resume from ckpt.pt: continues at step 7, adds one eval record + log2 = _run_trainer(cache, out, steps=9, nproc=1) + assert "RESUMED at step 6/9" in log2, log2[-2000:] + hist = json.loads((out / "history.json").read_text()) + assert [h["step"] for h in hist] == [3, 6, 9] + # timing probe path + log3 = _run_trainer(cache, tmp_path / "timing", steps=4, nproc=1, extra=("--time-steps", "3")) + assert "[dwm] TIMING" in log3 + + +def test_ddp_two_procs_gloo(cache, tmp_path): + """The sharded evaluation and all_gather path (2 CPU ranks, gloo).""" + out = tmp_path / "run2" + log = _run_trainer(cache, out, steps=3, nproc=2) + hist = json.loads((out / "history.json").read_text()) + assert len(hist) == 1 and hist[0]["eval_rows"] == 8 and hist[0]["eval_frames"] == 8 + assert (out / "ckpt.pt").exists() + + +def test_readout_interface(cache, tmp_path, data): + out = tmp_path / "run_ro" + _run_trainer(cache, out, steps=3, nproc=1) + crit = load_critic_dwm(out / "ckpt_best.pt", device="cpu") + rng = np.random.default_rng(3) + fb = data.sample_frames(4, rng, "val") + x, a, pr = fb["x"], fb["a"], fb["pr_now"] + q1 = crit.q(x, a, 0.95, n_particles=3, crn_seed=0, depth=1, mode="d1", proprio=pr, flow_steps=2) + assert q1.shape == (4,) and (q1 >= 0).all() and (q1 <= 1).all() + q1b = crit.q(x, a, 0.95, n_particles=3, crn_seed=0, depth=1, mode="d1", proprio=pr, flow_steps=2) + assert torch.equal(q1, q1b) # CRN: same seed -> same Q + q1c = crit.q(x, a, 0.95, n_particles=3, crn_seed=1, depth=1, mode="d1", proprio=pr, flow_steps=2) + assert not torch.equal(q1, q1c) + # dense-head logit averaging (the primary planning read-out): mean logit over particles, same CRN + qd, qlog = crit.q(x, a, 0.95, n_particles=3, crn_seed=0, depth=1, mode="d1", proprio=pr, flow_steps=2, + return_logit=True) + assert torch.equal(qd, q1) and qlog.shape == (4,) and torch.isfinite(qlog).all() + # temperature: q_logit unchanged, q moves toward 0.5 for T > 1 (monotone shrink of the logit) + qT, qlogT = crit.q(x, a, 0.95, n_particles=3, crn_seed=0, depth=1, mode="d1", proprio=pr, flow_steps=2, + return_logit=True, temperature=4.0) + assert torch.equal(qlogT, qlog) and ((qT - 0.5).abs() <= (qd - 0.5).abs() + 1e-6).all() + # two-stage screening: full-length outputs; non-rescored rows keep stage-1 values; rescored rows differ + x8 = torch.cat([x, x]); a8 = torch.cat([a, a * 0.5]); pr8 = torch.cat([pr, pr]) + q_s1, ql_s1 = crit.q(x8, a8, 0.95, n_particles=2, crn_seed=0, proprio=pr8, flow_steps=2, return_logit=True) + q_ts, ql_ts = crit.q(x8, a8, 0.95, n_particles=2, crn_seed=0, proprio=pr8, flow_steps=2, return_logit=True, + rescore_top=3, n_particles_rescore=5) + assert q_ts.shape == (8,) and ql_ts.shape == (8,) + top = torch.topk(ql_s1, 3).indices; keep = torch.ones(8, dtype=torch.bool); keep[top] = False + assert torch.equal(q_ts[keep], q_s1[keep]) and torch.equal(ql_ts[keep], ql_s1[keep]) + # calib.json next to the checkpoint is picked up by load_critic_dwm + (out / "calib.json").write_text('{"T": 2.5}') + crit2 = load_critic_dwm(out / "ckpt_best.pt", device="cpu") + assert crit2.temperature == 2.5 and load_critic_dwm(out / "ckpt_best.pt", device="cpu", calib=None).temperature == 1.0 + + class Hop: # hop policy on the pooled state + d_act = 56 + def __call__(self, pooled, eps): + assert pooled.shape[1] == 1545 and eps.shape[1] == 56 + return 0.1 * eps + q2, hops = crit.q(x, a, 0.95, n_particles=3, crn_seed=0, depth=2, mode="fold", proprio=pr, + hop_policy=Hop(), flow_steps=2, return_hops=True) + assert q2.shape == (4,) and len(hops) == 2 and hops[0].shape == (4, 3) + with pytest.raises(ValueError): + crit.q(x, a, 0.95, depth=2, mode="fold", proprio=pr) + r = crit.reward(x, pr) + assert r.shape == (4,) + xt, xp = crit.sample_future(x, a, 0.95, proprio=pr, n=2, crn_seed=0, flow_steps=2) + assert xt.shape == (8, N_TOK, D_TOK) and xp.shape == (8, 9) + assert pool_tokens(xt, xp).shape == (8, 1545) + + +def test_goal_label_and_goal_clf_readout(cache, tmp_path, data): + """--reward-mode goal on the token data; goal classifier training on the pooled cache; goal_clf read-out.""" + dg = TokenRSMData(cache, chunk=8, seed=0, reward_mode="goal") + g = np.load(cache / "goal.npz")["goal"] + assert np.array_equal(dg.r, g.astype(np.float32)) and 0 < dg.r.mean() < 1 + for e in range(dg.n_ep): # goal frames only inside successful episodes + if not dg.ep_success[e]: + assert dg.r[dg.ep_from[e]:dg.ep_to[e]].sum() == 0 + # trainer accepts the mode + out = tmp_path / "run_goal" + log = _run_trainer(cache, out, steps=3, nproc=1, extra=("--reward-mode", "goal")) + assert "goal label from" in log + # standalone classifier on the pooled cache + outc = tmp_path / "goal_clf" + cmd = [sys.executable, str(HERE / "train_goal_clf.py"), "--cache", str(cache), "--out", str(outc), + "--steps", "30", "--batch", "64", "--eval-every", "15", "--wandb-mode", "disabled"] + p = subprocess.run(cmd, capture_output=True, text=True, env=dict(os.environ, CUDA_VISIBLE_DEVICES=""), timeout=600) + assert p.returncode == 0, p.stdout[-2000:] + p.stderr[-2000:] + ck = torch.load(outc / "clf.pt", map_location="cpu", weights_only=False) + assert ck["config"]["d_in"] == 1545 and ck["config"]["label"] == "env_success_replay" + assert ck["norm"]["mu"].shape == (1545,) + # read-out with the goal classifier + crit = load_critic_dwm(out / "ckpt_best.pt", device="cpu") + rng = np.random.default_rng(5) + fb = data.sample_frames(4, rng, "val") + q, ql = crit.q(fb["x"], fb["a"], 0.95, n_particles=2, crn_seed=0, proprio=fb["pr_now"], flow_steps=2, + reward="goal_clf", reward_path=outc / "clf.pt", return_logit=True) + assert q.shape == (4,) and ql.shape == (4,) and (q >= 0).all() and (q <= 1).all() and torch.isfinite(ql).all() + q2 = crit.q(fb["x"], fb["a"], 0.95, n_particles=2, crn_seed=0, proprio=fb["pr_now"], flow_steps=2, reward="goal_clf") + assert torch.equal(q, q2) # cached classifier, same CRN -> same Q + r = crit.reward(fb["x"], fb["pr_now"], reward="goal_clf") + assert r.shape == (4,) + + +def test_calib_and_timing_scripts(cache, tmp_path): + out = tmp_path / "run_cal" + _run_trainer(cache, out, steps=3, nproc=1) + env = dict(os.environ, CUDA_VISIBLE_DEVICES="") + p = subprocess.run([sys.executable, str(HERE / "calib_dwm.py"), "--cache", str(cache), "--ckpt", str(out / "ckpt_best.pt"), + "--max-frames", "64"], capture_output=True, text=True, env=env, timeout=600) + assert p.returncode == 0, p.stdout[-2000:] + p.stderr[-2000:] + c = json.loads((out / "calib.json").read_text()) + assert c["T"] > 0 and c["bce_after"] <= c["bce_before"] + 1e-6 and "ece_after" in c + p = subprocess.run([sys.executable, str(HERE / "dwm_readout_timing.py"), "--cache", str(cache), "--ckpt", str(out / "ckpt_best.pt"), + "--n-cand", "20", "--reps", "1", "--micro", "16"], capture_output=True, text=True, env=env, timeout=900) + assert p.returncode == 0, p.stdout[-2000:] + p.stderr[-2000:] + r = json.loads((out / "readout_timing.json").read_text()) + assert "two_stage_4_top16_64_s" in r and r["flat_4_particles_s"] > 0 diff --git a/rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/test_lewm_port.py b/rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/test_lewm_port.py new file mode 100644 index 0000000000000000000000000000000000000000..5788305d7539faf2754c4073a3407fb75355be61 --- /dev/null +++ b/rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/test_lewm_port.py @@ -0,0 +1,143 @@ +"""Checks on the LeWM torch port (gen_q#268). CPU-only, seconds to run. + +The port is of a JAX reference this venv cannot execute (no jax), so its correctness has to be +ASSERTED rather than assumed. These are the four things that, if wrong, would silently turn LeWM +into a different method and make its column in the flagship table meaningless: + + 1. SIGReg is the Epps-Pulley statistic the reference computes -- checked against an independent + numpy implementation on the same random projections, and against its two limiting behaviours + (small on a standard normal, large on a collapsed representation). + 2. The AdaLN-zero block is the IDENTITY at initialisation. That is what "zero" means; if the + conditioning head were default-initialised, the predictor would start as noise and the recipe + -- which has no target network to stabilise it -- would not train. + 3. The prediction target is NOT detached. The reference comments this explicitly ("NO detach + (recipe)"): the encoder is pulled by the loss through the target as well as the prediction, and + collapse is prevented by SIGReg alone. Detaching is the single most natural "cleanup" someone + would apply, so the test pins it. + 4. The read-out round-trips: a checkpoint in train_lewm.py's format loads, scores, stays in [0,1], + and `fold` at depth 1 equals `d1`. + +usage: python test_lewm_port.py (or pytest test_lewm_port.py) +""" +import numpy as np +import torch + +from lewm_model import CTX, N_PREDS, AdaLNBlock, Encoder, LeWM, RewardProbe, sigreg_stat + + +def _sigreg_numpy(emb, A, knots=17): + """Independent implementation, transcribed from the reference's jnp version.""" + T, B, D = emb.shape + t = np.linspace(0.0, 3.0, knots) + dt = 3.0 / (knots - 1) + w = np.full((knots,), 2 * dt) + w[0] = dt + w[-1] = dt + phi = np.exp(-t ** 2 / 2.0) + weights = w * phi + x_t = (emb @ A)[..., None] * t + err = (np.cos(x_t).mean(-3) - phi) ** 2 + np.sin(x_t).mean(-3) ** 2 + return float(((err @ weights) * B).mean()) + + +def test_sigreg_matches_reference(): + g = torch.Generator().manual_seed(0) + emb = torch.randn(4, 64, 32, generator=g, dtype=torch.float64) + A = torch.randn(32, 128, generator=g, dtype=torch.float64) + A = A / A.norm(dim=0, keepdim=True) + got = float(sigreg_stat(emb, A=A, num_proj=128)) + want = _sigreg_numpy(emb.numpy(), A.numpy()) + assert abs(got - want) < 1e-8, f"SIGReg {got} != independent {want}" + + +def test_sigreg_penalises_collapse(): + g = torch.Generator().manual_seed(1) + normal = torch.randn(4, 256, 32, generator=g, dtype=torch.float64) + collapsed = torch.zeros(4, 256, 32, dtype=torch.float64) + 3.0 + A = torch.randn(32, 256, generator=g, dtype=torch.float64) + A = A / A.norm(dim=0, keepdim=True) + s_n = float(sigreg_stat(normal, A=A, num_proj=256)) + s_c = float(sigreg_stat(collapsed, A=A, num_proj=256)) + assert s_c > 10 * s_n, f"SIGReg does not penalise collapse: normal {s_n}, collapsed {s_c}" + + +def test_adaln_zero_is_identity_at_init(): + torch.manual_seed(0) + blk = AdaLNBlock(32, heads=4, mlp_dim=64) + x = torch.randn(3, CTX, 32) + c = torch.randn(3, CTX, 32) + mask = torch.tril(torch.ones(CTX, CTX, dtype=torch.bool))[None, None] + y = blk(x, c, mask) + assert torch.allclose(y, x, atol=0, rtol=0), \ + f"AdaLN-zero block is not the identity at init (max |dy| = {float((y - x).abs().max())})" + + +def test_encoder_stage_count(): + assert Encoder(16, in_ch=6, res=84).n_stages == 5 # 84->42->21->11->6->3 + assert Encoder(16, in_ch=3, res=64).n_stages == 4 # 64->32->16->8->4 + assert Encoder(16, in_ch=6, res=84).out_res <= 4 + + +def test_target_is_not_detached(): + """The encoder gradient must differ from the detached-target variant -- i.e. the loss really does + pull the target. If someone adds .detach(), this test is the one that fails.""" + torch.manual_seed(0) + m = LeWM(size="s", a_dim=14, in_ch=6, res=32, ctx=CTX) + frames = torch.randint(0, 255, (2, CTX + N_PREDS, 6, 32, 32), dtype=torch.uint8) + acts = torch.randn(2, CTX + N_PREDS, 14) + + def enc_grad(detach): + m.zero_grad(set_to_none=True) + pred, emb = m(frames, acts) + tgt = emb[:, N_PREDS:] + (pred - (tgt.detach() if detach else tgt)).pow(2).mean().backward() + return m.encoder.fc2.weight.grad.detach().clone() + + g_live = enc_grad(False) + g_det = enc_grad(True) + assert not torch.allclose(g_live, g_det, atol=1e-12), \ + "encoder gradient is identical with and without a detached target: the target is detached" + assert float(g_live.abs().sum()) > 0, "no gradient reaches the encoder at all" + + +def test_readout_round_trip(tmp=None): + import tempfile, os + import lewm_readout + torch.manual_seed(0) + a_dim, res, B = 56, 32, 5 + m = LeWM(size="s", a_dim=a_dim, in_ch=6, res=res, ctx=CTX) + pr = RewardProbe(m.emb_dim) + blob = {"model": "lewm", "lewm": m.state_dict(), "probe": pr.state_dict(), + "config": {"chunk": 8}, "d_act": a_dim, "step": 1, "q_action_winrate": 0.5, + "cams": ["agentview_image", "robot0_eye_in_hand_image"], + "arch": {"size": "s", "emb_dim": m.emb_dim, "a_dim": a_dim, "in_ch": 6, "res": res, + "ctx": CTX, "chunk": 8, "adim": 7}} + d = tempfile.mkdtemp() + p = os.path.join(d, "ckpt.pt") + torch.save(blob, p) + crit = lewm_readout.load_critic_lewm(p, device="cpu") + img = torch.randint(0, 255, (B, 6, res, res), dtype=torch.uint8) + a = torch.randn(B, a_dim).clamp(-1, 1) + q1, ql = crit.q((img, None), a, mode="d1", depth=1, gamma=0.99, return_logit=True) + qf, _ = crit.q((img, None), a, mode="fold", depth=1, gamma=0.99, return_logit=True) + q4, _ = crit.q((img, None), a, mode="fold", depth=4, gamma=0.99, return_logit=True) + for name, q in (("d1", q1), ("fold1", qf), ("fold4", q4)): + assert q.shape == (B,), f"{name}: shape {tuple(q.shape)}" + assert torch.isfinite(q).all(), f"{name}: non-finite" + assert bool((q >= 0).all() and (q <= 1).all()), f"{name}: outside [0,1]" + assert torch.allclose(q1, qf, atol=1e-6), "fold at depth 1 must equal d1" + # deterministic: the same inputs twice give the same answer bit for bit + q1b, _ = crit.q((img, None), a, mode="d1", depth=1, gamma=0.99, return_logit=True) + assert torch.equal(q1, q1b), "LeWM read-out is not deterministic" + # float frames in [0,1] (what the planner hands it) must match the uint8 path + qf_float, _ = crit.q((img.float() / 255.0, None), a, mode="d1", depth=1, gamma=0.99, + return_logit=True) + assert torch.allclose(q1, qf_float, atol=1e-5), "float-in-[0,1] frames disagree with uint8" + + +if __name__ == "__main__": + fns = [v for k, v in sorted(globals().items()) if k.startswith("test_")] + for f in fns: + f() + print(f" ok {f.__name__}") + print(f"\nall {len(fns)} LeWM port checks passed") diff --git a/rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/their_trainer_control.py b/rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/their_trainer_control.py new file mode 100644 index 0000000000000000000000000000000000000000..5488c588ca9bff7d497d3c9e1577c5b57019df53 --- /dev/null +++ b/rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/their_trainer_control.py @@ -0,0 +1,46 @@ +"""CONTROL: run the lane's own BC trainer to its full budget. + +Their bcdemos checkpoint records a held-out ODE-sampled MSE of 0.0032 at step +110000. Our pipeline plateaus near 0.042 at 120000. A 20k-step bisect showed both +paths equal (0.0495 theirs vs 0.0471 ours), so the question is whether their +number is reachable at all at the full budget, or whether it came from somewhere +else. Same loader, same head, same loss, same optimiser, logged every 5000 steps. +""" +import importlib.util, sys, numpy as np, torch + +W = ("/data/pulkitag/hamer_diffusion_policy_project/projects/" + "continual_learning_for_manipulation/.claude/worktrees/" + "08312026_jvq_recap_worktree/scripts/rlinf_jvq") +sys.path.insert(0, W) +_s = importlib.util.spec_from_file_location("lh", W + "/09032026_latent_head_bc.py") +lh = importlib.util.module_from_spec(_s); sys.modules["lh"] = lh; _s.loader.exec_module(lh) + +CACHE = "/data/pulkitag/users/rli14/libero10_demo_ogpo_cache_srv" +CH, BS, STEPS, DEV = 10, 1024, 120000, "cuda" + +def main(): + z, p, a, task, val = lh.load_cache(CACHE, CH) + tr = torch.nonzero(~val).squeeze(1); va = torch.nonzero(val).squeeze(1) + print(f"[ctl] {len(z)} frames, {len(tr)} train / {len(va)} val", flush=True) + torch.manual_seed(0) + m = lh.Head(4096, 8, len(lh.FS15), 1024, 4, CH).to(DEV) + opt = torch.optim.Adam(m.parameters(), lr=3e-4) + best = float("inf") + for step in range(1, STEPS + 1): + idx = tr[torch.randint(0, len(tr), (BS,))] + zb, pb, tb = z[idx].to(DEV), p[idx].to(DEV), task[idx].to(DEV) + ab = a[idx].to(DEV) + adv = torch.full((BS,), 2, dtype=torch.long, device=DEV) + k = torch.rand(BS, device=DEV); eps = torch.randn_like(ab) + x_k = (1 - k)[:, None, None] * ab + k[:, None, None] * eps + loss = ((m(zb, pb, tb, adv, x_k, k).view_as(ab) - (ab - eps)) ** 2).mean() + opt.zero_grad(); loss.backward(); opt.step() + if step % 5000 == 0 or step == STEPS: + v = lh.val_mse(m, z[va], p[va], task[va], a[va], DEV) + best = min(best, v) + print(f"[ctl] {step} cfm={float(loss):.5f} val_mse={v:.5f} best={best:.5f}", + flush=True) + print(f"[ctl] DONE best={best:.5f} (their checkpoint records 0.00319)", flush=True) + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/thr_test.py b/rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/thr_test.py new file mode 100644 index 0000000000000000000000000000000000000000..5167a92bcfd741037061bcdd47c96a049f70b280 --- /dev/null +++ b/rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/thr_test.py @@ -0,0 +1,32 @@ +"""Throughput comparison. thr_all = SR*max/mean_steps_all conflates success rate with +speed; the paired steps-to-success on episodes BOTH arms solved isolates speed alone.""" +import json, sys, statistics as st +from math import sqrt, erfc +E="/data/pulkitag/users/rli14/rsm_libero_runs/eval" +def load(f): + r=json.load(open(f"{E}/{f}.json")); d={} + for t,eps in r["episodes_detail"].items(): + for e in eps: d[(t,e["episode"])]=(bool(e["success"]), e["steps"]) + return r, d +pairs=[] +for i in range(1,len(sys.argv),2): pairs.append((sys.argv[i],sys.argv[i+1])) +TA=TB=SA=SB=0.0; dif=[]; wins=loss=0; n=0 +print(f"{'pair':26s} {'thr_all A':>10s} {'thr_all B':>10s} {'d%':>7s} {'thrS A':>8s} {'thrS B':>8s}") +for a,b in pairs: + RA,DA=load(a); RB,DB=load(b) + TA+=RA["throughput_all"]; TB+=RB["throughput_all"] + SA+=RA["throughput_succ"]; SB+=RB["throughput_succ"]; n+=1 + d=(RA["throughput_all"]-RB["throughput_all"])/RB["throughput_all"]*100 + print(f"{a[:26]:26s} {RA['throughput_all']:10.3f} {RB['throughput_all']:10.3f} " + f"{d:+7.1f} {RA['throughput_succ']:8.3f} {RB['throughput_succ']:8.3f}") + both=[k for k in set(DA)&set(DB) if DA[k][0] and DB[k][0]] + for k in both: + dd=DA[k][1]-DB[k][1]; dif.append(dd) + wins+= dd<0; loss+= dd>0 +print(f"\nMEAN thr_all {TA/n:.3f} vs {TB/n:.3f} {(TA-TB)/TB*100:+.1f}%") +print(f"MEAN thr_succ {SA/n:.3f} vs {SB/n:.3f} {(SA-SB)/SB*100:+.1f}%") +print(f"\nSPEED on {len(dif)} episodes BOTH arms solved (same init):") +print(f" mean {st.mean(dif):+.1f} steps median {st.median(dif):+.0f}") +print(f" A faster on {wins}, slower on {loss}, tied on {len(dif)-wins-loss}") +z=(wins-loss)/sqrt(max(wins+loss,1)); p=erfc(abs(z)/sqrt(2)) +print(f" sign test z={z:.2f} p={p:.3f} {'SIGNIFICANT' if p<0.05 else 'not significant'}") diff --git a/rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/train_goal_clf.py b/rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/train_goal_clf.py new file mode 100644 index 0000000000000000000000000000000000000000..d67bb31a4222c03dc17bb6f0674b6525464c382f --- /dev/null +++ b/rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/train_goal_clf.py @@ -0,0 +1,122 @@ +"""Standalone GOAL-STATE classifier on the pooled z-scored state (orchestrator, 2026-09-18). +PRIVILEGED-INFORMATION ABLATION: the label is env success obtained by state replay, which RISE and its +baselines never see (they use the 0/1 expert-membership reward). Not the primary read-out. + + p(goal | x) with x = clip((feat - mu) / max(sd, sd_floor), -z_clip, z_clip), feat = [z(1536) | proprio(9)] + (the cache's STATE DEFINITION, via data.LiberoRSMData), label = cache//goal.npz (env success by replay). + +MLP 1545 -> 512 x 2 -> 1, balanced BCE, AdamW 3e-4 wd 0.01, 20k steps at batch 4096, held-out AUC and +false-positive rate (p > 0.5 on goal = 0 frames) on the val episodes. Saves /clf.pt with +{"net", "config", "norm": {mu, sd, z_clip, sd_floor}} so dwm_readout can score sampled futures without the cache. +""" +from __future__ import annotations +import sys as _sys, os as _os +_sys.path.insert(0, _os.path.dirname(_os.path.abspath(__file__))) +import argparse, json, time +from pathlib import Path +import numpy as np +import torch +import torch.nn as nn +import torch.nn.functional as F + +from data import LiberoRSMData +from train_rsm import auc + + +def build_net(d_in=1545, width=512, depth=2): + layers, d = [], d_in + for _ in range(depth): + layers += [nn.Linear(d, width), nn.SiLU()]; d = width + layers += [nn.Linear(d, 1)] + return nn.Sequential(*layers) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--cache", required=True); ap.add_argument("--out", required=True) + ap.add_argument("--goal-file", default="", help="default /goal.npz") + ap.add_argument("--width", type=int, default=512); ap.add_argument("--depth", type=int, default=2) + ap.add_argument("--steps", type=int, default=20000); ap.add_argument("--batch", type=int, default=4096) + ap.add_argument("--lr", type=float, default=3e-4); ap.add_argument("--wd", type=float, default=0.01) + ap.add_argument("--eval-every", type=int, default=2000); ap.add_argument("--seed", type=int, default=0) + ap.add_argument("--wandb-entity", default=_os.environ.get("RSM_WANDB_ENTITY", "")) + ap.add_argument("--wandb-project", default=_os.environ.get("RSM_WANDB_PROJECT", "rsm_rise")) + ap.add_argument("--wandb-name", default=""); ap.add_argument("--wandb-mode", default="online") + args = ap.parse_args() + torch.manual_seed(args.seed); rng = np.random.default_rng(args.seed) + dev = "cuda" if torch.cuda.is_available() else "cpu" + out = Path(args.out); out.mkdir(parents=True, exist_ok=True) + + d = LiberoRSMData(args.cache, chunk=8, seed=args.seed, in_ram=True, reward_mode="dense") + gf = Path(args.goal_file) if args.goal_file else Path(args.cache) / "goal.npz" + g = np.load(gf, allow_pickle=True); goal = g["goal"].astype(np.float32) + assert len(goal) == int(d.ep_to[-1]), f"goal.npz has {len(goal)} frames, cache {int(d.ep_to[-1])}" + d.r = goal # per-frame label the sampler returns as r + p = float(goal.mean()); pos_w = torch.tensor(max((1 - p) / max(p, 1e-6), 1.0), device=dev) + print(f"[goal_clf] {d.n_ep} eps ({len(d.train_eps)} train / {len(d.val_eps)} val), dim={d.feat_dim}, " + f"goal frames {p:.4f} (pos_weight {float(pos_w):.1f}), z_clip={getattr(d, 'z_clip', 0)}", flush=True) + wb = None + if args.wandb_entity and args.wandb_mode != "disabled": + try: + import wandb, hashlib + wb = wandb.init(entity=args.wandb_entity, project=args.wandb_project, name=args.wandb_name or out.name, + id=hashlib.md5(str(out.resolve()).encode()).hexdigest()[:16], resume="allow", + mode=args.wandb_mode, dir=str(out), + config={**vars(args), "label": "env_success_replay", + "privileged": "env success via state replay (ablation; not the primary arm)"}) + print(f"[goal_clf] wandb: {wb.url}", flush=True) + except Exception as e: + print(f"[goal_clf] wandb disabled: {e}", flush=True) + net = build_net(d.feat_dim, args.width, args.depth).to(dev) + opt = torch.optim.AdamW(net.parameters(), lr=args.lr, weight_decay=args.wd) + + # fixed held-out set: ALL val frames (episode-level split), for AUC / FPR + val_idx = np.concatenate([np.arange(d.ep_from[e], d.ep_to[e]) for e in d.val_eps]) + xv = torch.from_numpy(d._feat(val_idx)).to(dev); yv = torch.from_numpy(goal[val_idx]).to(dev) + + def evaluate(): + net.eval() + with torch.no_grad(): + lg = torch.cat([net(xv[i:i + 8192]).squeeze(-1) for i in range(0, len(xv), 8192)]) + pr = torch.sigmoid(lg) + net.train() + y = yv.cpu().numpy(); pn = pr.cpu().numpy() + neg, pos = y < 0.5, y >= 0.5 + return {"val_auc": auc(pn, y), "val_fpr@0.5": float((pn[neg] > 0.5).mean()) if neg.any() else float("nan"), + "val_tpr@0.5": float((pn[pos] > 0.5).mean()) if pos.any() else float("nan"), + "val_mean_p_on_goal0": float(pn[neg].mean()) if neg.any() else float("nan"), + "val_mean_p_on_goal1": float(pn[pos].mean()) if pos.any() else float("nan"), + "val_bce": float(F.binary_cross_entropy_with_logits(lg, yv)), "n_val": int(len(y)), + "n_val_goal1": int(pos.sum())} + hist = []; t0 = time.time() + for step in range(1, args.steps + 1): + b = d.sample_frames(args.batch, rng, "train", dev) + logit = net(b["x"]).squeeze(-1) + loss = F.binary_cross_entropy_with_logits(logit, b["r"], pos_weight=pos_w) + opt.zero_grad(); loss.backward(); gn = float(torch.nn.utils.clip_grad_norm_(net.parameters(), 1.0)); opt.step() + if wb is not None and step % 100 == 0: + wb.log({"train/bce": float(loss), "train/gradnorm": gn}, step=step) + if step % args.eval_every == 0 or step == args.steps: + r = evaluate(); r["step"] = step; hist.append(r) + print(f"[goal_clf] {step} bce={float(loss):.4f} val_auc={r['val_auc']:.4f} fpr@0.5={r['val_fpr@0.5']:.4f} " + f"tpr@0.5={r['val_tpr@0.5']:.4f} mean_p(goal0)={r['val_mean_p_on_goal0']:.4f} " + f"({step/(time.time()-t0):.1f} it/s)", flush=True) + if wb is not None: + wb.log({f"eval/{k}": v for k, v in r.items() if k != "step"}, step=step) + (out / "history.json").write_text(json.dumps(hist, indent=1)) + torch.save({"net": net.state_dict(), + "config": {"d_in": d.feat_dim, "width": args.width, "depth": args.depth, + "sd_floor": 0.01, "z_clip": float(getattr(d, "z_clip", 0.0)), + "label": "env_success_replay", + "privileged": "env success via state replay (ablation; RISE baselines use the 0/1 expert-membership reward)", + "task": d.tasks[0], "cache": str(args.cache), + "step": step, "goal_file": str(gf)}, + "norm": {"mu": torch.from_numpy(np.asarray(d.norm_mu, np.float32)), + "sd": torch.from_numpy(np.asarray(d.norm_sd, np.float32)), + "z_clip": float(getattr(d, "z_clip", 0.0)), "sd_floor": 0.01}, + "last_eval": r}, out / "clf.pt") + print("[goal_clf] DONE " + json.dumps(hist[-1]), flush=True) + + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/train_lewm.py b/rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/train_lewm.py new file mode 100644 index 0000000000000000000000000000000000000000..4ba8d6c9d0c0904963356c696a8d998b025acd25 --- /dev/null +++ b/rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/train_lewm.py @@ -0,0 +1,244 @@ +#!/usr/bin/env python3 +"""Train LeWM (LeWorldModel) as a best-of-N scorer for the single-actor flagship (gen_q#268). + +The objective is the reference recipe, unchanged (see lewm_model.py for the port and its declared +deviations): JEPA next-embedding prediction with an AdaLN-zero causal predictor, collapse prevented +by SIGReg alone -- no stop-gradient, no EMA target -- AdamW 5e-5 / wd 1e-3 with a global-norm clip +of 1.0, lambda_sig 0.09. + + loss = || pred_proj(predictor(emb[:, :ctx], act[:, :ctx])) - emb[:, 1:] ||^2 + + 0.09 * sigreg(emb) + +REWARD PROBE. Trained alongside on DETACHED embeddings with its own AdamW(3e-4) and a +class-balanced BCE against the provenance/membership label -- the same label RSM's membership head, +TD-Flow and DINO-WM all read. Detaching is what makes this equivalent to the reference's two-phase +fit (world model first, probe on frozen embeddings second) while costing one pass instead of two: +the probe cannot shape the representation, so the world model that results is the same one the +reference's phase 1 produces. The probe is fitted on BOTH the encoder embedding of a real frame and +the PREDICTED embedding of the next one, because scoring applies it to predicted embeddings and a +probe fitted only on encoder outputs would be evaluated off its own training distribution -- that +mismatch would weaken the baseline for a reason that has nothing to do with the world model. + +CHECKPOINT SELECTION is the rule every other scorer in the table uses: keep the checkpoint that best +RANKS ACTIONS on held-out episodes (the true chunk against a shuffled one), not the last one. + +usage: train_lewm.py --cache cache/ --out runs//wm/lewm [--size m] [--steps 100000] +""" +from __future__ import annotations + +import argparse +import json +import os as _os +import time +from pathlib import Path + +import numpy as np +import torch +import torch.nn.functional as F + +from lewm_data import StreamingFrameData +from lewm_model import (CLIP, CTX, LAMBDA, LEWM_SIZES, LR, N_PREDS, PROBE_LR, WD, LeWM, RewardProbe, + sigreg_stat) + + +def auc(score, label): + s = np.asarray(score, np.float64).ravel() + y = np.asarray(label, np.float64).ravel() > 0.5 + if y.all() or (~y).all(): + return float("nan") + r = s.argsort().argsort().astype(np.float64) + 1.0 + n1 = float(y.sum()) + n0 = float(len(y) - n1) + return float((r[y].sum() - n1 * (n1 + 1) / 2.0) / (n1 * n0)) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--cache", required=True) + ap.add_argument("--hdf5", default="", help="source HDF5; default = cache/PACK.json src") + ap.add_argument("--out", required=True) + ap.add_argument("--size", default="m", choices=list(LEWM_SIZES), help="m = the official ~15M config") + ap.add_argument("--chunk", type=int, default=8, help="action chunk the world model is conditioned on") + ap.add_argument("--ctx", type=int, default=CTX) + ap.add_argument("--res", type=int, default=84) + ap.add_argument("--batch", type=int, default=128) + ap.add_argument("--steps", type=int, default=100000, + help="the reference default is 60000; 100000 matches every other scorer in the " + "flagship table, and a baseline given MORE than its own recipe's budget is " + "the safe direction to err in") + ap.add_argument("--lr", type=float, default=LR) + ap.add_argument("--wd", type=float, default=WD) + ap.add_argument("--clip", type=float, default=CLIP) + ap.add_argument("--lambda-sig", type=float, default=LAMBDA) + ap.add_argument("--num-proj", type=int, default=1024, help="SIGReg random projections") + ap.add_argument("--probe-lr", type=float, default=PROBE_LR) + ap.add_argument("--dropout", type=float, default=0.0) + ap.add_argument("--resident", type=int, default=96, help="episodes held in RAM (no image pack)") + ap.add_argument("--refresh-every", type=int, default=8, help="steps between episode swaps") + ap.add_argument("--eval-every", type=int, default=2500) + ap.add_argument("--eval-rows", type=int, default=1024) + ap.add_argument("--save-every", type=int, default=10000) + ap.add_argument("--resume", type=int, default=1) + ap.add_argument("--seed", type=int, default=0) + ap.add_argument("--log-every", type=int, default=100) + ap.add_argument("--wandb-entity", default=_os.environ.get("RSM_WANDB_ENTITY", "")) + ap.add_argument("--wandb-project", default=_os.environ.get("RSM_WANDB_PROJECT", "rsm_rise")) + ap.add_argument("--wandb-name", default="") + ap.add_argument("--wandb-mode", default="online", choices=["online", "offline", "disabled"]) + args = ap.parse_args() + + torch.manual_seed(args.seed) + rng = np.random.default_rng(args.seed) + dev = "cuda" if torch.cuda.is_available() else "cpu" + out = Path(args.out) + out.mkdir(parents=True, exist_ok=True) + + wb = None + if args.wandb_entity and args.wandb_mode != "disabled": + try: + import hashlib + + import wandb + _rid = hashlib.md5(str(out.resolve()).encode()).hexdigest()[:16] + wb = wandb.init(entity=args.wandb_entity, project=args.wandb_project, + name=args.wandb_name or out.name, id=_rid, resume="allow", + mode=args.wandb_mode, config=vars(args), dir=str(out)) + print(f"[lewm] wandb: {wb.url}", flush=True) + except Exception as e: + print(f"[lewm] wandb disabled: {e}", flush=True) + + d = StreamingFrameData(args.cache, args.hdf5, chunk=args.chunk, ctx=args.ctx, n_preds=N_PREDS, + resident=args.resident, refresh_every=args.refresh_every, seed=args.seed, + res=args.res) + d_act = d.d_act + model = LeWM(size=args.size, a_dim=d_act, in_ch=6, res=args.res, ctx=args.ctx, + dropout=args.dropout).to(dev) + probe = RewardProbe(model.emb_dim).to(dev) + opt = torch.optim.AdamW(model.parameters(), lr=args.lr, weight_decay=args.wd) + popt = torch.optim.AdamW(probe.parameters(), lr=args.probe_lr) + n_par = sum(p.numel() for p in model.parameters()) + print(f"[lewm] size={args.size} emb={model.emb_dim} params={n_par/1e6:.1f}M d_act={d_act} " + f"enc_stages={model.encoder.n_stages} enc_res={model.encoder.out_res} dev={dev}", flush=True) + + pos = float(d.ep_success.mean()) + pos_w = torch.tensor(max((1 - pos) / max(pos, 1e-6), 1.0), device=dev) + + start_step, best_win, hist = 0, -1.0, [] + ck = out / "ckpt.pt" + if args.resume and ck.exists(): + c = torch.load(ck, map_location=dev, weights_only=False) + model.load_state_dict(c["lewm"]) + probe.load_state_dict(c["probe"]) + if "opt" in c: + opt.load_state_dict(c["opt"]) + if "popt" in c: + popt.load_state_dict(c["popt"]) + start_step = int(c["step"]) + best_win = c.get("best_win", -1.0) + hist = c.get("hist", []) + rng = np.random.default_rng(args.seed + 9973 * start_step) + print(f"[lewm] RESUMED at step {start_step}/{args.steps} (best win {best_win:.3f})", flush=True) + if start_step >= args.steps: + print("[lewm] already complete", flush=True) + return + + @torch.no_grad() + def evaluate(): + model.eval(); probe.eval() + b = d.sample(min(args.eval_rows, 512), rng, "val", dev) + pred, emb = model(b["frames"], b["actions"]) + pl = float((pred - emb[:, N_PREDS:]).pow(2).mean()) + # does the probe on the PREDICTED embedding rank the true chunk above a shuffled one? + hist_emb = emb[:, : args.ctx] + a_true = b["actions"][:, : args.ctx] + perm = torch.randperm(a_true.shape[0], device=dev) + z_true = model.step_emb(hist_emb, a_true) + z_shuf = model.step_emb(hist_emb, a_true[perm]) + q_true = torch.sigmoid(probe(z_true)) + q_shuf = torch.sigmoid(probe(z_shuf)) + win = float((q_true > q_shuf).float().mean()) + gap = float((q_true - q_shuf).mean()) + pr = torch.sigmoid(probe(emb[:, args.ctx])).float().cpu().numpy() + a_ = auc(pr, b["label"].cpu().numpy()) + std = float(emb.reshape(-1, emb.shape[-1]).std(0).min()) + model.train(); probe.train() + return {"pred_mse_val": pl, "probe_auc": a_, "action_win": win, "action_gap": gap, + "emb_std_min": std} + + t0 = time.time() + model.train(); probe.train() + for step in range(start_step + 1, args.steps + 1): + b = d.sample(args.batch, rng, "train", dev) + pred, emb = model(b["frames"], b["actions"]) + # NOT detached: the target is the live encoder's own output. This is the recipe. + tgt = emb[:, N_PREDS:] + l_pred = (pred - tgt).pow(2).mean() + l_sig = sigreg_stat(emb.permute(1, 0, 2), num_proj=args.num_proj) + loss = l_pred + args.lambda_sig * l_sig + opt.zero_grad(set_to_none=True) + loss.backward() + gn = float(torch.nn.utils.clip_grad_norm_(model.parameters(), args.clip)) + opt.step() + + # ---- reward probe on DETACHED embeddings (see the module docstring) ---- + with torch.no_grad(): + z_enc = emb[:, args.ctx].detach() + z_pred = pred[:, -1].detach() + lg = probe(z_enc) + lg2 = probe(z_pred) + l_probe = 0.5 * (F.binary_cross_entropy_with_logits(lg, b["label"], pos_weight=pos_w) + + F.binary_cross_entropy_with_logits(lg2, b["label"], pos_weight=pos_w)) + popt.zero_grad(set_to_none=True) + l_probe.backward() + gn_p = float(torch.nn.utils.clip_grad_norm_(probe.parameters(), args.clip)) + popt.step() + + if step % 500 == 0: + print(f"[lewm] {step} pred={float(l_pred):.5f} sig={float(l_sig):.5f} " + f"probe={float(l_probe):.4f} gradnorm={gn:.3f} gradnorm_probe={gn_p:.3f} " + f"({step/(time.time()-t0):.2f} it/s)", flush=True) + if wb is not None and (step % args.log_every == 0 or step == 1): + wb.log({"train/loss": float(loss), "train/l_pred": float(l_pred), + "train/l_sigreg": float(l_sig), "train/l_probe": float(l_probe), + "train/gradnorm": gn, "train/gradnorm_probe": gn_p, + "train/it_per_s": step / max(time.time() - t0, 1e-6)}, step=step) + + if step % args.eval_every == 0 or step == args.steps: + e = evaluate() + hist.append({"step": step, **e}) + (out / "history.json").write_text(json.dumps(hist, indent=1)) + print(f"[lewm] EVAL {step}: pred_mse={e['pred_mse_val']:.5f} probe_auc={e['probe_auc']:.4f} " + f"ACTION win={e['action_win']:.3f} gap={e['action_gap']:+.5f} " + f"emb_std_min={e['emb_std_min']:.4f}", flush=True) + if wb is not None: + wb.log({f"eval/{k}": v for k, v in e.items()}, step=step) + blob = {"model": "lewm", "lewm": model.state_dict(), "probe": probe.state_dict(), + "config": vars(args), "arch": {"size": args.size, "emb_dim": model.emb_dim, + "a_dim": d_act, "in_ch": 6, "res": args.res, + "ctx": args.ctx, "chunk": args.chunk, + "adim": d.adim}, + "d_act": d_act, "step": step, "q_action_winrate": e["action_win"], + "cams": list(d.cams), "hdf5": d.hdf5, "cache": str(d.root)} + blob_r = dict(blob) + blob_r["opt"] = opt.state_dict(); blob_r["popt"] = popt.state_dict() + blob_r["best_win"] = max(best_win, e["action_win"]); blob_r["hist"] = hist + tmp = out / "ckpt.pt.tmp" + torch.save(blob_r, tmp) + _os.replace(tmp, out / "ckpt.pt") + if args.save_every and step % args.save_every == 0: + torch.save(blob, out / f"ckpt_s{step}.pt") + # A collapsed representation can rank actions by accident; require a live embedding. + healthy = e["emb_std_min"] > 1e-3 + if e["action_win"] > best_win and healthy: + best_win = e["action_win"] + torch.save(blob, out / "ckpt_best.pt") + print(f"[lewm] new BEST action winrate {best_win:.3f} at step {step}", flush=True) + elif not healthy: + print(f"[lewm] emb_std_min {e['emb_std_min']:.2e}: representation near collapse, " + f"NOT eligible as best", flush=True) + d.close() + print("[lewm] DONE", flush=True) + + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/train_rsm.py b/rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/train_rsm.py new file mode 100644 index 0000000000000000000000000000000000000000..175d4eaf2ddb92a1b0290ba491a292da250e0521 --- /dev/null +++ b/rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/train_rsm.py @@ -0,0 +1,1287 @@ +"""Joint reward-latent + action-conditioned occupancy training (RSM) on LIBERO-10. + +No TD target, no return regression: the occupancy target is a REAL logged future +frame drawn at k ~ Geom(1-beta), and reward enters only at read-out. + +Diagnostics follow COLLAPSE_ANALYSIS: batch losses can look healthy while the +critic is useless, so the headline validation metric is the ACTION-ranking gap +(does Q prefer the logged chunk over a foreign chunk at the same state), not the +state-ranking AUC. +""" +from __future__ import annotations +import sys as _sys, os as _os +_sys.path.insert(0, _os.path.dirname(_os.path.abspath(__file__))) +import os as _os +import argparse, json, time +from pathlib import Path +import numpy as np +import torch +import torch.nn.functional as F + +from model import (Encoder, RewardHead, OccFlow, ema_update) +from model import mlp, IdentityEncoder, PCAEncoder +from data import LiberoRSMData + + +def auc(score, label): + score = np.asarray(score, np.float64); label = np.asarray(label) > 0.5 + if label.all() or (~label).all(): + return float("nan") + order = np.argsort(score) + ranks = np.empty(len(score), np.float64); ranks[order] = np.arange(1, len(score) + 1) + npos = int(label.sum()); nneg = len(label) - npos + return float((ranks[label].sum() - npos * (npos + 1) / 2) / (npos * nneg)) + + +@torch.no_grad() +def sample_future(flow, enc_z, a, task, beta, rms, n_steps=8, n=1, x0=None): + """Euler ODE sample of the residual, returned as an absolute latent. + x0: optional initial noise [rows, D] -- lets a caller share the same draws across + candidates (common random numbers) so a comparison of Q values is paired.""" + B, D = enc_z.shape + 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.pt every N steps (checkpoint selection on validation inits)") + ap.add_argument("--reward-mode", default="dense", choices=["dense","terminal","soft","subgoal","subgoal_ind"], + help="dense = P(task succeeds|z), every frame of a success is a " + "positive (~50%%). terminal = last k frames only (~0.5%%), which " + "leaves Q near-constant in the action.") + ap.add_argument("--reward-npy", default="", + help="path to a float32 [n_frames] .npy of per-frame reward labels that " + "REPLACES --reward-mode entirely (rsm_rise #261 reward-head study)") + ap.add_argument("--action-augment", type=float, default=0.0, + help="RISE state-space kNN COUNTERFACTUAL ACTION AUGMENTATION (rsm_rise #279): " + "distance_threshold in the metric --augment-table was built in. 0 = OFF, and " + "with it off the sampler draws EXACTLY what it always did. See the block in " + "data.py for why the model needs counterfactual (s, a) pairs at all.") + ap.add_argument("--augment-mode", default="contrastive", choices=["contrastive", "invariant"], + help="contrastive = the counterfactual action carries the NEIGHBOUR's own future " + "(RISE's intent lifted to an occupancy model). invariant = the neighbour's " + "action is asserted to lead to the ANCHOR's future (the literal transcription " + "of next_obs = original next_obs); safe only if the neighbourhood is smaller " + "than the action gap the value must resolve.") + ap.add_argument("--augment-table", default="", + help="npz from scripts/real/build_aug_knn.py (rows/nbr_row/nbr_dist). Built ONCE, " + "uncapped by any threshold, so a whole threshold sweep reads one file. " + "Default: /aug_knn_feat.npz") + ap.add_argument("--augment-frac-cap", type=float, default=0.0, + help="upper bound on the AUGMENTED SHARE of each batch (0 = off = pure " + "proportional mixing). Proportional mixing is still the default -- RISE's " + "epoch%%2 alternation is the 457x-replay pathology -- but on this corpus the " + "k=15 pool is 15x the logged corpus, so proportional put 93%% of gradient " + "steps on counterfactual rows. This cap isolates aug_frac from the " + "relabelling as the explanatory variable (rsm_rise #279 run 5).") + ap.add_argument("--augment-neighbors", type=int, default=15, + help="RISE's num_neighbors: the cap is applied to the NEAREST different-episode " + "frames FIRST, then the threshold, exactly as RISE does it.") + ap.add_argument("--weight-npy", default="", + help="path to a float32 [n_frames] .npy of per-frame REWARD-LOSS sample " + "weights (gen_q #271 scheme C: w_neg on the S5/S6 hard negatives). " + "Affects the reward BCE only; unset = all ones = the old loss.") + ap.add_argument("--resume", type=int, default=1, + help="continue from /ckpt.pt if present. A 500k-step run " + "cannot fit one slurm window, so the run MUST be " + "restartable or the chain silently retrains from zero.") + ap.add_argument("--w-rrank", type=float, default=0.0, + help="weight on the READ-OUT RANKING loss (the port uses 2.0). " + "Ranks the success logit of a hop sampled under the REAL " + "action above one sampled under a shuffled action. This is " + "the action win rate we have only ever MEASURED; this term " + "optimises it. Hops are stop-grad, so it trains the reward " + "tower only and cannot corrupt the occupancy field. Distinct " + "from --w-actcon, which contrasts flow-matching ERRORS rather " + "than the success logits the Q read-out consumes.") + ap.add_argument("--rrank-tau", type=float, default=0.1) + ap.add_argument("--cache2", default="", help="second pack mixed into training batches (see below)") + ap.add_argument("--mix2", type=float, default=0.25, help="fraction of each training batch from --cache2") + ap.add_argument("--subgoal-dir2", default="", help="subgoal labels for --cache2") + ap.add_argument("--subgoal-dir", default="", + help="per-frame satisfied-subgoal labels from label_subgoals.py. " + "Required for --reward-mode subgoal, which is the only mode " + "whose target is a function of the state.") + ap.add_argument("--success-mask", default="", + help="admissibility mask from merge_verify.py. Logged successes " + "that do not reproduce in the eval environment are treated " + "as failures, so no reward is built for them.") + ap.add_argument("--seed", type=int, default=0) + ap.add_argument("--in-ram", type=int, default=1) + ap.add_argument("--wandb-entity", default=_os.environ.get("RSM_WANDB_ENTITY", ""), + help="W&B entity; '' (the default) disables W&B logging entirely. " + "rsm_rise sets RSM_WANDB_ENTITY=richardrl via its own wandb_env.sh; " + "nothing else changes, so other users of this script are unaffected.") + ap.add_argument("--wandb-project", default=_os.environ.get("RSM_WANDB_PROJECT", "rsm_rise")) + ap.add_argument("--wandb-name", default="", + help="run name (default: basename of --out)") + ap.add_argument("--wandb-mode", default="online", choices=["online", "offline", "disabled"]) + ap.add_argument("--wandb-id-salt", default="", + help="mixed into the run id (md5 of --out [+ salt]). A relaunch into the SAME --out after " + "deleting it would otherwise resume the old W&B run, whose step counter is ahead, " + "and W&B silently drops every log below that step.") + ap.add_argument("--log-every", type=int, default=100, + help="train-loss / grad-norm logging period (steps)") + ap.add_argument("--enc", default="mlp", choices=["mlp", "identity"], + help="identity: no learned encoder -- lat(x) = x (the z-scored cache feature, " + "d_z = feature dim), no EMA target, variance floor 0, reward warm-up 0. " + "For frozen foundation-model features modelled directly (rsm_rise DINO).") + ap.add_argument("--eval-minmse-n", type=int, default=0, + help="N>0: at every eval draw N futures per row (sample_future n=N) on a train " + "and a val batch of 2048 rows and log minmse_{train,val} = mean_rows min_i " + "|x'_i - x_{t+K}|^2/d in the latent the flow predicts in (identity: the " + "z-scored state), plus meanmse_* and staymse_* (x' = x_t). The fit criterion.") + ap.add_argument("--pca-dim", type=int, default=0, + help="k>0: fixed PCA map of the (z-scored) state to k dims, fitted on training frames " + "(model.PCAEncoder, stored in the checkpoint). Flow and reward head work in PCA " + "space; minmse is reported there AND mapped back to the full state (minmse_full_*).") + ap.add_argument("--pca-fit-frames", type=int, default=40000, help="training frames (strided) used to fit the PCA") + ap.add_argument("--flow-dropout", type=float, default=0.0, help="dropout inside the flow's residual blocks") + ap.add_argument("--flow-norm", type=int, default=0, + help="1: LayerNorm in the flow's residual blocks and before its output (model.OccFlow norm=True)") + ap.add_argument("--wd", type=float, default=0.01, help="AdamW weight decay (was hard-coded 0.01)") + ap.add_argument("--sample-clip", type=float, default=0.0, + help="clamp the sampled future latent to +-this in the diagnostics (0 = off). With " + "--enc identity the state itself is clip(+-z_clip), so clamping the sample to the " + "same box only removes off-manifold divergence of the Euler integration.") + ap.add_argument("--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() diff --git a/rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/train_rsm_dwm.py b/rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/train_rsm_dwm.py new file mode 100644 index 0000000000000000000000000000000000000000..5dd50da63f76cc8fb3e5eb04adf1e1bbc8f1f19b --- /dev/null +++ b/rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/train_rsm_dwm.py @@ -0,0 +1,765 @@ +"""DWM successor-model trainer: DINO-WM's ViT predictor, trained by conditional flow matching +to output beta-discounted successors in DINOv2 token space (LAUNCH_MATRIX rev. 4, Stage 1). + +Interface-compatible with train_rsm.py: same flags where they exist, same console prints, +same history.json keys (plus the min-MSE fit criterion), same W&B convention, same +ckpt.pt / ckpt_best.pt / ckpt_s.pt files. Multi-GPU by torchrun (DDP, one node): + + torchrun --standalone --nproc_per_node 8 train_rsm_dwm.py --cache cache/ \ + --out runs//rsm/DWM --batch 4096 --steps 100000 ... + +Run without torchrun for a single process. The token cache is memory-mapped, so the 8 +ranks share one page-cache copy of tok.f16.npy. +""" +from __future__ import annotations +import sys as _sys, os as _os +_sys.path.insert(0, _os.path.dirname(_os.path.abspath(__file__))) +import argparse, copy, datetime, json, queue, threading, time +from pathlib import Path +import numpy as np +import torch +import torch.distributed as dist +import torch.nn.functional as F + +from model import ema_update +from train_rsm import auc +from dwm_model import (DWM, DWMReward, Normalizer, TokenRSMData, sample_future_dwm, + N_TOK, D_TOK, RHO_FLOOR, Y_CLIP, SD_FLOOR, Z_CLIP) + + +# --------------------------------------------------------------------------- # +# distributed helpers +# --------------------------------------------------------------------------- # +def ddp_setup(): + if "WORLD_SIZE" in _os.environ and int(_os.environ["WORLD_SIZE"]) > 1: + backend = "nccl" if torch.cuda.is_available() else "gloo" + dist.init_process_group(backend, timeout=datetime.timedelta(minutes=120)) + rank, world = dist.get_rank(), dist.get_world_size() + local = int(_os.environ.get("LOCAL_RANK", 0)) + else: + rank, world, local = 0, 1, 0 + if torch.cuda.is_available(): + torch.cuda.set_device(local) + dev = torch.device("cuda", local) + else: + dev = torch.device("cpu") + return rank, world, local, dev + + +def _all_reduce_mean(t): + if dist.is_initialized(): + dist.all_reduce(t, op=dist.ReduceOp.SUM); t /= dist.get_world_size() + return t + + +def _gather_cat(t): + """all_gather equal-sized shards -> concatenated on every rank (order = rank order).""" + if not dist.is_initialized(): + return t + out = [torch.empty_like(t) for _ in range(dist.get_world_size())] + dist.all_gather(out, t.contiguous()) + return torch.cat(out, 0) + + +def _barrier(): + if dist.is_initialized(): + dist.barrier() + + +# --------------------------------------------------------------------------- # +# background batch prefetch (memmap gather + pinned H2D overlap the ViT step) +# --------------------------------------------------------------------------- # +class Prefetcher: + def __init__(self, data, rng, batch, beta_lo, beta_hi, device, n_slots=3, onestep=False): + self.d, self.rng, self.batch = data, rng, batch + # onestep (DINO-WM, gen_q#268): the target frame is the anchor plus ONE action chunk, not a + # draw from the beta-discounted occupancy. The anchor draw itself is untouched, so a + # latent-MSE run and a flow run see the same episodes and the same anchors. + self.onestep = onestep + self.lo, self.hi, self.dev = beta_lo, beta_hi, device + self.n = n_slots + self.slots = [None] * n_slots; self.events = [None] * n_slots + self.q = queue.Queue(maxsize=n_slots - 1) + self.stop = False + self.pin = device.type == "cuda" + self.th = threading.Thread(target=self._run, daemon=True); self.th.start() + + def _run(self): + i = 0 + while not self.stop: + s = i % self.n + if self.stop: + break + ev = self.events[s] + if ev is not None: + ev.synchronize() + e, t, fut, beta = self.d.draw(self.batch, self.rng, self.lo, self.hi, "train") + if self.onestep: + fut, beta = _onestep_future(self.d, e, t) + b = self.d.gather(e, t, fut, beta) + tens = {k: v for k, v in b.items() if torch.is_tensor(v)} + meta = {k: v for k, v in b.items() if not torch.is_tensor(v)} + if self.slots[s] is None: + self.slots[s] = {k: (torch.empty_like(v).pin_memory() if self.pin else torch.empty_like(v)) + for k, v in tens.items()} + for k, v in tens.items(): + self.slots[s][k].copy_(v) + self.q.put((s, meta)) + i += 1 + # leave the pinned buffers alive until the main thread's pending H2D copies are done + for ev in self.events: + if ev is not None: + try: + ev.synchronize() + except Exception: + pass + + def next(self): + s, meta = self.q.get() + out = {k: v.to(self.dev, non_blocking=True, copy=True) for k, v in self.slots[s].items()} + if self.pin: + ev = torch.cuda.Event(); ev.record(); self.events[s] = ev + out.update(meta) + return out + + def close(self): + """Stop and JOIN the worker: returning from main while the thread is inside a numpy/torch + copy aborts the interpreter at teardown ('terminate called without an active exception').""" + self.stop = True + for _ in range(600): # drain until the thread has left its loop + try: + while True: + self.q.get_nowait() + except queue.Empty: + pass + self.th.join(timeout=0.1) + if not self.th.is_alive(): + break + + +# --------------------------------------------------------------------------- # +def _onestep_future(d, e, t): + """(fut, beta) for the DINO-WM one-step target: the frame one ACTION CHUNK ahead. + + A DINO-WM hop is one chunk of `d.chunk` frames (0.4 s at 20 Hz), which is what the action the + model is conditioned on actually covers -- whereas an RSM/DWM hop spans 1/(1-beta) frames. That + is why gen_q#268 matches the two scorers on the NUMBER of hops (L in {1,2,4,8}) and not on beta: + a latent-dynamics model has no beta. beta is returned as ZERO so the predictor's beta + conditioning is a constant on this path and carries no information; the read-out passes the same + constant, so training and scoring agree. + Clamped to the episode's last frame: a terminal anchor predicts itself rather than the first + frame of the next episode. + """ + hi = d.ep_to[e] + fut = np.minimum(t + d.chunk, hi - 1) + return fut, np.zeros(len(t), dtype=np.float64) + + +def cfm_terms(model, norm, rms_tok, rms_pr, b, k=None, noise=None, perm=None, x_noise=0.0, + dynamics="flow"): + """Flow-matching pieces on one (micro-)batch. Returns dict with per-row errors. + x_noise: Gaussian noise (z-scored units) on the CONDITIONING state only (train_rsm.py's + --x-noise); the residual target is built from the clean state.""" + tok_now = norm.tok(b["tok_now"]); tok_fut = norm.tok(b["tok_fut"]) + pr_now = norm.pr(b["pr_now"]); pr_fut = norm.pr(b["pr_fut"]) + B = tok_now.shape[0] + y_tok = ((tok_fut - tok_now) / rms_tok).clamp(-Y_CLIP, Y_CLIP) # rms floored at RHO_FLOOR + y_pr = ((pr_fut - pr_now) / rms_pr).clamp(-Y_CLIP, Y_CLIP) + tok_now_clean, pr_now_clean = tok_now, pr_now + if x_noise > 0: + tok_now = tok_now + x_noise * torch.randn_like(tok_now) + pr_now = pr_now + x_noise * torch.randn_like(pr_now) + if dynamics == "latent_mse": + return _latent_mse_terms(model, b, tok_now, pr_now, tok_now_clean, pr_now_clean, + tok_fut, pr_fut, rms_tok, rms_pr, y_tok, y_pr, perm) + if k is None: + k = torch.rand(B, device=tok_now.device) + if noise is None: + noise = (torch.randn_like(y_tok), torch.randn_like(y_pr)) + n_tok, n_pr = noise + xk_tok = (1 - k)[:, None, None] * y_tok + k[:, None, None] * n_tok + xk_pr = (1 - k)[:, None] * y_pr + k[:, None] * n_pr + u_tok, u_pr = y_tok - n_tok, y_pr - n_pr + v_tok, v_pr = model(tok_now, pr_now, b["a_now"], b["beta"], xk_tok, xk_pr, k) + e_tok = (v_tok.float() - u_tok).pow(2).mean((-1, -2)) # [B] + e_pr = (v_pr.float() - u_pr).pow(2).mean(-1) if u_pr.shape[1] else torch.zeros_like(e_tok) + out = {"e_tok": e_tok, "e_pr": e_pr, "tok_now": tok_now, "pr_now": pr_now, + "tok_fut": tok_fut, "pr_fut": pr_fut, "y_tok": y_tok, "y_pr": y_pr} + if perm is not None: + v_tok2, v_pr2 = model(tok_now, pr_now, b["a_now"][perm], b["beta"], xk_tok, xk_pr, k) + out["e_tok_neg"] = (v_tok2.float() - u_tok).pow(2).mean((-1, -2)) + out["e_pr_neg"] = (v_pr2.float() - u_pr).pow(2).mean(-1) if u_pr.shape[1] else torch.zeros_like(e_tok) + return out + + +def _latent_mse_terms(model, b, tok_now, pr_now, tok_now_clean, pr_now_clean, tok_fut, pr_fut, + rms_tok, rms_pr, y_tok, y_pr, perm): + """DINO-WM's objective: DETERMINISTIC next-latent prediction under latent MSE (gen_q#268). + + Same predictor, same frozen DINOv2 patch features, same normaliser, same reward head -- the ONLY + thing that changes against the flow path is what the network regresses: + + flow : v_theta(x_k | s, a, beta, k) -> the conditional flow-matching velocity of the + normalised residual toward a draw from the beta-discounted occupancy + latent_mse : f_theta(s, a) -> the next latent one action chunk ahead, scored by + || f_theta(s,a) - s' ||^2 in the z-scored DINO latent space + + The predictor is queried at ONE fixed point of its flow-time/noise inputs (x_k = 0, k = 0), so + the "future" half of its token sequence is a learned query attending to the current frame's + patch tokens under the action embedding -- which is exactly DINO-WM's structure: a causal + transformer predicting the next frame's patch features from this frame's plus the action. + + HISTORY LENGTH. DINO-WM conditions on 3 frames; this port conditions on 1, and that is forced by + the evaluation protocol rather than chosen: the planner hands a scorer the SINGLE current frame + (`obs_t = {k: v[:, -1] ...}` in rsm_planner.plan_get_action), so a history-3 world model could + not be evaluated here at all without changing what every other scorer sees. It is a declared + deviation, not a silent one. + + The residual parameterisation (predict rms * v and add the current latent) is kept from the flow + path so the two share their conditioning and their output scale; it is a reparameterisation of + the same prediction and the LOSS is in the latent space, unclamped, as latent MSE requires. + """ + zeros_tok = torch.zeros_like(y_tok) + zeros_pr = torch.zeros_like(y_pr) + kz = torch.zeros(tok_now.shape[0], device=tok_now.device) + bz = torch.zeros_like(b["beta"]) + + def _pred(a): + v_tok, v_pr = model(tok_now, pr_now, a, bz, zeros_tok, zeros_pr, kz) + p_tok = tok_now_clean.float() + rms_tok * v_tok.float() + p_pr = (pr_now_clean.float() + rms_pr * v_pr.float()) if v_pr.shape[1] else v_pr.float() + return p_tok, p_pr + + p_tok, p_pr = _pred(b["a_now"]) + e_tok = (p_tok - tok_fut.float()).pow(2).mean((-1, -2)) + e_pr = (p_pr - pr_fut.float()).pow(2).mean(-1) if p_pr.shape[1] else torch.zeros_like(e_tok) + out = {"e_tok": e_tok, "e_pr": e_pr, "tok_now": tok_now, "pr_now": pr_now, + "tok_fut": tok_fut, "pr_fut": pr_fut, "y_tok": y_tok, "y_pr": y_pr} + if perm is not None: + n_tok, n_pr = _pred(b["a_now"][perm]) + out["e_tok_neg"] = (n_tok - tok_fut.float()).pow(2).mean((-1, -2)) + out["e_pr_neg"] = ((n_pr - pr_fut.float()).pow(2).mean(-1) if n_pr.shape[1] + else torch.zeros_like(e_tok)) + return out + + +def per_row_cfm(e_tok, e_pr, n_tok=N_TOK): + """One CFM number per row: mean over the 515 'tokens' of the per-token MSE.""" + return (n_tok * e_tok + e_pr) / (n_tok + 1) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--cache", required=True, help="cache/; reads tokens/tok.f16.npy from it") + ap.add_argument("--tokens", default="", help="override: directory holding tok.f16.npy") + ap.add_argument("--tok-rows", default="", + help="row-index .npy mapping THIS cache's frames into --tokens' file, for a " + "cache that is a row slice of a parent (cache/square_sub_20100 of " + "cache/square_expert_suboptimal). Avoids a multi-GB copy of the parent's " + "token file; token normalisation is then fitted on our rows and cached in " + "OUR cache dir, not the parent's.") + ap.add_argument("--out", required=True) + ap.add_argument("--depth", type=int, default=6) + ap.add_argument("--heads", type=int, default=16) + ap.add_argument("--dim-head", type=int, default=64) + ap.add_argument("--mlp", type=int, default=2048) + ap.add_argument("--dropout", type=float, default=0.1, help="DINO-WM's predictor dropout") + ap.add_argument("--grad-ckpt", type=int, default=0, + help="activation checkpointing per transformer layer (memory for ~30%% compute)") + ap.add_argument("--chunk", type=int, default=8) + ap.add_argument("--beta-lo", type=float, default=0.90) + ap.add_argument("--beta-hi", type=float, default=0.995) + ap.add_argument("--beta-q", type=float, default=0.95, help="query beta for diagnostics") + ap.add_argument("--batch", type=int, default=4096, help="GLOBAL batch (split over ranks)") + ap.add_argument("--micro", type=int, default=256, help="rows per forward on one GPU (grad accumulation)") + ap.add_argument("--steps", type=int, default=100000) + ap.add_argument("--lr", type=float, default=3e-4) + ap.add_argument("--wd", type=float, default=0.01) + ap.add_argument("--ema", type=float, default=0.995) + ap.add_argument("--w-reward", type=float, default=1.0) + ap.add_argument("--flow-steps", type=int, default=8) + ap.add_argument("--w-actcon", type=float, default=0.5, + help="action-contrastive weight (train_rsm.py): softplus(e_pos - e_neg) " + "with e_neg the CFM error under a within-batch permuted chunk") + ap.add_argument("--actcon-rows", type=int, default=0, + help="rows per micro-batch that get the (second, full-gradient) negative " + "forward; 0 = all rows") + ap.add_argument("--tok-drop", type=float, default=0.0, + help="training-time dropout of whole 'now' tokens (regulariser probe)") + ap.add_argument("--x-noise", type=float, default=0.0, + help="Gaussian noise (z-scored units) on the conditioning state during training " + "(train_rsm.py's --x-noise; stream B's regulariser against episode memorisation)") + ap.add_argument("--eval-every", type=int, default=5000) + ap.add_argument("--eval-minmse-n", type=int, default=16) + ap.add_argument("--eval-rows", type=int, default=2048) + ap.add_argument("--eval-frames", type=int, default=1024) + ap.add_argument("--success-gamma", type=float, default=0.98) + ap.add_argument("--reward-loss", default="bce", choices=["bce"]) + ap.add_argument("--reward-mode", default="dense", choices=["dense", "soft", "goal"], + help="goal = env-success-by-replay per-frame label (cache//goal.npz): a goal-STATE classifier") + ap.add_argument("--goal-file", default="", help="goal.npz for --reward-mode goal (default /goal.npz)") + ap.add_argument("--save-every", type=int, default=10000) + ap.add_argument("--resume", type=int, default=1) + ap.add_argument("--seed", type=int, default=0) + ap.add_argument("--in-ram", type=int, default=0, help="copy the token memmap into RAM per rank") + ap.add_argument("--warm-cache", type=int, default=1, help="sequential read of the token file " + "on local rank 0 before training (page cache)") + ap.add_argument("--wandb-entity", default=_os.environ.get("RSM_WANDB_ENTITY", "")) + ap.add_argument("--wandb-project", default=_os.environ.get("RSM_WANDB_PROJECT", "rsm_rise")) + ap.add_argument("--wandb-name", default="") + ap.add_argument("--wandb-mode", default="online", choices=["online", "offline", "disabled"]) + ap.add_argument("--log-every", type=int, default=100) + ap.add_argument("--print-every", type=int, default=100) + ap.add_argument("--compile", type=int, default=0, help="torch.compile the training forward") + ap.add_argument("--allow-old-pack", type=int, default=0, + help="run even if PACK.json lacks the final state-definition keys (probes only)") + # DINO-WM (gen_q#268): the DYNAMICS objective. `flow` (default) is unchanged DWM -- the + # beta-discounted successor fitted by conditional flow matching. `latent_mse` is DINO-WM: + # deterministic next-latent prediction one action chunk ahead, scored by MSE in the frozen + # DINOv2 latent space. Everything else (predictor, features, normaliser, reward head, + # optimiser, steps) is identical, so the pair isolates the dynamics model. + ap.add_argument("--dynamics", default="flow", choices=["flow", "latent_mse"], + help="flow = DWM's occupancy flow matching (DEFAULT, unchanged); " + "latent_mse = DINO-WM's deterministic next-latent prediction") + ap.add_argument("--time-steps", type=int, default=0, + help="if >0: run this many steps, print s/step and exit (throughput probe)") + args = ap.parse_args() + + rank, world, local, dev = ddp_setup() + is_main = rank == 0 + torch.manual_seed(args.seed * 1000 + rank) + out = Path(args.out) + if is_main: + out.mkdir(parents=True, exist_ok=True) + per_rank = args.batch // world + assert per_rank * world == args.batch, f"--batch {args.batch} not divisible by {world} ranks" + micro = min(args.micro, per_rank) + n_micro = per_rank // micro + assert n_micro * micro == per_rank, f"per-rank batch {per_rank} not divisible by --micro {micro}" + use_cuda = dev.type == "cuda" + ac = (lambda: torch.autocast("cuda", dtype=torch.bfloat16)) if use_cuda else (lambda: torch.autocast("cpu", enabled=False)) + + # ---- W&B (rank 0; entity/project from wandb_env.sh; resumable by run id) ---- + wb = None + if is_main and args.wandb_entity and args.wandb_mode != "disabled": + try: + import wandb, hashlib + _rid = hashlib.md5(str(out.resolve()).encode()).hexdigest()[:16] + wb = wandb.init(entity=args.wandb_entity, project=args.wandb_project, + name=args.wandb_name or out.name, id=_rid, resume="allow", + mode=args.wandb_mode, config=vars(args), dir=str(out)) + print(f"[dwm] wandb: {wb.url}", flush=True) + except Exception as e: + print(f"[dwm] wandb disabled: {e}", flush=True) + wb = None + + def _flat(prefix, obj, acc): + if isinstance(obj, dict): + for k, v in obj.items(): + _flat(f"{prefix}/{k}" if prefix else str(k), v, acc) + elif isinstance(obj, (int, float)): + acc[prefix] = float(obj) + return acc + + # ---- data ---- + # The action-contrastive auxiliary is OUR addition to the flow recipe, not part of DINO-WM. A + # latent-MSE run left at the flow default would therefore be "DINO-WM plus an auxiliary we + # invented", which is not the published comparator, so it is switched off unless the caller asks + # for it explicitly. Pass --w-actcon to override (and say so in any table that uses it). + if args.dynamics == "latent_mse" and abs(args.w_actcon - ap.get_default("w_actcon")) < 1e-12: + print(f"[dwm] --dynamics latent_mse: --w-actcon {args.w_actcon} -> 0.0 " + f"(DINO-WM is latent MSE only; pass --w-actcon explicitly to keep the auxiliary)", + flush=True) + args.w_actcon = 0.0 + if args.dynamics == "latent_mse": + print("[dwm] DYNAMICS = latent_mse (DINO-WM): deterministic next-latent prediction one " + f"chunk ({args.chunk} frames) ahead, latent MSE in the z-scored DINOv2 space; " + "beta conditioning is a constant 0 on this path", flush=True) + tokens_file = str(Path(args.tokens) / "tok.f16.npy") if args.tokens else "" + try: + _pack = json.loads((Path(args.cache) / "PACK.json").read_text()) + except Exception: + _pack = {} + if not args.allow_old_pack and not ("sd_floor" in _pack and "z_clip" in _pack): + raise SystemExit(f"[dwm] {args.cache}/PACK.json lacks 'sd_floor'/'z_clip' (the final Stage-1 state " + f"definition); refusing to launch. Pass --allow-old-pack 1 for probes.") + if _pack and is_main: + print(f"[dwm] PACK.json: sd_floor={_pack.get('sd_floor')} z_clip={_pack.get('z_clip')} " + f"(token space uses sd_floor={SD_FLOOR} z_clip={Z_CLIP} rho_floor={RHO_FLOOR} y_clip={Y_CLIP})", flush=True) + if rank != 0: + _barrier() # rank 0 fits + writes tok_stats.npz first; the others then load it + d = TokenRSMData(args.cache, chunk=args.chunk, seed=args.seed, reward_mode=args.reward_mode, + success_gamma=args.success_gamma, in_ram=bool(args.in_ram), + tokens_file=tokens_file, goal_file=args.goal_file, tok_rows=args.tok_rows) + if rank == 0: + _barrier() + if is_main: + try: + print(f"[dwm] host {_os.uname().nodename}: {len(_os.sched_getaffinity(0))} cpus in affinity mask, " + f"{torch.cuda.device_count() if use_cuda else 0} gpus visible", flush=True) + except Exception: + pass + print(f"[dwm] {d.n_ep} eps ({len(d.train_eps)} train / {len(d.val_eps)} val), " + f"{d.n_task} tasks, tokens={tuple(d.tok.shape)} proprio={d.n_pr}, " + f"positives={d.r.mean():.4f}, world={world} batch={args.batch} " + f"({per_rank}/rank, micro {micro} x {n_micro})", flush=True) + if args.warm_cache and not args.in_ram and local == 0: + t0 = time.time(); n = d.tok.shape[0]; step_rows = max(1, (1 << 28) // (N_TOK * D_TOK * 2)) + for i in range(0, n, step_rows): + _blk = np.array(d.tok[i:i + step_rows]); del _blk # copy => reads every page + print(f"[dwm] warmed page cache: {d.tok.nbytes/1e9:.1f} GB in {time.time()-t0:.0f}s", flush=True) + _barrier() + + d_act = args.chunk * d.adim + norm = Normalizer(d.stats).to(dev) + flow = DWM(N_TOK, D_TOK, d.n_pr, d_act, depth=args.depth, heads=args.heads, + dim_head=args.dim_head, mlp_dim=args.mlp, dropout=args.dropout, + emb_dropout=args.dropout, grad_ckpt=bool(args.grad_ckpt), tok_drop=args.tok_drop).to(dev) + rew = DWMReward(N_TOK, D_TOK, d.n_pr).to(dev) + n_flow = sum(p.numel() for p in flow.parameters()); n_rew = sum(p.numel() for p in rew.parameters()) + if is_main: + print(f"[dwm] params: flow {n_flow/1e6:.2f} M (ViT depth {args.depth}, {args.heads}x{args.dim_head}, " + f"mlp {args.mlp}, dim {flow.dim}, seq {2*flow.n_seq}) + reward {n_rew/1e6:.2f} M", flush=True) + flow_ema = copy.deepcopy(flow).eval(); rew_ema = copy.deepcopy(rew).eval() + for p in list(flow_ema.parameters()) + list(rew_ema.parameters()): + p.requires_grad_(False) + _trainable = list(flow.parameters()) + list(rew.parameters()) + opt = torch.optim.AdamW(_trainable, lr=args.lr, weight_decay=args.wd) + rms_tok = torch.ones(N_TOK, D_TOK, device=dev); rms_pr = torch.ones(max(d.n_pr, 1), device=dev)[:d.n_pr] + hist = []; best_win = -1.0; start_step = 0 + + _ck = out / "ckpt.pt" + if args.resume and _ck.exists(): + _c = torch.load(_ck, map_location=dev, weights_only=False) + flow.load_state_dict(_c["flow"]); rew.load_state_dict(_c["rew"]) + flow_ema.load_state_dict(_c["flow_ema"]); rew_ema.load_state_dict(_c["rew_ema"]) + if "opt" in _c: + opt.load_state_dict(_c["opt"]) + rms_tok = _c["rms_tok"].to(dev); rms_pr = _c["rms_pr"].to(dev) + best_win = _c.get("best_win", -1.0); hist = _c.get("hist", []) + start_step = int(_c["step"]) + if is_main: + print(f"[dwm] RESUMED at step {start_step}/{args.steps} (best action winrate {best_win:.3f})", + flush=True) + if start_step >= args.steps: + if is_main: + print("[dwm] already complete; nothing to do", flush=True) + return + _barrier() + + if world > 1: + ddp = torch.nn.parallel.DistributedDataParallel(flow, device_ids=[local] if use_cuda else None) + rew_d = torch.nn.parallel.DistributedDataParallel(rew, device_ids=[local] if use_cuda else None) + else: + ddp, rew_d = flow, rew + model = torch.compile(ddp, dynamic=False) if args.compile else ddp # compile on top of DDP + + # per-rank data stream, decorrelated across ranks and across restarts + rng = np.random.default_rng(args.seed + 9973 * start_step + 7919 * rank) + pf = Prefetcher(d, rng, per_rank, args.beta_lo, args.beta_hi, dev, + onestep=args.dynamics == "latent_mse") + pos_w = torch.tensor(max((1 - d.r.mean()) / max(d.r.mean(), 1e-6), 1.0), device=dev) + t0 = time.time(); t_last = time.time(); step_t = [] + + def save(step, gap_win, gap, cfm_v): + nonlocal best_win + blob = {"encoder": d.tok_info.get("encoder", "dinov2_vits14_tokens"), + "cam_res": d.tok_info.get("cam_res", 84), + # "model" is what a read-out dispatches on: a latent-MSE checkpoint must NOT be + # loaded by the flow read-out (it would Euler-integrate a network that was never + # trained as a velocity field and report the result as DINO-WM). + "model": "dinowm" if args.dynamics == "latent_mse" else "dwm", + "dynamics": args.dynamics, "hop_frames": int(args.chunk), + "flow": flow.state_dict(), "rew": rew.state_dict(), + "flow_ema": flow_ema.state_dict(), "rew_ema": rew_ema.state_dict(), + "norm": {k: torch.as_tensor(v) for k, v in d.stats.items()}, + "rms_tok": rms_tok.cpu(), "rms_pr": rms_pr.cpu(), "config": vars(args), + "arch": {"n_tok": N_TOK, "d_tok": D_TOK, "n_pr": d.n_pr, "d_act": d_act, + "depth": args.depth, "heads": args.heads, "dim_head": args.dim_head, + "mlp_dim": args.mlp, "dropout": args.dropout}, + "n_pr": d.n_pr, "tasks": d.tasks, "d_act": d_act, "step": step, + "q_action_winrate": gap_win} + blob_r = dict(blob); blob_r["opt"] = opt.state_dict() + blob_r["best_win"] = max(best_win, gap_win); blob_r["hist"] = hist + _tmp = out / "ckpt.pt.tmp"; torch.save(blob_r, _tmp); _os.replace(_tmp, out / "ckpt.pt") + if args.save_every and step % args.save_every == 0: + torch.save(blob, out / f"ckpt_s{step}.pt") + _cf = [h["cfm_val"] for h in hist[:-1] if "cfm_val" in h] + _healthy = (len(_cf) < 3) or (cfm_v <= 2.0 * float(np.median(_cf))) + if not _healthy: + print(f"[dwm] cfm_val {cfm_v:.3f} > 2x running median {float(np.median(_cf)):.3f}: " + f"occupancy unstable, NOT eligible as best", flush=True) + if gap_win > best_win and _healthy: + best_win = gap_win + torch.save(blob, out / "ckpt_best.pt") + print(f"[dwm] new BEST action winrate {gap_win:.3f} (gap {gap:+.5f}) at step {step}", flush=True) + + # ------------------------------------------------------------------ # + for step in range(start_step + 1, args.steps + 1): + b_full = pf.next() + opt.zero_grad(set_to_none=True) + acc_l = {"rew": 0.0, "cfm": 0.0, "cfm_pr": 0.0, "ac": 0.0, "loss": 0.0} + for mi in range(n_micro): + sl = slice(mi * micro, (mi + 1) * micro) + b = {k: (v[sl] if torch.is_tensor(v) else v[sl]) for k, v in b_full.items()} + last = mi == n_micro - 1 + ctx_f = ddp.no_sync() if (world > 1 and not last) else _nullctx() + ctx_r = rew_d.no_sync() if (world > 1 and not last) else _nullctx() + with ctx_f, ctx_r: + # running per-(token, channel) RMS of the residual, identical on all ranks + with torch.no_grad(): + tn = norm.tok(b["tok_now"]); tf_ = norm.tok(b["tok_fut"]) + cur = (tf_ - tn).pow(2).mean(0) + cur_pr = (norm.pr(b["pr_fut"]) - norm.pr(b["pr_now"])).pow(2).mean(0) + _all_reduce_mean(cur); _all_reduce_mean(cur_pr) + rms_tok.mul_(0.99).add_(cur.sqrt().clamp_min(RHO_FLOOR), alpha=0.01) + rms_pr.mul_(0.99).add_(cur_pr.sqrt().clamp_min(RHO_FLOOR), alpha=0.01) + with ac(): + # ---- reward head on the CURRENT frame (balanced BCE on the success label) ---- + logit = rew_d(norm.tok(b["tok_now"]), norm.pr(b["pr_now"])) + if args.reward_mode == "soft": + l_rew = F.binary_cross_entropy_with_logits(logit.float(), b["r_now"]) + else: + l_rew = F.binary_cross_entropy_with_logits(logit.float(), b["r_now"], pos_weight=pos_w) + # ---- occupancy: flow-match the normalised token residual ---- + l_ac = torch.zeros((), device=dev) + if args.w_actcon > 0 and args.actcon_rows and args.actcon_rows < micro: + # contrast on the first --actcon-rows rows (positive + negative forward), + # plain CFM on the rest: one positive forward per row either way + nr = args.actcon_rows + bs = {k: v[:nr] for k, v in b.items()} + br = {k: v[nr:] for k, v in b.items()} + c_sub = cfm_terms(model, norm, rms_tok, rms_pr, bs, perm=torch.randperm(nr, device=dev), x_noise=args.x_noise, dynamics=args.dynamics) + c_rest = cfm_terms(model, norm, rms_tok, rms_pr, br, x_noise=args.x_noise, dynamics=args.dynamics) + e_pos_c = per_row_cfm(c_sub["e_tok"], c_sub["e_pr"]) + e_neg_c = per_row_cfm(c_sub["e_tok_neg"], c_sub["e_pr_neg"]) + l_ac = F.softplus(e_pos_c - e_neg_c).mean() + c = {"e_tok": torch.cat([c_sub["e_tok"], c_rest["e_tok"]]), + "e_pr": torch.cat([c_sub["e_pr"], c_rest["e_pr"]])} + else: + perm = torch.randperm(micro, device=dev) if args.w_actcon > 0 else None + c = cfm_terms(model, norm, rms_tok, rms_pr, b, perm=perm, x_noise=args.x_noise, dynamics=args.dynamics) + if perm is not None: + e_pos_c = per_row_cfm(c["e_tok"], c["e_pr"]) + e_neg_c = per_row_cfm(c["e_tok_neg"], c["e_pr_neg"]) + l_ac = F.softplus(e_pos_c - e_neg_c).mean() + l_cfm = per_row_cfm(c["e_tok"], c["e_pr"]).mean() + l_cfm_pr = c["e_pr"].mean() + loss = args.w_reward * l_rew + l_cfm + args.w_actcon * l_ac + (loss / n_micro).backward() + for k_, v_ in (("rew", l_rew), ("cfm", l_cfm), ("cfm_pr", l_cfm_pr), ("ac", l_ac), ("loss", loss)): + acc_l[k_] += float(v_.detach()) / n_micro + gn_total = float(torch.nn.utils.clip_grad_norm_(_trainable, 1.0)) + opt.step() + ema_update(flow_ema, flow, args.ema); ema_update(rew_ema, rew, args.ema) + + if use_cuda and (step % args.print_every == 0 or args.time_steps): + torch.cuda.synchronize() + now = time.time(); step_t.append(now - t_last); t_last = now + if args.time_steps and step - start_step >= args.time_steps: + st = np.array(step_t[max(0, len(step_t) // 4):]) # drop warm-up + if is_main: + print(f"[dwm] TIMING {len(st)} steps: {st.mean():.3f} s/step (median {np.median(st):.3f}), " + f"global batch {args.batch}, world {world}, micro {micro}; " + f"projected {args.steps} steps = {args.steps*st.mean()/3600:.1f} h; " + f"peak mem {torch.cuda.max_memory_allocated()/2**30 if use_cuda else 0:.1f} GiB", flush=True) + pf.close() + if dist.is_initialized(): + dist.destroy_process_group() + return + if is_main and step % args.print_every == 0: + print(f"[dwm] {step} rew={acc_l['rew']:.4f} cfm={acc_l['cfm']:.4f} " + f"ac={acc_l['ac']:.4f} gradnorm={gn_total:.3f} " + f"rms_mean={float(rms_tok.mean()):.3f} ({np.mean(step_t[-args.print_every:]):.3f} s/step, " + f"{(step-start_step)/(time.time()-t0):.2f} it/s)", flush=True) + if wb is not None and (step % args.log_every == 0 or step == start_step + 1): + def _mod_gn(m): + sq = [p.grad.detach().float().pow(2).sum() for p in m.parameters() if p.grad is not None] + return float(torch.stack(sq).sum().sqrt()) if sq else 0.0 + wb.log({"train/loss": acc_l["loss"], "train/l_rew": acc_l["rew"], + "train/l_cfm": acc_l["cfm"], "train/l_cfm_pr": acc_l["cfm_pr"], + "train/l_actcon": acc_l["ac"], + "train/gradnorm": gn_total, "train/gradnorm_clipped": min(gn_total, 1.0), + "train/gradnorm_rew": _mod_gn(rew), "train/gradnorm_flow": _mod_gn(flow), + "train/rms_mean": float(rms_tok.mean()), "train/rms_pr_mean": float(rms_pr.mean()) if d.n_pr else 0.0, + "train/lr": opt.param_groups[0]["lr"], + "train/s_per_step": float(np.mean(step_t[-args.log_every:])), + "train/it_per_s": (step - start_step) / max(time.time() - t0, 1e-6)}, step=step) + + # ------------------------------------------------------------------ # + if step % args.eval_every == 0 or step == args.steps: + rec = evaluate(args, d, norm, flow_ema, rew_ema, rms_tok, rms_pr, dev, rank, world, + step, micro, ac) + if is_main: + rec["step"] = step + rec = {"step": step, **{k: v for k, v in rec.items() if k != "step"}} + hist.append(rec) + if wb is not None: + wb.log(_flat("eval", {k: v for k, v in rec.items() if k != "step"}, {}), step=step) + ident = rec["identity"] + print(f"[dwm] EVAL {step}: reward_auc={rec['reward_auc']:.4f} cfm={rec['cfm_val']:.4f} " + f"ACTION gap={rec['q_action_gap']:+.5f} win={rec['q_action_winrate']:.3f} | " + f"state auc={rec['q_success_auc']:.4f}", flush=True) + print(f"[dwm] MINMSE(n={args.eval_minmse_n}): train={rec['minmse_train']:.4f} " + f"val={rec['minmse_val']:.4f} meanmse={rec['meanmse_val']:.4f} " + f"staymse={rec['staymse_val']:.4f} (train stay {rec['staymse_train']:.4f})", flush=True) + print(f"[dwm] GENERALISATION: cfm train={rec['cfm_train']:.4f} val={rec['cfm_val']:.4f} " + f"(val/train {rec['val_over_train_cfm']:.2f}x, medians {rec['cfm_train_median']:.3f}/{rec['cfm_val_median']:.3f}) | " + f"minmse val/train {rec['val_over_train_minmse']:.2f}x " + f"(medians {rec['minmse_train_median']:.3f}/{rec['minmse_val_median']:.3f})", flush=True) + print(f"[dwm] IDENTITY Qbar: corr={ident['corr']:.3f} spearman={ident['spearman']:.3f} " + f"mse={ident['mse']:.5f} within-task={ident['corr_within_task']:.3f} " + f"(const-null mse {ident['mse_const']:.5f}) qhat={ident['q_hat_mean']:.4f} " + f"vs mc={ident['q_mc_mean']:.4f}", flush=True) + print("[dwm] by time-to-end: " + " ".join( + f"{k}:gap={v['action_gap']:+.5f}/win={v['action_winrate']:.2f}(n={v['n']})" + for k, v in rec["by_horizon"].items()), flush=True) + (out / "history.json").write_text(json.dumps(hist, indent=1)) + save(step, rec["q_action_winrate"], rec["q_action_gap"], rec["cfm_val"]) + _barrier() + pf.close() + if is_main: + print("[dwm] DONE", flush=True) + if dist.is_initialized(): + dist.destroy_process_group() + + +class _nullctx: + def __enter__(self): return self + def __exit__(self, *a): return False + + +# --------------------------------------------------------------------------- # +# evaluation, sharded across ranks (rows split by rank, gathered to every rank) +# --------------------------------------------------------------------------- # +@torch.no_grad() +def evaluate(args, d, norm, flow_ema, rew_ema, rms_tok, rms_pr, dev, rank, world, step, micro, ac): + flow_ema.eval(); rew_ema.eval() + rng = np.random.default_rng(args.seed + 12345 + step) # identical on every rank + n_rows = (args.eval_rows // world) * world + n_fr = (args.eval_frames // world) * world + N = args.eval_minmse_n + + def shard(arrs): + return [a[rank::world] for a in arrs] + + def _to(b): + return {k: (v.to(dev) if torch.is_tensor(v) else v) for k, v in b.items()} + + def minmse_block(split): + e, t, fut, beta = d.draw(n_rows, rng, args.beta_lo, args.beta_hi, split) + if args.dynamics == "latent_mse": + fut, beta = _onestep_future(d, e, t) # else validation would score another target + e, t, fut, beta = shard([e, t, fut, beta]) + mins, means, stays, cfms, cfm_prs, logits, r_now = [], [], [], [], [], [], [] + chunk = max(1, 4096 // max(N, 1)) + for i in range(0, len(t), chunk): + b = _to(d.gather(e[i:i + chunk], t[i:i + chunk], fut[i:i + chunk], beta[i:i + chunk])) + tn = norm.tok(b["tok_now"]); tf_ = norm.tok(b["tok_fut"]) + pn = norm.pr(b["pr_now"]) + B = tn.shape[0] + with ac(): + c = cfm_terms(flow_ema, norm, rms_tok, rms_pr, b, dynamics=args.dynamics) + logits.append(rew_ema(tn, pn).float()) + cfms.append(per_row_cfm(c["e_tok"], c["e_pr"])); cfm_prs.append(c["e_pr"]) + r_now.append(b["r_now"]) + xs, _ = sample_future_dwm(flow_ema, tn, pn, b["a_now"], b["beta"], rms_tok, rms_pr, + args.flow_steps, n=N, micro=micro, autocast=ac) + err = (xs.view(B, N, N_TOK, D_TOK) - tf_[:, None]).pow(2).mean((-1, -2)) # [B,N] + mins.append(err.min(1).values); means.append(err.mean(1)) + stays.append((tn - tf_).pow(2).mean((-1, -2))) + cat = lambda xs_: _gather_cat(torch.cat(xs_)).cpu().numpy() + return {"minmse": cat(mins), "meanmse": cat(means), "staymse": cat(stays), + "cfm": cat(cfms), "cfm_pr": cat(cfm_prs), "logit": cat(logits), "r_now": cat(r_now)} + + val = minmse_block("val") + tr = minmse_block("train") + r_auc = auc(val["logit"], val["r_now"]) + + # ---- headline: does Q RANK ACTIONS at a fixed state? (CRN across the two chunks) ---- + e, t, _, _ = d.draw(n_fr, rng, 0.5, 0.5, "val") + tkp = d.ep_task[e] + pw = np.arange(n_fr) + for _ti in np.unique(tkp): + _ix = np.nonzero(tkp == _ti)[0] + if len(_ix) > 1: + pw[_ix] = rng.permutation(_ix) + a_all = d._chunk_at(t, e); a_for_all = a_all[pw] + order = np.concatenate([np.arange(n_fr)[r::world] for r in range(world)]) # gathered row order + e_s, t_s = shard([e, t]) + a_s = torch.from_numpy(a_all[rank::world]).to(dev); af_s = torch.from_numpy(a_for_all[rank::world]).to(dev) + q_log, q_for = [], [] + n_part = 4 + chunk = max(1, 2048 // n_part) + for i in range(0, len(t_s), chunk): + b = _to(d.gather(e_s[i:i + chunk], t_s[i:i + chunk], t_s[i:i + chunk], np.zeros(min(chunk, len(t_s) - i)), with_fut=False)) + tn = norm.tok(b["tok_now"]); pn = norm.pr(b["pr_now"]); B = tn.shape[0] + beta_q = torch.full((B,), args.beta_q, device=dev) + x0 = (torch.randn(B * n_part, N_TOK, D_TOK, device=dev), torch.randn(B * n_part, d.n_pr, device=dev)) + + def q_of(a_chunk): + xt, xp = sample_future_dwm(flow_ema, tn, pn, a_chunk, beta_q, rms_tok, rms_pr, + args.flow_steps, n=n_part, x0=x0, micro=micro, autocast=ac) + with ac(): + p = torch.sigmoid(rew_ema(xt, xp).float()) + return p.view(B, n_part).mean(1) + q_log.append(q_of(a_s[i:i + chunk])); q_for.append(q_of(af_s[i:i + chunk])) + q_log = _gather_cat(torch.cat(q_log)).cpu().numpy(); q_for = _gather_cat(torch.cat(q_for)).cpu().numpy() + e_o, t_o = e[order], t[order] + succ = d.ep_success[e_o].astype(np.float32); te = (d.ep_to[e_o] - t_o).astype(np.float32) + tk_np = d.ep_task[e_o] + gap = float((q_log - q_for).mean()); gap_win = float((q_log > q_for).mean()) + q_succ_auc = auc(q_log, succ) + + # ---- MC identity: Qbar(s,a) = E_{k~Geom(1-beta)}[r(s_{t+k})] from the logged trajectory ---- + _kk = rng.geometric(1.0 - args.beta_q, size=(256, len(e_o))) - 1 + _ix = np.minimum(t_o[None, :] + _kk, d.ep_to[e_o][None, :] - 1) + q_mc = d.r[_ix].mean(0); _qh = q_log + identity = {"q_mc_mean": float(q_mc.mean()), "q_hat_mean": float(_qh.mean()), + "mse": float(((_qh - q_mc) ** 2).mean()), + "corr": float(np.corrcoef(_qh, q_mc)[0, 1]) if (_qh.std() > 1e-8 and q_mc.std() > 1e-8) else 0.0, + "spearman": float(np.corrcoef(np.argsort(np.argsort(_qh)), np.argsort(np.argsort(q_mc)))[0, 1]) + if (_qh.std() > 1e-8 and q_mc.std() > 1e-8) else 0.0, + "mse_const": float(((q_mc.mean() - q_mc) ** 2).mean())} + _wt = [] + for _ti in np.unique(tk_np): + _m = tk_np == _ti + if _m.sum() < 32 or _qh[_m].std() < 1e-8 or q_mc[_m].std() < 1e-8: + continue + _wt.append(float(np.corrcoef(_qh[_m], q_mc[_m])[0, 1])) + identity["corr_within_task"] = float(np.mean(_wt)) if _wt else 0.0 + identity["n_tasks_scored"] = len(_wt) + gl = q_log - q_for + by_horizon = {} + for name, lo_, hi_ in (("0-50", 0, 50), ("50-100", 50, 100), ("100-200", 100, 200), ("200+", 200, 1e9)): + m = (te >= lo_) & (te < hi_) + if m.sum() < 16: + continue + by_horizon[name] = {"n": int(m.sum()), "action_gap": float(gl[m].mean()), + "action_winrate": float((gl[m] > 0).mean()), "q_mean": float(q_log[m].mean())} + per_task = {} + for ti in np.unique(tk_np): + m = tk_np == ti + per_task[int(ti)] = {"n": int(m.sum()), "action_gap": float(gl[m].mean()), + "success_auc": auc(q_log[m], succ[m]), "succ_rate": float(succ[m].mean())} + rec = {"step": step, "reward_auc": r_auc, "cfm_val": float(val["cfm"].mean()), + "cfm_pr_val": float(val["cfm_pr"].mean()), + "cfm_train": float(tr["cfm"].mean()), "cfm_pr_train": float(tr["cfm_pr"].mean()), + "cfm_val_median": float(np.median(val["cfm"])), "cfm_train_median": float(np.median(tr["cfm"])), + "minmse_val_median": float(np.median(val["minmse"])), "minmse_train_median": float(np.median(tr["minmse"])), + "val_over_train_cfm": float(val["cfm"].mean() / max(tr["cfm"].mean(), 1e-9)), + "val_over_train_minmse": float(val["minmse"].mean() / max(tr["minmse"].mean(), 1e-9)), + "per_task": per_task, "by_horizon": by_horizon, + "q_action_gap": gap, "q_action_winrate": gap_win, + "q_success_auc": q_succ_auc, "q_mean": float(q_log.mean()), "identity": identity, + "minmse_train": float(tr["minmse"].mean()), "minmse_val": float(val["minmse"].mean()), + "meanmse_train": float(tr["meanmse"].mean()), "meanmse_val": float(val["meanmse"].mean()), + "staymse_train": float(tr["staymse"].mean()), "staymse_val": float(val["staymse"].mean()), + "meanmse": float(val["meanmse"].mean()), "staymse": float(val["staymse"].mean()), + "minmse_n": N, "eval_rows": n_rows, "eval_frames": n_fr, + "rms_mean": float(rms_tok.mean())} + return rec + + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/verify_successes.py b/rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/verify_successes.py new file mode 100644 index 0000000000000000000000000000000000000000..a6683a70f11df3de835d5328b9333fc26cfb3af4 --- /dev/null +++ b/rsm_rise/scripts/real/v7/nonmarkov/rsm_libero_nm/verify_successes.py @@ -0,0 +1,97 @@ +"""Replay-verify every logged success: does it actually succeed in the simulator? + +The R1 corpus's is_success labels are ~16% optimistic on the positive side (60-episode +audit: 5/32 logged successes did not reproduce, 0/28 logged failures did). BC-on-successes +clones that pool, and the critic's gamma^steps-to-success reward gives a false success a +full progress curve toward an event that never happened. + +This re-executes each logged action sequence from the logged initial sim_state and records +whether the episode actually succeeds. Emits a boolean mask aligned to the cache's episode +index, consumed via --success-mask. + +Error is one-sided (no logged failure ever reproduced as a success), so verification only +ever REMOVES episodes from the success pool. +""" +import argparse, os, re, sys +import numpy as np +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) + +SRC = "/data/pulkitag/users/rli14/pi05_lib10_sde_v1" +PAT = re.compile(r"ep_t(\d+)_b(\d+)_i(\d+)_(\d+)\.npz$") + + +def src_parquet(ep_src: str): + """cache ep_src -> the source episode parquet holding sim_state + actions.""" + m = PAT.search(ep_src) + if not m: + return None + t, b, i, idx = m.groups() + return (f"{SRC}/task{int(t)}_block{int(b)}/rank_0/id_{int(i)}" + f"/data/chunk-000/episode_{int(idx):06d}.parquet") + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--cache", required=True) + ap.add_argument("--task", type=int, required=True, help="libero_10 task id shard") + ap.add_argument("--out", required=True) + ap.add_argument("--shard", type=int, default=0); ap.add_argument("--num-shards", type=int, default=1) + ap.add_argument("--max-steps", type=int, default=520) + args = ap.parse_args() + + import pyarrow.parquet as pq + from libero.libero import benchmark, get_libero_path + from libero.libero.envs.env_wrapper import ControlEnv + from pathlib import Path + + m = np.load(f"{args.cache}/meta.npz", allow_pickle=True) + ep_src, ep_task = m["ep_src"], m["ep_task"] + is_demo, is_succ = m["ep_demo"].astype(bool), m["ep_success"].astype(bool) + # only logged SUCCESSES from ROLLOUTS need checking; demos are ground truth + todo = np.where((ep_task == args.task) & is_succ & ~is_demo)[0] + todo = todo[args.shard::args.num_shards] # within-task sharding for the full corpus + print(f"[verify] task {args.task}: {len(todo)} logged successes to replay", flush=True) + + bench = benchmark.get_benchmark_dict()["libero_10"]() + task = bench.get_task(args.task) + # Physics only: success is the task's goal predicate over sim state, so no + # cameras and no EGL are needed. That drops the GPU requirement entirely and lets + # this run on CPU nodes instead of competing with the training queue. + env = ControlEnv( + bddl_file_name=str(Path(get_libero_path("bddl_files")) + / task.problem_folder / task.bddl_file), + has_renderer=False, has_offscreen_renderer=False, use_camera_obs=False) + + rows = [] + for n, e in enumerate(todo): + p = src_parquet(str(ep_src[e])) + if p is None or not os.path.exists(p): + rows.append((int(e), -1)); continue # -1 = unresolvable, keep as-is + tb = pq.read_table(p, columns=["sim_state", "actions"]) + sim0 = np.asarray(tb["sim_state"][0].as_py(), dtype=np.float64) + acts = np.asarray([a.as_py() for a in tb["actions"]], dtype=np.float64) + env.reset() + env.env.sim.set_state_from_flattened(sim0) + env.env.sim.forward() + ok = False + for s in range(min(len(acts), args.max_steps)): + _o, _r, done, _i = env.step(acts[s]) + if done: + ok = True; break + rows.append((int(e), int(ok))) + if (n + 1) % 25 == 0: + got = [r for _, r in rows if r >= 0] + print(f"[verify] {n+1}/{len(todo)} reproduced {sum(got)}/{len(got)} " + f"({np.mean(got) if got else float('nan'):.3f})", flush=True) + env.close() + idx = np.array([r[0] for r in rows], np.int64) + val = np.array([r[1] for r in rows], np.int64) + np.savez(args.out, ep_index=idx, verified=val, task=args.task) + good = val[val >= 0] + print(f"[verify] task {args.task} DONE: {good.sum()}/{len(good)} reproduced " + f"({good.mean() if len(good) else float('nan'):.3f}); " + f"{int((val < 0).sum())} unresolvable", flush=True) + + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/real/v7/nonmarkov/rsm_nm_qall.py b/rsm_rise/scripts/real/v7/nonmarkov/rsm_nm_qall.py new file mode 100644 index 0000000000000000000000000000000000000000..e6965b55ba7608d8b05947d81fa7024acad8b529 --- /dev/null +++ b/rsm_rise/scripts/real/v7/nonmarkov/rsm_nm_qall.py @@ -0,0 +1,187 @@ +#!/usr/bin/env python +"""V7_NONMARKOV: RSM HISTORY-successor Q on the FROZEN tests C / A / B / STITCH (+ V7_STOVE TUNE ranking + the pre-registered +stovehist 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 by +EVERY 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, time +from pathlib import Path +import numpy as np, torch +R = 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 NMM +import rsm_scorer_ar as AR +import 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 + +# ---- successor +ck = 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) == 0 +hist = (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 0 +flow = 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 D +if 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)) == 50 +assert (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 + +# ---- head +head = 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.np +x0s = 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 = 0 +if 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) diff --git a/rsm_rise/scripts/real/v7/nonmarkov/run_eval_dw_nm.sh b/rsm_rise/scripts/real/v7/nonmarkov/run_eval_dw_nm.sh new file mode 100644 index 0000000000000000000000000000000000000000..34360e38113b11b2b88a718b13cf5745b80b3845 --- /dev/null +++ b/rsm_rise/scripts/real/v7/nonmarkov/run_eval_dw_nm.sh @@ -0,0 +1,35 @@ +#!/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//. TEST never. Resumable (done_* markers). +# usage: RUN= NAME= [SPLITS=tune,cv0,...] sbatch -J rr_cpu_nm_ev_ run_eval_dw.sh (model = _s) +set -uo pipefail +export PAIRTEST_VERSION=pairtest_v3 +cd /proj/dmfexp/zwhong/rsm_rise +PY=/proj/dmfexp/zwhong/rsm_rise/venv_rsm/bin/python; S=scripts/real/v7/pairtest; D=scripts/real/v7/nonmarkov +SPLITS=${SPLITS:-tune,cv0,cv1,cv2,cv3}; EV=runs/v7_nonmarkov/eval +echo "[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)" +done +echo "[nm_dw_eval] done $(date -u)" diff --git a/rsm_rise/scripts/real/v7/nonmarkov/run_eval_iql_nm.sh b/rsm_rise/scripts/real/v7/nonmarkov/run_eval_iql_nm.sh new file mode 100644 index 0000000000000000000000000000000000000000..59e8b091890fe08ba01fa8990632288d7cb80b40 --- /dev/null +++ b/rsm_rise/scripts/real/v7/nonmarkov/run_eval_iql_nm.sh @@ -0,0 +1,33 @@ +#!/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//). TEST never. +# usage: RUN=runs/v7_nonmarkov/[C/]iql// SPACE= sbatch -J rr_cpu_nm_ev_ run_eval_iql_nm.sh (TEST never) +set -uo pipefail +export PAIRTEST_VERSION=pairtest_v3 +cd /proj/dmfexp/zwhong/rsm_rise +PY=/proj/dmfexp/zwhong/rsm_rise/venv_rsm/bin/python; S=scripts/real/v7/pairtest; H=scripts/real/v7/iqlmatch +SPLITS=${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 2 +for 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" +done +echo "[nm_iql_eval] done $(date -u)" diff --git a/rsm_rise/scripts/real/v7/nonmarkov/run_eval_rsm_nm.sh b/rsm_rise/scripts/real/v7/nonmarkov/run_eval_rsm_nm.sh new file mode 100644 index 0000000000000000000000000000000000000000..ba0b1ee36f19978018dfdbda0846a647b3aaf0db --- /dev/null +++ b/rsm_rise/scripts/real/v7/nonmarkov/run_eval_rsm_nm.sh @@ -0,0 +1,27 @@ +#!/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//. TEST never. Resumable. +# usage: bash run_eval_rsm_nm.sh <1s|3s> (model name rsmnm__s_s) +set -uo pipefail +SP=$1; SPAN=$2; SD=$3; ST=$4 +export PAIRTEST_VERSION=pairtest_v3 +R=/proj/dmfexp/zwhong/rsm_rise; cd $R +PY=$R/venv_rsm/bin/python; S=scripts/real/v7/pairtest; Q=scripts/real/v7/nonmarkov/rsm_nm_qall.py; SPLITS=tune,cv0,cv1,cv2,cv3 +if [ $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.pt +else 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; fi +HOP=$B/hop/$SPAN/gauss_h50_s1/policy_s120000.pt +n=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; }; done +A="--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; fi +for 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_$sp +done +touch $EV/done_all_${SPLITS//,/_}; echo "[nm_rsm_eval] scored $n $(date -u)" diff --git a/rsm_rise/scripts/real/v7/nonmarkov/score_iql_nm.py b/rsm_rise/scripts/real/v7/nonmarkov/score_iql_nm.py new file mode 100644 index 0000000000000000000000000000000000000000..3121735367e48ad911224290396e71060bcf98bd --- /dev/null +++ b/rsm_rise/scripts/real/v7/nonmarkov/score_iql_nm.py @@ -0,0 +1,105 @@ +#!/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 the +model'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__.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 on +TUNE + 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, sys +from pathlib import Path +import numpy as np, torch +sys.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) diff --git a/rsm_rise/scripts/real/v7/nonmarkov/smoke.sbatch b/rsm_rise/scripts/real/v7/nonmarkov/smoke.sbatch new file mode 100644 index 0000000000000000000000000000000000000000..e5a9476f9609b01b691a827da69363e8026c85bf --- /dev/null +++ b/rsm_rise/scripts/real/v7/nonmarkov/smoke.sbatch @@ -0,0 +1,61 @@ +#!/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 pipefail +P=/proj/dmfexp/zwhong/rsm_rise; ROOT=/proj/dmfexp/zwhong/jm/rsm_rise; PY=$P/venv_rsm/bin/python; NM=$P/scripts/real/v7/nonmarkov +S=$P/runs/v7_nonmarkov/smoke; rm -rf $S; mkdir -p $S +export WANDB_MODE=disabled +cd $P && $PY $NM/build_hist.py || exit 1 +echo "=== regression: default off == jm original; history shapes" +cd $NM/rsm_libero_nm && $PY - <<'PY' || exit 1 +import sys, numpy as np, torch, importlib.util +C="/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 m +new = 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 M +f0 = 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") +PY +HI=$P/runs/v7_nonmarkov/hist/hist_D1.5.npy +echo "=== 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 1 +echo "=== 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 1 +ls $S/hop +echo "=== 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 1 +ls $S/head +echo "SMOKE ALL OK $(date -u)" diff --git a/rsm_rise/scripts/real/v7/nonmarkov/smoke2.sbatch b/rsm_rise/scripts/real/v7/nonmarkov/smoke2.sbatch new file mode 100644 index 0000000000000000000000000000000000000000..d604dbd9aa2c710c2e090b5aed0ffb29a8c31041 --- /dev/null +++ b/rsm_rise/scripts/real/v7/nonmarkov/smoke2.sbatch @@ -0,0 +1,30 @@ +#!/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 pipefail +P=/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 $S +export OMP_NUM_THREADS=8 WANDB_MODE=disabled +ok=1 +for 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 - < READY $(date -u)"; else echo "SMOKE2 FAILED"; fi diff --git a/rsm_rise/scripts/real/v7/nonmarkov/smokeC.sbatch b/rsm_rise/scripts/real/v7/nonmarkov/smokeC.sbatch new file mode 100644 index 0000000000000000000000000000000000000000..2a19c9748f94bb09912deb0579f9ff6fbed31214 --- /dev/null +++ b/rsm_rise/scripts/real/v7/nonmarkov/smokeC.sbatch @@ -0,0 +1,30 @@ +#!/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 pipefail +P=/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 $S +export OMP_NUM_THREADS=8 WANDB_MODE=disabled +ok=1 +for 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 - < READY $(date -u)"; else echo "SMOKEC FAILED"; fi diff --git a/rsm_rise/scripts/real/v7/nonmarkov/smoke_rsmnm.sbatch b/rsm_rise/scripts/real/v7/nonmarkov/smoke_rsmnm.sbatch new file mode 100644 index 0000000000000000000000000000000000000000..3db1b9b684a5bcdde6c51255d870efcd9ee53fe9 --- /dev/null +++ b/rsm_rise/scripts/real/v7/nonmarkov/smoke_rsmnm.sbatch @@ -0,0 +1,23 @@ +#!/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 pipefail +export PAIRTEST_VERSION=pairtest_v3 OMP_NUM_THREADS=16 +cd /proj/dmfexp/zwhong/rsm_rise +PY=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 2 +export 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 4 +echo "[smoke_rsmnm] OK $(date -u)" diff --git a/rsm_rise/scripts/real/v7/nonmarkov/table.py b/rsm_rise/scripts/real/v7/nonmarkov/table.py new file mode 100644 index 0000000000000000000000000000000000000000..11836d667d7f28d9885dc3477ca0582d5b87e1b5 --- /dev/null +++ b/rsm_rise/scripts/real/v7/nonmarkov/table.py @@ -0,0 +1,122 @@ +#!/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(partner +chunk) (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, re +from pathlib import Path +import numpy as np +R = 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)) diff --git a/rsm_rise/scripts/real/v7/nonmarkov/train_dw2_nm.py b/rsm_rise/scripts/real/v7/nonmarkov/train_dw2_nm.py new file mode 100644 index 0000000000000000000000000000000000000000..88fbe606a2a7ae2afed6420017536f908886f769 --- /dev/null +++ b/rsm_rise/scripts/real/v7/nonmarkov/train_dw2_nm.py @@ -0,0 +1,224 @@ +#!/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 (evaluated +weights), bf16 autocast, ckpts at 20/40/60/80/100k (+ resume ckpt.pt every 2k). TRAIN split only; in-training +diagnostics 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, time +from pathlib import Path +import numpy as np +import torch, torch.nn as nn, torch.nn.functional as F +import torch.distributed as dist +sys.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 // world +assert 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 = True +S = W.SPACES[args.space]; M = W.load_meta() + +# ---------------------------------------------------------------- stats (rank 0 fits once per space; atomic) +NHh = args.nhist +assert 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.shape +PRg = torch.from_numpy(M["pr"]).to(dev); Ag = torch.from_numpy(M["act"]).to(dev) + +# ---------------------------------------------------------------- samplers +tr_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 / ema +torch.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 = None +if 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 = None +if 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(), 0 +net.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) diff --git a/rsm_rise/scripts/real/v7/nonmarkov/train_dw2_nmxn.py b/rsm_rise/scripts/real/v7/nonmarkov/train_dw2_nmxn.py new file mode 100644 index 0000000000000000000000000000000000000000..9b1003085c35bf57baf70d65fb471e2adfc8a895 --- /dev/null +++ b/rsm_rise/scripts/real/v7/nonmarkov/train_dw2_nmxn.py @@ -0,0 +1,232 @@ +#!/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 the +z-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 (evaluated +weights), bf16 autocast, ckpts at 20/40/60/80/100k (+ resume ckpt.pt every 2k). TRAIN split only; in-training +diagnostics 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, time +from pathlib import Path +import numpy as np +import torch, torch.nn as nn, torch.nn.functional as F +import torch.distributed as dist +sys.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 // world +assert 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 = True +S = W.SPACES[args.space]; M = W.load_meta() + +# ---------------------------------------------------------------- stats (rank 0 fits once per space; atomic) +NHh = args.nhist +assert 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.shape +PRg = torch.from_numpy(M["pr"]).to(dev); Ag = torch.from_numpy(M["act"]).to(dev) + +# ---------------------------------------------------------------- samplers +tr_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 / ema +torch.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 = None +if 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 = None +if 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(), 0 +net.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) diff --git a/rsm_rise/scripts/real/v7/nonmarkov/train_iql_nm.py b/rsm_rise/scripts/real/v7/nonmarkov/train_iql_nm.py new file mode 100644 index 0000000000000000000000000000000000000000..65595eed3e8870296d15c23c74afade4aed576d7 --- /dev/null +++ b/rsm_rise/scripts/real/v7/nonmarkov/train_iql_nm.py @@ -0,0 +1,121 @@ +#!/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//iqlm__s [--steps 200000] [--smoke] +Resumable: last.pt (every 10k) holds nets + optimisers + RNG; DONE marker when finished.""" +import argparse, json, sys, time, hashlib +from pathlib import Path +import numpy as np, torch +import torch.nn.functional as Fn +sys.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 row +an = 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 = 0 +if (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) diff --git a/rsm_rise/scripts/real/v7/nonmarkov/train_iql_nmxn.py b/rsm_rise/scripts/real/v7/nonmarkov/train_iql_nmxn.py new file mode 100644 index 0000000000000000000000000000000000000000..c5f6174bb746bd24014ce2e1a376658402b21c70 --- /dev/null +++ b/rsm_rise/scripts/real/v7/nonmarkov/train_iql_nmxn.py @@ -0,0 +1,124 @@ +#!/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//iqlm__s [--steps 200000] [--smoke] +Resumable: last.pt (every 10k) holds nets + optimisers + RNG; DONE marker when finished.""" +import argparse, json, sys, time, hashlib +from pathlib import Path +import numpy as np, torch +import torch.nn.functional as Fn +sys.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 row +an = 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 = 0 +if (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) diff --git a/rsm_rise/scripts/real/v7/nonmarkov/train_reward2_nm.py b/rsm_rise/scripts/real/v7/nonmarkov/train_reward2_nm.py new file mode 100644 index 0000000000000000000000000000000000000000..7b8caadbcca5ca17b3e37c73b462045833c03170 --- /dev/null +++ b/rsm_rise/scripts/real/v7/nonmarkov/train_reward2_nm.py @@ -0,0 +1,198 @@ +#!/usr/bin/env python +"""V7_REWARD2 step 2: standalone action-conditioned reward head r(x, a) on the FROZEN v7 successor features. + +The v7 successor (progress_augc_h50_ps_s0) uses the identity encoder: its latent IS the z-scored state + x = clip((feat - mu) / max(sd, 0.01), -10, 10), feat = [DINO z (1536) | proprio (10)] (feat_stats.npz) +so "frozen successor features" = x; the script asserts enc_kind == identity and n_pr == 0 from the ckpt. +Action input (--act chunk50): the next 50 logged actions (padded by repeating the last, exactly as the +successor's data._chunk_at), each normalised with the v7 action norm a_n = 2 (a - min)/(max - min) - 1, +flattened to 500-d. --act a0: first action only (10-d). --act none: state-only ablation. +Target: reward_shaped2.f32.npy (make_labels.py). Loss: weighted Huber (delta 1) with reward_shaped2_w. +TRAIN episodes only; TUNE (cooking_v7_tune_test.json) for selection = lowest TUNE weighted Huber; TEST untouched here. +Checkpoint keys: {"rew2": state_dict, "arch": {...}, "act_norm": {"min","max"}, "config": vars(args), "tune": metrics} +""" +import argparse, json, os, time +from pathlib import Path +import numpy as np +import torch, torch.nn as nn, torch.nn.functional as F + +JM = Path("/proj/dmfexp/zwhong/jm/rsm_rise") +C = Path(__import__("os").environ.get("RR_V7_CACHE", str(JM / "cache/real_cooking_v7"))) # V7_LEARNPROJ env override (default unchanged) +p = argparse.ArgumentParser() +p.add_argument("--out", required=True) +p.add_argument("--act", default="chunk50", choices=["chunk50", "a0", "none"]) +p.add_argument("--chunk", type=int, default=50) +p.add_argument("--weights", default="balanced", choices=["balanced", "none"]) +p.add_argument("--width", type=int, default=512) +p.add_argument("--depth", type=int, default=2) +p.add_argument("--dropout", type=float, default=0.0) +p.add_argument("--x_noise", type=float, default=0.0) +p.add_argument("--act_drop", type=float, default=0.0, help="prob of zeroing the whole action input per row") +p.add_argument("--steps", type=int, default=20000) +p.add_argument("--batch", type=int, default=4096) +p.add_argument("--lr", type=float, default=3e-4) +p.add_argument("--wd", type=float, default=1e-4) +p.add_argument("--huber", type=float, default=1.0) +p.add_argument("--eval_every", type=int, default=1000) +p.add_argument("--seed", type=int, default=0) +# RSM_PAIRTEST run 17 (A_logged diagnosis): explicit "hover at a success meta-state" negatives. Off by default. +p.add_argument("--hover_margin", type=float, default=0.0, help="TRAIN rows on segments leaving 3/8 whose 50-chunk max ee " + "displacement is in the lowest 5%% for that stage (frames >= 50 before the episode end) get label y - margin") +p.add_argument("--hold_aug", type=float, default=0.0, help="prob per row (edge_from in 3/8) of replacing the chunk by " + "a_t repeated (go to the commanded pose and stay) with label y - hover_margin") +p.add_argument("--hist_index", default="", help="V7_NONMARKOV: int64 [N,2] history rows; X -> [x|x-x_D|x-x_2D] ('' = off)") +p.add_argument("--succ_ckpt", default=str(JM / "export/v7/rsm_ens20/progress_augc_h50_ps_s0/ckpt_s20000.pt")) +args = p.parse_args() +out = Path(args.out); out.mkdir(parents=True, exist_ok=True) +if (out / "DONE").exists(): + print("[r2] DONE exists, skip", out); raise SystemExit(0) +torch.manual_seed(args.seed); np.random.seed(args.seed) +dev = "cuda" if torch.cuda.is_available() else "cpu" # V7_NONMARKOV: cpu for the smoke only + +ck = torch.load(args.succ_ckpt, map_location="cpu", weights_only=False) +enc_kind = ck.get("enc_kind", ck["config"].get("enc", "mlp")); n_pr = int(ck.get("n_pr", 0) or 0) +print("[r2] successor enc_kind", enc_kind, "n_pr", n_pr, "d_in", ck.get("d_in"), "d_act", ck.get("d_act"), flush=True) +assert enc_kind == "identity" and n_pr == 0, "successor features are not the identity z-scored state" +del ck + +st = np.load(C / "feat_stats.npz") +mu, sd, zc = st["mu"].astype(np.float32), np.maximum(st["sd"].astype(np.float32), float(st["sd_floor"])), float(st["z_clip"]) +z = np.load(C / "z.f16.npy"); pr = np.load(C / "proprio.f32.npy") +feat = np.concatenate([z.astype(np.float32), pr], 1); del z +X = np.clip((feat - mu) / sd, -zc, zc).astype(np.float32); del feat +if args.hist_index: # V7_NONMARKOV history conditioning (same H(t) as the successor) + _h = np.load(args.hist_index).astype(np.int64); assert _h.shape == (len(X), 2) + X = np.concatenate([X, X - X[_h[:, 0]], X - X[_h[:, 1]]], 1); del _h + print("[r2] history H(t) from", args.hist_index, "d_x", X.shape[1], flush=True) +an = json.load(open(JM / "data/derived/cooking_v7_action_norm.json")) +amin, amax = np.array(an["action_min"], np.float32), np.array(an["action_max"], np.float32) +act = 2 * (np.load(C / "act.f32.npy") - amin) / (amax - amin) - 1 +meta = np.load(C / "meta.npz"); ep_from, ep_to = meta["ep_from"], meta["ep_to"] +N = len(X); row_ep = np.repeat(np.arange(len(ep_from)), ep_to - ep_from) +y = np.load(C / "reward_shaped2.f32.npy"); w = np.load(C / "reward_shaped2_w.f32.npy") +grp = np.load(C / "reward_shaped2_group.i8.npy") +if args.weights == "none": + w = np.ones_like(w) +split = json.load(open(JM / "data/derived/cooking_v7_split.json"))["episodes"] +tt = json.load(open(JM / "data/derived/cooking_v7_tune_test.json")) +train_eps = np.array([i for i in range(len(ep_from)) if split[str(i)]["split"] == "train"]) +tune_eps = np.array(sorted(tt["tune"])) +assert not set(train_eps) & set(tt["tune"]) and not set(train_eps) & set(tt["test"]) +rows_of = lambda eps: np.concatenate([np.arange(ep_from[e], ep_to[e]) for e in eps]) +tr_rows, tu_rows = rows_of(train_eps), rows_of(tune_eps) +print(f"[r2] N={N} train rows {len(tr_rows)} ({len(train_eps)} eps) tune rows {len(tu_rows)} ({len(tune_eps)} eps)", flush=True) + +hov_stage = np.zeros(N, bool) +if args.hover_margin > 0: + e_from = np.load(C / "edge_from.i16.npy").astype(np.int64); ar = np.load(C / "act.f32.npy", mmap_mode="r") + y = y.copy(); ep_end = ep_to[row_ep]; hov_stage = np.isin(e_from, [3, 8]) + for s_ in (3, 8): + cand = tr_rows[(e_from[tr_rows] == s_) & (tr_rows <= ep_end[tr_rows] - 50)] + fr = np.minimum(cand[:, None] + np.arange(50)[None], ep_end[cand][:, None] - 1) + P3 = np.asarray(ar[fr.ravel(), :3]).reshape(len(cand), 50, 3) + dc = np.linalg.norm(P3 - P3[:, :1], axis=2).max(1); hv = cand[dc <= np.percentile(dc, 5)] + y[hv] -= args.hover_margin + print(f"[r2] hover negatives stage {s_}: {len(hv)} TRAIN rows, label -{args.hover_margin}", flush=True) +hov_g = torch.from_numpy(hov_stage).to(dev) +Xg = torch.from_numpy(X).to(dev); Ag = torch.from_numpy(act.astype(np.float32)).to(dev) +yg = torch.from_numpy(y).to(dev); wg = torch.from_numpy(w).to(dev) +epto_g = torch.from_numpy(ep_to[row_ep]).to(dev) +CL = args.chunk if args.act == "chunk50" else 1 +d_a = 0 if args.act == "none" else CL * act.shape[1] + + +def act_in(idx): + if args.act == "none": + return None + fr = idx[:, None] + torch.arange(CL, device=dev)[None, :] + fr = torch.minimum(fr, epto_g[idx][:, None] - 1) + return Ag[fr].reshape(len(idx), -1) + + +class Rew2(nn.Module): + def __init__(self, d_x, d_a, width, depth, dropout): + super().__init__() + L, d = [], d_x + d_a + for _ in range(depth): + L += [nn.Linear(d, width), nn.SiLU()] + ([nn.Dropout(dropout)] if dropout > 0 else []) + d = width + L += [nn.Linear(d, 1)] + self.net = nn.Sequential(*L); self.d_a = d_a + + def forward(self, x, a=None): + h = x if self.d_a == 0 else torch.cat([x, a], -1) + return self.net(h).squeeze(-1) + + +model = Rew2(X.shape[1], d_a, args.width, args.depth, args.dropout).to(dev) +opt = torch.optim.AdamW(model.parameters(), lr=args.lr, weight_decay=args.wd) +sched = torch.optim.lr_scheduler.CosineAnnealingLR(opt, args.steps) +tr_g = torch.from_numpy(tr_rows).to(dev); tu_g = torch.from_numpy(tu_rows).to(dev) + + +@torch.no_grad() +def predict(rows_g): + model.eval(); outs = [] + for i in range(0, len(rows_g), 16384): + idx = rows_g[i:i + 16384]; outs.append(model(Xg[idx], act_in(idx))) + model.train(); return torch.cat(outs) + + +def spearman(a, b): + from scipy.stats import spearmanr + return float(spearmanr(a, b).correlation) + + +def auc(s, lab): + from scipy.stats import rankdata + s, lab = np.asarray(s, float), np.asarray(lab, bool); P, Nn = lab.sum(), (~lab).sum() + if P == 0 or Nn == 0: return float("nan") + rk = rankdata(s); return float((rk[lab].sum() - P * (P + 1) / 2) / (P * Nn)) + + +def tune_metrics(): + pr_ = predict(tu_g); yt, wt = yg[tu_g], wg[tu_g] + hub = F.huber_loss(pr_, yt, reduction="none", delta=args.huber) + pn, yn, gn = pr_.cpu().numpy(), yt.cpu().numpy(), grp[tu_rows] + m = {"tune_whuber": float((hub * wt).sum() / wt.sum()), "tune_huber": float(hub.mean()), + "tune_mae": float((pr_ - yt).abs().mean()), "tune_spearman": spearman(pn, yn), + "tune_frame_auc_G7_vs_FAIL": auc(pn[gn != 0], gn[gn != 0] == 1)} + for g, nm in ((0, "PROG"), (1, "G7"), (2, "FAIL")): + m[f"tune_mae_{nm}"] = float(np.abs(pn[gn == g] - yn[gn == g]).mean()) + return m + + +hist, best, t0 = [], None, time.time() +for step in range(1, args.steps + 1): + idx = tr_g[torch.randint(len(tr_g), (args.batch,), device=dev)] + x = Xg[idx] + if args.x_noise > 0: + x = x + args.x_noise * torch.randn_like(x) + a = act_in(idx) + if a is not None and args.act_drop > 0: + a = a * (torch.rand(len(a), 1, device=dev) >= args.act_drop).float() + yt = yg[idx] + if args.hold_aug > 0 and a is not None: + hm = hov_g[idx] & (torch.rand(len(idx), device=dev) < args.hold_aug) + if hm.any(): + a = a.clone(); a[hm] = Ag[idx[hm]].repeat(1, CL); yt = yt.clone(); yt[hm] = yt[hm] - args.hover_margin + loss = (F.huber_loss(model(x, a), yt, reduction="none", delta=args.huber) * wg[idx]).sum() / wg[idx].sum() + opt.zero_grad(set_to_none=True); loss.backward(); opt.step(); sched.step() + if step % args.eval_every == 0 or step == args.steps: + m = tune_metrics(); m.update(step=step, train_loss=float(loss), sec=time.time() - t0); hist.append(m) + print("[r2]", json.dumps({k: (round(v, 4) if isinstance(v, float) else v) for k, v in m.items()}), flush=True) + blob = {"rew2": model.state_dict(), + "arch": {"kind": "Rew2MLP", "d_x": int(X.shape[1]), "d_a": int(d_a), "act": args.act, "chunk": CL, + "adim": int(act.shape[1]), "width": args.width, "depth": args.depth, "act_fn": "SiLU", + "dropout": args.dropout, "input": "cat(x_zscored[1546], a_norm_flat[d_a])", + "output": "shaped reward (regression, no squashing)"}, + "act_norm": {"min": amin.tolist(), "max": amax.tolist(), + "rule": "a_n = 2 (a - min)/(max - min) - 1, per dim, raw absolute-pose actions"}, + "feat_stats": str(C / "feat_stats.npz"), "labels": "reward_shaped2.f32.npy", + "config": vars(args), "tune": m, "step": step} + torch.save(blob, out / "ckpt_last.pt") + if best is None or m["tune_whuber"] < best["tune_whuber"]: + best = m; torch.save(blob, out / "ckpt_best.pt") +json.dump({"history": hist, "best": best, "config": vars(args)}, open(out / "history.json", "w"), indent=1) +open(out / "DONE", "w").write(json.dumps(best)) +print("[r2] DONE best", json.dumps(best), flush=True) diff --git a/rsm_rise/scripts/real/v7/nonmarkov/upload.sh b/rsm_rise/scripts/real/v7/nonmarkov/upload.sh new file mode 100644 index 0000000000000000000000000000000000000000..0ce806d09675da0ec3d4262929585b2977adfc97 --- /dev/null +++ b/rsm_rise/scripts/real/v7/nonmarkov/upload.sh @@ -0,0 +1,40 @@ +#!/usr/bin/env bash +#SBATCH --partition=cpu +#SBATCH --account=grp_runtime +#SBATCH --nodes=1 --ntasks=1 --cpus-per-task=4 +#SBATCH --mem=8G +#SBATCH --time=10: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 export -> hf://buckets/rsm-bucket/rsm-shared/v7/nonmarkov//// + hist/ + results/. +# Stages hardlinks under runs/v7_nonmarkov/export/, SHA256SUMS per subtree, hf sync, re-download + sha256 -c -> export/VERIFY.txt. +# usage: [SUBS="rsmA ... results"] sbatch -J rr_cpu_nm_upload upload.sh (resumable: re-sync is incremental) +set -uo pipefail +ROOT=/proj/dmfexp/zwhong/rsm_rise; cd $ROOT +export HF_TOKEN=$(grep -oP '^HF_TOKEN_RSM_BUCKET=\K.*' .env) HF_HOME=$ROOT/.hf_cache HF_HUB_DISABLE_PROGRESS_BARS=1 +HF=/u/zwhong/.local/bin/hf; DST=hf://buckets/rsm-bucket/rsm-shared/v7/nonmarkov; NM=runs/v7_nonmarkov; E=$NM/export +SUBS=${SUBS:-"hist results headA hopA hopC iqlA iqlC dinowmA dinowmC rsmA rsmC"} +src(){ case $1 in rsmA) echo rsm;; rsmC) echo C/rsm;; hopA) echo hop;; hopC) echo C/hop;; headA) echo head;; iqlA) echo iql;; + iqlC) echo C/iql;; dinowmA) echo dinowm_clip1;; dinowmC) echo C/dinowm_wu5k;; esac; } +for s in $SUBS; do case $s in + hist) mkdir -p $E/hist; ln -f $NM/hist/* $E/hist/;; + results) R=$E/results; mkdir -p $R/eval $R/stove $R/stovehist $R/code + for m in $NM/eval/*; do n=$(basename $m); [ $n = smoke_rsmnm ] && continue; mkdir -p $R/eval/$n; cp -f $m/*.json $R/eval/$n/ 2>/dev/null; done + cp -f $NM/stove/*.npz $R/stove/ 2>/dev/null; cp -f $NM/stovehist/*.npz $NM/stovehist/*.json $R/stovehist/ + rsync -a --exclude __pycache__ --exclude 'wandb' scripts/real/v7/nonmarkov/ $R/code/ + cp -f status/real/v7_nonmarkov_table.md $R/RESULTS.md; cp -f $NM/select.json $R/; cp -f $NM/notes/README.md $R/README.md + cp -f $NM/notes/README.md $E/README.md;; + *) S=$NM/$(src $s); for r in $S/*/*/; do r=${r%/}; [ -f $r/DONE ] || { echo "[export] $r not DONE"; continue; } + sp=$(basename $(dirname $r)); d=$E/$s/$sp/$(basename $r); mkdir -p $d + for f in $r/ckpt_s*.pt $r/policy_s*.pt $r/ckpt_best.pt $r/ckpt_last.pt $r/last.pt $r/config.json $r/history.json $r/history.jsonl \ + $r/loop.json $r/DONE $r/wandb_url.txt; do [ -f $f ] && ln -f $f $d/; done; done;; +esac; done +rc=0 +for s in $SUBS; do ( cd $E/$s && find . -type f ! -name SHA256SUMS ! -name VERIFY.txt | sort | xargs sha256sum > SHA256SUMS ) + $HF buckets sync $E/$s $DST/$s 2>&1 | tail -3 + T=$(mktemp -d -p $ROOT/$NM); $HF buckets sync $DST/$s $T 2>&1 | tail -2 + if ( cd $T && sha256sum -c SHA256SUMS --quiet ); then echo "VERIFY_OK $s $(wc -l < $E/$s/SHA256SUMS) files"; else echo "VERIFY_FAIL $s"; fi + rm -rf $T; done | tee -a $E/VERIFY.txt +$HF buckets cp $E/README.md $DST/README.md 2>&1 | tail -1 +echo "[export] done $(date -u)" diff --git a/rsm_rise/scripts/real/v7/pairtest/bgsweep_table.py b/rsm_rise/scripts/real/v7/pairtest/bgsweep_table.py new file mode 100644 index 0000000000000000000000000000000000000000..0982414a85ff8de4ce9776d30145b97fdc32aefb --- /dev/null +++ b/rsm_rise/scripts/real/v7/pairtest/bgsweep_table.py @@ -0,0 +1,57 @@ +"""RSM_PAIRTEST run 13: beta x gamma sweep table (teacher-forced shaped head, unclamped vs clamped). Light: parses +run_bgsweep.sh logs + hopstat npz (hops, z_last, vraw = pre-clamp reward reads). +usage: venv_rsm/bin/python scripts/real/v7/pairtest/bgsweep_table.py > status/real/rsm_bgsweep_tune.md""" +import glob, json, re, numpy as np +R = "/proj/dmfexp/zwhong/rsm_rise" +GRID = [(g, b) for g in (0.998, 0.995, 0.99) for b in (0.95, 0.98, 0.99, 0.995, 0.997, 0.998) if b <= g] +# clamped cells that already exist from the hop sweep / stitch runs (gamma 0.998 b .99/.995/.997/.998; b99_g995) +OLDC = {(0.998, 0.99): "hs_arc_b99", (0.998, 0.995): "hs_arc_b995", (0.998, 0.997): "hs_arc_b997", (0.998, 0.998): "hs_arc_b998", + (0.995, 0.99): "hs_arc_b99_g995"} +TESTS = ["A_logged", "A_end", "A_hold", "B_logged", "B_syn"] +ST = json.load(open(f"{R}/status/real/rsm_stitch_tune.json"))["models"] +def ehops(b, g): + p = max((g - b) / (g * (1 - b)), 0.0); L = 0 if p <= 0 else int(np.ceil(np.log(1e-3) / np.log(p))) + pk = p ** np.arange(L + 1); pk = np.append(pk[:-1] * (1 - p), pk[-1]) if L > 0 else np.array([1.0]) + return float((np.arange(L + 1) * pk).sum()), float(pk[3:].sum()), L +def cell(txt, name): + out = {} + for t in TESTS: + m = re.findall(rf"\[score\] {name}_16x8 {t}: acc ([0-9.]+) ci \[([0-9.]+), ([0-9.]+)\]", txt) + out[t] = (float(m[-1][0]), float(m[-1][1])) if m else None + for k, nm in [("C16x2", name), ("C16x8", f"{name}_np16s8"), ("C64x4", f"{name}_np64s4")]: + m = re.findall(rf"\[score\] {re.escape(nm)}: BAD primary\(p50\) acc ([0-9.]+) ci \[([0-9.]+), ([0-9.]+)\]", txt) + out[k] = (float(m[-1][0]), float(m[-1][1])) if m else None + M = ST.get(f"{name}_16x8", {}).get("STITCH") + out["STITCH"] = (M["acc"], M["ci"][0]) if M and "acc" in M else None + sr = (M or {}).get("stitch_required") + out["ST_req"] = (sr["acc"], sr["ci"][0]) if sr and "acc" in sr else None + return out +fmt = lambda v: "-" if v is None else f"{v[0]:.2f}" + ("*" if v[0] >= 0.70 and v[1] > 0.5 else "") +COLS = TESTS + ["C16x2", "C16x8", "C64x4", "STITCH", "ST_req"] +print("# beta x gamma sweep, teacher-forced shaped head (c50_bal_adrop02), uncapped (tail 1e-3), TUNE only\n") +print("`*` = PASS (acc >= 0.70 and CI low > 0.5). A/B/STITCH at 16x8. vraw = goal-read reward before any clamp.\n") +print("| clamp | gamma | beta | E[hops] | cap | meas. hops | P(h>=3) | z RMS last hop | frac vraw outside [-1,10] | vraw p1/p99 | " + " | ".join(COLS) + " | passes A/B_log/C |") +print("|" + "---|" * (10 + len(COLS) + 1)) +for clamp in ("u", "c"): + for g, b in GRID: + tag = f"{clamp}_g{str(g)[2:]}_b{str(b)[2:]}"; name = f"bg_{tag}"; hsdir = f"{R}/runs/pairtest/bgsweep/{tag}" + if clamp == "c" and (g, b) in OLDC: + name = OLDC[(g, b)]; t0 = name[3:] + txt = "".join(open(x).read() for x in sorted(glob.glob(f"{R}/logs/slurm/rr_cpu_[hs][st]_{t0}.*.out"))) + hsdir = f"{R}/runs/pairtest/hopsweep/{t0}" + else: + txt = "".join(open(x).read() for x in sorted(glob.glob(f"{R}/logs/slurm/rr_cpu_bg_{tag}.*.out"))) + c = cell(txt, name); eh, g3, L = ehops(b, g) + hs = sorted(glob.glob(f"{hsdir}/hopstat_AB_*.npz")) + if hs: + Z = [np.load(f) for f in hs]; H = np.concatenate([z["hops"] for z in Z]); zl = np.concatenate([z["z_last"] for z in Z]) + V = np.concatenate([z["vraw"] for z in Z if "vraw" in z.files]) if any("vraw" in z.files for z in Z) else np.zeros(0) + hm, h3, zz = f"{H.mean():.2f}", f"{(H >= 3).mean():.2f}", f"{zl.mean():.2f}" + vo = f"{((V < -1) | (V > 10)).mean():.3f}" if V.size else "n/a" + vp = f"{np.percentile(V, 1):.1f}/{np.percentile(V, 99):.1f}" if V.size else "n/a" + else: + hm = h3 = zz = vo = vp = "-" + ok = all(c[k] is not None and c[k][0] >= 0.70 and c[k][1] > 0.5 for k in ("A_logged", "A_end", "A_hold", "B_logged", "C16x2", "C16x8", "C64x4")) + done = all(c[k] is not None for k in COLS[:-1]) + print(f"| {'no' if clamp == 'u' else 'yes'} | {g} | {b} | {eh:.2f} | {L} | {hm} | {h3} | {zz} | {vo} | {vp} | " + + " | ".join(fmt(c[k]) for k in COLS) + f" | {'YES' if ok else ('no' if done else '(pending)')} |") diff --git a/rsm_rise/scripts/real/v7/pairtest/bsyn_ctrl.py b/rsm_rise/scripts/real/v7/pairtest/bsyn_ctrl.py new file mode 100644 index 0000000000000000000000000000000000000000..f8f250b6dc5b9f4af6fba32b91ac5b9627dc4906 --- /dev/null +++ b/rsm_rise/scripts/real/v7/pairtest/bsyn_ctrl.py @@ -0,0 +1,50 @@ +#!/usr/bin/env python +"""RSM_PAIRTEST run 17 DIAGNOSTIC (not a frozen test; B_syn itself is unchanged): direction controls for B_syn. +B_syn alt = a_prog + (t+1)/50 * D * u (u toward the nearest failure arrival). Controls, same anchors / D / ramp: + Bctl_away: a_prog - (t+1)/50 * D * u (shift AWAY from failure) + Bctl_rand: a_prog + (t+1)/50 * D * v, v = random unit 3-vector (seed 0 per anchor index) +A critic that ranks by value should prefer a_prog over B_syn's alt MORE than over Bctl_away's alt; a pure +behaviour-support / distance-to-BC critic is direction-blind (same accuracy on all three). +usage: bsyn_ctrl.py --stage build (writes errmode/Bctl_{away,rand}_tune.npz in the errmode pair format) + bsyn_ctrl.py --stage z --model NAME (after errmode_test.py scored NAME on B_syn,Bctl_away,Bctl_rand) +""" +import argparse, json, os, sys +from pathlib import Path +import numpy as np, torch +sys.path.insert(0, str(Path(__file__).resolve().parent)) +os.environ.setdefault("PAIRTEST_VERSION", "pairtest_v3") +import pairtest as PT # noqa +ap = argparse.ArgumentParser(); ap.add_argument("--stage", required=True); ap.add_argument("--model", default="") +a = ap.parse_args(); O = PT.OUT / "errmode"; S = "tune" +if a.stage == "build": + T = dict(np.load(O / f"B_syn_{S}.npz")); n = len(T["anc"]) + G = T["prog"].reshape(n, PT.CHUNK, -1); H = T["alt"].reshape(n, PT.CHUNK, -1) + Du = (H[:, -1, :3] - G[:, -1, :3]); D = np.linalg.norm(Du, axis=1) + ramp = ((np.arange(PT.CHUNK) + 1) / PT.CHUNK)[None, :, None] + rng = np.random.default_rng(0); v = rng.normal(size=(n, 3)); v /= np.linalg.norm(v, axis=1, keepdims=True) + for nm, sh in (("Bctl_away", -Du), ("Bctl_rand", D[:, None] * v)): + K = G.copy(); K[:, :, :3] += ramp * sh[:, None, :] + d = {k: T[k] for k in T}; d["alt"] = K.reshape(n, -1).astype(np.float32); np.savez(O / f"{nm}_{S}.npz", **d) + print("[bctl] built", n, "anchors; D median", float(np.median(D))) +else: + F = PT.Feat() + import rsm_scorer_ar as AR + hop, _ = AR._load_rsm_scorer().load_hop_head(str(PT.HOP), 1546, 1, "cpu", feat_sd=F.sd) + ls = hop.pol.log_std.clamp(-5.0, 2.0).detach().double(); d = ls.numel() + E0 = float((-ls - 0.5 * np.log(2 * np.pi)).sum()) - d / 2.0; SD0 = float(np.sqrt(d / 2.0)) + sc = json.load(open(PT.ST / "h10_support_tune.json"))["diag"]["scale"] + base = a.model.replace("diagctl_", "tr_"); r = sc[base]["sQ"] / sc[base]["sZ"] + out = {} + for tn in ("B_syn", "Bctl_away", "Bctl_rand"): + T = dict(np.load(O / f"{tn}_{S}.npz")); Q = dict(np.load(O / f"q_{tn}_{S}_{a.model}.npz")) + x = torch.from_numpy(F.x(T["anc"])) + with torch.no_grad(): + mu, l = hop.pol(x * hop.scale, torch.zeros(len(x), dtype=torch.long)); mu = mu.double(); var = (2 * l.double()).exp() + zz = lambda A: (((-0.5 * ((torch.from_numpy(A).double() - mu) ** 2 / var + 2 * l.double() + np.log(2 * np.pi))).sum(-1) - E0) / SD0).numpy() + zg, za = zz(T["prog"]), zz(T["alt"]) + R = {} + for lam in (0, 0.1, 0.3, 1.0, 3.0, "inf"): + g = zg if lam == "inf" else Q["qg"] + float(lam) * r * zg; b = za if lam == "inf" else Q["qa"] + float(lam) * r * za + M = PT.metrics(g, b, T["ep"], list(T["key"])); R[str(lam)] = {"acc": M["acc"], "ci": M["ci"], "gap": M["gap_mean"]} + out[tn] = R; print(tn, {k: round(v["acc"], 3) for k, v in R.items()}, flush=True) + json.dump(out, open(PT.ST / f"rsm_bsyn_ctrl_{S}_{a.model}.json", "w"), indent=1) diff --git a/rsm_rise/scripts/real/v7/pairtest/bsyn_diag.py b/rsm_rise/scripts/real/v7/pairtest/bsyn_diag.py new file mode 100644 index 0000000000000000000000000000000000000000..890bc138891ac70aba0fed2127a494d91c55d94a --- /dev/null +++ b/rsm_rise/scripts/real/v7/pairtest/bsyn_diag.py @@ -0,0 +1,139 @@ +#!/usr/bin/env python +"""RSM_PAIRTEST run 8: DIAGNOSIS of B_syn (frozen test unchanged; this only reads its pairs + cached Q). + +G. geometry / in-distribution (model-free): + per anchor: D (shift length), cos(u, v_prog) (shift dir vs progress motion), endpoint distance to the GOOD + segment's arrival mean vs the FAILURE arrival target (prog vs alt), chunk-space NN distance of the RELATIVE xyz + trajectory (a[:, :3] - a[0, :3], 150-d) to TRAIN chunks of the same edge_from (prog vs alt; prog is held-out too, + so it is the fair reference), NN of the ABSOLUTE xyz trajectory to all TRAIN chunks, max per-step speed vs TRAIN + percentiles, workspace NN of the commanded end point. + Correlations of the cached Q gap (qg - qa) with those, accuracy by tertile -- for every cached model. +M. first-hop successor response (frozen v7 successor, beta 0.99, 8 flow steps, 32 CRN samples, prog vs alt at s_g): + decode sampled ee xyz = x[1536:1539]*sd+mu; response = / D; distance of the + sampled xyz to the failure arrival target; the self-forced d1 head read r(z_hat, hop action) prog vs alt. +""" +import json, os, sys +from pathlib import Path +import numpy as np, torch + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +os.environ.setdefault("PAIRTEST_VERSION", "pairtest_v3") +import pairtest as PT # noqa + +OUT = PT.OUT / "errmode"; RES = PT.OUT / os.environ.get("BSYN_RES", "bsyn_diag"); RES.mkdir(exist_ok=True) # run 11: per-model output dir +T = dict(np.load(OUT / "B_syn_tune.npz")); TL = dict(np.load(OUT / "B_logged_tune.npz")) +info, tt, ef, et = PT.load_meta() +e_from = np.load(PT.C / "edge_from.i16.npy").astype(np.int64); e_to = np.load(PT.C / "edge_to.i16.npy").astype(np.int64) +pr = np.load(PT.C / "proprio.f32.npy", mmap_mode="r"); act = np.load(PT.C / "act.f32.npy", mmap_mode="r") +row_ep = np.repeat(np.arange(len(ef)), et - ef); ep_end = lambda rows: et[row_ep[np.asarray(rows)]] +train = sorted(e for e, v in info.items() if v["split"] == "train") +anc = T["anc"]; n = len(anc); CH = PT.CHUNK +P = T["prog"].reshape(n, CH, -1); A = T["alt"].reshape(n, CH, -1) +sh = A[:, -1, :3] - P[:, -1, :3]; D = np.linalg.norm(sh, axis=1); u = sh / np.maximum(D[:, None], 1e-9) +v = P[:, -1, :3] - P[:, 0, :3]; vn = np.linalg.norm(v, axis=1) +cos = (u * v).sum(1) / np.maximum(vn, 1e-9) +out = {"n": int(n)} +# good arrival targets per edge_to; failure arrival = nearest of 5/6 (as the test) +arrG = {} +for e in train: + for s in np.unique(e_to[ef[e]:et[e]]): + rr = np.flatnonzero(e_to[ef[e]:et[e]] == s) + arrG.setdefault(int(s), []).append(np.asarray(pr[ef[e] + rr[-1], :3], np.float64)) +arrG = {k: np.mean(v_, 0) for k, v_ in arrG.items()} +arrF = {k: arrG[k] for k in (5, 6) if k in arrG} +p_now = np.asarray(pr[anc, :3], np.float64) +tgtF = np.stack([min(arrF.values(), key=lambda q: np.linalg.norm(q - p)) for p in p_now]) +tgtG = np.stack([arrG[int(e_to[t])] for t in anc]) +dG_p = np.linalg.norm(P[:, -1, :3] - tgtG, axis=1); dG_a = np.linalg.norm(A[:, -1, :3] - tgtG, axis=1) +dF_p = np.linalg.norm(P[:, -1, :3] - tgtF, axis=1); dF_a = np.linalg.norm(A[:, -1, :3] - tgtF, axis=1) +cosGF = ((tgtG - p_now) * (tgtF - p_now)).sum(1) / np.maximum(np.linalg.norm(tgtG - p_now, axis=1) * np.linalg.norm(tgtF - p_now, axis=1), 1e-9) +# TRAIN chunk bank (every 5th frame) +tr = np.concatenate([np.arange(ef[e], et[e] - 1, 5) for e in train]) +TB = PT.chunk(act, tr, ep_end(tr)).reshape(len(tr), CH, -1)[:, :, :3].astype(np.float32) +rel = lambda X: (X[:, :, :3] - X[:, :1, :3]).reshape(len(X), -1).astype(np.float32) +spd = lambda X: np.linalg.norm(np.diff(X[:, :, :3], axis=1), axis=2).max(1) +TBrel = rel(TB); TBabs = TB.reshape(len(TB), -1) +nnR_p = np.zeros(n, np.float32); nnR_a = np.zeros(n, np.float32) +for s0 in np.unique(e_from[anc]): + w = np.flatnonzero(e_from[anc] == s0); pool = np.flatnonzero(e_from[tr] == s0) + nnR_p[w] = PT.nn_dist(rel(P[w]), TBrel[pool])[0]; nnR_a[w] = PT.nn_dist(rel(A[w]), TBrel[pool])[0] +nnA_p = PT.nn_dist(P[:, :, :3].reshape(n, -1).astype(np.float32), TBabs)[0] +nnA_a = PT.nn_dist(A[:, :, :3].reshape(n, -1).astype(np.float32), TBabs)[0] +ws = np.asarray(pr[tr, :3], np.float32) +nnE_p = PT.nn_dist(P[:, -1, :3].astype(np.float32), ws)[0]; nnE_a = PT.nn_dist(A[:, -1, :3].astype(np.float32), ws)[0] +spT = spd(TB); spP, spA = spd(P), spd(A) +pct = lambda x: {str(p): round(float(np.percentile(x, p)), 4) for p in (10, 50, 90)} +out["G"] = {"D": pct(D), "prog_disp": pct(vn), "D_over_prog_disp": pct(D / np.maximum(vn, 1e-3)), + "cos_shift_vs_prog": pct(cos), "frac_cos_gt_0.5": float((cos > 0.5).mean()), + "cos_goodtarget_vs_failtarget": pct(cosGF), + "end_to_good_target": {"prog": pct(dG_p), "alt": pct(dG_a), "frac_alt_closer_to_good": float((dG_a < dG_p).mean())}, + "end_to_fail_target": {"prog": pct(dF_p), "alt": pct(dF_a)}, + "nn_rel_traj_same_stage": {"prog": pct(nnR_p), "alt": pct(nnR_a), "frac_alt_further": float((nnR_a > nnR_p).mean())}, + "nn_abs_traj_all": {"prog": pct(nnA_p), "alt": pct(nnA_a), "frac_alt_further": float((nnA_a > nnA_p).mean())}, + "nn_end_workspace": {"prog": pct(nnE_p), "alt": pct(nnE_a)}, + "max_step_speed": {"train": pct(spT), "prog": pct(spP), "alt": pct(spA), + "frac_alt_above_train_p99": float((spA > np.percentile(spT, 99)).mean()), + "frac_prog_above_train_p99": float((spP > np.percentile(spT, 99)).mean())}} +feats = {"D": D, "cos": cos, "ood_rel": nnR_a - nnR_p, "ood_abs": nnA_a - nnA_p, "alt_closer_good": (dG_a < dG_p).astype(float), + "cosGF": cosGF, "dspeed": spA - spP} +from scipy.stats import spearmanr +out["models"] = {} +for f in sorted(OUT.glob("q_B_syn_tune_*.npz")): + name = f.stem[len("q_B_syn_tune_"):]; Q = dict(np.load(f)) + if np.isnan(Q["qg"]).any(): + continue + gap = Q["qg"] - Q["qa"]; corr = (gap > 0) + 0.5 * (gap == 0) + M = {"acc": float(corr.mean()), "spearman_gap": {k: round(float(spearmanr(gap, x)[0]), 3) for k, x in feats.items()}} + for k in ("cos", "ood_rel", "D", "cosGF"): + q = np.percentile(feats[k], [33.3, 66.7]); b = np.digitize(feats[k], q) + M[f"acc_by_{k}_tertile"] = [round(float(corr[b == i].mean()), 3) for i in range(3)] + M["acc_alt_closer_good"] = round(float(corr[dG_a < dG_p].mean()), 3) if (dG_a < dG_p).any() else None + M["acc_alt_further_good"] = round(float(corr[dG_a >= dG_p].mean()), 3) + out["models"][name] = M +out["tertile_edges"] = {k: np.percentile(feats[k], [33.3, 66.7]).round(4).tolist() for k in ("cos", "ood_rel", "D", "cosGF")} +np.savez(RES / "geom.npz", **feats, nnR_p=nnR_p, nnR_a=nnR_a, dG_p=dG_p, dG_a=dG_a) +json.dump(out, open(RES / "geom.json", "w"), indent=1) +print(json.dumps(out["G"], indent=1), flush=True) +for k, M in out["models"].items(): + print(k, json.dumps(M), flush=True) + +# ---- M: first-hop successor response +if os.environ.get("SKIP_M"): + sys.exit() +F = PT.Feat(); mu_xyz = F.mu[1536:1539]; sd_xyz = F.sd[1536:1539] +kind, sc = PT.build_scorer(os.environ.get("BSYN_SPEC", "arc:runs/v7_reward2_sf/d1/ckpt_best.pt,np=16,tail=0.65"), F.sd, 1546) +be = sc.backend +import rsm_scorer_ar as AR +m = AR._load_rsm_scorer(); sample_future = m._rsm_modules()[1].sample_future +X = torch.from_numpy(F.x(anc)); NS = 32; g = torch.Generator().manual_seed(0) +resp, dFs_p, dFs_a, r_p, r_a, sp_p, sp_a, dz = [], [], [], [], [], [], [], [] +with torch.no_grad(): + for i in range(n): + z = be.enc(X[i:i + 1]).repeat(NS, 1); tk = torch.zeros(NS, dtype=torch.long); b = torch.full((NS,), 0.99) + x0 = torch.randn(NS, z.shape[1], generator=g); eps = torch.randn(NS, int(be.hop.d_act), generator=g) + zz = {} + for key, Ach in (("p", P[i]), ("a", A[i])): + a = torch.from_numpy(Ach.reshape(1, -1)).float().repeat(NS, 1) + zh = sample_future(be.flow, z, a, tk, b, be.rms, 8, n=1, x0=x0.clone()) + ag = be.hop.sample_eps(zh, tk, eps) + zz[key] = (zh, be.rew2(zh, ag).numpy()) + xyz = {k: (zz[k][0][:, 1536:1539].numpy() * sd_xyz + mu_xyz) for k in zz} + resp.append(float(((xyz["a"].mean(0) - xyz["p"].mean(0)) * u[i]).sum() / D[i])) + dFs_p.append(float(np.linalg.norm(xyz["p"] - tgtF[i], axis=1).mean())); dFs_a.append(float(np.linalg.norm(xyz["a"] - tgtF[i], axis=1).mean())) + r_p.append(float(zz["p"][1].mean())); r_a.append(float(zz["a"][1].mean())) + dz.append(float((zz["a"][0] - zz["p"][0]).norm(dim=1).mean())) + sp_p.append(float(xyz["p"].std(0).mean())) + if i % 100 == 0: + print(f"[M] {i}/{n}", flush=True) +resp, r_p, r_a = map(np.array, (resp, r_p, r_a)); dFs_p, dFs_a, dz = map(np.array, (dFs_p, dFs_a, dz)) +key = T["key"] +M = {"response_ratio(/D)": pct(resp), "frac_response_gt_0.25": float((resp > 0.25).mean()), + "sampled_dist_to_fail_target": {"prog": pct(dFs_p), "alt": pct(dFs_a), "frac_alt_closer": float((dFs_a < dFs_p).mean())}, + "sample_xyz_sd_prog": pct(np.array(sp_p)), "latent_dz_alt_vs_prog": pct(dz), + "hop1_read_r": {"prog": pct(r_p), "alt": pct(r_a), "acc(r_p>r_a)": float((r_p > r_a).mean())}, + "hop1_acc_by_seg": {k: round(float((r_p > r_a)[key == k].mean()), 3) for k in sorted(set(key))}, + "spearman_hop1gap_vs_resp": float(spearmanr(r_p - r_a, resp)[0])} +out["M"] = M +np.savez(RES / "hop1.npz", resp=resp, r_p=r_p, r_a=r_a, dFs_p=dFs_p, dFs_a=dFs_a, dz=dz) +json.dump(out, open(RES / "geom.json", "w"), indent=1) +print(json.dumps(M, indent=1), flush=True) diff --git a/rsm_rise/scripts/real/v7/pairtest/chain_diag.py b/rsm_rise/scripts/real/v7/pairtest/chain_diag.py new file mode 100644 index 0000000000000000000000000000000000000000..8cd0de698dc497736e460c06d6e4a8dc4f031991 --- /dev/null +++ b/rsm_rise/scripts/real/v7/pairtest/chain_diag.py @@ -0,0 +1,142 @@ +#!/usr/bin/env python +"""RSM_PAIRTEST run 5 -- DEBUG why the shaped head r2 fails INSIDE the chain (ar_adrop02 0.656, 0.00 on 0->6 pairs) +while the head alone ranks 0.77 and v7_old's chain 0.91. Diagnostic only (does not change pairtest_v3). + +On the frozen v3 TUNE pairs (p50, 90 pairs) run ONE chain walk per (pair, action, particle) -- the exact walk of +rsm_scorer_ar.q_chain_value_ar / rsm_scorer._q_chain_logit (coins, CRN noise, hop-head re-decides; beta .99, +gamma .998, 64 particles x 4 seeds) -- and read the SAME frozen node z_g several ways: + r2_hop r2(z_g, hop-sample a_g) (= the chain_ar read-out) + r2_hopmean r2(z_g, hop mean) (goal_action=hop_mean) + r2_clip3 clip(r2_hop, -1, 3) (bounded goal value: tests the +10 heavy tail) + old sigmoid(rew_old(z_g)/25) (= v7_old read-out) + lab_s2 reward_shaped2 of the nearest TRAIN frame to z_g (label oracle: successor right, head perfect) + lab_prog reward_progress of that frame + fail 1[nearest frame lies on a failure segment (edge_to 5/6)] + goal 1[nearest frame lies on a segment into 7] + nn_d distance to that frame +Also the FIRST hop alone (z_1 = flow(s_g, a_cand), the only place the candidate enters): same reads. +Head-alone r2(s_g, a) is included for reference. Output runs/pairtest/diag/chain_diag_tune.npz + status md. +""" +import json, os, sys, time +from pathlib import Path +import numpy as np, torch + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +os.environ.setdefault("PAIRTEST_VERSION", "pairtest_v3") +import pairtest as PT # noqa +import rsm_scorer_ar as AR # noqa + +R2 = PT.ROOT / "runs/v7_reward2/c50_bal_adrop02/ckpt_best.pt" +NP, SEEDS, BETA, GAMMA, T = int(os.environ.get("NP", 64)), int(os.environ.get("SEEDS", 4)), 0.99, 0.998, 25.0 +OUTD = PT.OUT / "diag"; OUTD.mkdir(parents=True, exist_ok=True) + + +def main(): + info, tt, ef, et = PT.load_meta(); F = PT.Feat() + P = dict(np.load(PT.OUT / "pairs_v3_tune.npz")); PJ = json.load(open(PT.OUT / "pairs_v3_tune.json")) + keep = np.flatnonzero(P["BAD_dist"] < PJ["thresholds"]["p50"]) + act = np.load(PT.C / "act.f32.npy", mmap_mode="r") + row_ep = np.repeat(np.arange(len(ef)), et - ef) + anc, aep, brow = P["anc_row"][keep], P["anc_ep"][keep], P["BAD_row"][keep] + Ag = PT.chunk(act, anc, et[aep]); Ab = PT.chunk(act, brow, et[row_ep[brow]]) + X = torch.from_numpy(F.x(anc)) + keys = [f"{PT.route(info, int(e))} | {PT.route(info, int(row_ep[b]))}" for e, b in zip(aep, brow)] + # label oracle pool: every 2nd TRAIN frame + train = sorted(e for e, v in info.items() if v["split"] == "train") + pool = np.concatenate([np.arange(ef[e], et[e], 2) for e in train]) + Pool = torch.from_numpy(F.x(pool)); pn = (Pool * Pool).sum(1) + s2 = np.load(PT.C / "reward_shaped2.f32.npy"); rp = np.load(PT.C / "reward_progress.f32.npy") + e_to = np.load(PT.C / "edge_to.i16.npy") + lab = {"lab_s2": torch.from_numpy(s2[pool]).float(), "lab_prog": torch.from_numpy(rp[pool]).float(), + "fail": torch.from_numpy(np.isin(e_to[pool], [5, 6]).astype(np.float32)), + "goal": torch.from_numpy((e_to[pool] == 7).astype(np.float32))} + + def nn_reads(z): + d2 = (z * z).sum(1)[:, None] + pn[None] - 2 * z @ Pool.T + v, j = d2.clamp_min(0).min(1) + out = {k: t[j] for k, t in lab.items()}; out["nn_d"] = v.sqrt(); return out + + # models + sc = PT.build_scorer("old", F.sd, X.shape[1])[1]; be = sc.backend + m = AR._load_rsm_scorer(); sample_future = m._rsm_modules()[1].sample_future + hop = be.hop; rew2 = AR.ActRewardHead(str(R2)) + flow, rms, rew_old = be.flow, be.rms, be.rew + p_cont = m.chain_continuation_p(BETA, GAMMA); L = int(m.chain_cap(BETA, GAMMA, 1e-3)) + print(f"[diag] pairs {len(keep)} p_cont {p_cont:.4f} cap {L} NP {NP} seeds {SEEDS}", flush=True) + READS = ["r2_hop", "r2_hopmean", "r2_clip3", "old", "lab_s2", "lab_prog", "fail", "goal", "nn_d"] + res = {f"{w}_{k}": np.zeros((len(keep), 2, SEEDS, NP), np.float32) for w in ("chain", "hop1") for k in READS} + res["hops"] = np.zeros((len(keep), 2, SEEDS, NP), np.float32) + res["head_alone"] = np.zeros((len(keep), 2), np.float32) + t0 = time.time() + if os.environ.get("SUMMARY_ONLY"): + Z = dict(np.load(OUTD / "chain_diag_tune.npz")); res = {k: Z[k] for k in res} + with torch.no_grad(): + for i in ([] if os.environ.get("SUMMARY_ONLY") else range(len(keep))): + A = torch.from_numpy(np.stack([Ag[i], Ab[i]])) + res["head_alone"][i] = rew2(X[i][None].expand(2, -1), A).numpy() + for s in range(SEEDS): + g = torch.Generator().manual_seed(1000 * s + 7) + rnd = lambda *sh: torch.randn(*sh, generator=g) + x0s = [rnd(NP, X.shape[1]) for _ in range(L + 1)] + epss = [rnd(NP, hop.d_act) for _ in range(L)] + coins = torch.rand(L, NP, generator=g); eps_goal = rnd(NP, hop.d_act); x0_h1 = rnd(NP, X.shape[1]) + for c in range(2): + z = X[i][None].expand(NP, -1).clone(); a = A[c][None].expand(NP, -1).clone() + tk = torch.zeros(NP, dtype=torch.long); bq = torch.full((NP,), BETA) + # first hop only (candidate's own effect) + z1 = sample_future(flow, z, a, tk, bq, rms, 8, n=1, x0=x0_h1) + alive = torch.ones(NP, dtype=torch.bool); hops = torch.zeros(NP) + for k in range(L): + cont = alive & (coins[k] < p_cont); idx = cont.nonzero(as_tuple=True)[0]; alive = cont + if idx.numel() == 0: + break + zn = sample_future(flow, z[idx], a[idx], tk[idx], bq[idx], rms, 8, n=1, x0=x0s[k][idx]) + an = hop.sample_eps(zn, tk[idx], epss[k][idx]) + z = z.index_copy(0, idx, zn); a = a.index_copy(0, idx, an); hops[idx] += 1 + zg = sample_future(flow, z, a, tk, bq, rms, 8, n=1, x0=x0s[L]) + for w, zz in (("chain", zg), ("hop1", z1)): + ah = hop.sample_eps(zz, tk, eps_goal); am = hop.sample_eps(zz, tk, torch.zeros_like(eps_goal)) + r_h = rew2(zz, ah) + rd = {"r2_hop": r_h, "r2_hopmean": rew2(zz, am), "r2_clip3": r_h.clamp(-1, 3), + "old": torch.sigmoid(rew_old(zz, tk).float() / T)} + rd.update(nn_reads(zz)) + for k2, v in rd.items(): + res[f"{w}_{k2}"][i, c, s] = v.float().numpy() + res["hops"][i, c, s] = hops.numpy() + if i % 10 == 0: + print(f"[diag] {i}/{len(keep)} {time.time() - t0:.0f}s", flush=True) + if not os.environ.get("SUMMARY_ONLY"): + np.savez(OUTD / "chain_diag_tune.npz", keys=np.array(keys), anc_ep=aep, **res) + # summary + pairs = sorted(set(keys)); karr = np.array(keys) + lines = ["# chain_diag (v3 TUNE p50 pairs; a_good vs a_bad at s_g; 64x4 chain rollouts, same walks for every read)", + "", "acc = P(mean read under a_good > under a_bad), episode-bootstrap CI; columns = read-outs of the SAME frozen nodes", + ""] + def acc(q): + corr = np.where(q[:, 0] > q[:, 1], 1.0, np.where(q[:, 0] == q[:, 1], 0.5, 0.0)); return corr + summ = {} + for w in ("hop1", "chain"): + lines += [f"## {w}", "", "| read | overall acc [CI] | mean(good) | mean(bad) | " + " | ".join(pairs) + " |", + "|---|---|---|---|" + "---|" * len(pairs)] + for k in READS: + q = res[f"{w}_{k}"].mean((2, 3)); corr = acc(q) + ci = PT.boot_ci(corr, aep); bp = [corr[karr == p].mean() for p in pairs] + summ[f"{w}_{k}"] = {"acc": float(corr.mean()), "ci": ci, "mg": float(q[:, 0].mean()), "mb": float(q[:, 1].mean()), + "by_pair": dict(zip(pairs, map(float, bp)))} + lines.append(f"| {k} | {corr.mean():.3f} [{ci[0]:.2f},{ci[1]:.2f}] | {q[:, 0].mean():.3f} | {q[:, 1].mean():.3f} | " + + " | ".join(f"{b:.2f} (n{(karr == pp).sum()})" for b, pp in zip(bp, pairs)) + " |") + lines.append("") + q = res["head_alone"]; corr = acc(q) + lines.append(f"head alone r2(s_g,a): acc {corr.mean():.3f}; " + ", ".join(f"{p}: {corr[karr == p].mean():.2f}" for p in pairs)) + # heavy-tail check: share of |Q| gap explained by particles whose r2 read > 5 + rh = res["chain_r2_hop"]; big = (rh > 5) + lines.append(f"chain r2_hop reads > 5: good {big[:, 0].mean():.4f}, bad {big[:, 1].mean():.4f}; " + f"goal-segment NN: good {res['chain_goal'][:, 0].mean():.4f} bad {res['chain_goal'][:, 1].mean():.4f}") + lines.append(f"mean hops {res['hops'].mean():.2f}") + json.dump(summ, open(OUTD / "chain_diag_tune.json", "w"), indent=1) + open(PT.ST / "rsm_pairtest_chain_diag.md", "w").write("\n".join(lines) + "\n") + print("\n".join(lines), flush=True) + + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/real/v7/pairtest/errmode_test.py b/rsm_rise/scripts/real/v7/pairtest/errmode_test.py new file mode 100644 index 0000000000000000000000000000000000000000..7bf4ce81a0db263be5d8945abdddc510f34ffd78 --- /dev/null +++ b/rsm_rise/scripts/real/v7/pairtest/errmode_test.py @@ -0,0 +1,267 @@ +#!/usr/bin/env python +"""RSM_PAIRTEST run 5 (owner 2026-11-20 ~07:50Z): two FROZEN offline tests for the two real-robot error modes. +Written before any model was scored on them; select on TUNE only; TEST needs the owner's OK (--allow-test). + +Common: state x = the successor's 1546-d z-scored input; situation distance = L2 in z-scored proprio (10-d, mu/sd over +TRAIN frames, as pairtest_v3). Chunks = logged 50x10 raw absolute-pose chunks (past the episode end the last action +repeats). Both chunks of a pair are scored AT s_g in ONE scorer call (common random numbers), Q averaged over seeds. +Metric = P(Q(progress chunk) > Q(alternative)) (ties 0.5), 95% bootstrap CI over held-out episodes (2000x); +PASS = acc >= 0.70 and CI low > 0.5. +Coincidence threshold THR (model-free, TRAIN only) = p50 of within-route NN proprio distances: anchors every 25th frame + of every TRAIN episode, pool = every 2nd frame of OTHER TRAIN episodes of the same route with the same edge_from + (the pairtest_v3 rule, extended from edge_from {0,2} to every edge_from). p25 also reported. + +A. STALL (error mode 1: "once at a success meta-state it stays there"). + Anchors: held-out episodes of route 3->8 (robot at success meta-state 3) and 8->7 (at 8), every 5th frame. + a_prog = logged chunk at s_g (continues 3->8 / 8->7). + A_logged (PRIMARY, revised 08:10Z BEFORE any model was scored on A -- model-free reason: the end-of-episode partner + below gave only 13 coincident pairs from 2 episodes, 0 at stage 8): a_stay = logged chunk of a HOVER frame: TRAIN + frames on segments leaving the same meta-state (edge_from == stage) whose chunk is in the lowest 5% of max ee + displacement for that stage (frames >= 50 before the episode end, so the + chunk is real logged motion, not end padding); the nearest in proprio. ALL anchors scored; accuracy also split coincident (d < THR) + / relaxed (d >= THR); PASS judged on all. + A_end (secondary): a_stay = logged chunk of the nearest of the LAST 10 frames of TRAIN episodes that END at the same + meta-state (stage 3: 0->1->3, 0->2->3, 2->3; stage 8: 3->8) -- arrived, then holds (last action repeated); all anchors. + A_hold (secondary, synthetic, every anchor incl. late 8->7 = approaching 7): a_stay = a_prog[0] repeated 50x + (go to the currently commanded pose and stay). +B. DEVIATION (error mode 2: "on the way to success it deviates toward failure"). + Anchors: held-out GOOD episodes (final in {3,8,7}), every 10th frame, on progress segments (edge_to in {1,2,3,8,7}): + 0->1, 1->3, 0->2, 2->3, 3->8, 8->7. + B_logged (PRIMARY): a_dev = logged chunk of the nearest TRAIN frame on a FAILURE segment (edge_to in {5,6}; routes + 0->5, 0->6, 0->2->6), same edge_from if any such segment exists (0, 2), else any failure segment (relaxed; stages 1, + 3, 8). ALL anchors are scored; the distance distribution is reported and the accuracy is split into coincident + (d < THR) and relaxed (d >= THR) subsets. PASS is judged on all B pairs (owner: "where no coincident partner + exists, use the nearest with a relaxed threshold"). + B_syn (secondary, synthetic): a_dev = a_prog with its xyz translated toward the failure arrival position: + a_dev[t, :3] = a_prog[t, :3] + (t+1)/50 * D * u, u = unit(p_fail - p_now), p_fail = mean ee position of TRAIN + arrival frames (last frame) of the failure segment (into 5 or 6) whose arrival is NEAREST to p_now, + D = max(||a_prog[49,:3] - a_prog[0,:3]||, 0.03 m). Rotation and gripper unchanged. +C. pairtest_v3 is kept as the regression check (pairtest.py, unchanged). + +usage: errmode_test.py --stage pairs [--split tune] + errmode_test.py --stage score --model NAME=SPEC [--np 16 --seeds 8] (SPEC as pairtest.py: old | ar: | + r2:, ,succ= ,np=..) +""" +import argparse, json, os, sys, time +from pathlib import Path +import numpy as np, torch + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +os.environ.setdefault("PAIRTEST_VERSION", "pairtest_v3") +import pairtest as PT # noqa + +OUT = PT.OUT / "errmode"; OUT.mkdir(parents=True, exist_ok=True) +TESTS = ["A_logged", "A_end", "A_hold", "B_logged", "B_syn"] +PRIMARY = {"A": "A_logged", "B": "B_logged"} + + +def stage_pairs(a): + info, tt, ef, et = PT.load_meta(); F = PT.Feat() + e_from = np.load(PT.C / "edge_from.i16.npy").astype(np.int64); e_to = np.load(PT.C / "edge_to.i16.npy").astype(np.int64) + pr = np.load(PT.C / "proprio.f32.npy", mmap_mode="r"); act = np.load(PT.C / "act.f32.npy", mmap_mode="r") + row_ep = np.repeat(np.arange(len(ef)), et - ef) + train, held = PT.split_eps(info, tt, a.split) + tr_rows = np.concatenate([np.arange(ef[e], et[e]) for e in train]) + prT = np.asarray(pr[tr_rows], np.float64); pmu = prT.mean(0); psd = np.maximum(prT.std(0), 1e-3) + px = lambda rows: ((np.asarray(pr[np.asarray(rows, np.int64)], np.float64) - pmu) / psd).astype(np.float32) + # ---- threshold (TRAIN only) + by_route = {} + for e in train: + by_route.setdefault(PT.route(info, e), []).append(e) + dnn = [] + for r, eps in sorted(by_route.items()): + for s0 in np.unique(e_from[np.concatenate([np.arange(ef[e], et[e]) for e in eps])]): + rows = [np.arange(ef[e], et[e], 2)[e_from[ef[e]:et[e]:2] == s0] for e in eps] + pe = np.concatenate([[e] * len(x) for e, x in zip(eps, rows)]).astype(np.int64) + Pp = px(np.concatenate(rows)) + for e in eps: + q = np.arange(ef[e], et[e], 25); q = q[e_from[q] == s0] + if len(q) and (pe != e).sum(): + dnn.append(PT.nn_dist(px(q), Pp[pe != e])[0]) + dnn = np.concatenate(dnn); thr = {f"p{p}": float(np.percentile(dnn, p)) for p in (10, 25, 50)} + meta = {"split": a.split, "thresholds": thr, "THR": thr["p50"], "dnn_n": int(len(dnn)), + "proprio_mu": pmu.tolist(), "proprio_sd": psd.tolist()} + print("[pairs] thresholds", thr, flush=True) + ep_end = lambda rows: et[row_ep[np.asarray(rows)]] + T = {} + # ---- A + fin = {e: info[e]["final_state"] for e in info} + anc, stage = [], [] + for e in held: + rt = PT.route(info, e) + if rt in ("3->8", "8->7"): + q = np.arange(ef[e], et[e], 5); anc.append(q); stage.append(np.full(len(q), int(rt[0]))) + anc = np.concatenate(anc); stage = np.concatenate(stage); Ag = PT.chunk(act, anc, ep_end(anc)) + disp = lambda A: np.linalg.norm(A.reshape(len(A), PT.CHUNK, -1)[:, :, :3] - A.reshape(len(A), PT.CHUNK, -1)[:, :1, :3], axis=2).max(1) + co = lambda d: d < thr["p50"] + # A_end: nearest of the LAST 10 frames of TRAIN episodes ending at the same meta-state (arrived and holding) + part = np.full(len(anc), -1, np.int64); dist = np.full(len(anc), np.inf, np.float32) + for s in (3, 8): + pool = np.concatenate([np.arange(max(ef[e], et[e] - 10), et[e]) for e in train if fin[e] == s]) + w = np.flatnonzero(stage == s) + d, j = PT.nn_dist(px(anc[w]), px(pool)); part[w] = pool[j]; dist[w] = d + T["A_end"] = dict(anc=anc, ep=row_ep[anc], stage=stage, alt=PT.chunk(act, part, ep_end(part)), dist=dist, partner=part, + keep=np.ones(len(anc), bool), key=np.array([f"stage{s}{'' if co(d) else ' (relaxed)'}" for s, d in zip(stage, dist)])) + # A_logged (PRIMARY): HOVER chunk -- TRAIN frames on segments leaving the same meta-state (edge_from == stage) whose + # logged chunk is in the lowest 5% of max ee displacement for that stage; nearest in proprio; all anchors scored + partH = np.full(len(anc), -1, np.int64); distH = np.full(len(anc), np.inf, np.float32); hov = {} + for s in (3, 8): + cand = tr_rows[(e_from[tr_rows] == s) & (tr_rows <= ep_end(tr_rows) - PT.CHUNK)] # no end-of-episode padding + dc = disp(PT.chunk(act, cand, ep_end(cand))); cut = float(np.percentile(dc, 5)); pool = cand[dc <= cut] + hov[str(s)] = {"cut_m": cut, "pool": int(len(pool)), "pool_eps": int(len(np.unique(row_ep[pool])))} + w = np.flatnonzero(stage == s) + d, j = PT.nn_dist(px(anc[w]), px(pool)); partH[w] = pool[j]; distH[w] = d + AH = PT.chunk(act, partH, ep_end(partH)) + T["A_logged"] = dict(anc=anc, ep=row_ep[anc], stage=stage, alt=AH, dist=distH, partner=partH, keep=np.ones(len(anc), bool), + key=np.array([f"stage{s}{'' if co(d) else ' (relaxed)'}" for s, d in zip(stage, distH)])) + Ast = T["A_end"]["alt"] + hold = np.repeat(Ag.reshape(len(anc), PT.CHUNK, -1)[:, :1], PT.CHUNK, 1).reshape(len(anc), -1) + late = np.array([(t - ef[row_ep[t]]) / max(et[row_ep[t]] - ef[row_ep[t]], 1) >= 0.5 for t in anc]) + T["A_hold"] = dict(anc=anc, ep=row_ep[anc], stage=stage, alt=hold, dist=np.zeros(len(anc), np.float32), partner=part * 0 - 1, + keep=np.ones(len(anc), bool), + key=np.array([("approach7" if (s == 8 and l) else f"stage{s}") for s, l in zip(stage, late)])) + for k in ("A_logged", "A_end", "A_hold"): + T[k]["prog"] = Ag + meta["A"] = {"n_anchors": int(len(anc)), "n_eps": int(len(np.unique(row_ep[anc]))), "hover_pool": hov, + "hover_coincident": int(co(distH).sum()), "hover_dist_pct": {str(p): float(np.percentile(distH, p)) for p in (5, 25, 50, 75)}, + "end_coincident": int(co(dist).sum()), "end_dist_pct": {str(p): float(np.percentile(dist, p)) for p in (5, 25, 50, 75)}, + "disp_prog_median": float(np.median(disp(Ag))), "disp_hover_median": float(np.median(disp(AH))), + "disp_end_median": float(np.median(disp(Ast)))} + # ---- B + anc = np.concatenate([np.arange(ef[e], et[e], 10) for e in held if info[e]["final_state"] in PT.GOOD]) + anc = anc[np.isin(e_to[anc], [1, 2, 3, 8, 7])] + Ag = PT.chunk(act, anc, ep_end(anc)) + fail_rows = tr_rows[np.isin(e_to[tr_rows], [5, 6])] + part = np.full(len(anc), -1, np.int64); dist = np.full(len(anc), np.inf, np.float32) + for s0 in np.unique(e_from[anc]): + w = np.flatnonzero(e_from[anc] == s0) + pool = fail_rows[e_from[fail_rows] == s0] + if len(pool) == 0: + pool = fail_rows + d, j = PT.nn_dist(px(anc[w]), px(pool)); part[w] = pool[j]; dist[w] = d + seg_key = np.array([f"{e_from[t]}->{e_to[t]}" for t in anc]) + T["B_logged"] = dict(anc=anc, ep=row_ep[anc], stage=e_from[anc], prog=Ag, alt=PT.chunk(act, part, ep_end(part)), dist=dist, + partner=part, keep=np.ones(len(anc), bool), + key=np.array([f"{k} | {PT.route(info, int(row_ep[p]))}{'' if d < thr['p50'] else ' (relaxed)'}" + for k, p, d in zip(seg_key, part, dist)])) + # synthetic: arrival positions of failure segments + arr = {} + for e in train: + if info[e]["final_state"] in (5, 6): + arr.setdefault(int(info[e]["final_state"]), []).append(np.asarray(pr[et[e] - 1, :3], np.float64)) + arr = {k: np.mean(v, 0) for k, v in arr.items()} + p_now = np.asarray(pr[anc, :3], np.float64) + tgt = np.stack([min(arr.values(), key=lambda q: np.linalg.norm(q - p)) for p in p_now]) + u = tgt - p_now; u /= np.maximum(np.linalg.norm(u, axis=1, keepdims=True), 1e-9) + G = Ag.reshape(len(anc), PT.CHUNK, -1).copy() + D = np.maximum(np.linalg.norm(G[:, -1, :3] - G[:, 0, :3], axis=1), 0.03) + G[:, :, :3] += ((np.arange(PT.CHUNK) + 1) / PT.CHUNK)[None, :, None] * (D[:, None, None] * u[:, None, :]) + T["B_syn"] = dict(anc=anc, ep=row_ep[anc], stage=e_from[anc], prog=Ag, alt=G.reshape(len(anc), -1).astype(np.float32), + dist=np.zeros(len(anc), np.float32), partner=part * 0 - 1, keep=np.ones(len(anc), bool), key=seg_key) + meta["B"] = {"n_anchors": int(len(anc)), "n_eps": int(len(np.unique(row_ep[anc]))), + "coincident": int((dist < thr["p50"]).sum()), + "dist_pct": {str(p): float(np.percentile(dist, p)) for p in (5, 25, 50, 75, 95)}, + "dist_pct_by_seg": {k: {str(p): float(np.percentile(dist[seg_key == k], p)) for p in (10, 50, 90)} + for k in sorted(set(seg_key))}, + "n_by_seg": {k: int((seg_key == k).sum()) for k in sorted(set(seg_key))}, + "fail_arrival_xyz": {str(k): v.tolist() for k, v in arr.items()}, "syn_D_median": float(np.median(D))} + for k, d in T.items(): + np.savez(OUT / f"{k}_{a.split}.npz", **d) + json.dump(meta, open(OUT / f"pairs_{a.split}.json", "w"), indent=1) + print(json.dumps({k: v for k, v in meta.items() if "proprio" not in k}, indent=1), flush=True) + + +def stage_score(a): + F = PT.Feat() + meta = json.load(open(OUT / f"pairs_{a.split}.json")) + resp = PT.ST / f"rsm_errmode_{a.split}.json" + res = PT.locked_merge(resp, lambda c: c or {"models": {}}) + res["pairs"] = {k: v for k, v in meta.items() if "proprio" not in k} + for spec_kv in a.model: + name, spec = spec_kv.split("=", 1) + # run 15: SPEC 'cached' = Q precomputed by another scorer (iql_all.py); the cache must be complete + kind, sc = ("cached", None) if spec == "cached" else PT.build_scorer(spec, F.sd, 1546) + R = res["models"].get(name, {}); R["spec"] = spec; R["seeds"] = a.seeds + for tn in (a.tests.split(",") if a.tests else TESTS): + Tz = dict(np.load(OUT / f"{tn}_{a.split}.npz")) + idx = np.flatnonzero(Tz["keep"]); n = len(idx) + cache = OUT / f"q_{tn}_{a.split}_{name}.npz" + Q = dict(np.load(cache)) if cache.exists() else {"qg": np.full(n, np.nan), "qa": np.full(n, np.nan)} + if len(Q["qg"]) != n: + raise RuntimeError(f"{cache} has {len(Q['qg'])} rows, test has {n}") + X = torch.from_numpy(F.x(Tz["anc"][idx])); t0 = time.time(); last = t0 + if kind == "cached" and np.isnan(Q["qg"]).any() | np.isnan(Q["qa"]).any(): + raise RuntimeError(f"{cache}: cached spec but the cache is missing or incomplete") + for ii in np.flatnonzero(np.isnan(Q["qg"])): + i = idx[ii]; A = torch.from_numpy(np.stack([Tz["prog"][i], Tz["alt"][i]])).float() + x = X[ii][None] + with torch.no_grad(): + if kind == "r2": + q = sc(x.expand(2, -1), A).numpy().astype(np.float64) + else: + q = np.zeros(2) + for s in range(a.seeds): + sc.score(x, A.reshape(2, PT.CHUNK, -1), seed=s); q += np.asarray(sc.last_q.cpu(), float) + q /= a.seeds + Q["qg"][ii], Q["qa"][ii] = q + if time.time() - last > 60: + np.savez(cache, **Q); last = time.time() + print(f"[score] {name} {tn} {ii}/{n} {time.time() - t0:.0f}s", flush=True) + np.savez(cache, **Q) + eps = Tz["ep"][idx]; keys = list(Tz["key"][idx]) + M = PT.metrics(Q["qg"], Q["qa"], eps, keys) + if tn in ("B_logged", "A_logged", "A_end"): + co = Tz["dist"][idx] < meta["THR"] + M["coincident"] = PT.metrics(Q["qg"][co], Q["qa"][co], eps[co], [keys[j] for j in np.flatnonzero(co)]) + M["relaxed"] = PT.metrics(Q["qg"][~co], Q["qa"][~co], eps[~co], [keys[j] for j in np.flatnonzero(~co)]) + M["PASS"] = bool(M.get("acc", 0) >= 0.70 and M.get("ci", [0])[0] > 0.5) + R[tn] = M + print(f"[score] {name} {tn}: acc {M.get('acc')} ci {M.get('ci')} gap {M.get('gap_mean')} n {M.get('n_pairs')}/{M.get('n_eps')} PASS {M['PASS']}", flush=True) + # merge-safe write: several scorer jobs share this file -- re-read, replace only this model's entry + def _upd(cur, _p=res["pairs"]): + cur = cur or {"models": {}}; cur["pairs"] = _p; cur["models"][name] = R; return cur + res = PT.locked_merge(resp, _upd) + if os.environ.get("PT_MODEL_JSON_DIR"): # V7_NOAUG run 4: private per-model copy (shared json loses entries); default off + _d = Path(os.environ["PT_MODEL_JSON_DIR"]); _d.mkdir(parents=True, exist_ok=True) + json.dump(R, open(_d / f"AB_{a.split}.json", "w"), indent=1, default=float) + write_md(res, a.split) + + +def write_md(res, split): + L = [f"# error-mode tests ({split}) -- A STALL / B DEVIATION (errmode_test.py docstring = spec)", ""] + p = res["pairs"]; L.append(f"THR (p50 TRAIN within-route NN proprio) = {p['THR']:.3f}; A: {json.dumps(p['A'])}; B n {p['B']['n_anchors']} " + f"coincident {p['B']['coincident']}, dist pct {p['B']['dist_pct']}") + L += ["", "| model | " + " | ".join(TESTS) + " |", "|---|" + "---|" * len(TESTS)] + for nm, R in res["models"].items(): + cells = [] + for tn in TESTS: + M = R.get(tn, {}) + cells.append("-" if "acc" not in M else f"{M['acc']:.3f} [{M['ci'][0]:.2f},{M['ci'][1]:.2f}] n{M['n_pairs']}/{M['n_eps']}" + + (" **PASS**" if M["PASS"] else "")) + L.append(f"| {nm} | " + " | ".join(cells) + " |") + L.append("") + for nm, R in res["models"].items(): + L.append(f"## {nm} ({R['spec']})") + for tn in TESTS: + M = R.get(tn, {}) + if "by_route_pair" in M: + L.append(f"- {tn}: gap {M['gap_mean']:+.4f}; " + "; ".join(f"{k}: {v['acc']:.2f} (n{v['n']})" for k, v in M["by_route_pair"].items())) + for sub in ("coincident", "relaxed"): + if sub in M and "acc" in M[sub]: + L.append(f" - {sub}: {M[sub]['acc']:.3f} [{M[sub]['ci'][0]:.2f},{M[sub]['ci'][1]:.2f}] n{M[sub]['n_pairs']}") + L.append("") + open(PT.ST / f"rsm_errmode_{split}.md", "w").write("\n".join(L) + "\n") + + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--stage", choices=["pairs", "score"], required=True) + ap.add_argument("--split", default="tune", choices=["tune", "test", "cv0", "cv1", "cv2", "cv3"]) + ap.add_argument("--model", action="append", default=[]) + ap.add_argument("--seeds", type=int, default=8) + ap.add_argument("--tests", default="") + ap.add_argument("--allow-test", action="store_true") + a = ap.parse_args() + if a.split == "test" and not a.allow_test: + sys.exit("TEST needs the owner's OK (--allow-test)") + stage_pairs(a) if a.stage == "pairs" else stage_score(a) diff --git a/rsm_rise/scripts/real/v7/pairtest/errmode_test_frozen_v1.py b/rsm_rise/scripts/real/v7/pairtest/errmode_test_frozen_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..341f3acd0db06b5e00928472ccffa9294787d5e3 --- /dev/null +++ b/rsm_rise/scripts/real/v7/pairtest/errmode_test_frozen_v1.py @@ -0,0 +1,260 @@ +#!/usr/bin/env python +"""RSM_PAIRTEST run 5 (owner 2026-11-20 ~07:50Z): two FROZEN offline tests for the two real-robot error modes. +Written before any model was scored on them; select on TUNE only; TEST needs the owner's OK (--allow-test). + +Common: state x = the successor's 1546-d z-scored input; situation distance = L2 in z-scored proprio (10-d, mu/sd over +TRAIN frames, as pairtest_v3). Chunks = logged 50x10 raw absolute-pose chunks (past the episode end the last action +repeats). Both chunks of a pair are scored AT s_g in ONE scorer call (common random numbers), Q averaged over seeds. +Metric = P(Q(progress chunk) > Q(alternative)) (ties 0.5), 95% bootstrap CI over held-out episodes (2000x); +PASS = acc >= 0.70 and CI low > 0.5. +Coincidence threshold THR (model-free, TRAIN only) = p50 of within-route NN proprio distances: anchors every 25th frame + of every TRAIN episode, pool = every 2nd frame of OTHER TRAIN episodes of the same route with the same edge_from + (the pairtest_v3 rule, extended from edge_from {0,2} to every edge_from). p25 also reported. + +A. STALL (error mode 1: "once at a success meta-state it stays there"). + Anchors: held-out episodes of route 3->8 (robot at success meta-state 3) and 8->7 (at 8), every 5th frame. + a_prog = logged chunk at s_g (continues 3->8 / 8->7). + A_logged (PRIMARY, revised 08:10Z BEFORE any model was scored on A -- model-free reason: the end-of-episode partner + below gave only 13 coincident pairs from 2 episodes, 0 at stage 8): a_stay = logged chunk of a HOVER frame: TRAIN + frames on segments leaving the same meta-state (edge_from == stage) whose chunk is in the lowest 5% of max ee + displacement for that stage (frames >= 50 before the episode end, so the + chunk is real logged motion, not end padding); the nearest in proprio. ALL anchors scored; accuracy also split coincident (d < THR) + / relaxed (d >= THR); PASS judged on all. + A_end (secondary): a_stay = logged chunk of the nearest of the LAST 10 frames of TRAIN episodes that END at the same + meta-state (stage 3: 0->1->3, 0->2->3, 2->3; stage 8: 3->8) -- arrived, then holds (last action repeated); all anchors. + A_hold (secondary, synthetic, every anchor incl. late 8->7 = approaching 7): a_stay = a_prog[0] repeated 50x + (go to the currently commanded pose and stay). +B. DEVIATION (error mode 2: "on the way to success it deviates toward failure"). + Anchors: held-out GOOD episodes (final in {3,8,7}), every 10th frame, on progress segments (edge_to in {1,2,3,8,7}): + 0->1, 1->3, 0->2, 2->3, 3->8, 8->7. + B_logged (PRIMARY): a_dev = logged chunk of the nearest TRAIN frame on a FAILURE segment (edge_to in {5,6}; routes + 0->5, 0->6, 0->2->6), same edge_from if any such segment exists (0, 2), else any failure segment (relaxed; stages 1, + 3, 8). ALL anchors are scored; the distance distribution is reported and the accuracy is split into coincident + (d < THR) and relaxed (d >= THR) subsets. PASS is judged on all B pairs (owner: "where no coincident partner + exists, use the nearest with a relaxed threshold"). + B_syn (secondary, synthetic): a_dev = a_prog with its xyz translated toward the failure arrival position: + a_dev[t, :3] = a_prog[t, :3] + (t+1)/50 * D * u, u = unit(p_fail - p_now), p_fail = mean ee position of TRAIN + arrival frames (last frame) of the failure segment (into 5 or 6) whose arrival is NEAREST to p_now, + D = max(||a_prog[49,:3] - a_prog[0,:3]||, 0.03 m). Rotation and gripper unchanged. +C. pairtest_v3 is kept as the regression check (pairtest.py, unchanged). + +usage: errmode_test.py --stage pairs [--split tune] + errmode_test.py --stage score --model NAME=SPEC [--np 16 --seeds 8] (SPEC as pairtest.py: old | ar: | + r2:, ,succ= ,np=..) +""" +import argparse, json, os, sys, time +from pathlib import Path +import numpy as np, torch + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +os.environ.setdefault("PAIRTEST_VERSION", "pairtest_v3") +import pairtest as PT # noqa + +OUT = PT.OUT / "errmode"; OUT.mkdir(parents=True, exist_ok=True) +TESTS = ["A_logged", "A_end", "A_hold", "B_logged", "B_syn"] +PRIMARY = {"A": "A_logged", "B": "B_logged"} + + +def stage_pairs(a): + info, tt, ef, et = PT.load_meta(); F = PT.Feat() + e_from = np.load(PT.C / "edge_from.i16.npy").astype(np.int64); e_to = np.load(PT.C / "edge_to.i16.npy").astype(np.int64) + pr = np.load(PT.C / "proprio.f32.npy", mmap_mode="r"); act = np.load(PT.C / "act.f32.npy", mmap_mode="r") + row_ep = np.repeat(np.arange(len(ef)), et - ef) + train = sorted(e for e, v in info.items() if v["split"] == "train") + held = sorted(tt["tune"] if a.split == "tune" else tt["test"]) + tr_rows = np.concatenate([np.arange(ef[e], et[e]) for e in train]) + prT = np.asarray(pr[tr_rows], np.float64); pmu = prT.mean(0); psd = np.maximum(prT.std(0), 1e-3) + px = lambda rows: ((np.asarray(pr[np.asarray(rows, np.int64)], np.float64) - pmu) / psd).astype(np.float32) + # ---- threshold (TRAIN only) + by_route = {} + for e in train: + by_route.setdefault(PT.route(info, e), []).append(e) + dnn = [] + for r, eps in sorted(by_route.items()): + for s0 in np.unique(e_from[np.concatenate([np.arange(ef[e], et[e]) for e in eps])]): + rows = [np.arange(ef[e], et[e], 2)[e_from[ef[e]:et[e]:2] == s0] for e in eps] + pe = np.concatenate([[e] * len(x) for e, x in zip(eps, rows)]).astype(np.int64) + Pp = px(np.concatenate(rows)) + for e in eps: + q = np.arange(ef[e], et[e], 25); q = q[e_from[q] == s0] + if len(q) and (pe != e).sum(): + dnn.append(PT.nn_dist(px(q), Pp[pe != e])[0]) + dnn = np.concatenate(dnn); thr = {f"p{p}": float(np.percentile(dnn, p)) for p in (10, 25, 50)} + meta = {"split": a.split, "thresholds": thr, "THR": thr["p50"], "dnn_n": int(len(dnn)), + "proprio_mu": pmu.tolist(), "proprio_sd": psd.tolist()} + print("[pairs] thresholds", thr, flush=True) + ep_end = lambda rows: et[row_ep[np.asarray(rows)]] + T = {} + # ---- A + fin = {e: info[e]["final_state"] for e in info} + anc, stage = [], [] + for e in held: + rt = PT.route(info, e) + if rt in ("3->8", "8->7"): + q = np.arange(ef[e], et[e], 5); anc.append(q); stage.append(np.full(len(q), int(rt[0]))) + anc = np.concatenate(anc); stage = np.concatenate(stage); Ag = PT.chunk(act, anc, ep_end(anc)) + disp = lambda A: np.linalg.norm(A.reshape(len(A), PT.CHUNK, -1)[:, :, :3] - A.reshape(len(A), PT.CHUNK, -1)[:, :1, :3], axis=2).max(1) + co = lambda d: d < thr["p50"] + # A_end: nearest of the LAST 10 frames of TRAIN episodes ending at the same meta-state (arrived and holding) + part = np.full(len(anc), -1, np.int64); dist = np.full(len(anc), np.inf, np.float32) + for s in (3, 8): + pool = np.concatenate([np.arange(max(ef[e], et[e] - 10), et[e]) for e in train if fin[e] == s]) + w = np.flatnonzero(stage == s) + d, j = PT.nn_dist(px(anc[w]), px(pool)); part[w] = pool[j]; dist[w] = d + T["A_end"] = dict(anc=anc, ep=row_ep[anc], stage=stage, alt=PT.chunk(act, part, ep_end(part)), dist=dist, partner=part, + keep=np.ones(len(anc), bool), key=np.array([f"stage{s}{'' if co(d) else ' (relaxed)'}" for s, d in zip(stage, dist)])) + # A_logged (PRIMARY): HOVER chunk -- TRAIN frames on segments leaving the same meta-state (edge_from == stage) whose + # logged chunk is in the lowest 5% of max ee displacement for that stage; nearest in proprio; all anchors scored + partH = np.full(len(anc), -1, np.int64); distH = np.full(len(anc), np.inf, np.float32); hov = {} + for s in (3, 8): + cand = tr_rows[(e_from[tr_rows] == s) & (tr_rows <= ep_end(tr_rows) - PT.CHUNK)] # no end-of-episode padding + dc = disp(PT.chunk(act, cand, ep_end(cand))); cut = float(np.percentile(dc, 5)); pool = cand[dc <= cut] + hov[str(s)] = {"cut_m": cut, "pool": int(len(pool)), "pool_eps": int(len(np.unique(row_ep[pool])))} + w = np.flatnonzero(stage == s) + d, j = PT.nn_dist(px(anc[w]), px(pool)); partH[w] = pool[j]; distH[w] = d + AH = PT.chunk(act, partH, ep_end(partH)) + T["A_logged"] = dict(anc=anc, ep=row_ep[anc], stage=stage, alt=AH, dist=distH, partner=partH, keep=np.ones(len(anc), bool), + key=np.array([f"stage{s}{'' if co(d) else ' (relaxed)'}" for s, d in zip(stage, distH)])) + Ast = T["A_end"]["alt"] + hold = np.repeat(Ag.reshape(len(anc), PT.CHUNK, -1)[:, :1], PT.CHUNK, 1).reshape(len(anc), -1) + late = np.array([(t - ef[row_ep[t]]) / max(et[row_ep[t]] - ef[row_ep[t]], 1) >= 0.5 for t in anc]) + T["A_hold"] = dict(anc=anc, ep=row_ep[anc], stage=stage, alt=hold, dist=np.zeros(len(anc), np.float32), partner=part * 0 - 1, + keep=np.ones(len(anc), bool), + key=np.array([("approach7" if (s == 8 and l) else f"stage{s}") for s, l in zip(stage, late)])) + for k in ("A_logged", "A_end", "A_hold"): + T[k]["prog"] = Ag + meta["A"] = {"n_anchors": int(len(anc)), "n_eps": int(len(np.unique(row_ep[anc]))), "hover_pool": hov, + "hover_coincident": int(co(distH).sum()), "hover_dist_pct": {str(p): float(np.percentile(distH, p)) for p in (5, 25, 50, 75)}, + "end_coincident": int(co(dist).sum()), "end_dist_pct": {str(p): float(np.percentile(dist, p)) for p in (5, 25, 50, 75)}, + "disp_prog_median": float(np.median(disp(Ag))), "disp_hover_median": float(np.median(disp(AH))), + "disp_end_median": float(np.median(disp(Ast)))} + # ---- B + anc = np.concatenate([np.arange(ef[e], et[e], 10) for e in held if info[e]["final_state"] in PT.GOOD]) + anc = anc[np.isin(e_to[anc], [1, 2, 3, 8, 7])] + Ag = PT.chunk(act, anc, ep_end(anc)) + fail_rows = tr_rows[np.isin(e_to[tr_rows], [5, 6])] + part = np.full(len(anc), -1, np.int64); dist = np.full(len(anc), np.inf, np.float32) + for s0 in np.unique(e_from[anc]): + w = np.flatnonzero(e_from[anc] == s0) + pool = fail_rows[e_from[fail_rows] == s0] + if len(pool) == 0: + pool = fail_rows + d, j = PT.nn_dist(px(anc[w]), px(pool)); part[w] = pool[j]; dist[w] = d + seg_key = np.array([f"{e_from[t]}->{e_to[t]}" for t in anc]) + T["B_logged"] = dict(anc=anc, ep=row_ep[anc], stage=e_from[anc], prog=Ag, alt=PT.chunk(act, part, ep_end(part)), dist=dist, + partner=part, keep=np.ones(len(anc), bool), + key=np.array([f"{k} | {PT.route(info, int(row_ep[p]))}{'' if d < thr['p50'] else ' (relaxed)'}" + for k, p, d in zip(seg_key, part, dist)])) + # synthetic: arrival positions of failure segments + arr = {} + for e in train: + if info[e]["final_state"] in (5, 6): + arr.setdefault(int(info[e]["final_state"]), []).append(np.asarray(pr[et[e] - 1, :3], np.float64)) + arr = {k: np.mean(v, 0) for k, v in arr.items()} + p_now = np.asarray(pr[anc, :3], np.float64) + tgt = np.stack([min(arr.values(), key=lambda q: np.linalg.norm(q - p)) for p in p_now]) + u = tgt - p_now; u /= np.maximum(np.linalg.norm(u, axis=1, keepdims=True), 1e-9) + G = Ag.reshape(len(anc), PT.CHUNK, -1).copy() + D = np.maximum(np.linalg.norm(G[:, -1, :3] - G[:, 0, :3], axis=1), 0.03) + G[:, :, :3] += ((np.arange(PT.CHUNK) + 1) / PT.CHUNK)[None, :, None] * (D[:, None, None] * u[:, None, :]) + T["B_syn"] = dict(anc=anc, ep=row_ep[anc], stage=e_from[anc], prog=Ag, alt=G.reshape(len(anc), -1).astype(np.float32), + dist=np.zeros(len(anc), np.float32), partner=part * 0 - 1, keep=np.ones(len(anc), bool), key=seg_key) + meta["B"] = {"n_anchors": int(len(anc)), "n_eps": int(len(np.unique(row_ep[anc]))), + "coincident": int((dist < thr["p50"]).sum()), + "dist_pct": {str(p): float(np.percentile(dist, p)) for p in (5, 25, 50, 75, 95)}, + "dist_pct_by_seg": {k: {str(p): float(np.percentile(dist[seg_key == k], p)) for p in (10, 50, 90)} + for k in sorted(set(seg_key))}, + "n_by_seg": {k: int((seg_key == k).sum()) for k in sorted(set(seg_key))}, + "fail_arrival_xyz": {str(k): v.tolist() for k, v in arr.items()}, "syn_D_median": float(np.median(D))} + for k, d in T.items(): + np.savez(OUT / f"{k}_{a.split}.npz", **d) + json.dump(meta, open(OUT / f"pairs_{a.split}.json", "w"), indent=1) + print(json.dumps({k: v for k, v in meta.items() if "proprio" not in k}, indent=1), flush=True) + + +def stage_score(a): + F = PT.Feat() + meta = json.load(open(OUT / f"pairs_{a.split}.json")) + resp = PT.ST / f"rsm_errmode_{a.split}.json" + res = json.load(open(resp)) if resp.exists() else {"models": {}} + res["pairs"] = {k: v for k, v in meta.items() if "proprio" not in k} + for spec_kv in a.model: + name, spec = spec_kv.split("=", 1) + kind, sc = PT.build_scorer(spec, F.sd, 1546) + R = res["models"].get(name, {}); R["spec"] = spec; R["seeds"] = a.seeds + for tn in (a.tests.split(",") if a.tests else TESTS): + Tz = dict(np.load(OUT / f"{tn}_{a.split}.npz")) + idx = np.flatnonzero(Tz["keep"]); n = len(idx) + cache = OUT / f"q_{tn}_{a.split}_{name}.npz" + Q = dict(np.load(cache)) if cache.exists() else {"qg": np.full(n, np.nan), "qa": np.full(n, np.nan)} + if len(Q["qg"]) != n: + raise RuntimeError(f"{cache} has {len(Q['qg'])} rows, test has {n}") + X = torch.from_numpy(F.x(Tz["anc"][idx])); t0 = time.time(); last = t0 + for ii in np.flatnonzero(np.isnan(Q["qg"])): + i = idx[ii]; A = torch.from_numpy(np.stack([Tz["prog"][i], Tz["alt"][i]])).float() + x = X[ii][None] + with torch.no_grad(): + if kind == "r2": + q = sc(x.expand(2, -1), A).numpy().astype(np.float64) + else: + q = np.zeros(2) + for s in range(a.seeds): + sc.score(x, A.reshape(2, PT.CHUNK, -1), seed=s); q += np.asarray(sc.last_q.cpu(), float) + q /= a.seeds + Q["qg"][ii], Q["qa"][ii] = q + if time.time() - last > 60: + np.savez(cache, **Q); last = time.time() + print(f"[score] {name} {tn} {ii}/{n} {time.time() - t0:.0f}s", flush=True) + np.savez(cache, **Q) + eps = Tz["ep"][idx]; keys = list(Tz["key"][idx]) + M = PT.metrics(Q["qg"], Q["qa"], eps, keys) + if tn in ("B_logged", "A_logged", "A_end"): + co = Tz["dist"][idx] < meta["THR"] + M["coincident"] = PT.metrics(Q["qg"][co], Q["qa"][co], eps[co], [keys[j] for j in np.flatnonzero(co)]) + M["relaxed"] = PT.metrics(Q["qg"][~co], Q["qa"][~co], eps[~co], [keys[j] for j in np.flatnonzero(~co)]) + M["PASS"] = bool(M.get("acc", 0) >= 0.70 and M.get("ci", [0])[0] > 0.5) + R[tn] = M + print(f"[score] {name} {tn}: acc {M.get('acc')} ci {M.get('ci')} gap {M.get('gap_mean')} n {M.get('n_pairs')}/{M.get('n_eps')} PASS {M['PASS']}", flush=True) + res["models"][name] = R + json.dump(res, open(resp, "w"), indent=1, default=float) + write_md(res, a.split) + + +def write_md(res, split): + L = [f"# error-mode tests ({split}) -- A STALL / B DEVIATION (errmode_test.py docstring = spec)", ""] + p = res["pairs"]; L.append(f"THR (p50 TRAIN within-route NN proprio) = {p['THR']:.3f}; A: {json.dumps(p['A'])}; B n {p['B']['n_anchors']} " + f"coincident {p['B']['coincident']}, dist pct {p['B']['dist_pct']}") + L += ["", "| model | " + " | ".join(TESTS) + " |", "|---|" + "---|" * len(TESTS)] + for nm, R in res["models"].items(): + cells = [] + for tn in TESTS: + M = R.get(tn, {}) + cells.append("-" if "acc" not in M else f"{M['acc']:.3f} [{M['ci'][0]:.2f},{M['ci'][1]:.2f}] n{M['n_pairs']}/{M['n_eps']}" + + (" **PASS**" if M["PASS"] else "")) + L.append(f"| {nm} | " + " | ".join(cells) + " |") + L.append("") + for nm, R in res["models"].items(): + L.append(f"## {nm} ({R['spec']})") + for tn in TESTS: + M = R.get(tn, {}) + if "by_route_pair" in M: + L.append(f"- {tn}: gap {M['gap_mean']:+.4f}; " + "; ".join(f"{k}: {v['acc']:.2f} (n{v['n']})" for k, v in M["by_route_pair"].items())) + for sub in ("coincident", "relaxed"): + if sub in M and "acc" in M[sub]: + L.append(f" - {sub}: {M[sub]['acc']:.3f} [{M[sub]['ci'][0]:.2f},{M[sub]['ci'][1]:.2f}] n{M[sub]['n_pairs']}") + L.append("") + open(PT.ST / f"rsm_errmode_{split}.md", "w").write("\n".join(L) + "\n") + + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--stage", choices=["pairs", "score"], required=True) + ap.add_argument("--split", default="tune", choices=["tune", "test"]) + ap.add_argument("--model", action="append", default=[]) + ap.add_argument("--seeds", type=int, default=8) + ap.add_argument("--tests", default="") + ap.add_argument("--allow-test", action="store_true") + a = ap.parse_args() + if a.split == "test" and not a.allow_test: + sys.exit("TEST needs the owner's OK (--allow-test)") + stage_pairs(a) if a.stage == "pairs" else stage_score(a) diff --git a/rsm_rise/scripts/real/v7/pairtest/h10_support.py b/rsm_rise/scripts/real/v7/pairtest/h10_support.py new file mode 100644 index 0000000000000000000000000000000000000000..61fb579b1eb3ea633d8aa2fadc6bfee16e24d935 --- /dev/null +++ b/rsm_rise/scripts/real/v7/pairtest/h10_support.py @@ -0,0 +1,125 @@ +#!/usr/bin/env python +"""RSM_PAIRTEST run 17, H10 (orchestrator 2026-11-21 02:55Z): behaviour-support (pessimism) term on top of a FROZEN +RSM read-out, scored on the FROZEN tests C / A / B / STITCH (TUNE only here; TEST is closed). + + Q'(s, a) = Q_RSM(s, a) + lam_eff * z(s, a) + z(s, a) = standardised exact log-likelihood of the raw 50x10 chunk under the hop policy pi_b = gauss_h50_ps_s1 + (BCHead: diagonal Gaussian, state-independent log_std): z = (log pi_b(a|s) - E_{a'~pi_b(.|s)} log pi_b(a'|s)) + / SD_{a'~pi_b}, closed form: E = sum(-ls - log(2pi)/2) - d/2, SD = sqrt(d/2) (d = 500). So z is + -(Mahalanobis^2 - d) / sqrt(2d): "how many pi_b-sample SDs less likely than a typical pi_b proposal". + On the robot the candidates are pi_b-like proposals, so standardising against pi_b samples is what + "standardise across the candidates at s" becomes when only 2 candidates are scored offline. + lam_eff = lam * sQ / sZ, sQ = pooled SD of the base model's cached Q over all TUNE pair chunks of all tests, + sZ = same for z (scale-free lam; lam = 1 means equal spread). lam grid fixed here, BEFORE scoring: + {0.03, 0.1, 0.3, 1, 3} and lam = inf (z alone, i.e. pi_b likelihood as the critic). +Nothing about pairs / rules / metrics changes: this script only writes Q caches under new model names +_h10l; the unchanged scorers then read them with SPEC "cached" (run_h10.sh). + +SELECTION RULE (written before any H10 score was seen): over (base, lam) on TUNE, keep cells that PASS C, A_logged, +A_hold, B_logged and STITCH and lose <= 0.02 accuracy vs the base on each of them; among those pick max B_syn +accuracy; ties -> smaller lam. B_syn PASS with the other five kept = H10 succeeds on TUNE (then TRAIN-CV check). +usage: h10_support.py --split tune --base tr_chal_64x1 [--base ...] +""" +import argparse, json, sys +from pathlib import Path +import numpy as np, torch + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import os +os.environ.setdefault("PAIRTEST_VERSION", "pairtest_v3") +import pairtest as PT # noqa + +TESTS = ["A_logged", "A_end", "A_hold", "B_logged", "B_syn"] +FAMS = ["S_02f", "S_02s", "S_01f", "S_26", "S_1end"] +LAMS = [0.03, 0.1, 0.3, 1.0, 3.0, "inf"] + +ap = argparse.ArgumentParser() +ap.add_argument("--split", default="tune", choices=["tune"]) # TEST closed (owner OK needed for a second read) +ap.add_argument("--base", action="append", required=True) +a = ap.parse_args() +S = a.split +torch.set_num_threads(int(os.environ.get("SLURM_CPUS_PER_TASK", "8"))) +info, tt, ef, et = PT.load_meta(); F = PT.Feat() +row_ep = np.repeat(np.arange(len(ef)), et - ef) +act = np.load(PT.C / "act.f32.npy", mmap_mode="r") +import rsm_scorer_ar as AR +hop, _ = AR._load_rsm_scorer().load_hop_head(str(PT.HOP), 1546, 1, "cpu", feat_sd=F.sd) +ls = hop.pol.log_std.clamp(-5.0, 2.0).detach().double() +d = int(ls.numel()); E0 = float((-ls - 0.5 * np.log(2 * np.pi)).sum()) - d / 2.0; SD0 = float(np.sqrt(d / 2.0)) + + +@torch.no_grad() +def zlp(rows, A): + out = np.zeros(len(rows)); maha = np.zeros(len(rows)) + for b in range(0, len(rows), 256): + x = torch.from_numpy(F.x(rows[b:b + 256])); aa = torch.from_numpy(np.asarray(A[b:b + 256], np.float32)).double() + mu, l = hop.pol(x * hop.scale, torch.zeros(len(x), dtype=torch.long)) + mu = mu.double(); var = (2 * l.double()).exp() + lp = (-0.5 * ((aa - mu) ** 2 / var + 2 * l.double() + np.log(2 * np.pi))).sum(-1) + out[b:b + 256] = ((lp - E0) / SD0).numpy(); maha[b:b + 256] = (((aa - mu) ** 2) / var).sum(-1).numpy() + return out, maha + + +# ---- z for every (test, column) --------------------------------------------------------------------------------------- +Z = {}; MAHA = {} +P = dict(np.load(PT.OUT / f"pairs_v3_{S}.npz")) +if (PT.OUT / f"pairs_v3_{S}_ctrl.npz").exists(): + P.update(dict(np.load(PT.OUT / f"pairs_v3_{S}_ctrl.npz"))) +anc = P["anc_row"] +Z["C"] = {} +Z["C"]["g"], MAHA["C/g"] = zlp(anc, PT.chunk(act, anc, et[P["anc_ep"]])) +for c in ("BAD", "NOTPROG", "GOODNB"): + if f"{c}_row" in P: + rb = P[f"{c}_row"]; Z["C"][c], MAHA[f"C/{c}"] = zlp(anc, PT.chunk(act, rb, et[row_ep[rb]])) +for tn in TESTS: + Tz = dict(np.load(PT.OUT / "errmode" / f"{tn}_{S}.npz")); idx = np.flatnonzero(Tz["keep"]); r = Tz["anc"][idx] + Z[tn] = {}; Z[tn]["qg"], MAHA[f"{tn}/g"] = zlp(r, Tz["prog"][idx]); Z[tn]["qa"], MAHA[f"{tn}/a"] = zlp(r, Tz["alt"][idx]) +for fam in FAMS: + Tz = dict(np.load(PT.OUT / "stitch" / f"{fam}_{S}.npz")) + if len(Tz["anc"]) == 0: + continue + Z[fam] = {}; Z[fam]["qg"], MAHA[f"{fam}/g"] = zlp(Tz["anc"], Tz["prog"]); Z[fam]["qa"], MAHA[f"{fam}/a"] = zlp(Tz["anc"], Tz["alt"]) +np.savez(PT.OUT / f"h10_z_{S}.npz", **{f"{k}/{c}": v for k, cc in Z.items() for c, v in cc.items()}) +diag = {"d": d, "E0": E0, "SD0": SD0, "log_std_mean": float(ls.mean()), + "z_median": {k: float(np.median(v)) for k, v in ((f"{t}/{c}", z) for t, cc in Z.items() for c, z in cc.items())}, + "zgap_good_minus_alt_mean": {t: float(np.mean(cc["g" if t == "C" else "qg"] - cc["BAD" if t == "C" else "qa"])) for t, cc in Z.items()}, + "zgap_acc": {t: float(np.mean((cc["g" if t == "C" else "qg"] > cc["BAD" if t == "C" else "qa"]) + 0.5 * (cc["g" if t == "C" else "qg"] == cc["BAD" if t == "C" else "qa"]))) for t, cc in Z.items()}} +print("[h10] z diag", json.dumps(diag, indent=1), flush=True) + + +def path(t, n): + if t == "C": + return PT.OUT / f"q_v3_{S}_{n}.npz" + if t in TESTS: + return PT.OUT / "errmode" / f"q_{t}_{S}_{n}.npz" + return PT.OUT / "stitch" / f"q_{t}_{S}_{n}.npz" + + +C_need = np.zeros(len(anc), bool) +for c in ("BAD", "NOTPROG"): + if f"{c}_row" in P: + C_need |= P[f"{c}_dist"] < json.load(open(PT.OUT / f"pairs_v3_{S}.json"))["thresholds"]["p50"] +names = [] +for base in a.base: + Qb = {t: dict(np.load(path(t, base))) for t in Z} + allq, allz = [], [] + for t, cc in Z.items(): + for c in cc: + q = Qb[t][c]; m = C_need if t == "C" else np.ones(len(q), bool) + allq.append(q[m]); allz.append(cc[c][m]) + sQ, sZ = float(np.std(np.concatenate(allq))), float(np.std(np.concatenate(allz))) + diag.setdefault("scale", {})[base] = {"sQ": sQ, "sZ": sZ} + for lam in LAMS: + n = f"{base}_h10l{lam}"; names.append(n) + for t, cc in Z.items(): + D = {} + for k, v in Qb[t].items(): + if k in cc: + D[k] = cc[k] if lam == "inf" else v + float(lam) * sQ / sZ * cc[k] + else: + D[k] = v # *_w columns unchanged + np.savez(path(t, n), **D) + print(f"[h10] {base}: sQ {sQ:.4f} sZ {sZ:.4f}; wrote {len(LAMS)} lam caches", flush=True) +json.dump({"diag": diag, "names": names}, open(PT.ST / f"h10_support_{S}.json", "w"), indent=1) +open(PT.OUT / f"h10_names_{S}.txt", "w").write("\n".join(names) + "\n") +print("[h10] done", flush=True) diff --git a/rsm_rise/scripts/real/v7/pairtest/h10_table.py b/rsm_rise/scripts/real/v7/pairtest/h10_table.py new file mode 100644 index 0000000000000000000000000000000000000000..86d5f5bf660dfcc7b52f2eb805e8c6aef5897838 --- /dev/null +++ b/rsm_rise/scripts/real/v7/pairtest/h10_table.py @@ -0,0 +1,35 @@ +#!/usr/bin/env python +"""H10 table + the pre-registered selection rule (h10_support.py docstring). Reads json only.""" +import json, sys +from pathlib import Path +ST = Path("/proj/dmfexp/zwhong/rsm_rise/status/real"); S = "tune" +C = json.load(open(ST / f"rsm_pairtest_v3_{S}.json"))["models"]; E = json.load(open(ST / f"rsm_errmode_{S}.json"))["models"] +T = json.load(open(ST / f"rsm_stitch_{S}.json"))["models"] +names = json.load(open(ST / f"h10_support_{S}.json"))["names"] +bases = sorted({n.split("_h10l")[0] for n in names}) +COLS = ["C", "A_logged", "A_end", "A_hold", "B_logged", "B_syn", "STITCH"] +def get(n, c): + M = C[n]["BAD_primary"] if c == "C" else (T[n]["STITCH"] if c == "STITCH" else E[n][c]) + return M["acc"], M["ci"][0], M["ci"][1], (M["acc"] >= 0.70 and M["ci"][0] > 0.5) +L = ["# H10 behaviour-support term (TUNE) -- Q' = Q + lam * sQ/sZ * z(log pi_b)", "", + "| model | " + " | ".join(COLS) + " |", "|---|" + "---|" * len(COLS)] +ok = [] +for b in bases: + for n in [b] + [x for x in names if x.startswith(b + "_h10l")]: + try: + v = {c: get(n, c) for c in COLS} + except KeyError as k: + L.append(f"| {n} | missing {k} |"); continue + L.append(f"| {n} | " + " | ".join(f"{a:.3f} [{lo:.2f},{hi:.2f}]" + (" **P**" if p else "") for a, lo, hi, p in v.values()) + " |") + if n != b: + vb = {c: get(b, c) for c in COLS} + keep = all(v[c][3] and v[c][0] >= vb[c][0] - 0.02 for c in ("C", "A_logged", "A_hold", "B_logged", "STITCH")) + if keep: + lam = n.split("_h10l")[1]; ok.append((v["B_syn"][0], -(1e9 if lam == "inf" else float(lam)), n, v["B_syn"][3])) +L += ["", "Rule: PASS + <= 0.02 loss vs base on C, A_logged, A_hold, B_logged, STITCH; then max B_syn; ties smaller lam."] +if ok: + best = max(ok); L.append(f"Eligible: {', '.join(x[2] for x in sorted(ok, reverse=True))}") + L.append(f"PICK: {best[2]} (B_syn {best[0]:.3f}, B_syn PASS {best[3]})") +else: + L.append("PICK: none eligible (every lam > 0 breaks one of the five kept tests)") +open(ST / "rsm_h10_tune.md", "w").write("\n".join(L) + "\n"); print("\n".join(L)) diff --git a/rsm_rise/scripts/real/v7/pairtest/h13_hybrid.py b/rsm_rise/scripts/real/v7/pairtest/h13_hybrid.py new file mode 100644 index 0000000000000000000000000000000000000000..50f926ca2ccc600319bcf2511f37a2a36ac6aeb2 --- /dev/null +++ b/rsm_rise/scripts/real/v7/pairtest/h13_hybrid.py @@ -0,0 +1,53 @@ +#!/usr/bin/env python +"""RSM_PAIRTEST run 18, H13 (orchestrator 2026-11-21 05:00Z): hybrid read-out Q_h = Q_RSM / sR + w * Q_IQL / sI on +CACHED Q only (CPU, TUNE only; TEST closed). + Q_IQL = NEW IQL pick iqlR2_s2_e5000 (= V7_STOVE 'iql_new', same checkpoint). + sR, sI = pooled WITHIN-ANCHOR SD of each critic over the 128 cached V7_STOVE TUNE candidates (so w = 1 means equal + spread across a real candidate set; on 128 candidates Q_h ranks exactly as z(Q_RSM) + w z(IQL)). The same fixed + scales are used on the frozen pair tests (2 chunks per state cannot be standardised on their own). + w grid FIXED BEFORE SCORING: {0.03, 0.1, 0.3, 1, 3, inf (IQL alone)}. +SELECTION RULE (written before any H13 score was seen): on TUNE, keep cells that PASS C, A_logged, A_hold, B_logged and +STITCH and lose <= 0.02 vs the base on each; among those pick max V7_STOVE bestPAN>bestSTOVE on TUNE pan anchors +(ties -> smaller w). H13 succeeds if the pick also raises bestP>bestS by >= 0.05 over the base. +Writes caches _h13w (read by the unchanged scorers via SPEC 'cached') and status/real/h13_stove_tune.json. +usage: h13_hybrid.py --base tr_chal_64x1=runs/v7_stove/q_default_tune.npz [--base name=stovefile ...]""" +import argparse, json, os, sys +from pathlib import Path +import numpy as np +os.environ.setdefault("PAIRTEST_VERSION", "pairtest_v3") +R = Path("/proj/dmfexp/zwhong/rsm_rise"); OUT = R / "runs/pairtest"; ST = R / "status/real"; SO = R / "runs/v7_stove" +IQL = "iqlR2_s2_e5000"; WS = [0.03, 0.1, 0.3, 1.0, 3.0, "inf"]; S = "tune" +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("--base", action="append", required=True); a = ap.parse_args() +def path(t, n): + if t == "C": return OUT / f"q_v3_{S}_{n}.npz" + if t in TESTS: return OUT / "errmode" / f"q_{t}_{S}_{n}.npz" + return OUT / "stitch" / f"q_{t}_{S}_{n}.npz" +A = dict(np.load(SO / "anchors.npz")); lab = np.load(SO / "cand_labels.npz")["lab"] +zi = np.load(SO / "q_iql_new_tune.npz"); idx_i, QI = zi["idx"], zi["q"] +def stove(idx, Q): + sel = np.flatnonzero(A["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 dict(top_pan=float((top == 1).mean()), top_stove=float((top == 2).mean()), + bestP_gt_bestS=float(np.where(g > 0, 1, np.where(g == 0, .5, 0)).mean()), n=int(len(ii)), n_both=int(both.sum())) +names, res = [], {} +for b in a.base: + name, sf = b.split("="); zr = np.load(R / sf); assert (zr["idx"] == idx_i).all(); QR = zr["q"] + sR, sI = float(np.sqrt(np.nanmean(np.nanvar(QR, 1)))), float(np.sqrt(np.nanmean(np.nanvar(QI, 1)))) + res[name] = {"sR": sR, "sI": sI, "base": stove(idx_i, QR), "iql": stove(idx_i, QI)} + for w in WS: + n = f"{name}_h13w{w}"; names.append(n) + Qh = QI / sI if w == "inf" else QR / sR + float(w) * QI / sI + res[name][str(w)] = stove(idx_i, Qh) + for t in ["C"] + TESTS + FAMS: + if not path(t, name).exists() or not path(t, IQL).exists(): + continue + qb, qi = dict(np.load(path(t, name))), dict(np.load(path(t, IQL))); D = {} + for k, v in qb.items(): + if k.endswith("_w") or k not in qi: D[k] = v + else: D[k] = qi[k] / sI if w == "inf" else v / sR + float(w) * qi[k] / sI + np.savez(path(t, n), **D) + print(f"[h13] {name}: sR {sR:.4f} sI {sI:.4f}", json.dumps(res[name]), flush=True) +json.dump({"names": names, "stove": res, "iql": IQL}, open(ST / "h13_stove_tune.json", "w"), indent=1) +open(OUT / "h13_names_tune.txt", "w").write("\n".join(names) + "\n"); print("[h13] done") diff --git a/rsm_rise/scripts/real/v7/pairtest/h13_table.py b/rsm_rise/scripts/real/v7/pairtest/h13_table.py new file mode 100644 index 0000000000000000000000000000000000000000..a8e518f15f5cd9c1be5540acaf7257993165be94 --- /dev/null +++ b/rsm_rise/scripts/real/v7/pairtest/h13_table.py @@ -0,0 +1,26 @@ +#!/usr/bin/env python +"""H13 table + pre-registered rule (h13_hybrid.py docstring). json only -> status/real/rsm_h13_tune.md""" +import json +from pathlib import Path +ST = Path("/proj/dmfexp/zwhong/rsm_rise/status/real"); S = "tune" +C = json.load(open(ST / f"rsm_pairtest_v3_{S}.json"))["models"]; E = json.load(open(ST / f"rsm_errmode_{S}.json"))["models"] +T = json.load(open(ST / f"rsm_stitch_{S}.json"))["models"]; H = json.load(open(ST / "h13_stove_tune.json")) +COLS = ["C", "A_logged", "A_end", "A_hold", "B_logged", "B_syn", "STITCH"]; KEEP = ["C", "A_logged", "A_hold", "B_logged", "STITCH"] +def get(n, c): + M = C[n]["BAD_primary"] if c == "C" else (T[n]["STITCH"] if c == "STITCH" else E[n][c]) + return M["acc"], M["ci"][0], (M["acc"] >= 0.70 and M["ci"][0] > 0.5) +L = ["# H13 hybrid read-out (TUNE): Q_h = Q_RSM/sR + w * Q_IQL(iqlR2_s2_e5000)/sI", "", + "| model | " + " | ".join(COLS) + " | stove topPAN | topSTOVE | bestP>bestS |", "|---|" + "---|" * (len(COLS) + 3)] +for b, sv in H["stove"].items(): + rows = [(b, sv["base"])] + [(f"{b}_h13w{w}", sv[w]) for w in ["0.03", "0.1", "0.3", "1.0", "3.0", "inf"]] + best = None; base = {c: get(b, c)[0] for c in COLS} + for n, st in rows: + g = {c: get(n, c) for c in COLS} + L.append(f"| {n} | " + " | ".join(f"{g[c][0]:.3f}{'' if g[c][2] else ' F'}" for c in COLS) + + f" | {st['top_pan']:.2f} | {st['top_stove']:.2f} | {st['bestP_gt_bestS']:.2f} |") + ok = n != b and all(g[c][2] and g[c][0] >= base[c] - 0.02 for c in KEEP) + if ok and (best is None or st["bestP_gt_bestS"] > best[1]): best = (n, st["bestP_gt_bestS"]) + L.append(f"| IQL alone (stove only) | | | | | | | | {sv['iql']['top_pan']:.2f} | {sv['iql']['top_stove']:.2f} | {sv['iql']['bestP_gt_bestS']:.2f} |") + L += ["", f"**Rule pick for {b}: {best[0] if best else 'none'}** " + f"(base bestP>bestS {sv['base']['bestP_gt_bestS']:.2f}; success needs +0.05)", ""] +open(ST / "rsm_h13_tune.md", "w").write("\n".join(L) + "\n"); print("\n".join(L)) diff --git a/rsm_rise/scripts/real/v7/pairtest/h18_holddiag.py b/rsm_rise/scripts/real/v7/pairtest/h18_holddiag.py new file mode 100644 index 0000000000000000000000000000000000000000..547047bcd5e3166891ce4816c9270770a00a38b9 --- /dev/null +++ b/rsm_rise/scripts/real/v7/pairtest/h18_holddiag.py @@ -0,0 +1,97 @@ +"""RSM_PAIRTEST run 23 (H18-diag, read-only diagnosis; frozen tests untouched, TUNE only). +Why did hold negatives (H17) LOWER A_hold? For the frozen TUNE A_hold pairs, re-score prog vs hold chunks with the +CHALLENGER read-out (64 particles, seed 0) on several successors and record, per particle, the goal-read latent and +the (clamped) reward read. Label each goal latent by its nearest TRAIN frame (every 4th TRAIN row): edge (from->to) +and the shaped2 label of that frame. Output: per model x stage x chunk (prog/hold) the distribution of goal edges, +mean read, mean NN-label, and the share of particles whose goal read lands back at the anchor's own meta-state. +usage: h18_holddiag.py NAME=SUCC_CKPT ... (writes runs/pairtest/h18diag/.json + status/real/rsm_h18_holddiag.md) +""" +import json, os, sys, time +from pathlib import Path +import numpy as np, torch + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +os.environ.setdefault("PAIRTEST_VERSION", "pairtest_v3") +import pairtest as PT # noqa + +ROOT = PT.ROOT; OUT = ROOT / "runs/pairtest/h18diag"; OUT.mkdir(parents=True, exist_ok=True) +HEAD = "runs/v7_reward2/c50_bal_adrop02/ckpt_best.pt" +NP = 64 + + +def main(): + F = PT.Feat(); info, tt, ef, et = PT.load_meta() + e_from = np.load(PT.C / "edge_from.i16.npy").astype(np.int64); e_to = np.load(PT.C / "edge_to.i16.npy").astype(np.int64) + lab_p = PT.C / "reward_shaped2.f32.npy" + lab = np.load(lab_p, mmap_mode="r") if lab_p.exists() else None + train, _ = PT.split_eps(info, tt, "tune") + rows = np.concatenate([np.arange(ef[e], et[e], 4) for e in train]) + XT = torch.from_numpy(F.x(rows)) + T = dict(np.load(PT.OUT / "errmode/A_hold_tune.npz")); idx = np.flatnonzero(T["keep"]) + stage = T["stage"][idx] if "stage" in T else np.zeros(len(idx)) + X = torch.from_numpy(F.x(T["anc"][idx])) + anc_edge = [(int(e_from[r]), int(e_to[r])) for r in T["anc"][idx]] + print("[h18] pairs", len(idx), "stages", {str(s): int((stage == s).sum()) for s in np.unique(stage)}, "train rows", len(rows), flush=True) + for kv in sys.argv[1:]: + name, succ = kv.split("=", 1) + spec = f"arc:{HEAD},np={NP},beta=0.99,gamma=0.995,tail=1e-3" + (f",succ={succ}" if succ != "default" else "") + _, sc = PT.build_scorer(spec, F.sd, 1546) + be = sc.backend; base = be.rew2; rec = [] + + class Rec: + arch = base.arch + def __call__(self, z, a): + v = base(z, a); rec.append((z.detach().float().cpu(), v.detach().float().cpu())); return v + be.rew2 = Rec() + res = []; t0 = time.time() + for i in range(len(idx)): + A = torch.from_numpy(np.stack([T["prog"][idx[i]], T["alt"][idx[i]]])).float().reshape(2, PT.CHUNK, -1) + rec.clear() + with torch.no_grad(): + sc.score(X[i][None], A, seed=0) + q = np.asarray(sc.last_q.cpu(), float) + Z = torch.cat([r[0] for r in rec]); V = torch.cat([r[1] for r in rec]).numpy().ravel() + assert len(Z) == 2 * NP, (len(Z), "unexpected rew2 call layout") + d = torch.cdist(Z, XT); nn = d.argmin(1).numpy(); dmin = d.min(1).values.numpy() + nr = rows[nn]; n = NP + out = {"stage": str(T["key"][idx[i]]), "anc_edge": anc_edge[i], "q": q.tolist()} + for j, k in enumerate(("prog", "hold")): + sl = slice(j * n, (j + 1) * n) + ed = [f"{int(e_from[r])}->{int(e_to[r])}" for r in nr[sl]] + out[k] = {"v": float(np.clip(V[sl], -1, 10).mean()), "v_raw": float(V[sl].mean()), "nn_d": float(dmin[sl].mean()), + "nn_lab": float(np.mean([lab[r] for r in nr[sl]])) if lab is not None else None, + "edges": {e: ed.count(e) for e in set(ed)}, + "same_edge": float(np.mean([(int(e_from[r]), int(e_to[r])) == anc_edge[i] for r in nr[sl]]))} + res.append(out) + if i % 25 == 0: + print(f"[h18] {name} {i}/{len(idx)} {time.time() - t0:.0f}s", flush=True) + json.dump(res, open(OUT / f"{name}.json", "w"), default=float) + summarize() + + +def summarize(): + L = ["# H18-diag: where do the A_hold goal reads land? (TUNE, CHALLENGER read-out 64x1, seed 0)", "", + "per model x stage: acc(prog>hold) | mean clamped read prog / hold | NN-label prog / hold | same-edge share prog / hold | NN dist prog / hold | top goal edges prog ; hold", ""] + for f in sorted(OUT.glob("*.json")): + R = json.load(open(f)) + for s in sorted({r["stage"] for r in R}): + S = [r for r in R if r["stage"] == s] + m = lambda k, c: np.mean([r[c][k] for r in S if r[c][k] is not None]) if any(r[c][k] is not None for r in S) else float("nan") + acc = np.mean([r["q"][0] > r["q"][1] for r in S]) + def top(c): + t = {} + for r in S: + for e, n in r[c]["edges"].items(): + t[e] = t.get(e, 0) + n + tot = sum(t.values()); return ", ".join(f"{e} {n / tot:.2f}" for e, n in sorted(t.items(), key=lambda x: -x[1])[:4]) + L.append(f"- {f.stem} stage {s} (n {len(S)}): acc {acc:.3f} | v {m('v', 'prog'):.3f} / {m('v', 'hold'):.3f} | lab {m('nn_lab', 'prog'):.3f} / {m('nn_lab', 'hold'):.3f}" + f" | same {m('same_edge', 'prog'):.2f} / {m('same_edge', 'hold'):.2f} | d {m('nn_d', 'prog'):.1f} / {m('nn_d', 'hold'):.1f} | {top('prog')} ; {top('hold')}") + (PT.ST / "rsm_h18_holddiag.md").write_text("\n".join(L) + "\n") + print("\n".join(L), flush=True) + + +if __name__ == "__main__": + if sys.argv[1:] == ["--summary"]: + summarize() + else: + main() diff --git a/rsm_rise/scripts/real/v7/pairtest/hopsweep_table.py b/rsm_rise/scripts/real/v7/pairtest/hopsweep_table.py new file mode 100644 index 0000000000000000000000000000000000000000..cb43e02a2418048ae1273001308b5b68db095b45 --- /dev/null +++ b/rsm_rise/scripts/real/v7/pairtest/hopsweep_table.py @@ -0,0 +1,41 @@ +"""RSM_PAIRTEST run 9: collect the hop-count sweep (run_hopsweep.sh logs + hopstat npz) into a markdown table. +Light: parses log lines and small npz files. usage: python hopsweep_table.py > status/real/rsm_hopsweep_tune.md""" +import glob, re, os, numpy as np +R = "/proj/dmfexp/zwhong/rsm_rise" +G = 0.998 +CFG = [("sf", "sf_b99_cap2", .99, 2), ("sf", "sf_b99_cap4", .99, 4), ("sf", "sf_b99", .99, None), ("sf", "sf_b995", .995, None), + ("sf", "sf_b997", .997, None), ("sf", "sf_b998", .998, None), + ("shaped_arc", "arc_b99_cap2", .99, 2), ("shaped_arc", "arc_b99_cap4", .99, 4), ("shaped_arc", "arc_b99", .99, None), + ("shaped_arc", "arc_b995", .995, None), ("shaped_arc", "arc_b997", .997, None), ("shaped_arc", "arc_b998", .998, None), + ("old", "old_b99", .99, None), ("old", "old_b995", .995, None), ("old", "old_b998", .998, None)] +TESTS = ["A_logged", "A_end", "A_hold", "B_logged", "B_syn"] +def cap_of(b, tail=1e-3): + p = (G - b) / (G * (1 - b)) + return 0 if p <= 0 else int(np.ceil(np.log(tail) / np.log(p))) +print("| head | beta / cap | E[hops] (trunc) | meas. hops | P(hops>=3) | z RMS start -> last hop | " + " | ".join(TESTS) + " | C 16x2 | C 16x8 | C 64x4 | done |") +print("|" + "---|" * (6 + len(TESTS) + 4)) +for head, tag, b, cap in CFG: + logs = sorted(glob.glob(f"{R}/logs/slurm/rr_cpu_hs_{tag}.*.out")) + txt = open(logs[-1]).read() if logs else "" + acc = {} + for t in TESTS: + m = re.findall(rf"\[score\] hs_{tag}_16x8 {t}: acc ([0-9.]+) ci \[([0-9.]+), ([0-9.]+)\].*PASS (\w+)", txt) + acc[t] = f"{float(m[-1][0]):.3f} [{float(m[-1][1]):.2f},{float(m[-1][2]):.2f}]" if m else "-" + for k, nm in [("C16x2", f"hs_{tag}"), ("C16x8", f"hs_{tag}_np16s8"), ("C64x4", f"hs_{tag}_np64s4")]: + m = re.findall(rf"\[score\] {nm}: BAD primary\(p50\) acc ([0-9.]+) ci \[([0-9.]+), ([0-9.]+)\]", txt) + acc[k] = f"{float(m[-1][0]):.3f} [{float(m[-1][1]):.2f},{float(m[-1][2]):.2f}]" if m else "-" + p = max((G - b) / (G * (1 - b)), 0.0); L = cap if cap is not None else cap_of(b) + pk = p ** np.arange(L + 1); pk = np.append(pk[:-1] * (1 - p), pk[-1]) if L > 0 else np.array([1.0]) + eh = float((np.arange(L + 1) * pk).sum()); ge3 = float(pk[3:].sum()) + hs = sorted(glob.glob(f"{R}/runs/pairtest/hopsweep/{tag}/hopstat_AB_*.npz")) + src = tag if head != "old" else tag.replace("old", "arc") # old head: same coins/flow/hop walk -> use arc walk stats + if head == "old": hs = sorted(glob.glob(f"{R}/runs/pairtest/hopsweep/{src}/hopstat_AB_*.npz")) + if hs: + H = np.concatenate([np.load(f)["hops"] for f in hs]); zl = np.concatenate([np.load(f)["z_last"] for f in hs]) + zs = np.concatenate([np.load(f)["z_start"] for f in hs]) + meas = f"{H.mean():.2f}"; mge3 = f"{(H >= 3).mean():.3f}"; zz = f"{zs.mean():.2f} -> {zl.mean():.2f}" + (" (arc walk)" if head == "old" else "") + else: + meas = mge3 = zz = "-" + bc = f"{b}" + (f" cap{cap}" if cap is not None else f" (cap {L})") + print(f"| {head} | {bc} | {eh:.2f} | {meas} | {mge3} (exp {ge3:.3f}) | {zz} | " + " | ".join(acc[t] for t in TESTS) + + f" | {acc['C16x2']} | {acc['C16x8']} | {acc['C64x4']} | {'yes' if '[hopsweep] done' in txt else 'no'} |") diff --git a/rsm_rise/scripts/real/v7/pairtest/iql_all.py b/rsm_rise/scripts/real/v7/pairtest/iql_all.py new file mode 100644 index 0000000000000000000000000000000000000000..355239d50e722cceb365f03b49e694eba1fa39dd --- /dev/null +++ b/rsm_rise/scripts/real/v7/pairtest/iql_all.py @@ -0,0 +1,120 @@ +#!/usr/bin/env python +"""RSM_PAIRTEST run 15 (owner 2026-11-21 ~01:30Z "compare the iql too"): IQL critics on the FROZEN tests C / A / B / STITCH. +Pairs are read as-is (pairs_v3_.npz [+ _ctrl], errmode/_.npz, stitch/_.npz); nothing about +pairs, rules or metrics changes. Only Q caches are written, in each test's own cache format, then the unchanged scorers +read them with SPEC "cached" (pairtest.py =cached route; errmode_test.py / stitch_test.py got the same route in run 15). + +Q exactly as iql_pairs.py / rsm_real's IDQLScorer: Q(s, a) = min_k critic_target_k(obs(s), norm(a[0])), obs = the anchor +frame from the v7 robomimic hdf5 (rise_stack make_obs), a[0] = FIRST action of the 50x10 chunk the test gives (logged +chunk rows of cache/act.f32.npy; checked equal to hdf5 actions_raw on the anchor rows), v7 action norm. Deterministic: +no particles / seeds. B_syn's translation is (t+1)/50 * D * u, so at t=0 the IQL sees 1/50 of the shift; A_hold's stay +chunk repeats a_prog[0], so its first action equals the progress chunk's and IQL ties (0.5) by construction. +Ensemble (--ens NAME): mean over the given checkpoints of their min-target Q (the V7_REWARD2 "mean" ensemble). + +usage: iql_all.py --split tune|test [--allow-test] --model NAME=CKPT ... [--ens NAME] +""" +import argparse, os, sys +from pathlib import Path +import numpy as np + +R = "/proj/dmfexp/zwhong/jm/rsm_rise" +sys.path.insert(0, f"{R}/scripts/real") +C = Path(f"{R}/cache/real_cooking_v7") +HDF5 = f"{R}/data/raw/cooking_v7_expert_suboptimal.hdf5" +NORM = f"{R}/data/derived/cooking_v7_action_norm.json" +OUT = Path("/proj/dmfexp/zwhong/rsm_rise/runs/pairtest") +TESTS = ["A_logged", "A_end", "A_hold", "B_logged", "B_syn"] +FAMS = ["S_02f", "S_02s", "S_01f", "S_26", "S_1end"] +AD = 10 + +ap = argparse.ArgumentParser() +ap.add_argument("--split", required=True, choices=["tune", "test"]); ap.add_argument("--allow-test", action="store_true") +ap.add_argument("--model", action="append", required=True); ap.add_argument("--ens", default="") +ap.add_argument("--vf", type=float, default=0.9) +a = ap.parse_args() +if a.split == "test" and not a.allow_test: + sys.exit("TEST needs the owner's OK (--allow-test)") +import h5py, torch +from v7_iql_score import IQLV7 +from rise_stack import obs as _obs +torch.set_num_threads(int(os.environ.get("SLURM_CPUS_PER_TASK", "8"))) +S = a.split +m = np.load(C / "meta.npz"); ef, et = m["ep_from"].astype(np.int64), m["ep_to"].astype(np.int64) +row_ep = np.repeat(np.arange(len(ef)), et - ef) +act = np.load(C / "act.f32.npy", mmap_mode="r") + +# ---- collect every (anchor row, first action) request of every test ------------------------------------------------ +jobs = [] # (cache path, {col: (anchor_rows, first_actions_raw)}) +P = dict(np.load(OUT / f"pairs_v3_{S}.npz")) +if (OUT / f"pairs_v3_{S}_ctrl.npz").exists(): + P.update(dict(np.load(OUT / f"pairs_v3_{S}_ctrl.npz"))) +anc = P["anc_row"]; cols = {"g": (anc, np.asarray(act[anc], np.float32))} +for c in ("BAD", "NOTPROG", "GOODNB"): + if f"{c}_row" in P: + cols[c] = (anc, np.asarray(act[P[f"{c}_row"]], np.float32)) # partner's logged chunk, scored AT the anchor +jobs.append(("C", lambda n: OUT / f"q_v3_{S}_{n}.npz", cols)) +for tn in TESTS: + Tz = dict(np.load(OUT / "errmode" / f"{tn}_{S}.npz")); idx = np.flatnonzero(Tz["keep"]); r = Tz["anc"][idx] + jobs.append((tn, (lambda n, tn=tn: OUT / "errmode" / f"q_{tn}_{S}_{n}.npz"), + {"qg": (r, Tz["prog"][idx, :AD].astype(np.float32)), "qa": (r, Tz["alt"][idx, :AD].astype(np.float32))})) + assert np.allclose(Tz["prog"][idx, :AD], act[r], atol=1e-6), f"{tn}: prog[0] != logged action at anchor" +for fam in FAMS: + Tz = dict(np.load(OUT / "stitch" / f"{fam}_{S}.npz")); r = Tz["anc"] + if len(r) == 0: + continue + jobs.append((fam, (lambda n, fam=fam: OUT / "stitch" / f"q_{fam}_{S}_{n}.npz"), + {"qg": (r, Tz["prog"][:, :AD].astype(np.float32)), "qa": (r, Tz["alt"][:, :AD].astype(np.float32))})) + +all_rows = np.unique(np.concatenate([v[0] for _, _, cc in jobs for v in cc.values()])) +print(f"[iqlall] {S}: {len(all_rows)} distinct anchor frames, {sum(len(v[0]) for _, _, cc in jobs for v in cc.values())} (frame, action) reads", flush=True) + +models = [] +for kv in a.model: + n, ck = kv.split("=", 1); q = IQLV7(ck, action_norm=NORM, hdf5=HDF5, device="cpu") + assert abs(q.sc.vf_quantile - a.vf) < 1e-6, (n, q.sc.vf_quantile) + models.append((n, q)) +sc0, an = models[0][1].sc, models[0][1].an +keys, OU = sc0.keys, sc0.ObsUtils + +# ---- per anchor frame: obs once, all requested actions, all models ---------------------------------------------------- +req = {} # row -> list of (job i, col, position, raw action) +for ji, (_, _, cc) in enumerate(jobs): + for col, (rows, A) in cc.items(): + for p, (rr, aa) in enumerate(zip(rows, A)): + req.setdefault(int(rr), []).append((ji, col, p, aa)) +res = {n: [{col: np.full(len(v[0]), np.nan) for col, v in cc.items()} for _, _, cc in jobs] for n, _ in models} +with h5py.File(HDF5, "r") as f: + d = f["data"]; demo_of = {int(d[k].attrs["episode_index"]): k for k in d} + chk = 0 + for e in np.unique(row_ep[all_rows]): + g = d[demo_of[int(e)]]; go = g["obs"]; assert g["actions_raw"].shape[0] == et[e] - ef[e] + rows = [int(r) for r in all_rows[row_ep[all_rows] == e]]; ts = [r - int(ef[e]) for r in rows] + araw = g["actions_raw"][()] + assert np.allclose(araw[ts], act[rows], atol=1e-4), f"ep {e}: cache act != hdf5 actions_raw"; chk += len(rows) + ag, wr, st = go["agentview_image"][()], go["robot0_eye_in_hand_image"][()], go["ee_state"][()] + for r, t in zip(rows, ts): + o = _obs.make_obs({"global": ag[t], "wrist": wr[t]}, st[t], an.gripper_thresh, images84={"global": ag[t], "wrist": wr[t]}, t=t) + L = req[r]; A = torch.from_numpy(an.norm(np.stack([x[3] for x in L]).astype(np.float32)).astype(np.float32)) + ob = {} + for k in keys: + x = torch.from_numpy(np.stack([_obs.obs_key(o, k)] * len(L))).float() + if OU.key_is_obs_modality(k, "rgb"): + x = OU.process_obs(x, obs_modality="rgb") + ob[k] = x + with torch.no_grad(): + for n, q in models: + qs = torch.cat([c(obs_dict=ob, acts=A) for c in q.sc.algo.nets["critic_target"]], 1).min(1)[0].numpy() + for (ji, col, p, _), v in zip(L, qs): + res[n][ji][col][p] = v + print(f"[iqlall] ep {e}: {len(rows)} frames", flush=True) +print(f"[iqlall] action check: cache act == hdf5 actions_raw on {chk} frames", flush=True) +if a.ens: + res[a.ens] = [{col: np.mean([res[n][ji][col] for n, _ in models], 0) for col in jobs[ji][2]} for ji in range(len(jobs))] +for n in res: + for ji, (nm, path, cc) in enumerate(jobs): + D = res[n][ji]; assert not any(np.isnan(v).any() for v in D.values()), (n, nm) + if nm == "C": + D = {**D, **{c + "_w": np.zeros(len(anc)) for c in D if c != "g"}} + np.savez(path(n), **D) + print(f"[iqlall] wrote caches for {n}", flush=True) +print("[iqlall] done", flush=True) diff --git a/rsm_rise/scripts/real/v7/pairtest/iql_pairs.py b/rsm_rise/scripts/real/v7/pairtest/iql_pairs.py new file mode 100644 index 0000000000000000000000000000000000000000..074ded192f03aef7371201472afe60bdda560375 --- /dev/null +++ b/rsm_rise/scripts/real/v7/pairtest/iql_pairs.py @@ -0,0 +1,61 @@ +#!/usr/bin/env python +"""RSM_PAIRTEST IQL baseline: score the frozen pairtest_v1 pairs with an IQL critic. +Q(s_g, a) = min_k critic_target_k(obs(s_g), norm(a)), a = the FIRST raw action of the logged chunk (the critic's own +action space; RISE's deploy path scores the first action). Loading/obs exactly as scripts/real/v7/reward2/iql_value_auc.py. +Writes runs/pairtest/q__.npz with keys g, BAD, NOTPROG (+ zero within-sd), then pairtest.py --stage score +--model =cached reads the cache. +usage: iql_pairs.py --name NAME --ckpt PATH [--split tune] [--vf 0.9]""" +import argparse, json, os, sys +import numpy as np + +R = "/proj/dmfexp/zwhong/jm/rsm_rise" +sys.path.insert(0, f"{R}/scripts/real") +C = f"{R}/cache/real_cooking_v7" +HDF5 = f"{R}/data/raw/cooking_v7_expert_suboptimal.hdf5" +NORM = f"{R}/data/derived/cooking_v7_action_norm.json" +OUT = "/proj/dmfexp/zwhong/rsm_rise/runs/pairtest" + +ap = argparse.ArgumentParser() +ap.add_argument("--name", required=True); ap.add_argument("--ckpt", required=True) +ap.add_argument("--split", default="tune"); ap.add_argument("--tag", default="_v2"); ap.add_argument("--vf", type=float, default=0.9) +a = ap.parse_args() +import h5py, torch +from v7_iql_score import IQLV7 +from rise_stack import obs as _obs +torch.set_num_threads(int(os.environ.get("SLURM_CPUS_PER_TASK", "8"))) +P = dict(np.load(f"{OUT}/pairs{a.tag}_{a.split}.npz")) +m = np.load(f"{C}/meta.npz"); ef, et = m["ep_from"].astype(np.int64), m["ep_to"].astype(np.int64) +row_ep = np.repeat(np.arange(len(ef)), et - ef) +q = IQLV7(a.ckpt, action_norm=NORM, hdf5=HDF5, device="cpu"); sc, an = q.sc, q.an +assert abs(sc.vf_quantile - a.vf) < 1e-6, sc.vf_quantile +algo, keys, OU = sc.algo, sc.keys, sc.ObsUtils +anc, anc_ep = P["anc_row"], P["anc_ep"] +with h5py.File(HDF5, "r") as f: + d = f["data"]; demo_of = {int(d[k].attrs["episode_index"]): k for k in d} + def raw_act(rows): + out = [] + for r in rows: + e = int(row_ep[r]); g = d[demo_of[e]]; assert g["actions_raw"].shape[0] == et[e] - ef[e] + out.append(g["actions_raw"][int(r - ef[e])]) + return an.norm(np.stack(out).astype(np.float32)).astype(np.float32) + acts = {"g": raw_act(anc), **{c: raw_act(P[c + "_row"]) for c in ("BAD", "NOTPROG") if c + "_row" in P}} + res = {k: np.zeros(len(anc)) for k in acts} + for e in np.unique(anc_ep): + g = d[demo_of[int(e)]]; go = g["obs"]; idx = np.flatnonzero(anc_ep == e); ts = (anc[idx] - ef[e]).astype(int) + ag, wr, st = go["agentview_image"][()], go["robot0_eye_in_hand_image"][()], go["ee_state"][()] + obs_l = [_obs.make_obs({"global": ag[t], "wrist": wr[t]}, st[t], an.gripper_thresh, + images84={"global": ag[t], "wrist": wr[t]}, t=t) for t in ts] + ob = {} + for k in keys: + x = torch.from_numpy(np.stack([_obs.obs_key(o, k) for o in obs_l])).float() + if OU.key_is_obs_modality(k, "rgb"): + x = OU.process_obs(x, obs_modality="rgb") + ob[k] = x + with torch.no_grad(): + for k in acts: + ac = torch.from_numpy(acts[k][idx]) + qs = torch.cat([c(obs_dict=ob, acts=ac) for c in algo.nets["critic_target"]], 1) + res[k][idx] = qs.min(1)[0].numpy() + print(f"[iqlpairs] ep {e}: {len(idx)} anchors, Qg-Qb mean {np.mean(res['g'][idx] - res['BAD'][idx]):.4f}", flush=True) +np.savez(f"{OUT}/q{a.tag}_{a.split}_{a.name}.npz", **res, **{k + "_w": np.zeros(len(anc)) for k in res if k != "g"}) +print("[iqlpairs] done", flush=True) diff --git a/rsm_rise/scripts/real/v7/pairtest/iql_select.py b/rsm_rise/scripts/real/v7/pairtest/iql_select.py new file mode 100644 index 0000000000000000000000000000000000000000..3078b2b43b6ffb7eb19719f2632908f1a876407f --- /dev/null +++ b/rsm_rise/scripts/real/v7/pairtest/iql_select.py @@ -0,0 +1,25 @@ +#!/usr/bin/env python +"""RSM_PAIRTEST run 15: NEW-IQL pick on TUNE ONLY (rule written in status/real/RSM_PAIRTEST.md before any TEST IQL score). +Candidates: RSHAPED2 t0.9 singles s0-s3 x epochs {1250,2500,3750,5000} and the 4-seed mean ensemble per epoch (20). +score = mean TUNE acc of C (pairtest_v3 BAD_primary), A_logged, B_logged (the three PRIMARY tests; A_hold is a tie by +construction for a first-action critic, so it cannot discriminate). Ties (|diff| < 1e-9): ensemble first, then earlier epoch. +Writes status/real/iql_pick.json {pick, ens, models[NAME=CKPT], table}.""" +import json +ST = "/proj/dmfexp/zwhong/rsm_rise/status/real" +C = json.load(open(f"{ST}/rsm_pairtest_v3_tune.json"))["models"]; AB = json.load(open(f"{ST}/rsm_errmode_tune.json"))["models"] +rows = [] +for ep in (1250, 2500, 3750, 5000): + man = {x["name"]: x["path"] for x in json.load(open(f"{ST}/v7_reward2_iql/manifest_e{ep}.json"))["entries"] if "RSHAPED2" in x["name"]} + names = [f"iqlR2_s{s}_e{ep}" for s in range(4)] + [f"iqlR2_ens_e{ep}"] + for n in names: + acc = [C[n]["BAD_primary"]["acc"], AB[n]["A_logged"]["acc"], AB[n]["B_logged"]["acc"]] + ens = "ens" in n + mods = [f"iqlR2_s{s}_e{ep}={man[f'iql_v7_RSHAPED2_t09_s{s}_e{ep}']}" for s in range(4)] if ens else \ + [f"{n}={man[n.replace('iqlR2_', 'iql_v7_RSHAPED2_t09_')]}"] + rows.append(dict(name=n, ep=ep, ens=ens, C=acc[0], A_logged=acc[1], B_logged=acc[2], score=sum(acc) / 3, models=mods)) +best = sorted(rows, key=lambda r: (-round(r["score"], 9), not r["ens"], r["ep"]))[0] +json.dump({"pick": best["name"], "ens": best["name"] if best["ens"] else "", "models": best["models"], "table": rows}, + open(f"{ST}/iql_pick.json", "w"), indent=1) +for r in rows: + print(f"{r['name']:18s} C {r['C']:.3f} A_log {r['A_logged']:.3f} B_log {r['B_logged']:.3f} score {r['score']:.4f}") +print("PICK", best["name"]) diff --git a/rsm_rise/scripts/real/v7/pairtest/make_ctrl.py b/rsm_rise/scripts/real/v7/pairtest/make_ctrl.py new file mode 100644 index 0000000000000000000000000000000000000000..53bf5a61217e23082b529c78428ba96c624e3937 --- /dev/null +++ b/rsm_rise/scripts/real/v7/pairtest/make_ctrl.py @@ -0,0 +1,26 @@ +#!/usr/bin/env python +"""RSM_PAIRTEST control (added 2026-11-20 ~08:10Z; does NOT change the frozen pairs): for every anchor of +pairs{VTAG}_{split}.npz, GOODNB = the nearest (same z-scored proprio metric, mu/sd from the pairs json) TRAIN frame on a +PROGRESS segment (edge_to not in {5,6}) of a GOOD-route episode (final_state in {3,8,7}) with the SAME edge_from. +Its logged chunk is a 'foreign but good' action. If Q(s_g, a_good) > Q(s_g, a_goodnb) as often as > Q(s_g, a_bad), the +test rewards the anchor's OWN chunk, not good-vs-bad; the clean contrast is then Q(s_g, a_goodnb) vs Q(s_g, a_bad). +Writes pairs{VTAG}_{split}_ctrl.npz (GOODNB_row, GOODNB_ep, GOODNB_dist).""" +import os, sys, json +import numpy as np +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import pairtest as PT +split = sys.argv[1] if len(sys.argv) > 1 else "tune" +info, tt, ef, et = PT.load_meta() +P = dict(np.load(PT.OUT / f"pairs{PT.VTAG}_{split}.npz")); J = json.load(open(PT.OUT / f"pairs{PT.VTAG}_{split}.json")) +e_from = np.load(PT.C / "edge_from.i16.npy").astype(np.int64); e_to = np.load(PT.C / "edge_to.i16.npy").astype(np.int64) +pr = np.load(PT.C / "proprio.f32.npy", mmap_mode="r"); mu, sd = np.array(J["proprio_mu"]), np.array(J["proprio_sd"]) +px = lambda rows: ((np.asarray(pr[np.asarray(rows, np.int64)], np.float64) - mu) / sd).astype(np.float32) +train = sorted(e for e, v in info.items() if v["split"] == "train" and v["final_state"] in PT.GOOD) +tr = np.concatenate([np.arange(ef[e], et[e]) for e in train]); row_ep = np.repeat(np.arange(len(ef)), et - ef) +anc = P["anc_row"]; out_r = np.full(len(anc), -1, np.int64); out_d = np.full(len(anc), np.inf, np.float32) +for s0 in (0, 2): + pool = tr[(e_from[tr] == s0) & ~np.isin(e_to[tr], [5, 6])]; w = np.flatnonzero(e_from[anc] == s0) + if len(w) and len(pool): + d, j = PT.nn_dist(px(anc[w]), px(pool)); out_r[w] = pool[j]; out_d[w] = d +np.savez(PT.OUT / f"pairs{PT.VTAG}_{split}_ctrl.npz", GOODNB_row=out_r, GOODNB_ep=row_ep[out_r], GOODNB_dist=out_d) +print("[ctrl] GOODNB dist pct", np.percentile(out_d, [5, 25, 50]).round(3), "vs BAD", np.percentile(P["BAD_dist"], [5, 25, 50]).round(3)) diff --git a/rsm_rise/scripts/real/v7/pairtest/pairtest.py b/rsm_rise/scripts/real/v7/pairtest/pairtest.py new file mode 100644 index 0000000000000000000000000000000000000000..42a53db2a9887809d04688c9be1d5ec82fc12a44 --- /dev/null +++ b/rsm_rise/scripts/real/v7/pairtest/pairtest.py @@ -0,0 +1,468 @@ +#!/usr/bin/env python +"""RSM_PAIRTEST (owner 2026-11-20): offline good-vs-bad action ranking test for the cooking v7 RSM. + +FROZEN TEST (v1, written before any model was scored; never edit the pair rule to make a model pass): + Episodes: route/final_state from data/derived/cooking_v7_split.json. GOOD = final_state in {3, 8, 7}. + BAD = final_state in {5, 6} (primary). NOTPROG = final_state 1 (route 0->1; secondary variant). + State x = clip((cat[DINO z, proprio] - mu) / max(sd, sd_floor), +-z_clip), feat_stats of export/v7/rsm_ens20 + (the successor's own input, 1546-d). Distance = L2 in x. + Anchors: held-out GOOD episodes (TUNE for selection; TEST only with --split test), frames t = 0, 25, 50, ... + Partner: s_b = nearest frame (all frames) of any TRAIN episode of the partner class. + Coincidence threshold: from TRAIN only. For anchors every 25th frame of every TRAIN episode, d_NN = distance to the + nearest frame (every 2nd frame) of a DIFFERENT TRAIN episode of the SAME route. Candidate thresholds + p10 < p25 < p50 of d_NN. PRIMARY = the smallest that yields >= 100 TUNE BAD pairs from >= 8 TUNE good episodes + (model-free rule; all three are reported). + a_good = logged 50-step raw chunk at s_g, a_bad = logged chunk at s_b (frames past the episode end repeat the last). + Scoring: BOTH chunks at s_g, in ONE scorer call (common random numbers), plus 6 hop-head samples at s_g (diagnostic + within-state spread). Q averaged over seeds 0..S-1 (S=2). Planner read-out = rsm_real#17: chain, beta 0.99, + gamma 0.998, 16 particles, temperature 25, chain_tail_eps 1e-3. + Metric: acc = mean over pairs of [Q_g > Q_b] (+0.5 on ties); 95% bootstrap CI resampling GOOD episodes (2000x); + per route pair (good route | bad route) and overall; mean gap Q_g - Q_b; gap / within-state sd. + PASS = overall BAD acc >= 0.70 and CI lower bound > 0.5 on TUNE, then confirmed once on TEST. + Reference row "MC": discounted shaped return (reward_shaped2, gamma 0.998, last frame absorbing) of the LOGGED + continuation from s_g vs from s_b -- checks that the pairs really are good-vs-bad in outcome. + +usage: pairtest.py --stage pairs (model-free, writes runs/pairtest/pairs_.npz + json) + pairtest.py --stage score --model NAME=SPEC ... (SPEC: old | ar: | r2: | succ=,...) +""" +import argparse, hashlib, json, os, sys, time +from pathlib import Path +import numpy as np, torch + +JM = Path("/proj/dmfexp/zwhong/jm/rsm_rise"); C = Path(os.environ.get("RR_V7_CACHE", str(JM / "cache/real_cooking_v7"))) # V7_LEARNPROJ: env override (default unchanged) +ROOT = Path("/proj/dmfexp/zwhong/rsm_rise"); OUT = ROOT / "runs/pairtest"; ST = ROOT / "status/real" +SUCC = JM / "export/v7/rsm_ens20/progress_augc_h50_ps_s0/ckpt_s20000.pt" +HOP = Path(os.environ.get("RR_V7_HOP", str(JM / "export/v7/hop/gauss_h50_ps_s1/policy_s120000.pt"))) +FS = Path(os.environ.get("RR_V7_FS", str(JM / "export/v7/rsm_ens20/feat_stats.npz"))) +sys.path.insert(0, str(ROOT / "scripts/real/v7/reward2")) +GOOD, BAD, NOTPROG = {3, 8, 7}, {5, 6}, {1} +CHUNK, STRIDE, GAMMA_MC = 50, 25, 0.998 +TEST_VERSION = os.environ.get("PAIRTEST_VERSION", "pairtest_v2") +VTAG = {"pairtest_v1": "", "pairtest_v2": "_v2", "pairtest_v3": "_v3"}[TEST_VERSION] +# v3 (registered ~07:45Z, model-free reason: v2 gave 19 pairs; coincident situations exist only in the first ~100 frames +# after state 0, so a 25-frame anchor stride samples them 2-4x per episode): identical to v2, anchor stride 5. +ANCHOR_STRIDE = 5 if TEST_VERSION == "pairtest_v3" else 25 +torch.set_num_threads(int(os.environ.get("SLURM_CPUS_PER_TASK", "8"))) + + +def load_meta(): + sp = json.load(open(JM / "data/derived/cooking_v7_split.json"))["episodes"] + tt = json.load(open(JM / "data/derived/cooking_v7_tune_test.json")) + m = np.load(C / "meta.npz"); ef, et = m["ep_from"].astype(np.int64), m["ep_to"].astype(np.int64) + info = {int(k): v for k, v in sp.items()} + return info, tt, ef, et + + +class Feat: + def __init__(self): + st = np.load(FS); self.mu = st["mu"].astype(np.float32) + self.sd = np.maximum(st["sd"].astype(np.float32), float(st["sd_floor"])); self.zc = float(st["z_clip"]) + self.z = np.load(C / "z.f16.npy", mmap_mode="r"); self.pr = np.load(C / "proprio.f32.npy", mmap_mode="r") + + def x(self, rows): + rows = np.asarray(rows, np.int64) + f = np.concatenate([np.asarray(self.z[rows], np.float32), np.asarray(self.pr[rows], np.float32)], 1) + return np.clip((f - self.mu) / self.sd, -self.zc, self.zc).astype(np.float32) + + +def nn_dist(Q, P, bs=512): + """min L2 distance and argmin from each row of Q to rows of P (torch, CPU).""" + Pt = torch.from_numpy(P); pn = (Pt * Pt).sum(1) + d_out, i_out = [], [] + for i in range(0, len(Q), bs): + q = torch.from_numpy(Q[i:i + bs]); d2 = (q * q).sum(1)[:, None] + pn[None] - 2 * q @ Pt.T + v, j = d2.clamp_min(0).min(1); d_out.append(v.sqrt()); i_out.append(j) + return torch.cat(d_out).numpy(), torch.cat(i_out).numpy() + + +def route(info, e): + return "->".join(str(s) for s in info[e]["path"]) + + +def stage_pairs(a): + if TEST_VERSION != "pairtest_v1": + return stage_pairs_v2(a) + info, tt, ef, et = load_meta(); F = Feat() + train = sorted(e for e, v in info.items() if v["split"] == "train") + held = sorted(tt["tune"] if a.split == "tune" else tt["test"]) + # ---- threshold from TRAIN within-route NN distances + by_route = {} + for e in train: + by_route.setdefault(route(info, e), []).append(e) + dnn = [] + for r, eps in sorted(by_route.items()): + pr = np.concatenate([np.arange(ef[e], et[e], 2) for e in eps]); pe = np.repeat(eps, [len(range(ef[e], et[e], 2)) for e in eps]) + P = F.x(pr) + for e in eps: + q = np.arange(ef[e], et[e], STRIDE); Xq = F.x(q) + Pm = P[pe != e] + d, _ = nn_dist(Xq, Pm); dnn.append(d) + print(f"[pairs] route {r}: {len(eps)} train eps", flush=True) + dnn = np.concatenate(dnn) + thr = {f"p{p}": float(np.percentile(dnn, p)) for p in (10, 25, 50)} + print("[pairs] within-route NN thresholds", thr, flush=True) + # ---- partner pools (TRAIN, all frames) + out = {"version": TEST_VERSION, "split": a.split, "thresholds": thr, "dnn_train_n": int(len(dnn)), + "dnn_train_pct": {str(p): float(np.percentile(dnn, p)) for p in (1, 5, 10, 25, 50, 75, 90)}} + anc_eps = [e for e in held if info[e]["final_state"] in GOOD] + anc = np.concatenate([np.arange(ef[e], et[e], STRIDE) for e in anc_eps]) + anc_ep = np.concatenate([[e] * len(range(ef[e], et[e], STRIDE)) for e in anc_eps]).astype(np.int64) + Xa = F.x(anc) + arrays = {"anc_row": anc, "anc_ep": anc_ep, "dnn_train": dnn.astype(np.float32)} + for cls, fsset in (("BAD", BAD), ("NOTPROG", NOTPROG)): + peps = [e for e in train if info[e]["final_state"] in fsset] + prow = np.concatenate([np.arange(ef[e], et[e]) for e in peps]) + prow_ep = np.concatenate([[e] * (et[e] - ef[e]) for e in peps]).astype(np.int64) + d, j = nn_dist(Xa, F.x(prow)) + arrays[f"{cls}_row"], arrays[f"{cls}_ep"], arrays[f"{cls}_dist"] = prow[j], prow_ep[j], d.astype(np.float32) + cnt = {} + for k, v in thr.items(): + keep = d < v + cnt[k] = {"pairs": int(keep.sum()), "good_eps": int(len(np.unique(anc_ep[keep])))} + out[f"{cls}_counts"] = cnt + out[f"{cls}_dist_pct"] = {str(p): float(np.percentile(d, p)) for p in (5, 25, 50)} + print(f"[pairs] {cls}: {len(peps)} train eps, counts {cnt}", flush=True) + prim = None + for k in ("p10", "p25", "p50"): + c = out["BAD_counts"][k] + if c["pairs"] >= 100 and c["good_eps"] >= 8: + prim = k; break + if a.split == "test": # TEST uses the threshold frozen on TUNE + prim = json.load(open(OUT / f"pairs{VTAG}_tune.json"))["primary_threshold"] + out["primary_threshold"] = prim or "p50" + out["primary_threshold_value"] = thr[out["primary_threshold"]] + out["n_anchors"] = int(len(anc)); out["n_good_eps"] = len(anc_eps) + OUT.mkdir(parents=True, exist_ok=True) + np.savez(OUT / f"pairs{VTAG}_{a.split}.npz", **arrays) + out["sha_npz"] = hashlib.sha256(open(OUT / f"pairs{VTAG}_{a.split}.npz", "rb").read()).hexdigest()[:16] + json.dump(out, open(OUT / f"pairs{VTAG}_{a.split}.json", "w"), indent=1) + print(json.dumps(out, indent=1), flush=True) + + +def stage_pairs_v2(a): + """pairtest_v2 (registered 2026-11-20 ~07:30Z after v1 produced 25 pairs from 6 TUNE eps: model-free reason). + v1 finding: in the 1546-d DINO space every bad (suboptimal-session) frame is far from every expert frame, even at the + same symbolic state (2->3 anchors at state 2: nearest 0->2->6 frame at d~40 vs within-route NN p50 24), so DINO-L2 + coincidence measures the recording session, not the situation. v2 = coincident SITUATION: + anchor s_g: every 25th frame of a held-out GOOD episode whose current segment starts at a state a bad route also + branches from (edge_from in {0, 2}); + partner s_b: TRAIN frames on a FAILURE segment (edge_to in {5, 6}) with the SAME edge_from; nearest in z-scored + proprio (10-d, mu/sd over TRAIN frames) -> a_bad = the logged action of the robot, at a matched pose and the same + task stage, heading into failure; + threshold from TRAIN: within-route NN proprio distance (anchors every 25th frame of train eps with edge_from in + {0, 2}; pool = every 2nd frame of OTHER train eps of the same route and same edge_from); p10/p25/p50, primary by the + same rule as v1 (smallest with >= 100 TUNE pairs from >= 8 good eps). DINO-x distance of every pair is stored.""" + info, tt, ef, et = load_meta(); F = Feat() + e_from = np.load(C / "edge_from.i16.npy").astype(np.int64); e_to = np.load(C / "edge_to.i16.npy").astype(np.int64) + pr_all = np.load(C / "proprio.f32.npy", mmap_mode="r") + train, held = split_eps(info, tt, a.split) + tr_rows = np.concatenate([np.arange(ef[e], et[e]) for e in train]) + pmu = np.asarray(pr_all[tr_rows], np.float64).mean(0); psd = np.maximum(np.asarray(pr_all[tr_rows], np.float64).std(0), 1e-3) + px = lambda rows: ((np.asarray(pr_all[np.asarray(rows, np.int64)], np.float64) - pmu) / psd).astype(np.float32) + BR = (0, 2) + by_route = {} + for e in train: + by_route.setdefault(route(info, e), []).append(e) + dnn = [] + for r, eps in sorted(by_route.items()): + for s0 in BR: + rows = [np.arange(ef[e], et[e], 2)[e_from[ef[e]:et[e]:2] == s0] for e in eps] + pe = np.concatenate([[e] * len(x) for e, x in zip(eps, rows)]).astype(np.int64) + if len(pe) == 0: + continue + Pp = px(np.concatenate(rows)) + for e in eps: + q = np.arange(ef[e], et[e], STRIDE); q = q[e_from[q] == s0] + if len(q) == 0 or (pe != e).sum() == 0: + continue + d, _ = nn_dist(px(q), Pp[pe != e]); dnn.append(d) + dnn = np.concatenate(dnn) + thr = {f"p{p}": float(np.percentile(dnn, p)) for p in (10, 25, 50)} + print("[pairs v2] within-route NN proprio thresholds", thr, flush=True) + out = {"version": TEST_VERSION, "split": a.split, "thresholds": thr, "dnn_train_n": int(len(dnn)), "space": "proprio z (10-d)", + "dnn_train_pct": {str(p): float(np.percentile(dnn, p)) for p in (1, 5, 10, 25, 50, 75, 90)}, + "proprio_mu": pmu.tolist(), "proprio_sd": psd.tolist()} + anc_eps = [e for e in held if info[e]["final_state"] in GOOD] + anc = np.concatenate([np.arange(ef[e], et[e], ANCHOR_STRIDE) for e in anc_eps]); anc = anc[np.isin(e_from[anc], BR)] + row_ep = np.repeat(np.arange(len(ef)), et - ef); anc_ep = row_ep[anc].astype(np.int64) + arrays = {"anc_row": anc, "anc_ep": anc_ep, "dnn_train": dnn.astype(np.float32)} + Pa = px(anc); bad_row = np.full(len(anc), -1, np.int64); bad_d = np.full(len(anc), np.inf, np.float32) + for s0 in BR: + pool = tr_rows[(e_from[tr_rows] == s0) & np.isin(e_to[tr_rows], [5, 6])] + w = np.flatnonzero(e_from[anc] == s0) + if len(w) == 0 or len(pool) == 0: + continue + d, j = nn_dist(Pa[w], px(pool)); bad_row[w] = pool[j]; bad_d[w] = d + arrays["BAD_row"], arrays["BAD_ep"], arrays["BAD_dist"] = bad_row, row_ep[bad_row].astype(np.int64), bad_d + arrays["BAD_dino_dist"] = np.linalg.norm(F.x(anc) - F.x(bad_row), axis=1).astype(np.float32) + cnt = {k: {"pairs": int((bad_d < v).sum()), "good_eps": int(len(np.unique(anc_ep[bad_d < v])))} for k, v in thr.items()} + out["BAD_counts"] = cnt; out["BAD_dist_pct"] = {str(p): float(np.percentile(bad_d, p)) for p in (5, 25, 50)} + out["anchors_by_edge_from"] = {str(s0): int((e_from[anc] == s0).sum()) for s0 in BR} + print("[pairs v2] BAD counts", cnt, flush=True) + prim = next((k for k in ("p10", "p25", "p50") if cnt[k]["pairs"] >= 100 and cnt[k]["good_eps"] >= 8), None) + if a.split == "test": + prim = json.load(open(OUT / f"pairs{VTAG}_tune.json"))["primary_threshold"] + out["primary_threshold"] = prim or "p50"; out["primary_threshold_value"] = thr[out["primary_threshold"]] + out["n_anchors"] = int(len(anc)); out["n_good_eps"] = int(len(np.unique(anc_ep))) + OUT.mkdir(parents=True, exist_ok=True) + np.savez(OUT / f"pairs{VTAG}_{a.split}.npz", **arrays) + out["sha_npz"] = hashlib.sha256(open(OUT / f"pairs{VTAG}_{a.split}.npz", "rb").read()).hexdigest()[:16] + json.dump(out, open(OUT / f"pairs{VTAG}_{a.split}.json", "w"), indent=1) + print(json.dumps({k: v for k, v in out.items() if "proprio" not in k}, indent=1), flush=True) + + +def chunk(act, rows, ep_end): + fr = np.minimum(np.asarray(rows)[:, None] + np.arange(CHUNK)[None], np.asarray(ep_end)[:, None] - 1) + return np.asarray(act[fr.ravel()], np.float32).reshape(len(rows), -1) + + +def mc_return(r, rows, ep_end, gamma=GAMMA_MC): + out = [] + for t, h in zip(rows, ep_end): + seg = r[t:h].astype(np.float64); n = len(seg); w = (1 - gamma) * gamma ** np.arange(n) + out.append(float((w * seg).sum() + gamma ** n * seg[-1])) + return np.array(out) + + +def locked_merge(path, update): + """run 14: read-modify-write of a shared results json under an exclusive flock + atomic rename (several scorer + jobs write the same file; the plain open(w) let a concurrent reader see an empty file -> JSONDecodeError).""" + import fcntl, os + with open(str(path) + ".lock", "w") as lk: + fcntl.flock(lk, fcntl.LOCK_EX) + cur = json.load(open(path)) if path.exists() and path.stat().st_size > 0 else None + cur = update(cur) + tmp = f"{path}.tmp{os.getpid()}" + json.dump(cur, open(tmp, "w"), indent=1, default=float); os.replace(tmp, path) + return cur + + +def build_scorer(spec, sd, d): + from types import SimpleNamespace + import rsm_scorer_ar as AR + m = AR._load_rsm_scorer() + opts = dict(kv.split("=", 1) for kv in spec.split(",")[1:]) if "," in spec else {} + kind = spec.split(",")[0] + kw = dict(backend="mlp", ckpt=str(opts.get("succ", SUCC)), hop_ckpt=str(opts.get("hop", HOP)), mode="chain", + beta=float(opts.get("beta", 0.99)), gamma=float(opts.get("gamma", 0.998)), + n_particles=int(opts.get("np", 16)), score_kind="prob", temperature=float(opts.get("T", 25.0)), chain_tail_eps=float(opts.get("tail", 1e-3)), + device=__import__("os").environ.get("PT_DEVICE", "cpu"), state=SimpleNamespace(d=d, sd=torch.from_numpy(sd).float(), normalize=None)) + if kind == "old": + return "rsm", m.RSMScorer(**kw) + if kind.startswith("ar:"): + return "rsm", AR.build_rsm_scorer_ar(kind[3:], **kw) + if kind.startswith("arc:"): # run 5: chain_ar with the r2 read clamped to the label range [-1, 10] (model, not test, change) + return "rsm", AR.build_rsm_scorer_ar(kind[4:], value_clip=(-1.0, 10.0), **kw) + if kind.startswith("r2:"): + return "r2", AR.ActRewardHead(kind[3:]) + if kind.startswith("qaux:"): # run 6: ONE-SHOT Q from the reward-predictive successor's qaux head (no chain) + return "r2", QauxOneShot(str(opts["succ"]), float(kind[5:]), d) + raise ValueError(spec) + + +class QauxOneShot: + """Q(s, a; beta) = sigmoid(qaux(flow.cond([z, a_raw, task, fourier(beta)]))) -- the w_qaux head of + code/rsm_libero_rpred/train_rsm.py:994-999 read at a fixed beta, one forward pass, no sampling.""" + + def __init__(self, ckpt, beta, d): + import rsm_scorer_ar as AR + m = AR._load_rsm_scorer(); model_mod, _, is_ope = m._rsm_modules() + self.enc, _, self.flow, _, _ = is_ope.load_critic(ckpt, d, 1, "cpu", data=None) + blob = torch.load(ckpt, map_location="cpu", weights_only=False) + W = blob["qaux"]; self.head = torch.nn.Linear(W["weight"].shape[1], 1); self.head.load_state_dict(W) + self.bf = model_mod.beta_fourier; self.beta = beta + self.flow.eval(); self.enc.eval() + + @torch.no_grad() + def __call__(self, x, A): + z = self.enc(x.float()); n = z.shape[0] + tk = torch.zeros(n, dtype=torch.long); b = torch.full((n,), self.beta) + c = self.flow.cond(torch.cat([z, A.reshape(n, -1).float(), self.flow.task(tk), self.bf(b, self.flow.n_fourier)], -1)) + return torch.sigmoid(self.head(c)).squeeze(-1) + + +def split_eps(info, tt, split): + """(train, held) episode lists. tune/test = the frozen split (unchanged). cvK (run 17, TRAIN-CV guard): held = TRAIN + fold K of 4, train = the other 3 TRAIN folds; folds stratified by route (TRAIN eps of each route sorted by id, fold = + rank % 4). Pair rules are applied unchanged with this (train, held); models trained on all TRAIN -> in-sample.""" + train = sorted(e for e, v in info.items() if v["split"] == "train") + if split in ("tune", "test"): + return train, sorted(tt[split]) + k = int(split[2:]); fold = {} + by_r = {} + for e in train: + by_r.setdefault(route(info, e), []).append(e) + for r, eps in by_r.items(): + for i, e in enumerate(sorted(eps)): + fold[e] = i % 4 + return sorted(e for e in train if fold[e] != k), sorted(e for e in train if fold[e] == k) + + +def boot_ci(corr, eps, n=2000, seed=0): + rng = np.random.default_rng(seed); ue = np.unique(eps); by = {e: corr[eps == e] for e in ue} + vals = [] + for _ in range(n): + s = rng.choice(ue, len(ue)); c = np.concatenate([by[e] for e in s]); vals.append(c.mean()) + return [float(np.percentile(vals, 2.5)), float(np.percentile(vals, 97.5))] + + +def metrics(qg, qb, eps, keys, sd_w=None): + corr = np.where(qg > qb, 1.0, np.where(qg == qb, 0.5, 0.0)) + res = {"n_pairs": int(len(corr)), "n_eps": int(len(np.unique(eps)))} + if len(corr) == 0: + return res + res.update(acc=float(corr.mean()), ci=boot_ci(corr, eps), gap_mean=float((qg - qb).mean()), + gap_median=float(np.median(qg - qb))) + if sd_w is not None: + res["gap_over_within_sd_median"] = float(np.median((qg - qb) / np.maximum(sd_w, 1e-9))) + res["within_sd_median"] = float(np.median(sd_w)) + res["acc_ep_mean"] = float(np.mean([corr[eps == e].mean() for e in np.unique(eps)])) + res["by_route_pair"] = {} + for k in sorted(set(keys)): + w = np.array([kk == k for kk in keys]) + res["by_route_pair"][k] = {"n": int(w.sum()), "n_eps": int(len(np.unique(eps[w]))), "acc": float(corr[w].mean()), + "gap_mean": float((qg[w] - qb[w]).mean())} + return res + + +def stage_score(a): + info, tt, ef, et = load_meta(); F = Feat() + P = dict(np.load(OUT / f"pairs{VTAG}_{a.split}.npz")); PJ = json.load(open(OUT / f"pairs{VTAG}_{a.split}.json")) + assert PJ["version"] == TEST_VERSION + act = np.load(C / "act.f32.npy", mmap_mode="r"); r_sh = np.load(C / "reward_shaped2.f32.npy", mmap_mode="r") + row_ep = np.repeat(np.arange(len(ef)), et - ef) + _ctrl = OUT / f"pairs{VTAG}_{a.split}_ctrl.npz" + if _ctrl.exists(): + P.update(dict(np.load(_ctrl))) + CLS = [c for c in ("BAD", "NOTPROG", "GOODNB") if f"{c}_row" in P] + anc = P["anc_row"]; anc_ep = P["anc_ep"]; Xa = torch.from_numpy(F.x(anc)) + Ag = chunk(act, anc, et[anc_ep]) + res_all = {"version": TEST_VERSION, "split": a.split, "pairs_json": PJ, "models": {}} + rsp = ST / f"rsm_pairtest{VTAG}_{a.split}.json" + if rsp.exists(): + res_all["models"] = json.load(open(rsp)).get("models", {}) + hop = None + for spec_kv in a.model: + name, spec = spec_kv.split("=", 1) + cache = OUT / f"q{VTAG}_{a.split}_{name}.npz" + t0 = time.time() + if cache.exists() and not a.force: + Qd = dict(np.load(cache)) + else: + Qd = {} + if name == "MC": + Qd["g"] = mc_return(r_sh, anc, et[anc_ep]) + for cls in CLS: + rb = P[f"{cls}_row"]; Qd[cls] = mc_return(r_sh, rb, et[row_ep[rb]]); Qd[cls + "_w"] = np.zeros(len(rb)) + else: + kind, sc = build_scorer(spec, F.sd, Xa.shape[1]) + if kind == "rsm" and hop is None: + import rsm_scorer_ar as AR + hop, _ = AR._load_rsm_scorer().load_hop_head(str(HOP), Xa.shape[1], 1, "cpu", feat_sd=F.sd) + Ab = {cls: chunk(act, P[f"{cls}_row"], et[row_ep[P[f"{cls}_row"]]]) for cls in CLS} + n = len(anc); qg = np.zeros(n); qb = {c: np.zeros(n) for c in Ab}; sdw = np.zeros(n) + gen = torch.Generator().manual_seed(1234) + need = np.zeros(n, bool) + for c in CLS: + if c != "GOODNB": + need |= P[f"{c}_dist"] < PJ["thresholds"]["p50"] # every reported threshold is <= p50 + for i in np.flatnonzero(need): + x = Xa[i][None] + with torch.no_grad(): + H = hop.sample_eps(x.expand(6, -1), torch.zeros(6, dtype=torch.long), + torch.randn(6, hop.d_act, generator=gen)) if hop is not None else None + if H is not None and H.shape[1] < Ag.shape[1]: # V7_LEARNPROJ run 4: chunk-8 hop (80-d) -> pad to the 50-step + H = H.reshape(6, -1, Ag.shape[1] // CHUNK).float(); H = torch.cat([H, H[:, -1:].expand(-1, CHUNK - H.shape[1], -1)], 1) # layout (repeat last); no-op for chunk 50 + cand = [torch.from_numpy(Ag[i][None])] + [torch.from_numpy(Ab[c][i][None]) for c in CLS] + ([H.reshape(6, -1).float()] if H is not None else []) + A = torch.cat(cand) + if kind == "r2": + q = sc(x.expand(len(A), -1), A).numpy().astype(np.float64) + else: + q = np.zeros(len(A)) + for s in range(a.seeds): + sc.score(x, A.reshape(len(A), CHUNK, -1), seed=s); q += np.asarray(sc.last_q.cpu(), float) + q /= a.seeds + qg[i] = q[0] + for j, c in enumerate(CLS): + qb[c][i] = q[1 + j] + sdw[i] = float(np.std(q[1 + len(CLS):])) if len(q) > 1 + len(CLS) else 0.0 + if i % 50 == 0: + print(f"[score] {name} {i}/{n} {time.time() - t0:.0f}s q={q[:1 + len(CLS)].round(4)}", flush=True) + Qd = {"g": qg, **{c: qb[c] for c in CLS}, **{c + "_w": sdw for c in CLS}} + np.savez(cache, **Qd) + thr_name = PJ["primary_threshold"]; R = {"spec": spec, "sec": time.time() - t0} + if "GOODNB" in CLS and "GOODNB" not in Qd: + print(f"[score] {name}: cached Q has no GOODNB column -- rerun with --force for the control", flush=True) + if "GOODNB" in Qd: + # control (not the PASS metric): own chunk vs a good neighbour's chunk, and the clean contrast + # good-neighbour chunk vs bad chunk, both at s_g, on the BAD-coincident anchors + for tn in ("p25", "p50"): + keep = P["BAD_dist"] < PJ["thresholds"][tn] + keys = [f"{route(info, int(e))}" for e in anc_ep[keep]] + R[f"CTRL_own_vs_goodnb_{tn}"] = metrics(Qd["g"][keep], Qd["GOODNB"][keep], anc_ep[keep], keys) + R[f"CTRL_goodnb_vs_bad_{tn}"] = metrics(Qd["GOODNB"][keep], Qd["BAD"][keep], anc_ep[keep], keys) + for cls in [c for c in CLS if c != "GOODNB"]: + for tn in ("p10", "p25", "p50"): + keep = P[f"{cls}_dist"] < PJ["thresholds"][tn] + keys = [f"{route(info, int(e))} | {route(info, int(b))}" for e, b in zip(anc_ep[keep], P[f"{cls}_ep"][keep])] + R[f"{cls}_{tn}"] = metrics(Qd["g"][keep], Qd[cls][keep], anc_ep[keep], keys, + Qd.get(f"{cls}_w", np.zeros(len(anc)))[keep]) + R[f"{cls}_primary"] = R[f"{cls}_{thr_name}"] + pm = R["BAD_primary"] + R["PASS"] = bool(pm.get("acc", 0) >= 0.70 and pm.get("ci", [0])[0] > 0.5) + res_all["models"][name] = R + print(f"[score] {name}: BAD primary({thr_name}) acc {pm.get('acc')} ci {pm.get('ci')} gap {pm.get('gap_mean')} " + f"n {pm.get('n_pairs')}/{pm.get('n_eps')} eps; NOTPROG acc {R.get('NOTPROG_primary', {}).get('acc')} PASS {R['PASS']}", + flush=True) + # run 14: merge-safe write (several scorer jobs share this file) -- re-read, replace only this model's entry + def _upd(cur): + if cur is not None: + m = cur.get("models", {}); m[name] = R; res_all["models"] = m + return res_all + res_all = locked_merge(rsp, _upd) + if os.environ.get("PT_MODEL_JSON_DIR"): # V7_NOAUG run 2: private per-model copy (the shared tune json lost entries); default off + _d = Path(os.environ["PT_MODEL_JSON_DIR"]); _d.mkdir(parents=True, exist_ok=True) + json.dump(R, open(_d / f"C_{a.split}.json", "w"), indent=1, default=float) + write_md(res_all, a.split) + + +def write_md(res, split): + PJ = res["pairs_json"]; tn = PJ["primary_threshold"] + L = [f"# RSM pair test ({TEST_VERSION}, split {split.upper()})", "", + f"Primary coincidence threshold {tn} = {PJ['primary_threshold_value']:.3f} (TRAIN within-route NN distances: " + + ", ".join(f"{k} {v:.3f}" for k, v in PJ["thresholds"].items()) + ")", + f"Pair counts BAD {PJ['BAD_counts']}; NOTPROG {PJ.get('NOTPROG_counts')}", "", + "| model | BAD acc [95% CI] | gap mean | n pairs/eps | gap/within-sd (med) | BAD p25 acc | BAD p50 acc | NOTPROG acc [CI] | PASS |", + "|---|---|---|---|---|---|---|---|---|"] + for k, R in res["models"].items(): + b, n = R["BAD_primary"], R.get("NOTPROG_primary", {}) + if "acc" not in b: + L.append(f"| {k} | no pairs | | | | | | | |"); continue + L.append(f"| {k} | {b['acc']:.3f} [{b['ci'][0]:.3f}, {b['ci'][1]:.3f}] | {b['gap_mean']:.4f} | {b['n_pairs']}/{b['n_eps']} | " + f"{b.get('gap_over_within_sd_median', float('nan')):.2f} | {R['BAD_p25'].get('acc', float('nan')):.3f} | " + f"{R['BAD_p50'].get('acc', float('nan')):.3f} | " + + (f"{n['acc']:.3f} [{n['ci'][0]:.3f}, {n['ci'][1]:.3f}]" if "acc" in n else "-") + f" | {R['PASS']} |") + L += ["", "## control (own chunk vs good-neighbour chunk; good-neighbour chunk vs bad chunk), p50 anchors", ""] + for k, R in res["models"].items(): + if "CTRL_own_vs_goodnb_p50" in R: + o, g = R["CTRL_own_vs_goodnb_p50"], R["CTRL_goodnb_vs_bad_p50"] + L.append(f"- {k}: own>goodnb {o.get('acc', float('nan')):.3f} {o.get('ci')}; goodnb>bad {g.get('acc', float('nan')):.3f} {g.get('ci')} (n {g.get('n_pairs')})") + L += ["", "## per route pair (BAD, primary threshold)", ""] + for k, R in res["models"].items(): + L.append(f"- {k}: " + "; ".join(f"{rp}: {v['acc']:.2f} (n {v['n']}/{v['n_eps']}ep, gap {v['gap_mean']:.4f})" + for rp, v in R["BAD_primary"].get("by_route_pair", {}).items())) + open(ST / f"rsm_pairtest{VTAG}_{split}.md", "w").write("\n".join(L) + "\n"); print("\n".join(L), flush=True) + + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--stage", choices=["pairs", "score"], required=True) + ap.add_argument("--split", default="tune", choices=["tune", "test", "cv0", "cv1", "cv2", "cv3"]) + ap.add_argument("--model", action="append", default=[]) + ap.add_argument("--seeds", type=int, default=2) + ap.add_argument("--force", action="store_true") + ap.add_argument("--allow-test", action="store_true") + a = ap.parse_args() + if a.split == "test" and not a.allow_test: + sys.exit("TEST is read once, for the frozen finalist only: pass --allow-test") + stage_pairs(a) if a.stage == "pairs" else stage_score(a) diff --git a/rsm_rise/scripts/real/v7/pairtest/pairtest_v1_frozen.py b/rsm_rise/scripts/real/v7/pairtest/pairtest_v1_frozen.py new file mode 100644 index 0000000000000000000000000000000000000000..c26fb2a730b93ddb7dd7d74d8afe7bb4f7554e9e --- /dev/null +++ b/rsm_rise/scripts/real/v7/pairtest/pairtest_v1_frozen.py @@ -0,0 +1,301 @@ +#!/usr/bin/env python +"""RSM_PAIRTEST (owner 2026-11-20): offline good-vs-bad action ranking test for the cooking v7 RSM. + +FROZEN TEST (v1, written before any model was scored; never edit the pair rule to make a model pass): + Episodes: route/final_state from data/derived/cooking_v7_split.json. GOOD = final_state in {3, 8, 7}. + BAD = final_state in {5, 6} (primary). NOTPROG = final_state 1 (route 0->1; secondary variant). + State x = clip((cat[DINO z, proprio] - mu) / max(sd, sd_floor), +-z_clip), feat_stats of export/v7/rsm_ens20 + (the successor's own input, 1546-d). Distance = L2 in x. + Anchors: held-out GOOD episodes (TUNE for selection; TEST only with --split test), frames t = 0, 25, 50, ... + Partner: s_b = nearest frame (all frames) of any TRAIN episode of the partner class. + Coincidence threshold: from TRAIN only. For anchors every 25th frame of every TRAIN episode, d_NN = distance to the + nearest frame (every 2nd frame) of a DIFFERENT TRAIN episode of the SAME route. Candidate thresholds + p10 < p25 < p50 of d_NN. PRIMARY = the smallest that yields >= 100 TUNE BAD pairs from >= 8 TUNE good episodes + (model-free rule; all three are reported). + a_good = logged 50-step raw chunk at s_g, a_bad = logged chunk at s_b (frames past the episode end repeat the last). + Scoring: BOTH chunks at s_g, in ONE scorer call (common random numbers), plus 6 hop-head samples at s_g (diagnostic + within-state spread). Q averaged over seeds 0..S-1 (S=2). Planner read-out = rsm_real#17: chain, beta 0.99, + gamma 0.998, 16 particles, temperature 25, chain_tail_eps 1e-3. + Metric: acc = mean over pairs of [Q_g > Q_b] (+0.5 on ties); 95% bootstrap CI resampling GOOD episodes (2000x); + per route pair (good route | bad route) and overall; mean gap Q_g - Q_b; gap / within-state sd. + PASS = overall BAD acc >= 0.70 and CI lower bound > 0.5 on TUNE, then confirmed once on TEST. + Reference row "MC": discounted shaped return (reward_shaped2, gamma 0.998, last frame absorbing) of the LOGGED + continuation from s_g vs from s_b -- checks that the pairs really are good-vs-bad in outcome. + +usage: pairtest.py --stage pairs (model-free, writes runs/pairtest/pairs_.npz + json) + pairtest.py --stage score --model NAME=SPEC ... (SPEC: old | ar: | r2: | succ=,...) +""" +import argparse, hashlib, json, os, sys, time +from pathlib import Path +import numpy as np, torch + +JM = Path("/proj/dmfexp/zwhong/jm/rsm_rise"); C = JM / "cache/real_cooking_v7" +ROOT = Path("/proj/dmfexp/zwhong/rsm_rise"); OUT = ROOT / "runs/pairtest"; ST = ROOT / "status/real" +SUCC = JM / "export/v7/rsm_ens20/progress_augc_h50_ps_s0/ckpt_s20000.pt" +HOP = JM / "export/v7/hop/gauss_h50_ps_s1/policy_s120000.pt" +FS = JM / "export/v7/rsm_ens20/feat_stats.npz" +sys.path.insert(0, str(ROOT / "scripts/real/v7/reward2")) +GOOD, BAD, NOTPROG = {3, 8, 7}, {5, 6}, {1} +CHUNK, STRIDE, GAMMA_MC = 50, 25, 0.998 +TEST_VERSION = "pairtest_v1" +torch.set_num_threads(int(os.environ.get("SLURM_CPUS_PER_TASK", "8"))) + + +def load_meta(): + sp = json.load(open(JM / "data/derived/cooking_v7_split.json"))["episodes"] + tt = json.load(open(JM / "data/derived/cooking_v7_tune_test.json")) + m = np.load(C / "meta.npz"); ef, et = m["ep_from"].astype(np.int64), m["ep_to"].astype(np.int64) + info = {int(k): v for k, v in sp.items()} + return info, tt, ef, et + + +class Feat: + def __init__(self): + st = np.load(FS); self.mu = st["mu"].astype(np.float32) + self.sd = np.maximum(st["sd"].astype(np.float32), float(st["sd_floor"])); self.zc = float(st["z_clip"]) + self.z = np.load(C / "z.f16.npy", mmap_mode="r"); self.pr = np.load(C / "proprio.f32.npy", mmap_mode="r") + + def x(self, rows): + rows = np.asarray(rows, np.int64) + f = np.concatenate([np.asarray(self.z[rows], np.float32), np.asarray(self.pr[rows], np.float32)], 1) + return np.clip((f - self.mu) / self.sd, -self.zc, self.zc).astype(np.float32) + + +def nn_dist(Q, P, bs=512): + """min L2 distance and argmin from each row of Q to rows of P (torch, CPU).""" + Pt = torch.from_numpy(P); pn = (Pt * Pt).sum(1) + d_out, i_out = [], [] + for i in range(0, len(Q), bs): + q = torch.from_numpy(Q[i:i + bs]); d2 = (q * q).sum(1)[:, None] + pn[None] - 2 * q @ Pt.T + v, j = d2.clamp_min(0).min(1); d_out.append(v.sqrt()); i_out.append(j) + return torch.cat(d_out).numpy(), torch.cat(i_out).numpy() + + +def route(info, e): + return "->".join(str(s) for s in info[e]["path"]) + + +def stage_pairs(a): + info, tt, ef, et = load_meta(); F = Feat() + train = sorted(e for e, v in info.items() if v["split"] == "train") + held = sorted(tt["tune"] if a.split == "tune" else tt["test"]) + # ---- threshold from TRAIN within-route NN distances + by_route = {} + for e in train: + by_route.setdefault(route(info, e), []).append(e) + dnn = [] + for r, eps in sorted(by_route.items()): + pr = np.concatenate([np.arange(ef[e], et[e], 2) for e in eps]); pe = np.repeat(eps, [len(range(ef[e], et[e], 2)) for e in eps]) + P = F.x(pr) + for e in eps: + q = np.arange(ef[e], et[e], STRIDE); Xq = F.x(q) + Pm = P[pe != e] + d, _ = nn_dist(Xq, Pm); dnn.append(d) + print(f"[pairs] route {r}: {len(eps)} train eps", flush=True) + dnn = np.concatenate(dnn) + thr = {f"p{p}": float(np.percentile(dnn, p)) for p in (10, 25, 50)} + print("[pairs] within-route NN thresholds", thr, flush=True) + # ---- partner pools (TRAIN, all frames) + out = {"version": TEST_VERSION, "split": a.split, "thresholds": thr, "dnn_train_n": int(len(dnn)), + "dnn_train_pct": {str(p): float(np.percentile(dnn, p)) for p in (1, 5, 10, 25, 50, 75, 90)}} + anc_eps = [e for e in held if info[e]["final_state"] in GOOD] + anc = np.concatenate([np.arange(ef[e], et[e], STRIDE) for e in anc_eps]) + anc_ep = np.concatenate([[e] * len(range(ef[e], et[e], STRIDE)) for e in anc_eps]).astype(np.int64) + Xa = F.x(anc) + arrays = {"anc_row": anc, "anc_ep": anc_ep, "dnn_train": dnn.astype(np.float32)} + for cls, fsset in (("BAD", BAD), ("NOTPROG", NOTPROG)): + peps = [e for e in train if info[e]["final_state"] in fsset] + prow = np.concatenate([np.arange(ef[e], et[e]) for e in peps]) + prow_ep = np.concatenate([[e] * (et[e] - ef[e]) for e in peps]).astype(np.int64) + d, j = nn_dist(Xa, F.x(prow)) + arrays[f"{cls}_row"], arrays[f"{cls}_ep"], arrays[f"{cls}_dist"] = prow[j], prow_ep[j], d.astype(np.float32) + cnt = {} + for k, v in thr.items(): + keep = d < v + cnt[k] = {"pairs": int(keep.sum()), "good_eps": int(len(np.unique(anc_ep[keep])))} + out[f"{cls}_counts"] = cnt + out[f"{cls}_dist_pct"] = {str(p): float(np.percentile(d, p)) for p in (5, 25, 50)} + print(f"[pairs] {cls}: {len(peps)} train eps, counts {cnt}", flush=True) + prim = None + for k in ("p10", "p25", "p50"): + c = out["BAD_counts"][k] + if c["pairs"] >= 100 and c["good_eps"] >= 8: + prim = k; break + if a.split == "test": # TEST uses the threshold frozen on TUNE + prim = json.load(open(OUT / "pairs_tune.json"))["primary_threshold"] + out["primary_threshold"] = prim or "p50" + out["primary_threshold_value"] = thr[out["primary_threshold"]] + out["n_anchors"] = int(len(anc)); out["n_good_eps"] = len(anc_eps) + OUT.mkdir(parents=True, exist_ok=True) + np.savez(OUT / f"pairs_{a.split}.npz", **arrays) + out["sha_npz"] = hashlib.sha256(open(OUT / f"pairs_{a.split}.npz", "rb").read()).hexdigest()[:16] + json.dump(out, open(OUT / f"pairs_{a.split}.json", "w"), indent=1) + print(json.dumps(out, indent=1), flush=True) + + +def chunk(act, rows, ep_end): + fr = np.minimum(np.asarray(rows)[:, None] + np.arange(CHUNK)[None], np.asarray(ep_end)[:, None] - 1) + return np.asarray(act[fr.ravel()], np.float32).reshape(len(rows), -1) + + +def mc_return(r, rows, ep_end, gamma=GAMMA_MC): + out = [] + for t, h in zip(rows, ep_end): + seg = r[t:h].astype(np.float64); n = len(seg); w = (1 - gamma) * gamma ** np.arange(n) + out.append(float((w * seg).sum() + gamma ** n * seg[-1])) + return np.array(out) + + +def build_scorer(spec, sd, d): + from types import SimpleNamespace + import rsm_scorer_ar as AR + m = AR._load_rsm_scorer() + opts = dict(kv.split("=", 1) for kv in spec.split(",")[1:]) if "," in spec else {} + kind = spec.split(",")[0] + kw = dict(backend="mlp", ckpt=str(opts.get("succ", SUCC)), hop_ckpt=str(opts.get("hop", HOP)), mode="chain", + beta=float(opts.get("beta", 0.99)), gamma=float(opts.get("gamma", 0.998)), + n_particles=int(opts.get("np", 16)), score_kind="prob", temperature=25.0, chain_tail_eps=1e-3, + device="cpu", state=SimpleNamespace(d=d, sd=torch.from_numpy(sd).float(), normalize=None)) + if kind == "old": + return "rsm", m.RSMScorer(**kw) + if kind.startswith("ar:"): + return "rsm", AR.build_rsm_scorer_ar(kind[3:], **kw) + if kind.startswith("r2:"): + return "r2", AR.ActRewardHead(kind[3:]) + raise ValueError(spec) + + +def boot_ci(corr, eps, n=2000, seed=0): + rng = np.random.default_rng(seed); ue = np.unique(eps); by = {e: corr[eps == e] for e in ue} + vals = [] + for _ in range(n): + s = rng.choice(ue, len(ue)); c = np.concatenate([by[e] for e in s]); vals.append(c.mean()) + return [float(np.percentile(vals, 2.5)), float(np.percentile(vals, 97.5))] + + +def metrics(qg, qb, eps, keys, sd_w=None): + corr = np.where(qg > qb, 1.0, np.where(qg == qb, 0.5, 0.0)) + res = {"n_pairs": int(len(corr)), "n_eps": int(len(np.unique(eps)))} + if len(corr) == 0: + return res + res.update(acc=float(corr.mean()), ci=boot_ci(corr, eps), gap_mean=float((qg - qb).mean()), + gap_median=float(np.median(qg - qb))) + if sd_w is not None: + res["gap_over_within_sd_median"] = float(np.median((qg - qb) / np.maximum(sd_w, 1e-9))) + res["within_sd_median"] = float(np.median(sd_w)) + res["acc_ep_mean"] = float(np.mean([corr[eps == e].mean() for e in np.unique(eps)])) + res["by_route_pair"] = {} + for k in sorted(set(keys)): + w = np.array([kk == k for kk in keys]) + res["by_route_pair"][k] = {"n": int(w.sum()), "n_eps": int(len(np.unique(eps[w]))), "acc": float(corr[w].mean()), + "gap_mean": float((qg[w] - qb[w]).mean())} + return res + + +def stage_score(a): + info, tt, ef, et = load_meta(); F = Feat() + P = dict(np.load(OUT / f"pairs_{a.split}.npz")); PJ = json.load(open(OUT / f"pairs_{a.split}.json")) + assert PJ["version"] == TEST_VERSION + act = np.load(C / "act.f32.npy", mmap_mode="r"); r_sh = np.load(C / "reward_shaped2.f32.npy", mmap_mode="r") + row_ep = np.repeat(np.arange(len(ef)), et - ef) + anc = P["anc_row"]; anc_ep = P["anc_ep"]; Xa = torch.from_numpy(F.x(anc)) + Ag = chunk(act, anc, et[anc_ep]) + res_all = {"version": TEST_VERSION, "split": a.split, "pairs_json": PJ, "models": {}} + rsp = ST / f"rsm_pairtest_{a.split}.json" + if rsp.exists(): + res_all["models"] = json.load(open(rsp)).get("models", {}) + hop = None + for spec_kv in a.model: + name, spec = spec_kv.split("=", 1) + cache = OUT / f"q_{a.split}_{name}.npz" + t0 = time.time() + if cache.exists() and not a.force: + Qd = dict(np.load(cache)) + else: + Qd = {} + if name == "MC": + Qd["g"] = mc_return(r_sh, anc, et[anc_ep]) + for cls in ("BAD", "NOTPROG"): + rb = P[f"{cls}_row"]; Qd[cls] = mc_return(r_sh, rb, et[row_ep[rb]]); Qd[cls + "_w"] = np.zeros(len(rb)) + else: + kind, sc = build_scorer(spec, F.sd, Xa.shape[1]) + if kind == "rsm" and hop is None: + import rsm_scorer_ar as AR + hop, _ = AR._load_rsm_scorer().load_hop_head(str(HOP), Xa.shape[1], 1, "cpu", feat_sd=F.sd) + Ab = {cls: chunk(act, P[f"{cls}_row"], et[row_ep[P[f"{cls}_row"]]]) for cls in ("BAD", "NOTPROG")} + n = len(anc); qg = np.zeros(n); qb = {c: np.zeros(n) for c in Ab}; sdw = np.zeros(n) + gen = torch.Generator().manual_seed(1234) + for i in range(n): + x = Xa[i][None] + with torch.no_grad(): + H = hop.sample_eps(x.expand(6, -1), torch.zeros(6, dtype=torch.long), + torch.randn(6, hop.d_act, generator=gen)) if hop is not None else None + cand = [torch.from_numpy(Ag[i][None]), torch.from_numpy(Ab["BAD"][i][None]), + torch.from_numpy(Ab["NOTPROG"][i][None])] + ([H.reshape(6, -1).float()] if H is not None else []) + A = torch.cat(cand) + if kind == "r2": + q = sc(x.expand(len(A), -1), A).numpy().astype(np.float64) + else: + q = np.zeros(len(A)) + for s in range(a.seeds): + sc.score(x, A.reshape(len(A), CHUNK, -1), seed=s); q += np.asarray(sc.last_q.cpu(), float) + q /= a.seeds + qg[i], qb["BAD"][i], qb["NOTPROG"][i] = q[0], q[1], q[2] + sdw[i] = float(np.std(q[3:])) if len(q) > 3 else 0.0 + if i % 50 == 0: + print(f"[score] {name} {i}/{n} {time.time() - t0:.0f}s q={q[:3].round(4)}", flush=True) + Qd = {"g": qg, "BAD": qb["BAD"], "NOTPROG": qb["NOTPROG"], "BAD_w": sdw, "NOTPROG_w": sdw} + np.savez(cache, **Qd) + thr_name = PJ["primary_threshold"]; R = {"spec": spec, "sec": time.time() - t0} + for cls in ("BAD", "NOTPROG"): + for tn in ("p10", "p25", "p50"): + keep = P[f"{cls}_dist"] < PJ["thresholds"][tn] + keys = [f"{route(info, int(e))} | {route(info, int(b))}" for e, b in zip(anc_ep[keep], P[f"{cls}_ep"][keep])] + R[f"{cls}_{tn}"] = metrics(Qd["g"][keep], Qd[cls][keep], anc_ep[keep], keys, + Qd.get(f"{cls}_w", np.zeros(len(anc)))[keep]) + R[f"{cls}_primary"] = R[f"{cls}_{thr_name}"] + pm = R["BAD_primary"] + R["PASS"] = bool(pm.get("acc", 0) >= 0.70 and pm.get("ci", [0])[0] > 0.5) + res_all["models"][name] = R + print(f"[score] {name}: BAD primary({thr_name}) acc {pm.get('acc')} ci {pm.get('ci')} gap {pm.get('gap_mean')} " + f"n {pm.get('n_pairs')}/{pm.get('n_eps')} eps; NOTPROG acc {R['NOTPROG_primary'].get('acc')} PASS {R['PASS']}", + flush=True) + json.dump(res_all, open(rsp, "w"), indent=1, default=float) + write_md(res_all, a.split) + + +def write_md(res, split): + PJ = res["pairs_json"]; tn = PJ["primary_threshold"] + L = [f"# RSM pair test ({TEST_VERSION}, split {split.upper()})", "", + f"Primary coincidence threshold {tn} = {PJ['primary_threshold_value']:.3f} (TRAIN within-route NN distances: " + + ", ".join(f"{k} {v:.3f}" for k, v in PJ["thresholds"].items()) + ")", + f"Pair counts BAD {PJ['BAD_counts']}; NOTPROG {PJ['NOTPROG_counts']}", "", + "| model | BAD acc [95% CI] | gap mean | n pairs/eps | gap/within-sd (med) | BAD p25 acc | BAD p50 acc | NOTPROG acc [CI] | PASS |", + "|---|---|---|---|---|---|---|---|---|"] + for k, R in res["models"].items(): + b, n = R["BAD_primary"], R["NOTPROG_primary"] + if "acc" not in b: + L.append(f"| {k} | no pairs | | | | | | | |"); continue + L.append(f"| {k} | {b['acc']:.3f} [{b['ci'][0]:.3f}, {b['ci'][1]:.3f}] | {b['gap_mean']:.4f} | {b['n_pairs']}/{b['n_eps']} | " + f"{b.get('gap_over_within_sd_median', float('nan')):.2f} | {R['BAD_p25'].get('acc', float('nan')):.3f} | " + f"{R['BAD_p50'].get('acc', float('nan')):.3f} | " + + (f"{n['acc']:.3f} [{n['ci'][0]:.3f}, {n['ci'][1]:.3f}]" if "acc" in n else "-") + f" | {R['PASS']} |") + L += ["", "## per route pair (BAD, primary threshold)", ""] + for k, R in res["models"].items(): + L.append(f"- {k}: " + "; ".join(f"{rp}: {v['acc']:.2f} (n {v['n']}/{v['n_eps']}ep, gap {v['gap_mean']:.4f})" + for rp, v in R["BAD_primary"].get("by_route_pair", {}).items())) + open(ST / f"rsm_pairtest_{split}.md", "w").write("\n".join(L) + "\n"); print("\n".join(L), flush=True) + + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--stage", choices=["pairs", "score"], required=True) + ap.add_argument("--split", default="tune", choices=["tune", "test"]) + ap.add_argument("--model", action="append", default=[]) + ap.add_argument("--seeds", type=int, default=2) + ap.add_argument("--force", action="store_true") + ap.add_argument("--allow-test", action="store_true") + a = ap.parse_args() + if a.split == "test" and not a.allow_test: + sys.exit("TEST is read once, for the frozen finalist only: pass --allow-test") + stage_pairs(a) if a.stage == "pairs" else stage_score(a) diff --git a/rsm_rise/scripts/real/v7/pairtest/r18_table.py b/rsm_rise/scripts/real/v7/pairtest/r18_table.py new file mode 100644 index 0000000000000000000000000000000000000000..787544add6917b8342c932f2d36683f32d22e712 --- /dev/null +++ b/rsm_rise/scripts/real/v7/pairtest/r18_table.py @@ -0,0 +1,29 @@ +"""RSM_PAIRTEST run 18: TUNE + TRAIN-CV table (json only; login-node safe). usage: r18_table.py ...""" +import json, sys +from pathlib import Path +R = Path("/proj/dmfexp/zwhong/rsm_rise"); ST = R / "status/real" +TESTS = [("C", "pt", "BAD_primary"), ("A_log", "em", "A_logged"), ("A_end", "em", "A_end"), ("A_hold", "em", "A_hold"), + ("B_log", "em", "B_logged"), ("B_syn", "em", "B_syn"), ("STITCH", "st", "STITCH")] +F = {"pt": "rsm_pairtest_v3_{}.json", "em": "rsm_errmode_{}.json", "st": "rsm_stitch_{}.json"} +SPL = ["tune", "cv0", "cv1", "cv2", "cv3"] +D = {s: {k: (json.load(open(ST / v.format(s)))["models"] if (ST / v.format(s)).exists() else {}) for k, v in F.items()} for s in SPL} +def acc(s, m, src, key): + M = D[s][src].get(m, {}) + pf = R / f"runs/v7_noaug/eval/{m}/C_{s}.json" + if src == "pt" and not M and pf.exists(): M = json.load(open(pf)) + for k in key.split("."): + M = M.get(k, {}) if isinstance(M, dict) else {} + return M.get("acc") if isinstance(M, dict) else None +allm = sorted({m for s in SPL for src in D[s].values() for m in src}) +names = [] +for a in sys.argv[1:]: + names += [m for m in allm if m.startswith(a[:-1])] if a.endswith("*") else [a] +f = lambda v: "-" if v is None else f"{v:.3f}" +print("| model | split | " + " | ".join(t[0] for t in TESTS) + " |"); print("|---" * (2 + len(TESTS)) + "|") +for m in names: + print(f"| {m} | TUNE | " + " | ".join(f(acc("tune", m, src, k)) for _, src, k in TESTS) + " |") + cells = [] + for _, src, k in TESTS: + v = [acc(s, m, src, k) for s in SPL[1:]]; v = [x for x in v if x is not None] + cells.append("-" if not v else f"{sum(v)/len(v):.3f} ({len(v)})") + print(f"| {m} | CV mean (n folds) | " + " | ".join(cells) + " |") diff --git a/rsm_rise/scripts/real/v7/pairtest/run_bgsweep.sh b/rsm_rise/scripts/real/v7/pairtest/run_bgsweep.sh new file mode 100644 index 0000000000000000000000000000000000000000..710e6756b0601595e993c2f89a5b04b005080abf --- /dev/null +++ b/rsm_rise/scripts/real/v7/pairtest/run_bgsweep.sh @@ -0,0 +1,31 @@ +#!/usr/bin/env bash +#SBATCH --partition=cpu +#SBATCH --account=grp_runtime +#SBATCH --nodes=1 --ntasks=1 --cpus-per-task=32 +#SBATCH --mem=96G +#SBATCH --time=23: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 +# RSM_PAIRTEST run 13 (owner 21:30Z: replace the clamp by a beta x gamma sweep). Teacher-forced shaped head +# (c50_bal_adrop02), UNCLAMPED (CLAMP=0 -> "ar:") or clamped reference (CLAMP=1 -> "arc:"), uncapped (tail 1e-3). +# Frozen tests, TUNE only: A/B errmode 16x8, C pairtest_v3 16x2 / 16x8 / 64x4, STITCH 16x8. Hop stats + raw reward +# reads (vraw, pre-clamp) dumped per test into runs/pairtest/bgsweep//. +# usage: CLAMP=0|1 BETA= GAMMA= TAG= sbatch -J rr_cpu_bg_ run_bgsweep.sh +set -uo pipefail +export PAIRTEST_VERSION=pairtest_v3 +cd /proj/dmfexp/zwhong/rsm_rise +PY=/proj/dmfexp/zwhong/rsm_rise/venv_rsm/bin/python; S=scripts/real/v7/pairtest +R2=runs/v7_reward2/c50_bal_adrop02/ckpt_best.pt +if [ "$CLAMP" = 1 ]; then spec="arc:$R2"; else spec="ar:$R2"; fi +ex=",beta=$BETA,gamma=$GAMMA,tail=1e-3"; t=bg_${TAG} +export HOPSTAT_DIR=runs/pairtest/bgsweep/$TAG; mkdir -p $HOPSTAT_DIR +# eviction-safe: cpu jobs can be preempted and requeued from zero -> each finished stage leaves a marker and is skipped +st(){ local k=$1; shift; [ -f $HOPSTAT_DIR/done_$k ] && { echo "[bgsweep] skip $k (done)"; return; } + export HOPSTAT_TAG=$k; "$@" && touch $HOPSTAT_DIR/done_$k; } +st AB $PY $S/errmode_test.py --stage score --split tune --seeds 8 --model ${t}_16x8=$spec,np=16$ex +st C16x2 $PY $S/pairtest.py --stage score --split tune --seeds 2 --model ${t}=$spec,np=16$ex +st C16x8 $PY $S/pairtest.py --stage score --split tune --seeds 8 --model ${t}_np16s8=$spec,np=16$ex +st ST $PY $S/stitch_test.py --stage score --split tune --seeds 8 --model ${t}_16x8=$spec,np=16$ex +st C64x4 $PY $S/pairtest.py --stage score --split tune --seeds 4 --model ${t}_np64s4=$spec,np=64$ex +echo "[bgsweep] done $(date -u)" diff --git a/rsm_rise/scripts/real/v7/pairtest/run_bsyn_ctrl.sh b/rsm_rise/scripts/real/v7/pairtest/run_bsyn_ctrl.sh new file mode 100644 index 0000000000000000000000000000000000000000..46307c33f5d4e867a73d525b676991f63b6af87d --- /dev/null +++ b/rsm_rise/scripts/real/v7/pairtest/run_bsyn_ctrl.sh @@ -0,0 +1,18 @@ +#!/usr/bin/env bash +#SBATCH --partition=cpu +#SBATCH --account=grp_runtime +#SBATCH --nodes=1 --ntasks=1 --cpus-per-task=16 +#SBATCH --mem=16G +#SBATCH --time=04: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 +# run 17 diagnostic: B_syn direction controls (bsyn_ctrl.py), CHALLENGER 64x1 read-out, TUNE. +set -uo pipefail +export PAIRTEST_VERSION=pairtest_v3 +cd /proj/dmfexp/zwhong/rsm_rise +PY=/proj/dmfexp/zwhong/rsm_rise/venv_rsm/bin/python; S=scripts/real/v7/pairtest +$PY $S/bsyn_ctrl.py --stage build || exit 2 +$PY $S/errmode_test.py --stage score --split tune --seeds 1 --tests B_syn,Bctl_away,Bctl_rand \ + --model "diagctl_chal_64x1=arc:runs/v7_reward2/c50_bal_adrop02/ckpt_best.pt,np=64,beta=0.99,gamma=0.995,tail=1e-3" || exit 3 +$PY $S/bsyn_ctrl.py --stage z --model diagctl_chal_64x1 diff --git a/rsm_rise/scripts/real/v7/pairtest/run_bsyn_diag.sh b/rsm_rise/scripts/real/v7/pairtest/run_bsyn_diag.sh new file mode 100644 index 0000000000000000000000000000000000000000..b7e96e88ebed688dde7100e60f56d9dea926e959 --- /dev/null +++ b/rsm_rise/scripts/real/v7/pairtest/run_bsyn_diag.sh @@ -0,0 +1,12 @@ +#!/usr/bin/env bash +#SBATCH --partition=cpu +#SBATCH --account=grp_runtime +#SBATCH --nodes=1 --ntasks=1 --cpus-per-task=32 +#SBATCH --mem=96G +#SBATCH --time=03: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 +set -uo pipefail +export PAIRTEST_VERSION=pairtest_v3 +cd /proj/dmfexp/zwhong/rsm_rise +/proj/dmfexp/zwhong/rsm_rise/venv_rsm/bin/python scripts/real/v7/pairtest/bsyn_diag.py diff --git a/rsm_rise/scripts/real/v7/pairtest/run_budget_tune.sh b/rsm_rise/scripts/real/v7/pairtest/run_budget_tune.sh new file mode 100644 index 0000000000000000000000000000000000000000..8b65c4f55b4250016f60afa989e3df705f68c7c7 --- /dev/null +++ b/rsm_rise/scripts/real/v7/pairtest/run_budget_tune.sh @@ -0,0 +1,18 @@ +#!/usr/bin/env bash +#SBATCH --job-name=rr_cpu_pairtest_bud +#SBATCH --partition=cpu +#SBATCH --account=grp_runtime +#SBATCH --nodes=1 --ntasks=1 --cpus-per-task=32 +#SBATCH --mem=96G +#SBATCH --time=08:00:00 +#SBATCH --output=/proj/dmfexp/zwhong/rsm_rise/logs/slurm/rr_cpu_pairtest_bud.%j.out +#SBATCH --error=/proj/dmfexp/zwhong/rsm_rise/logs/slurm/rr_cpu_pairtest_bud.%j.err +# H1b: particle-budget sweep for v7_old on frozen v3 TUNE pairs (how many rollouts does the planner need?) +set -euo pipefail +export PAIRTEST_VERSION=pairtest_v3 +cd /proj/dmfexp/zwhong/rsm_rise +PY=/proj/dmfexp/zwhong/rsm_rise/venv_rsm/bin/python; S=scripts/real/v7/pairtest +$PY $S/pairtest.py --stage score --split tune --seeds 1 --model v7_old_np64s1=old,np=64 +$PY $S/pairtest.py --stage score --split tune --seeds 1 --model v7_old_np128s1=old,np=128 +$PY $S/pairtest.py --stage score --split tune --seeds 1 --model v7_old_np256s1=old,np=256 +$PY $S/pairtest.py --stage score --split tune --seeds 8 --model v7_old_np16s8=old,np=16 diff --git a/rsm_rise/scripts/real/v7/pairtest/run_c_arc.sh b/rsm_rise/scripts/real/v7/pairtest/run_c_arc.sh new file mode 100644 index 0000000000000000000000000000000000000000..2b446b784fd549d602764cae7d7de1b531bd9946 --- /dev/null +++ b/rsm_rise/scripts/real/v7/pairtest/run_c_arc.sh @@ -0,0 +1,17 @@ +#!/usr/bin/env bash +#SBATCH --job-name=rr_cpu_pt3_arc +#SBATCH --partition=cpu +#SBATCH --account=grp_runtime +#SBATCH --nodes=1 --ntasks=1 --cpus-per-task=32 +#SBATCH --mem=96G +#SBATCH --time=04:00:00 +#SBATCH --output=/proj/dmfexp/zwhong/rsm_rise/logs/slurm/rr_cpu_pt3_arc.%j.out +#SBATCH --error=/proj/dmfexp/zwhong/rsm_rise/logs/slurm/rr_cpu_pt3_arc.%j.err +# C regression (frozen pairtest_v3, TUNE) for the fixed shaped chain (r2 clamped to [-1,10]) +set -euo pipefail +export PAIRTEST_VERSION=pairtest_v3 +cd /proj/dmfexp/zwhong/rsm_rise +PY=/proj/dmfexp/zwhong/rsm_rise/venv_rsm/bin/python; S=scripts/real/v7/pairtest; R2=runs/v7_reward2/c50_bal_adrop02/ckpt_best.pt +$PY $S/pairtest.py --stage score --split tune --seeds 2 --model arc_adrop02=arc:$R2 +$PY $S/pairtest.py --stage score --split tune --seeds 8 --model arc_adrop02_np16s8=arc:$R2,np=16 +$PY $S/pairtest.py --stage score --split tune --seeds 4 --model arc_adrop02_np64s4=arc:$R2,np=64 diff --git a/rsm_rise/scripts/real/v7/pairtest/run_chain_diag.sh b/rsm_rise/scripts/real/v7/pairtest/run_chain_diag.sh new file mode 100644 index 0000000000000000000000000000000000000000..3544746257336bef133d3dd6196cd824fe922465 --- /dev/null +++ b/rsm_rise/scripts/real/v7/pairtest/run_chain_diag.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +#SBATCH --job-name=rr_cpu_chaindiag +#SBATCH --partition=cpu +#SBATCH --account=grp_runtime +#SBATCH --nodes=1 --ntasks=1 --cpus-per-task=32 +#SBATCH --mem=96G +#SBATCH --time=04:00:00 +#SBATCH --output=/proj/dmfexp/zwhong/rsm_rise/logs/slurm/rr_cpu_chaindiag.%j.out +#SBATCH --error=/proj/dmfexp/zwhong/rsm_rise/logs/slurm/rr_cpu_chaindiag.%j.err +set -euo pipefail +export PAIRTEST_VERSION=pairtest_v3 +cd /proj/dmfexp/zwhong/rsm_rise +/proj/dmfexp/zwhong/rsm_rise/venv_rsm/bin/python scripts/real/v7/pairtest/chain_diag.py diff --git a/rsm_rise/scripts/real/v7/pairtest/run_ctrl_v3.sh b/rsm_rise/scripts/real/v7/pairtest/run_ctrl_v3.sh new file mode 100644 index 0000000000000000000000000000000000000000..06de17479c04d10eb0b084b29a41df0e6edc6efe --- /dev/null +++ b/rsm_rise/scripts/real/v7/pairtest/run_ctrl_v3.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +#SBATCH --job-name=rr_cpu_pairtest3c +#SBATCH --partition=cpu +#SBATCH --account=grp_runtime +#SBATCH --nodes=1 --ntasks=1 --cpus-per-task=16 +#SBATCH --mem=96G +#SBATCH --time=04:00:00 +#SBATCH --output=/proj/dmfexp/zwhong/rsm_rise/logs/slurm/rr_cpu_pairtest3c.%j.out +#SBATCH --error=/proj/dmfexp/zwhong/rsm_rise/logs/slurm/rr_cpu_pairtest3c.%j.err +# v3 + good-neighbour control; rescoring (--force) adds the GOODNB column (BAD columns reproduce: same seeds/pairs) +set -euo pipefail +export PAIRTEST_VERSION=pairtest_v3 +cd /proj/dmfexp/zwhong/rsm_rise +PY=/proj/dmfexp/zwhong/rsm_rise/venv_rsm/bin/python; S=scripts/real/v7/pairtest; R2=runs/v7_reward2 +[ -f runs/pairtest/pairs_v3_tune_ctrl.npz ] || $PY $S/make_ctrl.py tune +for m in MC=mc r2_adrop02=r2:$R2/c50_bal_adrop02/ckpt_best.pt v7_old=old ar_adrop02=ar:$R2/c50_bal_adrop02/ckpt_best.pt ar_bal_s0=ar:$R2/c50_bal_s0/ckpt_best.pt; do + n=${m%%=*}; f=runs/pairtest/q_v3_tune_$n.npz + if [ -f $f ] && $PY -c "import numpy as np,sys; sys.exit(0 if 'GOODNB' in np.load('$f') else 1)"; then F=""; else F=--force; fi + $PY $S/pairtest.py --stage score --split tune $F --model $m +done diff --git a/rsm_rise/scripts/real/v7/pairtest/run_cv.sh b/rsm_rise/scripts/real/v7/pairtest/run_cv.sh new file mode 100644 index 0000000000000000000000000000000000000000..5f5815c57a9476945cfd09d8717c2330f288446e --- /dev/null +++ b/rsm_rise/scripts/real/v7/pairtest/run_cv.sh @@ -0,0 +1,36 @@ +#!/usr/bin/env bash +#SBATCH --partition=cpu +#SBATCH --account=grp_runtime +#SBATCH --nodes=1 --ntasks=1 --cpus-per-task=16 +#SBATCH --mem=16G +#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 +# RSM_PAIRTEST run 17: TRAIN-CV guard (K=4 route-stratified TRAIN folds, pairtest.split_eps). Frozen pair rules applied +# with held = fold K, train = other folds. Models are trained on all TRAIN -> scores are IN-SAMPLE (reported as such). +# usage: PAIRS=1 sbatch -J rr_cpu_cv_pairs run_cv.sh (all 4 folds, model-free) +# SPLIT=cvK MODEL=chal|default|old NP= SEEDS= sbatch -J rr_cpu_cv_<..> run_cv.sh +# SPLIT=cvK MODEL=custom NAME= SPEC= NP= SEEDS= ... +set -uo pipefail +export PAIRTEST_VERSION=pairtest_v3 +cd /proj/dmfexp/zwhong/rsm_rise +PY=/proj/dmfexp/zwhong/rsm_rise/venv_rsm/bin/python; S=scripts/real/v7/pairtest +if [ "${PAIRS:-0}" = 1 ]; then + for k in 0 1 2 3; do + $PY $S/pairtest.py --stage pairs --split cv$k && $PY $S/errmode_test.py --stage pairs --split cv$k && \ + $PY $S/stitch_test.py --stage pairs --split cv$k || exit 2 + done; exit 0 +fi +case $MODEL in # the TEST-read specs (run_testread.sh), unchanged + default) spec="arc:runs/v7_reward2_sf/d1/ckpt_best.pt,np=$NP,beta=0.99,gamma=0.998,tail=0.9"; t=tr_default_${NP}x${SEEDS} ;; + chal) spec="arc:runs/v7_reward2/c50_bal_adrop02/ckpt_best.pt,np=$NP,beta=0.99,gamma=0.995,tail=1e-3"; t=tr_chal_${NP}x${SEEDS} ;; + old) spec="old,np=$NP,beta=0.99,gamma=0.998,tail=1e-3"; t=tr_old_${NP}x${SEEDS} ;; + custom) spec="$SPEC"; t=$NAME ;; +esac +D=runs/pairtest/cv/${SPLIT}_$t; mkdir -p $D +st(){ local k=$1; shift; [ -f $D/done_$k ] && { echo "[cv] skip $k (done)"; return; }; "$@" && touch $D/done_$k; } +st C $PY $S/pairtest.py --stage score --split $SPLIT --seeds $SEEDS --model $t=$spec +st AB $PY $S/errmode_test.py --stage score --split $SPLIT --seeds $SEEDS --model $t=$spec +st ST $PY $S/stitch_test.py --stage score --split $SPLIT --seeds $SEEDS --model $t=$spec +echo "[cv] done $SPLIT $t $(date -u)" diff --git a/rsm_rise/scripts/real/v7/pairtest/run_errmode.sh b/rsm_rise/scripts/real/v7/pairtest/run_errmode.sh new file mode 100644 index 0000000000000000000000000000000000000000..fa9b9eee62ada1c06d119f35dd4bb451e1353a0e --- /dev/null +++ b/rsm_rise/scripts/real/v7/pairtest/run_errmode.sh @@ -0,0 +1,17 @@ +#!/usr/bin/env bash +#SBATCH --partition=cpu +#SBATCH --account=grp_runtime +#SBATCH --nodes=1 --ntasks=1 --cpus-per-task=32 +#SBATCH --mem=96G +#SBATCH --time=08:00:00 +#SBATCH --signal=B:USR1@600 +#SBATCH --output=/proj/dmfexp/zwhong/rsm_rise/logs/slurm/%x.%j.out +#SBATCH --error=/proj/dmfexp/zwhong/rsm_rise/logs/slurm/%x.%j.err +# usage: sbatch -J rr_cpu_em_ run_errmode.sh pairs | sbatch -J ... run_errmode.sh score NAME=SPEC [TESTS] +# scoring resumes from runs/pairtest/errmode/q_*.npz (cpu jobs may be evicted and restarted) +set -euo pipefail +export PAIRTEST_VERSION=pairtest_v3 +cd /proj/dmfexp/zwhong/rsm_rise +PY=/proj/dmfexp/zwhong/rsm_rise/venv_rsm/bin/python; S=scripts/real/v7/pairtest +if [ "$1" = pairs ]; then $PY $S/errmode_test.py --stage pairs --split tune; exit; fi +$PY $S/errmode_test.py --stage score --split tune --seeds ${SEEDS:-8} --model "$2" ${3:+--tests $3} diff --git a/rsm_rise/scripts/real/v7/pairtest/run_h10.sh b/rsm_rise/scripts/real/v7/pairtest/run_h10.sh new file mode 100644 index 0000000000000000000000000000000000000000..32eda1fed7e187ce5f8d9d26e8a3775ea33766c8 --- /dev/null +++ b/rsm_rise/scripts/real/v7/pairtest/run_h10.sh @@ -0,0 +1,22 @@ +#!/usr/bin/env bash +#SBATCH --partition=cpu +#SBATCH --account=grp_runtime +#SBATCH --nodes=1 --ntasks=1 --cpus-per-task=16 +#SBATCH --mem=16G +#SBATCH --time=04: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 +# RSM_PAIRTEST run 17 H10: behaviour-support term on cached RSM Q (TUNE only). usage: sbatch -J rr_cpu_h10 run_h10.sh BASE... +set -uo pipefail +export PAIRTEST_VERSION=pairtest_v3 +cd /proj/dmfexp/zwhong/rsm_rise +PY=/proj/dmfexp/zwhong/rsm_rise/venv_rsm/bin/python; S=scripts/real/v7/pairtest +B=(); for b in "$@"; do B+=(--base $b); done +$PY $S/h10_support.py --split tune "${B[@]}" || exit 2 +M=(); while read -r n; do [ -n "$n" ] && M+=(--model "$n=cached"); done < runs/pairtest/h10_names_tune.txt +$PY $S/pairtest.py --stage score --split tune "${M[@]}" || exit 3 +$PY $S/errmode_test.py --stage score --split tune "${M[@]}" || exit 4 +$PY $S/stitch_test.py --stage score --split tune "${M[@]}" || exit 5 +$PY $S/h10_table.py +echo "[h10] done $(date -u)" diff --git a/rsm_rise/scripts/real/v7/pairtest/run_h13.sh b/rsm_rise/scripts/real/v7/pairtest/run_h13.sh new file mode 100644 index 0000000000000000000000000000000000000000..ff4ffe9ad798daeb7238e1af95adf1ffedb46b32 --- /dev/null +++ b/rsm_rise/scripts/real/v7/pairtest/run_h13.sh @@ -0,0 +1,22 @@ +#!/usr/bin/env bash +#SBATCH --partition=cpu +#SBATCH --account=grp_runtime +#SBATCH --nodes=1 --ntasks=1 --cpus-per-task=16 +#SBATCH --mem=16G +#SBATCH --time=04: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 +# RSM_PAIRTEST run 17 H13: hybrid RSM+IQL on cached Q (TUNE only). usage: sbatch -J rr_cpu_h10 run_h10.sh BASE... +set -uo pipefail +export PAIRTEST_VERSION=pairtest_v3 +cd /proj/dmfexp/zwhong/rsm_rise +PY=/proj/dmfexp/zwhong/rsm_rise/venv_rsm/bin/python; S=scripts/real/v7/pairtest +B=(); for b in "$@"; do B+=(--base $b); done +$PY $S/h13_hybrid.py "${B[@]}" || exit 2 +M=(); while read -r n; do [ -n "$n" ] && M+=(--model "$n=cached"); done < runs/pairtest/h13_names_tune.txt +$PY $S/pairtest.py --stage score --split tune "${M[@]}" || exit 3 +$PY $S/errmode_test.py --stage score --split tune "${M[@]}" || exit 4 +$PY $S/stitch_test.py --stage score --split tune "${M[@]}" || exit 5 +$PY $S/h13_table.py +echo "[h13] done $(date -u)" diff --git a/rsm_rise/scripts/real/v7/pairtest/run_h1_np64.sh b/rsm_rise/scripts/real/v7/pairtest/run_h1_np64.sh new file mode 100644 index 0000000000000000000000000000000000000000..3854a8c4b479ead765b3219d70314c2443a767b3 --- /dev/null +++ b/rsm_rise/scripts/real/v7/pairtest/run_h1_np64.sh @@ -0,0 +1,17 @@ +#!/usr/bin/env bash +#SBATCH --job-name=rr_cpu_pairtest_h1 +#SBATCH --partition=cpu +#SBATCH --account=grp_runtime +#SBATCH --nodes=1 --ntasks=1 --cpus-per-task=32 +#SBATCH --mem=96G +#SBATCH --time=06:00:00 +#SBATCH --output=/proj/dmfexp/zwhong/rsm_rise/logs/slurm/rr_cpu_pairtest_h1.%j.out +#SBATCH --error=/proj/dmfexp/zwhong/rsm_rise/logs/slurm/rr_cpu_pairtest_h1.%j.err +# H1: chain_ar near chance because of particle variance (goal value +10). Same frozen v3 pairs, 64 particles x 4 seeds. +set -euo pipefail +export PAIRTEST_VERSION=pairtest_v3 +cd /proj/dmfexp/zwhong/rsm_rise +PY=/proj/dmfexp/zwhong/rsm_rise/venv_rsm/bin/python; S=scripts/real/v7/pairtest; R2=runs/v7_reward2 +for m in ar_adrop02_np64s4=ar:$R2/c50_bal_adrop02/ckpt_best.pt,np=64 v7_old_np64s4=old,np=64; do + $PY $S/pairtest.py --stage score --split tune --seeds 4 --model $m +done diff --git a/rsm_rise/scripts/real/v7/pairtest/run_hopsweep.sh b/rsm_rise/scripts/real/v7/pairtest/run_hopsweep.sh new file mode 100644 index 0000000000000000000000000000000000000000..f50e35af00bcfb00bbfe113537e292a2f8188123 --- /dev/null +++ b/rsm_rise/scripts/real/v7/pairtest/run_hopsweep.sh @@ -0,0 +1,28 @@ +#!/usr/bin/env bash +#SBATCH --partition=cpu +#SBATCH --account=grp_runtime +#SBATCH --nodes=1 --ntasks=1 --cpus-per-task=32 +#SBATCH --mem=96G +#SBATCH --time=12: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 +# RSM_PAIRTEST run 9: HOP-COUNT SWEEP (owner 20:00Z). Frozen A/B (errmode 16x8) + C (pairtest_v3 16x2/16x8/64x4), TUNE. +# usage: HEADK=sf|arc|old BETA=0.99 TAIL=1e-3 TAG=x sbatch -J rr_cpu_hs_ run_hopsweep.sh +# Hop stats (per particle hops, z RMS at last hop) dumped by rsm_scorer_ar when HOPSTAT_DIR is set (arc/sf only). +set -uo pipefail +export PAIRTEST_VERSION=pairtest_v3 +cd /proj/dmfexp/zwhong/rsm_rise +PY=/proj/dmfexp/zwhong/rsm_rise/venv_rsm/bin/python; S=scripts/real/v7/pairtest +case $HEADK in + sf) spec="arc:runs/v7_reward2_sf/d1/ckpt_best.pt" ;; + arc) spec="arc:runs/v7_reward2/c50_bal_adrop02/ckpt_best.pt" ;; + old) spec="old" ;; +esac +ex=",beta=$BETA,tail=$TAIL" +t=hs_${TAG} +export HOPSTAT_DIR=runs/pairtest/hopsweep/$TAG +export HOPSTAT_TAG=AB; $PY $S/errmode_test.py --stage score --split tune --seeds 8 --model ${t}_16x8=$spec,np=16$ex +export HOPSTAT_TAG=C16x2; $PY $S/pairtest.py --stage score --split tune --seeds 2 --model ${t}=$spec,np=16$ex +export HOPSTAT_TAG=C16x8; $PY $S/pairtest.py --stage score --split tune --seeds 8 --model ${t}_np16s8=$spec,np=16$ex +export HOPSTAT_TAG=C64x4; $PY $S/pairtest.py --stage score --split tune --seeds 4 --model ${t}_np64s4=$spec,np=64$ex +echo "[hopsweep] done $(date -u)" diff --git a/rsm_rise/scripts/real/v7/pairtest/run_iql_all.sh b/rsm_rise/scripts/real/v7/pairtest/run_iql_all.sh new file mode 100644 index 0000000000000000000000000000000000000000..2c195dc63b273e680d00ac58bbc0b1bc46925d38 --- /dev/null +++ b/rsm_rise/scripts/real/v7/pairtest/run_iql_all.sh @@ -0,0 +1,35 @@ +#!/usr/bin/env bash +#SBATCH --partition=cpu +#SBATCH --account=grp_runtime +#SBATCH --nodes=1 --ntasks=1 --cpus-per-task=16 +#SBATCH --mem=32G +#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 +# RSM_PAIRTEST run 15 (owner ~01:30Z "compare the iql too"): IQL critics on the frozen C / A / B / STITCH tests. +# usage: SPLIT=tune|test [ENS=name] sbatch -J rr_cpu_iqlall_ run_iql_all.sh NAME=CKPT ... +# PICK=1 SPLIT=test sbatch ... run_iql_all.sh -> reads status/real/iql_pick.json (TUNE rule), scores pick + OLD +set -uo pipefail +export PAIRTEST_VERSION=pairtest_v3 +cd /proj/dmfexp/zwhong/rsm_rise +R=/proj/dmfexp/zwhong/jm/rsm_rise; S=/proj/dmfexp/zwhong/rsm_rise/scripts/real/v7/pairtest +PY=/proj/dmfexp/zwhong/rsm_rise/venv_rsm/bin/python +AT=""; [ "$SPLIT" = test ] && AT="--allow-test" +ARGS=("$@"); ENSA=() +if [ "${PICK:-0}" = 1 ]; then + $PY $S/iql_select.py || exit 3 + mapfile -t ARGS < <($PY -c "import json; p=json.load(open('status/real/iql_pick.json')); [print(x) for x in p['models']]") + E=$($PY -c "import json; print(json.load(open('status/real/iql_pick.json')).get('ens',''))"); [ -n "$E" ] && ENS=$E +fi +[ -n "${ENS:-}" ] && ENSA=(--ens $ENS) +M=(); for kv in "${ARGS[@]}"; do M+=(--model "$kv"); done +( cd $R && source scripts/env.sh && $R/env/bin/python $S/iql_all.py --split $SPLIT $AT "${M[@]}" "${ENSA[@]}" ) || exit 2 +N=(); for kv in "${ARGS[@]}"; do N+=("${kv%%=*}"); done; [ -n "${ENS:-}" ] && N+=("$ENS") +[ "${PICK:-0}" = 1 ] && [ -n "${ENS:-}" ] && N=("$ENS") # TEST: score the pick only, not its member seeds +for n in "${N[@]}"; do + $PY $S/pairtest.py --stage score --split $SPLIT $AT --model $n=cached || exit 4 + $PY $S/errmode_test.py --stage score --split $SPLIT $AT --model $n=cached || exit 5 + $PY $S/stitch_test.py --stage score --split $SPLIT $AT --model $n=cached || exit 6 +done +echo "[iqlall] done $SPLIT ${N[*]} $(date -u)" diff --git a/rsm_rise/scripts/real/v7/pairtest/run_iql_pairs.sh b/rsm_rise/scripts/real/v7/pairtest/run_iql_pairs.sh new file mode 100644 index 0000000000000000000000000000000000000000..6d725aeab4f30af01b597f93df8ed0b396f474b5 --- /dev/null +++ b/rsm_rise/scripts/real/v7/pairtest/run_iql_pairs.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +#SBATCH --job-name=rr_cpu_pairtest_iql +#SBATCH --partition=cpu +#SBATCH --account=grp_runtime +#SBATCH --nodes=1 --ntasks=1 --cpus-per-task=16 +#SBATCH --mem=96G +#SBATCH --time=03:00:00 +#SBATCH --output=/proj/dmfexp/zwhong/rsm_rise/logs/slurm/rr_cpu_pairtest_iql.%j.out +#SBATCH --error=/proj/dmfexp/zwhong/rsm_rise/logs/slurm/rr_cpu_pairtest_iql.%j.err +# IQL baseline on the frozen pairtest_v2 TUNE pairs. usage: sbatch run_iql_pairs.sh NAME=CKPT ... +set -o pipefail +TAG=${TAG:-_v3} +R=/proj/dmfexp/zwhong/jm/rsm_rise; S=/proj/dmfexp/zwhong/rsm_rise/scripts/real/v7/pairtest +cd $R; source scripts/env.sh; PY=$R/env/bin/python +M=() +for kv in "$@"; do n=${kv%%=*}; c=${kv#*=} + [ -f /proj/dmfexp/zwhong/rsm_rise/runs/pairtest/q${TAG}_tune_$n.npz ] || $PY $S/iql_pairs.py --name $n --ckpt $c --split tune --tag $TAG || exit 2 + M+=(--model "$n=cached"); done +cd /proj/dmfexp/zwhong/rsm_rise +PAIRTEST_VERSION=pairtest${TAG} /proj/dmfexp/zwhong/rsm_rise/venv_rsm/bin/python $S/pairtest.py --stage score --split tune "${M[@]}" diff --git a/rsm_rise/scripts/real/v7/pairtest/run_pairtest.sh b/rsm_rise/scripts/real/v7/pairtest/run_pairtest.sh new file mode 100644 index 0000000000000000000000000000000000000000..09323328c4a758d95126860d291f96ae2651ca03 --- /dev/null +++ b/rsm_rise/scripts/real/v7/pairtest/run_pairtest.sh @@ -0,0 +1,24 @@ +#!/usr/bin/env bash +#SBATCH --job-name=rr_cpu_pairtest +#SBATCH --partition=cpu +#SBATCH --account=grp_runtime +#SBATCH --nodes=1 --ntasks=1 --cpus-per-task=16 +#SBATCH --mem=96G +#SBATCH --time=04:00:00 +#SBATCH --output=/proj/dmfexp/zwhong/rsm_rise/logs/slurm/rr_cpu_pairtest.%j.out +#SBATCH --error=/proj/dmfexp/zwhong/rsm_rise/logs/slurm/rr_cpu_pairtest.%j.err +# usage: sbatch run_pairtest.sh [extra --model NAME=SPEC ...] (pairs stage runs only if pairs_tune.npz is missing) +set -euo pipefail +export PAIRTEST_VERSION=${PAIRTEST_VERSION:-pairtest_v1} +cd /proj/dmfexp/zwhong/rsm_rise +PY=/proj/dmfexp/zwhong/rsm_rise/venv_rsm/bin/python +S=scripts/real/v7/pairtest/pairtest.py +R2=/proj/dmfexp/zwhong/rsm_rise/runs/v7_reward2 +[ -f runs/pairtest/pairs_tune.npz ] || $PY $S --stage pairs --split tune +if [ $# -gt 0 ]; then $PY $S --stage score --split tune "$@"; exit 0; fi +$PY $S --stage score --split tune \ + --model MC=mc \ + --model r2_adrop02=r2:$R2/c50_bal_adrop02/ckpt_best.pt \ + --model v7_old=old \ + --model ar_adrop02=ar:$R2/c50_bal_adrop02/ckpt_best.pt \ + --model ar_bal_s0=ar:$R2/c50_bal_s0/ckpt_best.pt diff --git a/rsm_rise/scripts/real/v7/pairtest/run_pairtest_v2.sh b/rsm_rise/scripts/real/v7/pairtest/run_pairtest_v2.sh new file mode 100644 index 0000000000000000000000000000000000000000..697ed26fe4fd4a6e55a52314aac053784d77f299 --- /dev/null +++ b/rsm_rise/scripts/real/v7/pairtest/run_pairtest_v2.sh @@ -0,0 +1,24 @@ +#!/usr/bin/env bash +#SBATCH --job-name=rr_cpu_pairtest2 +#SBATCH --partition=cpu +#SBATCH --account=grp_runtime +#SBATCH --nodes=1 --ntasks=1 --cpus-per-task=16 +#SBATCH --mem=96G +#SBATCH --time=04:00:00 +#SBATCH --output=/proj/dmfexp/zwhong/rsm_rise/logs/slurm/rr_cpu_pairtest2.%j.out +#SBATCH --error=/proj/dmfexp/zwhong/rsm_rise/logs/slurm/rr_cpu_pairtest2.%j.err +# usage: sbatch run_pairtest.sh [extra --model NAME=SPEC ...] (pairs stage runs only if pairs_tune.npz is missing) +set -euo pipefail +export PAIRTEST_VERSION=pairtest_v2 +cd /proj/dmfexp/zwhong/rsm_rise +PY=/proj/dmfexp/zwhong/rsm_rise/venv_rsm/bin/python +S=scripts/real/v7/pairtest/pairtest.py +R2=/proj/dmfexp/zwhong/rsm_rise/runs/v7_reward2 +[ -f runs/pairtest/pairs_v2_tune.npz ] || $PY $S --stage pairs --split tune +if [ $# -gt 0 ]; then $PY $S --stage score --split tune "$@"; exit 0; fi +$PY $S --stage score --split tune \ + --model MC=mc \ + --model r2_adrop02=r2:$R2/c50_bal_adrop02/ckpt_best.pt \ + --model v7_old=old \ + --model ar_adrop02=ar:$R2/c50_bal_adrop02/ckpt_best.pt \ + --model ar_bal_s0=ar:$R2/c50_bal_s0/ckpt_best.pt diff --git a/rsm_rise/scripts/real/v7/pairtest/run_pairtest_v3.sh b/rsm_rise/scripts/real/v7/pairtest/run_pairtest_v3.sh new file mode 100644 index 0000000000000000000000000000000000000000..fdd868678afde371f8bc2fcdcc099bd13d6ed271 --- /dev/null +++ b/rsm_rise/scripts/real/v7/pairtest/run_pairtest_v3.sh @@ -0,0 +1,24 @@ +#!/usr/bin/env bash +#SBATCH --job-name=rr_cpu_pairtest3 +#SBATCH --partition=cpu +#SBATCH --account=grp_runtime +#SBATCH --nodes=1 --ntasks=1 --cpus-per-task=16 +#SBATCH --mem=96G +#SBATCH --time=04:00:00 +#SBATCH --output=/proj/dmfexp/zwhong/rsm_rise/logs/slurm/rr_cpu_pairtest3.%j.out +#SBATCH --error=/proj/dmfexp/zwhong/rsm_rise/logs/slurm/rr_cpu_pairtest3.%j.err +# usage: sbatch run_pairtest.sh [extra --model NAME=SPEC ...] (pairs stage runs only if pairs_tune.npz is missing) +set -euo pipefail +export PAIRTEST_VERSION=pairtest_v3 +cd /proj/dmfexp/zwhong/rsm_rise +PY=/proj/dmfexp/zwhong/rsm_rise/venv_rsm/bin/python +S=scripts/real/v7/pairtest/pairtest.py +R2=/proj/dmfexp/zwhong/rsm_rise/runs/v7_reward2 +[ -f runs/pairtest/pairs_v3_tune.npz ] || $PY $S --stage pairs --split tune +if [ $# -gt 0 ]; then $PY $S --stage score --split tune "$@"; exit 0; fi +$PY $S --stage score --split tune \ + --model MC=mc \ + --model r2_adrop02=r2:$R2/c50_bal_adrop02/ckpt_best.pt \ + --model v7_old=old \ + --model ar_adrop02=ar:$R2/c50_bal_adrop02/ckpt_best.pt \ + --model ar_bal_s0=ar:$R2/c50_bal_s0/ckpt_best.pt diff --git a/rsm_rise/scripts/real/v7/pairtest/run_stitch.sh b/rsm_rise/scripts/real/v7/pairtest/run_stitch.sh new file mode 100644 index 0000000000000000000000000000000000000000..939ba5e1ff917ab63ff6829dbcf2ef59b203b247 --- /dev/null +++ b/rsm_rise/scripts/real/v7/pairtest/run_stitch.sh @@ -0,0 +1,30 @@ +#!/usr/bin/env bash +#SBATCH --partition=cpu +#SBATCH --account=grp_runtime +#SBATCH --nodes=1 --ntasks=1 --cpus-per-task=32 +#SBATCH --mem=96G +#SBATCH --time=12: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 +# RSM_PAIRTEST run 12 (owner 21:00Z KEEP STITCHING): frozen STITCH test (stitch_test.py) at 16x8 + optionally A/B +# (errmode 16x8) and C (pairtest_v3 16x2 / 64x4) for hop settings not yet in the hop sweep. TUNE only. +# usage: HEADK=sf|arc BETA= GAMMA= TAIL= TAG= ABC=0|1 sbatch -J rr_cpu_st_ run_stitch.sh (PAIRS=1: build pairs only) +set -uo pipefail +export PAIRTEST_VERSION=pairtest_v3 +cd /proj/dmfexp/zwhong/rsm_rise +PY=/proj/dmfexp/zwhong/rsm_rise/venv_rsm/bin/python; S=scripts/real/v7/pairtest +if [ "${PAIRS:-0}" = 1 ]; then $PY $S/stitch_test.py --stage pairs --split tune; exit $?; fi +case $HEADK in + sf) spec="arc:runs/v7_reward2_sf/d1/ckpt_best.pt" ;; + arc) spec="arc:runs/v7_reward2/c50_bal_adrop02/ckpt_best.pt" ;; + old) spec="old" ;; +esac +ex=",beta=$BETA,gamma=$GAMMA,tail=$TAIL"; t=hs_${TAG} +export HOPSTAT_DIR=runs/pairtest/hopsweep/$TAG +export HOPSTAT_TAG=ST; $PY $S/stitch_test.py --stage score --split tune --seeds 8 --model ${t}_16x8=$spec,np=16$ex +if [ "${ABC:-0}" = 1 ]; then + export HOPSTAT_TAG=AB; $PY $S/errmode_test.py --stage score --split tune --seeds 8 --model ${t}_16x8=$spec,np=16$ex + export HOPSTAT_TAG=C16x2; $PY $S/pairtest.py --stage score --split tune --seeds 2 --model ${t}=$spec,np=16$ex + export HOPSTAT_TAG=C64x4; $PY $S/pairtest.py --stage score --split tune --seeds 4 --model ${t}_np64s4=$spec,np=64$ex +fi +echo "[stitch] done $(date -u)" diff --git a/rsm_rise/scripts/real/v7/pairtest/run_succck.sh b/rsm_rise/scripts/real/v7/pairtest/run_succck.sh new file mode 100644 index 0000000000000000000000000000000000000000..790a97cc24b0b8417fe7b678cd4616b2afcd36f6 --- /dev/null +++ b/rsm_rise/scripts/real/v7/pairtest/run_succck.sh @@ -0,0 +1,22 @@ +#!/usr/bin/env bash +#SBATCH --partition=cpu +#SBATCH --account=grp_runtime +#SBATCH --nodes=1 --ntasks=1 --cpus-per-task=16 +#SBATCH --mem=16G +#SBATCH --time=06: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 +# Owner 2026-11-21 "how long was the successor trained for? are we sure it converged?": CHALLENGER read-out (c50 head, +# clamp, b.99 g.995 uncapped, 64x1) with the SAME successor run at other checkpoints. TUNE only. usage: STEP= sbatch run_succck.sh +set -uo pipefail +export PAIRTEST_VERSION=pairtest_v3 +cd /proj/dmfexp/zwhong/rsm_rise +PY=/proj/dmfexp/zwhong/rsm_rise/venv_rsm/bin/python; S=scripts/real/v7/pairtest +spec="arc:runs/v7_reward2/c50_bal_adrop02/ckpt_best.pt,np=64,beta=0.99,gamma=0.995,tail=1e-3,succ=/proj/dmfexp/zwhong/jm/rsm_rise/runs/real_cooking_v7/rsm/progress_augc_h50_ps_s0/ckpt_s${STEP}.pt" +t=sc_chal_s${STEP}_64x1; D=runs/pairtest/succck/tune_$t; mkdir -p $D; export HOPSTAT_DIR=$D +st(){ local k=$1; shift; [ -f $D/done_$k ] && return; export HOPSTAT_TAG=$k; "$@" && touch $D/done_$k; } +st C $PY $S/pairtest.py --stage score --split tune --seeds 1 --model $t=$spec +st AB $PY $S/errmode_test.py --stage score --split tune --seeds 1 --model $t=$spec +st ST $PY $S/stitch_test.py --stage score --split tune --seeds 1 --model $t=$spec +echo "[succck] done $t $(date -u)" diff --git a/rsm_rise/scripts/real/v7/pairtest/run_test4_np64.sh b/rsm_rise/scripts/real/v7/pairtest/run_test4_np64.sh new file mode 100644 index 0000000000000000000000000000000000000000..96a3a8af6910b61714e0d91c24a72f169f81d1e9 --- /dev/null +++ b/rsm_rise/scripts/real/v7/pairtest/run_test4_np64.sh @@ -0,0 +1,17 @@ +#!/usr/bin/env bash +#SBATCH --job-name=rr_cpu_pairtest4T +#SBATCH --partition=cpu +#SBATCH --account=grp_runtime +#SBATCH --nodes=1 --ntasks=1 --cpus-per-task=32 +#SBATCH --mem=96G +#SBATCH --time=06:00:00 +#SBATCH --output=/proj/dmfexp/zwhong/rsm_rise/logs/slurm/rr_cpu_pairtest4T.%j.out +#SBATCH --error=/proj/dmfexp/zwhong/rsm_rise/logs/slurm/rr_cpu_pairtest4T.%j.err +# TEST confirmation of finalist v7_old_np64s4 (H1, submitted 1334483 BEFORE the first TEST read; selected on TUNE 0.911 at ~09:50Z). Second TEST read overall, first for this finalist. +set -euo pipefail +export PAIRTEST_VERSION=pairtest_v3 +cd /proj/dmfexp/zwhong/rsm_rise +PY=/proj/dmfexp/zwhong/rsm_rise/venv_rsm/bin/python; S=scripts/real/v7/pairtest +[ -f runs/pairtest/pairs_v3_test.npz ] || $PY $S/pairtest.py --stage pairs --split test --allow-test +[ -f runs/pairtest/pairs_v3_test_ctrl.npz ] || $PY $S/make_ctrl.py test +$PY $S/pairtest.py --stage score --split test --allow-test --seeds 4 --model v7_old_np64s4=old,np=64 diff --git a/rsm_rise/scripts/real/v7/pairtest/run_test_v3.sh b/rsm_rise/scripts/real/v7/pairtest/run_test_v3.sh new file mode 100644 index 0000000000000000000000000000000000000000..a3132e5f367cde14314447bf3382ca0fdb1ea32b --- /dev/null +++ b/rsm_rise/scripts/real/v7/pairtest/run_test_v3.sh @@ -0,0 +1,17 @@ +#!/usr/bin/env bash +#SBATCH --job-name=rr_cpu_pairtest3T +#SBATCH --partition=cpu +#SBATCH --account=grp_runtime +#SBATCH --nodes=1 --ntasks=1 --cpus-per-task=16 +#SBATCH --mem=96G +#SBATCH --time=03:00:00 +#SBATCH --output=/proj/dmfexp/zwhong/rsm_rise/logs/slurm/rr_cpu_pairtest3T.%j.out +#SBATCH --error=/proj/dmfexp/zwhong/rsm_rise/logs/slurm/rr_cpu_pairtest3T.%j.err +# ONE-TIME TEST confirmation of the frozen finalist v7_old (selected on TUNE 2026-11-20 ~08:40Z) on pairtest_v3 + control. +set -euo pipefail +export PAIRTEST_VERSION=pairtest_v3 +cd /proj/dmfexp/zwhong/rsm_rise +PY=/proj/dmfexp/zwhong/rsm_rise/venv_rsm/bin/python; S=scripts/real/v7/pairtest +[ -f runs/pairtest/pairs_v3_test.npz ] || $PY $S/pairtest.py --stage pairs --split test --allow-test +[ -f runs/pairtest/pairs_v3_test_ctrl.npz ] || $PY $S/make_ctrl.py test +$PY $S/pairtest.py --stage score --split test --allow-test --model MC=mc --model v7_old=old diff --git a/rsm_rise/scripts/real/v7/pairtest/run_testread.sh b/rsm_rise/scripts/real/v7/pairtest/run_testread.sh new file mode 100644 index 0000000000000000000000000000000000000000..4d47e78f17278ce22f26b3f8926aea75729495ec --- /dev/null +++ b/rsm_rise/scripts/real/v7/pairtest/run_testread.sh @@ -0,0 +1,35 @@ +#!/usr/bin/env bash +#SBATCH --partition=cpu +#SBATCH --account=grp_runtime +#SBATCH --nodes=1 --ntasks=1 --cpus-per-task=32 +#SBATCH --mem=96G +#SBATCH --time=23: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 +# RSM_PAIRTEST run 14: owner 2026-11-21 ~00:40Z "yes show on TEST" -- the ONE authorised TEST read of the frozen tests +# (C pairtest_v3, A/B errmode, STITCH) for the 3 read-outs chosen on TUNE. TUNE re-scored at the same budgets for the +# side-by-side table. No edits to pair rules / models / settings. +# usage: MODEL=default|chal|old SPLIT=tune|test NP= SEEDS= sbatch -J rr_cpu_tr_<...> run_testread.sh +# PAIRS=1 SPLIT=test: build the A/B + STITCH TEST pairs (C TEST pairs exist since run 1) +set -uo pipefail +export PAIRTEST_VERSION=pairtest_v3 +cd /proj/dmfexp/zwhong/rsm_rise +PY=/proj/dmfexp/zwhong/rsm_rise/venv_rsm/bin/python; S=scripts/real/v7/pairtest +AT=""; [ "$SPLIT" = test ] && AT="--allow-test" +if [ "${PAIRS:-0}" = 1 ]; then + $PY $S/errmode_test.py --stage pairs --split $SPLIT $AT && $PY $S/stitch_test.py --stage pairs --split $SPLIT $AT; exit $? +fi +case $MODEL in # frozen on TUNE before the TEST read (owner list 2026-11-21) + default) spec="arc:runs/v7_reward2_sf/d1/ckpt_best.pt,np=$NP,beta=0.99,gamma=0.998,tail=0.9" ;; # cap 1 (PR 20 cooking_v7_rsm) + chal) spec="arc:runs/v7_reward2/c50_bal_adrop02/ckpt_best.pt,np=$NP,beta=0.99,gamma=0.995,tail=1e-3" ;; + old) spec="old,np=$NP,beta=0.99,gamma=0.998,tail=1e-3" ;; +esac +t=tr_${MODEL}_${NP}x${SEEDS} +D=runs/pairtest/testread/${SPLIT}_$t; mkdir -p $D; export HOPSTAT_DIR=$D +st(){ local k=$1; shift; [ -f $D/done_$k ] && { echo "[testread] skip $k (done)"; return; } + export HOPSTAT_TAG=$k; "$@" && touch $D/done_$k; } +st C $PY $S/pairtest.py --stage score --split $SPLIT $AT --seeds $SEEDS --model $t=$spec +st AB $PY $S/errmode_test.py --stage score --split $SPLIT $AT --seeds $SEEDS --model $t=$spec +st ST $PY $S/stitch_test.py --stage score --split $SPLIT $AT --seeds $SEEDS --model $t=$spec +echo "[testread] done $SPLIT $t $(date -u)" diff --git a/rsm_rise/scripts/real/v7/pairtest/stitch_table.py b/rsm_rise/scripts/real/v7/pairtest/stitch_table.py new file mode 100644 index 0000000000000000000000000000000000000000..373689511641fbb2231ac2d09c37c4ba29e6aef6 --- /dev/null +++ b/rsm_rise/scripts/real/v7/pairtest/stitch_table.py @@ -0,0 +1,44 @@ +"""RSM_PAIRTEST run 12: STITCH + A/B/C table across hop settings. Light (json + log parsing). +usage: venv_rsm/bin/python scripts/real/v7/pairtest/stitch_table.py > status/real/rsm_stitch_tune.md""" +import glob, json, re, numpy as np +R = "/proj/dmfexp/zwhong/rsm_rise" +CFG = [("b998", .998, .998, None, "single jump (no stitching)"), ("b99_cap1", .99, .998, 1, ""), ("b99_cap2", .99, .998, 2, ""), + ("b99_cap3", .99, .998, 3, ""), ("b99_g995", .99, .995, None, "gamma 0.995"), ("b995_cap2", .995, .998, 2, ""), + ("b99", .99, .998, None, "uncapped")] +FAMS = ["S_02f", "S_02s", "S_01f", "S_26", "S_1end"] +ST = json.load(open(f"{R}/status/real/rsm_stitch_tune.json")) if glob.glob(f"{R}/status/real/rsm_stitch_tune.json") else {"models": {}} +EM = json.load(open(f"{R}/status/real/rsm_errmode_tune.json"))["models"] +f = lambda M: "-" if not M or "acc" not in M else f"{M['acc']:.3f} [{M['ci'][0]:.2f},{M['ci'][1]:.2f}]" + ("*" if M.get("PASS") else "") +def ehops(b, g, cap): + p = max((g - b) / (g * (1 - b)), 0.0) + L = cap if cap is not None else (0 if p <= 0 else int(np.ceil(np.log(1e-3) / np.log(p)))) + pk = p ** np.arange(L + 1); pk = np.append(pk[:-1] * (1 - p), pk[-1]) if L > 0 else np.array([1.0]) + return float((np.arange(L + 1) * pk).sum()), float(pk[3:].sum()) +if "pairs" in ST: + P = ST["pairs"]; print("## STITCH pairs (model-free)\n") + print(f"V* (route-graph, TRAIN, normalised): {P['V_star']}\n") + print("| family | n pairs/eps | coincident | dist p10/p50/p90 | oracle EP-MC acc | oracle ST-MC acc | stitch_required | EP gap | ST gap |") + print("|---|---|---|---|---|---|---|---|---|") + for k in FAMS: + q = P.get(k, {}) + if not q or not q.get("n"): + print(f"| {k} | 0 | | | | | | | |"); continue + dp = q["dist_pct"] + print(f"| {k} | {q['n']}/{q['n_eps']} | {q['coincident']} | {dp['10']:.2f}/{dp['50']:.2f}/{dp['90']:.2f} | {q['oracle_EP_acc']:.2f} | " + f"{q['oracle_ST_acc']:.2f} | {q['stitch_required']} | {q['EP_gap_mean']:+.3f} | {q['ST_gap_mean']:+.3f} |") +print("\n## models (TUNE; * = PASS acc>=0.70 & CI low>0.5)\n") +print("| head | setting | E[hops] | P(h>=3) | STITCH | STITCH stitch_req | " + " | ".join(FAMS) + " | A_log | A_hold | B_log | B_syn | C 16x2 | C 64x4 |") +print("|" + "---|" * (6 + len(FAMS) + 6)) +for head in ("sf", "arc"): + for tag, b, g, cap, note in CFG: + t = f"{head}_{tag}"; M = ST["models"].get(f"hs_{t}_16x8", {}); E = EM.get(f"hs_{t}_16x8", {}) + txt = "".join(open(x).read() for x in sorted(glob.glob(f"{R}/logs/slurm/rr_cpu_[hs][st]_{t}.*.out"))) + C = {} + for k, nm in [("16x2", f"hs_{t}"), ("64x4", f"hs_{t}_np64s4")]: + m = re.findall(rf"\[score\] {nm}: BAD primary\(p50\) acc ([0-9.]+) ci \[([0-9.]+), ([0-9.]+)\].*PASS (\w+)", txt) + C[k] = f"{float(m[-1][0]):.3f} [{float(m[-1][1]):.2f},{float(m[-1][2]):.2f}]" + ("*" if m[-1][3] == "True" else "") if m else "-" + eh, g3 = ehops(b, g, cap) + st = f"{tag} {note}".strip() + print(f"| {head} | {st} | {eh:.2f} | {g3:.2f} | {f(M.get('STITCH'))} | {f(M.get('STITCH', {}).get('stitch_required'))} | " + + " | ".join(f(M.get(k)) for k in FAMS) + " | " + + " | ".join(f(E.get(k)) for k in ("A_logged", "A_hold", "B_logged", "B_syn")) + f" | {C['16x2']} | {C['64x4']} |") diff --git a/rsm_rise/scripts/real/v7/pairtest/stitch_test.py b/rsm_rise/scripts/real/v7/pairtest/stitch_test.py new file mode 100644 index 0000000000000000000000000000000000000000..34a63c2b32505d757280658f65403a4a3dcf4761 --- /dev/null +++ b/rsm_rise/scripts/real/v7/pairtest/stitch_test.py @@ -0,0 +1,216 @@ +#!/usr/bin/env python +"""RSM_PAIRTEST run 12 (owner 2026-11-20 ~21:00Z "KEEP STITCHING"): FROZEN STITCHING test. +Written before any model was scored on it; pair rules are TRAIN-defined, anchors are TUNE; TEST needs --allow-test +(owner's OK). Never edit the pair rule to make a model pass. + +Idea: anchors where the good outcome is only reachable by composing segments recorded in DIFFERENT episodes. +Common pieces are exactly errmode_test.py's: state x = the successor's 1546-d input, situation distance = L2 in +z-scored proprio (TRAIN mu/sd), logged 50x10 chunks (last action repeats past the episode end), both chunks scored AT +the anchor in ONE scorer call (CRN), Q averaged over seeds, acc = P(Q_good > Q_alt) (ties 0.5), 95% bootstrap CI over +held-out episodes, PASS = acc >= 0.70 and CI low > 0.5. THR = errmode THR (p50 TRAIN within-route NN proprio). + +Families (anchors every 5th frame): + S_02f TUNE 0->2->6 episodes, frames on the 0->2 segment. good = logged chunk (heads to 2; from 2 the success + continuation 2->3->8->7 exists only in OTHER episodes); alt = nearest TRAIN frame on a DIRECT failure segment + leaving 0 (0->5, 0->6) -> its logged chunk. + S_02s same anchors; alt = STAY chunk: nearest TRAIN hover frame leaving 0 (edge_from 0, chunk in the lowest 5% of + max ee displacement among non-padded edge_from-0 frames; the errmode A_logged hover rule at stage 0). + S_01f TUNE 0->1 (0->1-only) episodes, frames on 0->1. good = logged chunk (heads to 1; 1->3 only in OTHER + episodes); alt = nearest TRAIN direct-failure frame leaving 0. + S_26 TUNE 0->2->6 episodes, first 50 frames of the 2->6 segment (at the branch). good = logged chunk of the + nearest TRAIN frame within the first 50 frames of a 2->3 segment (other episodes); alt = logged (failing) chunk. + S_1end TUNE 0->1 episodes, last 50 frames (arrived at 1, the episode ends there). good = logged chunk of the + nearest TRAIN frame within the first 50 frames of a 1->3 segment; alt = logged chunk (hold / end padding). + STITCH (PRIMARY) = all families pooled. + +Oracles (model-free, reward_shaped2, gamma 0.998, normalised units (1-g) sum g^k r_k as pairtest MC): + EP-MC = the chunk's SOURCE episode's own logged continuation, last frame absorbing (what in-episode futures + contain; no stitching). + ST-MC = the source segment's remainder, then g^n V*(segment end node), V* = value iteration on the TRAIN route + graph: V*(n) = max(level(n) [stay], max_{seg type n->m} mean_TRAIN[G_seg + g^L_seg V*(m)]), absorbing 5/6/7. + stitch_required pair: ST-MC(good) > ST-MC(alt) and EP-MC(good) <= EP-MC(alt). Reported: counts per family, + oracle accuracies, and model accuracy on all / stitch_required pairs. +Stitching benefit of a hop setting = acc(setting) - acc(single jump beta=gamma) on STITCH and on stitch_required. + +usage: stitch_test.py --stage pairs [--split tune] + stitch_test.py --stage score --model NAME=SPEC [--seeds 8] (SPEC as pairtest.py) +""" +import argparse, json, os, sys, time +from pathlib import Path +import numpy as np, torch + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +os.environ.setdefault("PAIRTEST_VERSION", "pairtest_v3") +import pairtest as PT # noqa + +OUT = PT.OUT / "stitch"; OUT.mkdir(parents=True, exist_ok=True) +FAMS = ["S_02f", "S_02s", "S_01f", "S_26", "S_1end"] +G = PT.GAMMA_MC +LEVEL = {0: 0.0, 1: 1.0, 2: 1.0, 3: 2.0, 8: 3.0, 7: 10.0, 5: -1.0, 6: -1.0} + + +def segments(e_from, e_to, ef, et, eps): + """contiguous (start, end, from, to) runs of each episode.""" + out = [] + for e in eps: + a, b = ef[e], et[e] + k = np.flatnonzero((np.diff(e_from[a:b]) != 0) | (np.diff(e_to[a:b]) != 0)) + 1 + bnd = np.concatenate([[0], k, [b - a]]) + a + out += [(int(s), int(t), int(e_from[s]), int(e_to[s]), int(e)) for s, t in zip(bnd[:-1], bnd[1:])] + return out + + +def stage_pairs(a): + info, tt, ef, et = PT.load_meta() + e_from = np.load(PT.C / "edge_from.i16.npy").astype(np.int64); e_to = np.load(PT.C / "edge_to.i16.npy").astype(np.int64) + pr = np.load(PT.C / "proprio.f32.npy", mmap_mode="r"); act = np.load(PT.C / "act.f32.npy", mmap_mode="r") + r = np.asarray(np.load(PT.C / "reward_shaped2.f32.npy", mmap_mode="r"), np.float64) + row_ep = np.repeat(np.arange(len(ef)), et - ef) + train, held = PT.split_eps(info, tt, a.split) + em = json.load(open(PT.OUT / "errmode" / f"pairs_{a.split}.json")) # same THR / proprio stats as errmode + pmu, psd, THR = np.array(em["proprio_mu"]), np.array(em["proprio_sd"]), em["THR"] + px = lambda rows: ((np.asarray(pr[np.asarray(rows, np.int64)], np.float64) - pmu) / psd).astype(np.float32) + ep_end = lambda rows: et[row_ep[np.asarray(rows)]] + tr_rows = np.concatenate([np.arange(ef[e], et[e]) for e in train]) + # ---- route-graph V* (TRAIN) + segT = segments(e_from, e_to, ef, et, train) + seg_end = np.zeros(len(e_from), np.int64) + for s, t, *_ in segments(e_from, e_to, ef, et, sorted(info)): + seg_end[s:t] = t + stats = {} + for s, t, f, to, e in segT: + n = t - s; Gs = float(((1 - G) * G ** np.arange(n) * r[s:t]).sum()) + stats.setdefault((f, to), []).append((Gs, G ** n)) + V = {k: v for k, v in LEVEL.items()} + for _ in range(50): + for nd in (1, 2, 3, 8, 0): + outs = [np.mean([g + d * V[to] for g, d in v]) for (f, to), v in stats.items() if f == nd] + V[nd] = max([LEVEL[nd]] + outs) + ep_mc = lambda rows: PT.mc_return(r, rows, ep_end(rows)) + def st_mc(rows): + o = [] + for t in rows: + h = seg_end[t]; n = h - t + o.append(float(((1 - G) * G ** np.arange(n) * r[t:h]).sum() + G ** n * V[int(e_to[t])])) + return np.array(o) + # ---- pools (TRAIN) + fail0 = tr_rows[(e_from[tr_rows] == 0) & np.isin(e_to[tr_rows], [5, 6])] + cand = tr_rows[(e_from[tr_rows] == 0) & (tr_rows <= ep_end(tr_rows) - PT.CHUNK)] + disp = lambda A: np.linalg.norm(A.reshape(len(A), PT.CHUNK, -1)[:, :, :3] - A.reshape(len(A), PT.CHUNK, -1)[:, :1, :3], axis=2).max(1) + dc = disp(PT.chunk(act, cand, ep_end(cand))); hover0 = cand[dc <= np.percentile(dc, 5)] + seg_start = np.zeros(len(e_from), np.int64) + for s, t, *_ in segments(e_from, e_to, ef, et, sorted(info)): + seg_start[s:t] = s + early = lambda f, to: tr_rows[(e_from[tr_rows] == f) & (e_to[tr_rows] == to) & (tr_rows - seg_start[tr_rows] < 50)] + pool23, pool13 = early(2, 3), early(1, 3) + rt = {e: PT.route(info, e) for e in held} + def rows_where(route, f, to, first=None, last=None): + o = [] + for e in held: + if rt[e] != route: + continue + q = np.arange(ef[e], et[e]); q = q[(e_from[q] == f) & (e_to[q] == to)] + if first is not None: + q = q[q - seg_start[q] < first] + if last is not None: + q = q[q >= et[e] - last] + o.append(q[::5]) + return np.concatenate(o) if o else np.zeros(0, np.int64) + T, meta = {}, {"split": a.split, "THR": THR, "V_star": {str(k): v for k, v in V.items()}, + "seg_types": {f"{k[0]}->{k[1]}": len(v) for k, v in stats.items()}, + "pools": {"fail0": int(len(fail0)), "hover0": int(len(hover0)), "early23": int(len(pool23)), "early13": int(len(pool13))}} + def make(name, anc, good_rows, alt_rows, dist): + T[name] = dict(anc=anc, ep=row_ep[anc], prog=PT.chunk(act, good_rows, ep_end(good_rows)), + alt=PT.chunk(act, alt_rows, ep_end(alt_rows)), dist=dist, good_src=good_rows, alt_src=alt_rows, + ep_g=ep_mc(good_rows), ep_a=ep_mc(alt_rows), st_g=st_mc(good_rows), st_a=st_mc(alt_rows), + keep=np.ones(len(anc), bool), + key=np.array([f"{name}{'' if d < THR else ' (relaxed)'}" for d in dist])) + nn = lambda anc, pool: PT.nn_dist(px(anc), px(pool)) + anc = rows_where("0->2->6", 0, 2) + d, j = nn(anc, fail0); make("S_02f", anc, anc, fail0[j], d) + d, j = nn(anc, hover0); make("S_02s", anc, anc, hover0[j], d) + anc = rows_where("0->1", 0, 1) + d, j = nn(anc, fail0); make("S_01f", anc, anc, fail0[j], d) + anc = rows_where("0->2->6", 2, 6, first=50) + d, j = nn(anc, pool23); make("S_26", anc, pool23[j], anc, d) + anc = rows_where("0->1", 0, 1, last=50) + d, j = nn(anc, pool13); make("S_1end", anc, pool13[j], anc, d) + for k, D in T.items(): + sr = (D["st_g"] > D["st_a"]) & (D["ep_g"] <= D["ep_a"]) + D["stitch_req"] = sr + meta[k] = {"n": int(len(D["anc"])), "n_eps": int(len(np.unique(D["ep"]))), "coincident": int((D["dist"] < THR).sum()), + "dist_pct": {str(p): float(np.percentile(D["dist"], p)) for p in (10, 50, 90)} if len(D["anc"]) else {}, + "oracle_EP_acc": float(np.mean(D["ep_g"] > D["ep_a"])) if len(D["anc"]) else None, + "oracle_ST_acc": float(np.mean(D["st_g"] > D["st_a"])) if len(D["anc"]) else None, + "stitch_required": int(sr.sum()), + "EP_gap_mean": float(np.mean(D["ep_g"] - D["ep_a"])) if len(D["anc"]) else None, + "ST_gap_mean": float(np.mean(D["st_g"] - D["st_a"])) if len(D["anc"]) else None} + np.savez(OUT / f"{k}_{a.split}.npz", **D) + json.dump(meta, open(OUT / f"pairs_{a.split}.json", "w"), indent=1) + print(json.dumps(meta, indent=1), flush=True) + + +def stage_score(a): + F = PT.Feat() + meta = json.load(open(OUT / f"pairs_{a.split}.json")) + resp = PT.ST / f"rsm_stitch_{a.split}.json" + for spec_kv in a.model: + name, spec = spec_kv.split("=", 1) + # run 15: SPEC 'cached' = Q precomputed by another scorer (iql_all.py); the cache must be complete + kind, sc = ("cached", None) if spec == "cached" else PT.build_scorer(spec, F.sd, 1546) + R = {"spec": spec, "seeds": a.seeds}; allc = {k: [] for k in ("qg", "qa", "ep", "key", "sr")} + for fam in FAMS: + Tz = dict(np.load(OUT / f"{fam}_{a.split}.npz")); n = len(Tz["anc"]) + if n == 0: + R[fam] = {"n_pairs": 0}; continue + cache = OUT / f"q_{fam}_{a.split}_{name}.npz" + Q = dict(np.load(cache)) if cache.exists() else {"qg": np.full(n, np.nan), "qa": np.full(n, np.nan)} + X = torch.from_numpy(F.x(Tz["anc"])); last = time.time() + if kind == "cached" and np.isnan(Q["qg"]).any() | np.isnan(Q["qa"]).any(): + raise RuntimeError(f"{cache}: cached spec but the cache is missing or incomplete") + for i in np.flatnonzero(np.isnan(Q["qg"])): + A = torch.from_numpy(np.stack([Tz["prog"][i], Tz["alt"][i]])).float(); x = X[i][None] + with torch.no_grad(): + if kind == "r2": + q = sc(x.expand(2, -1), A).numpy().astype(np.float64) + else: + q = np.zeros(2) + for s in range(a.seeds): + sc.score(x, A.reshape(2, PT.CHUNK, -1), seed=s); q += np.asarray(sc.last_q.cpu(), float) + q /= a.seeds + Q["qg"][i], Q["qa"][i] = q + if time.time() - last > 60: + np.savez(cache, **Q); last = time.time() + np.savez(cache, **Q) + keys = list(Tz["key"]); M = PT.metrics(Q["qg"], Q["qa"], Tz["ep"], keys) + sr = Tz["stitch_req"].astype(bool) + if sr.any(): + M["stitch_required"] = PT.metrics(Q["qg"][sr], Q["qa"][sr], Tz["ep"][sr], [keys[j] for j in np.flatnonzero(sr)]) + M["PASS"] = bool(M.get("acc", 0) >= 0.70 and M.get("ci", [0])[0] > 0.5); R[fam] = M + allc["qg"].append(Q["qg"]); allc["qa"].append(Q["qa"]); allc["ep"].append(Tz["ep"]); allc["key"] += [fam] * n; allc["sr"].append(sr) + print(f"[stitch] {name} {fam}: acc {M.get('acc')} ci {M.get('ci')} n {M['n_pairs']}/{M['n_eps']}", flush=True) + qg, qa, ep, sr = (np.concatenate(allc[k]) for k in ("qg", "qa", "ep", "sr")) + M = PT.metrics(qg, qa, ep, allc["key"]) + if sr.any(): + M["stitch_required"] = PT.metrics(qg[sr], qa[sr], ep[sr], [allc["key"][j] for j in np.flatnonzero(sr)]) + M["PASS"] = bool(M.get("acc", 0) >= 0.70 and M.get("ci", [0])[0] > 0.5); R["STITCH"] = M + print(f"[stitch] {name} STITCH: acc {M.get('acc')} ci {M.get('ci')} n {M['n_pairs']}/{M['n_eps']} PASS {M['PASS']}", flush=True) + def _upd(cur): + cur = cur or {"models": {}}; cur["pairs"] = meta; cur["models"][name] = R; return cur + PT.locked_merge(resp, _upd) + if os.environ.get("PT_MODEL_JSON_DIR"): # V7_NOAUG run 4: private per-model copy (shared json loses entries); default off + _d = Path(os.environ["PT_MODEL_JSON_DIR"]); _d.mkdir(parents=True, exist_ok=True) + json.dump(R, open(_d / f"ST_{a.split}.json", "w"), indent=1, default=float) + + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--stage", choices=["pairs", "score"], required=True) + ap.add_argument("--split", default="tune", choices=["tune", "test", "cv0", "cv1", "cv2", "cv3"]) + ap.add_argument("--model", action="append", default=[]) + ap.add_argument("--seeds", type=int, default=8) + ap.add_argument("--allow-test", action="store_true") + a = ap.parse_args() + if a.split == "test" and not a.allow_test: + sys.exit("TEST needs the owner's OK (--allow-test)") + stage_pairs(a) if a.stage == "pairs" else stage_score(a) diff --git a/rsm_rise/scripts/real/v7/pairtest/testread_gpu/slot0.sh b/rsm_rise/scripts/real/v7/pairtest/testread_gpu/slot0.sh new file mode 100644 index 0000000000000000000000000000000000000000..bd305f0630034b3425965146a6497560936def54 --- /dev/null +++ b/rsm_rise/scripts/real/v7/pairtest/testread_gpu/slot0.sh @@ -0,0 +1,4 @@ +#!/usr/bin/env bash +cd /proj/dmfexp/zwhong/rsm_rise; export SLURM_CPUS_PER_TASK=12 +SPLIT=test PAIRS=1 bash scripts/real/v7/pairtest/run_testread.sh && touch runs/pairtest/testread/PAIRS_TEST_DONE +MODEL=old SPLIT=test NP=64 SEEDS=4 PT_DEVICE=cuda bash scripts/real/v7/pairtest/run_testread.sh || { echo "[gpu] old test 64x4 failed on cuda -> cpu"; MODEL=old SPLIT=test NP=64 SEEDS=4 PT_DEVICE=cpu bash scripts/real/v7/pairtest/run_testread.sh; } diff --git a/rsm_rise/scripts/real/v7/pairtest/testread_gpu/slot1.sh b/rsm_rise/scripts/real/v7/pairtest/testread_gpu/slot1.sh new file mode 100644 index 0000000000000000000000000000000000000000..799bbcbd4883ea63047126fa82371074b0b84a1f --- /dev/null +++ b/rsm_rise/scripts/real/v7/pairtest/testread_gpu/slot1.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +cd /proj/dmfexp/zwhong/rsm_rise; export SLURM_CPUS_PER_TASK=12 +MODEL=old SPLIT=tune NP=64 SEEDS=4 PT_DEVICE=cuda bash scripts/real/v7/pairtest/run_testread.sh || { echo "[gpu] old tune 64x4 failed on cuda -> cpu"; MODEL=old SPLIT=tune NP=64 SEEDS=4 PT_DEVICE=cpu bash scripts/real/v7/pairtest/run_testread.sh; } diff --git a/rsm_rise/scripts/real/v7/pairtest/testread_gpu/slot2.sh b/rsm_rise/scripts/real/v7/pairtest/testread_gpu/slot2.sh new file mode 100644 index 0000000000000000000000000000000000000000..38063178f7372cc629fe1c638cb40c0df7da9214 --- /dev/null +++ b/rsm_rise/scripts/real/v7/pairtest/testread_gpu/slot2.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +cd /proj/dmfexp/zwhong/rsm_rise; export SLURM_CPUS_PER_TASK=12 +until [ -f runs/pairtest/testread/PAIRS_TEST_DONE ]; do sleep 20; done +MODEL=default SPLIT=test NP=64 SEEDS=4 PT_DEVICE=cuda bash scripts/real/v7/pairtest/run_testread.sh || { echo "[gpu] default test 64x4 failed on cuda -> cpu"; MODEL=default SPLIT=test NP=64 SEEDS=4 PT_DEVICE=cpu bash scripts/real/v7/pairtest/run_testread.sh; } +MODEL=chal SPLIT=test NP=64 SEEDS=4 PT_DEVICE=cuda bash scripts/real/v7/pairtest/run_testread.sh || { echo "[gpu] chal test 64x4 failed on cuda -> cpu"; MODEL=chal SPLIT=test NP=64 SEEDS=4 PT_DEVICE=cpu bash scripts/real/v7/pairtest/run_testread.sh; } diff --git a/rsm_rise/scripts/real/v7/pairtest/testread_gpu/slot3.sh b/rsm_rise/scripts/real/v7/pairtest/testread_gpu/slot3.sh new file mode 100644 index 0000000000000000000000000000000000000000..fc7a04828dff0ffaf82ffab981f335ebe2168030 --- /dev/null +++ b/rsm_rise/scripts/real/v7/pairtest/testread_gpu/slot3.sh @@ -0,0 +1,4 @@ +#!/usr/bin/env bash +cd /proj/dmfexp/zwhong/rsm_rise; export SLURM_CPUS_PER_TASK=12 +MODEL=default SPLIT=tune NP=64 SEEDS=4 PT_DEVICE=cuda bash scripts/real/v7/pairtest/run_testread.sh || { echo "[gpu] default tune 64x4 failed on cuda -> cpu"; MODEL=default SPLIT=tune NP=64 SEEDS=4 PT_DEVICE=cpu bash scripts/real/v7/pairtest/run_testread.sh; } +MODEL=chal SPLIT=tune NP=64 SEEDS=4 PT_DEVICE=cuda bash scripts/real/v7/pairtest/run_testread.sh || { echo "[gpu] chal tune 64x4 failed on cuda -> cpu"; MODEL=chal SPLIT=tune NP=64 SEEDS=4 PT_DEVICE=cpu bash scripts/real/v7/pairtest/run_testread.sh; } diff --git a/rsm_rise/scripts/real/v7/pairtest/testread_gpu/slot4.sh b/rsm_rise/scripts/real/v7/pairtest/testread_gpu/slot4.sh new file mode 100644 index 0000000000000000000000000000000000000000..8e9c2252f971f43d2614c82c3c7e9548bcbda703 --- /dev/null +++ b/rsm_rise/scripts/real/v7/pairtest/testread_gpu/slot4.sh @@ -0,0 +1,6 @@ +#!/usr/bin/env bash +cd /proj/dmfexp/zwhong/rsm_rise; export SLURM_CPUS_PER_TASK=12 +until [ -f runs/pairtest/testread/PAIRS_TEST_DONE ]; do sleep 20; done +MODEL=old SPLIT=test NP=16 SEEDS=1 PT_DEVICE=cuda bash scripts/real/v7/pairtest/run_testread.sh || { echo "[gpu] old test 16x1 failed on cuda -> cpu"; MODEL=old SPLIT=test NP=16 SEEDS=1 PT_DEVICE=cpu bash scripts/real/v7/pairtest/run_testread.sh; } +MODEL=old SPLIT=test NP=16 SEEDS=2 PT_DEVICE=cuda bash scripts/real/v7/pairtest/run_testread.sh || { echo "[gpu] old test 16x2 failed on cuda -> cpu"; MODEL=old SPLIT=test NP=16 SEEDS=2 PT_DEVICE=cpu bash scripts/real/v7/pairtest/run_testread.sh; } +MODEL=old SPLIT=test NP=64 SEEDS=1 PT_DEVICE=cuda bash scripts/real/v7/pairtest/run_testread.sh || { echo "[gpu] old test 64x1 failed on cuda -> cpu"; MODEL=old SPLIT=test NP=64 SEEDS=1 PT_DEVICE=cpu bash scripts/real/v7/pairtest/run_testread.sh; } diff --git a/rsm_rise/scripts/real/v7/pairtest/testread_gpu/slot5.sh b/rsm_rise/scripts/real/v7/pairtest/testread_gpu/slot5.sh new file mode 100644 index 0000000000000000000000000000000000000000..b37743818136fefac00210b42f9414d462d0af7b --- /dev/null +++ b/rsm_rise/scripts/real/v7/pairtest/testread_gpu/slot5.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +cd /proj/dmfexp/zwhong/rsm_rise; export SLURM_CPUS_PER_TASK=12 +MODEL=old SPLIT=tune NP=16 SEEDS=1 PT_DEVICE=cuda bash scripts/real/v7/pairtest/run_testread.sh || { echo "[gpu] old tune 16x1 failed on cuda -> cpu"; MODEL=old SPLIT=tune NP=16 SEEDS=1 PT_DEVICE=cpu bash scripts/real/v7/pairtest/run_testread.sh; } +MODEL=old SPLIT=tune NP=16 SEEDS=2 PT_DEVICE=cuda bash scripts/real/v7/pairtest/run_testread.sh || { echo "[gpu] old tune 16x2 failed on cuda -> cpu"; MODEL=old SPLIT=tune NP=16 SEEDS=2 PT_DEVICE=cpu bash scripts/real/v7/pairtest/run_testread.sh; } +MODEL=old SPLIT=tune NP=64 SEEDS=1 PT_DEVICE=cuda bash scripts/real/v7/pairtest/run_testread.sh || { echo "[gpu] old tune 64x1 failed on cuda -> cpu"; MODEL=old SPLIT=tune NP=64 SEEDS=1 PT_DEVICE=cpu bash scripts/real/v7/pairtest/run_testread.sh; } diff --git a/rsm_rise/scripts/real/v7/pairtest/testread_gpu/slot6.sh b/rsm_rise/scripts/real/v7/pairtest/testread_gpu/slot6.sh new file mode 100644 index 0000000000000000000000000000000000000000..89a078efa448c7c36c1c865b13a5dfe11ca4e877 --- /dev/null +++ b/rsm_rise/scripts/real/v7/pairtest/testread_gpu/slot6.sh @@ -0,0 +1,9 @@ +#!/usr/bin/env bash +cd /proj/dmfexp/zwhong/rsm_rise; export SLURM_CPUS_PER_TASK=12 +until [ -f runs/pairtest/testread/PAIRS_TEST_DONE ]; do sleep 20; done +MODEL=default SPLIT=test NP=16 SEEDS=1 PT_DEVICE=cuda bash scripts/real/v7/pairtest/run_testread.sh || { echo "[gpu] default test 16x1 failed on cuda -> cpu"; MODEL=default SPLIT=test NP=16 SEEDS=1 PT_DEVICE=cpu bash scripts/real/v7/pairtest/run_testread.sh; } +MODEL=default SPLIT=test NP=16 SEEDS=2 PT_DEVICE=cuda bash scripts/real/v7/pairtest/run_testread.sh || { echo "[gpu] default test 16x2 failed on cuda -> cpu"; MODEL=default SPLIT=test NP=16 SEEDS=2 PT_DEVICE=cpu bash scripts/real/v7/pairtest/run_testread.sh; } +MODEL=default SPLIT=test NP=64 SEEDS=1 PT_DEVICE=cuda bash scripts/real/v7/pairtest/run_testread.sh || { echo "[gpu] default test 64x1 failed on cuda -> cpu"; MODEL=default SPLIT=test NP=64 SEEDS=1 PT_DEVICE=cpu bash scripts/real/v7/pairtest/run_testread.sh; } +MODEL=chal SPLIT=test NP=16 SEEDS=1 PT_DEVICE=cuda bash scripts/real/v7/pairtest/run_testread.sh || { echo "[gpu] chal test 16x1 failed on cuda -> cpu"; MODEL=chal SPLIT=test NP=16 SEEDS=1 PT_DEVICE=cpu bash scripts/real/v7/pairtest/run_testread.sh; } +MODEL=chal SPLIT=test NP=16 SEEDS=2 PT_DEVICE=cuda bash scripts/real/v7/pairtest/run_testread.sh || { echo "[gpu] chal test 16x2 failed on cuda -> cpu"; MODEL=chal SPLIT=test NP=16 SEEDS=2 PT_DEVICE=cpu bash scripts/real/v7/pairtest/run_testread.sh; } +MODEL=chal SPLIT=test NP=64 SEEDS=1 PT_DEVICE=cuda bash scripts/real/v7/pairtest/run_testread.sh || { echo "[gpu] chal test 64x1 failed on cuda -> cpu"; MODEL=chal SPLIT=test NP=64 SEEDS=1 PT_DEVICE=cpu bash scripts/real/v7/pairtest/run_testread.sh; } diff --git a/rsm_rise/scripts/real/v7/pairtest/testread_gpu/slot7.sh b/rsm_rise/scripts/real/v7/pairtest/testread_gpu/slot7.sh new file mode 100644 index 0000000000000000000000000000000000000000..27756910bb5db7214e7111668455775dba4cef6f --- /dev/null +++ b/rsm_rise/scripts/real/v7/pairtest/testread_gpu/slot7.sh @@ -0,0 +1,8 @@ +#!/usr/bin/env bash +cd /proj/dmfexp/zwhong/rsm_rise; export SLURM_CPUS_PER_TASK=12 +MODEL=default SPLIT=tune NP=16 SEEDS=1 PT_DEVICE=cuda bash scripts/real/v7/pairtest/run_testread.sh || { echo "[gpu] default tune 16x1 failed on cuda -> cpu"; MODEL=default SPLIT=tune NP=16 SEEDS=1 PT_DEVICE=cpu bash scripts/real/v7/pairtest/run_testread.sh; } +MODEL=default SPLIT=tune NP=16 SEEDS=2 PT_DEVICE=cuda bash scripts/real/v7/pairtest/run_testread.sh || { echo "[gpu] default tune 16x2 failed on cuda -> cpu"; MODEL=default SPLIT=tune NP=16 SEEDS=2 PT_DEVICE=cpu bash scripts/real/v7/pairtest/run_testread.sh; } +MODEL=default SPLIT=tune NP=64 SEEDS=1 PT_DEVICE=cuda bash scripts/real/v7/pairtest/run_testread.sh || { echo "[gpu] default tune 64x1 failed on cuda -> cpu"; MODEL=default SPLIT=tune NP=64 SEEDS=1 PT_DEVICE=cpu bash scripts/real/v7/pairtest/run_testread.sh; } +MODEL=chal SPLIT=tune NP=16 SEEDS=1 PT_DEVICE=cuda bash scripts/real/v7/pairtest/run_testread.sh || { echo "[gpu] chal tune 16x1 failed on cuda -> cpu"; MODEL=chal SPLIT=tune NP=16 SEEDS=1 PT_DEVICE=cpu bash scripts/real/v7/pairtest/run_testread.sh; } +MODEL=chal SPLIT=tune NP=16 SEEDS=2 PT_DEVICE=cuda bash scripts/real/v7/pairtest/run_testread.sh || { echo "[gpu] chal tune 16x2 failed on cuda -> cpu"; MODEL=chal SPLIT=tune NP=16 SEEDS=2 PT_DEVICE=cpu bash scripts/real/v7/pairtest/run_testread.sh; } +MODEL=chal SPLIT=tune NP=64 SEEDS=1 PT_DEVICE=cuda bash scripts/real/v7/pairtest/run_testread.sh || { echo "[gpu] chal tune 64x1 failed on cuda -> cpu"; MODEL=chal SPLIT=tune NP=64 SEEDS=1 PT_DEVICE=cpu bash scripts/real/v7/pairtest/run_testread.sh; } diff --git a/rsm_rise/scripts/real/v7/pairtest/testread_table.py b/rsm_rise/scripts/real/v7/pairtest/testread_table.py new file mode 100644 index 0000000000000000000000000000000000000000..b8a373e64370ca90440b1ae8a5f632a00fd8d5f7 --- /dev/null +++ b/rsm_rise/scripts/real/v7/pairtest/testread_table.py @@ -0,0 +1,60 @@ +"""run 14: TEST vs TUNE table for the one authorised TEST read (models tr__x). Reads json only. +Frozen PASS rule: acc >= 0.70 and 95% CI low > 0.5. 'few' = fewer than 3 episodes or 20 pairs (too few to judge).""" +import json +from pathlib import Path +ST = Path("/proj/dmfexp/zwhong/rsm_rise/status/real") +MODELS = [("default", "DEFAULT sf_d1 clamp b.99 g.998 cap1"), ("chal", "CHALLENGER c50 clamp b.99 g.995"), + ("old", "OLD issue-17 b.99 g.998")] +BUD = ["16x1", "16x2", "64x1", "64x4"] +TESTS = [("C", "pt", "BAD_primary"), ("A_logged", "em", "A_logged"), ("A_end", "em", "A_end"), ("A_hold", "em", "A_hold"), + ("B_logged", "em", "B_logged"), ("B_syn", "em", "B_syn"), ("STITCH", "st", "STITCH"), ("ST_req", "st", "STITCH.stitch_required")] +def load(split): + f = {"pt": f"rsm_pairtest_v3_{split}.json", "em": f"rsm_errmode_{split}.json", "st": f"rsm_stitch_{split}.json"} + return {k: (json.load(open(ST / v))["models"] if (ST / v).exists() else {}) for k, v in f.items()} +D = {s: load(s) for s in ("tune", "test")} +def cell(split, m, b, src, key): + M = D[split][src].get(f"tr_{m}_{b}", {}) + for k in key.split("."): + M = M.get(k, {}) if isinstance(M, dict) else {} + if not M or "acc" not in M: + return "-" + a, ci, n, e = M["acc"], M.get("ci", [float("nan")] * 2), M.get("n_pairs", M.get("n")), M.get("n_eps") + ok = a >= 0.70 and ci[0] > 0.5; few = (e or 0) < 3 or (n or 0) < 20 + return f"{a:.2f} [{ci[0]:.2f},{ci[1]:.2f}]{' P' if ok else ' F'}{' (few)' if few else ''}" +def counts(split, src, key, m="default", b="16x2"): + M = D[split][src].get(f"tr_{m}_{b}", {}) + for k in key.split("."): + M = M.get(k, {}) if isinstance(M, dict) else {} + return f"{M.get('n_pairs', M.get('n', '?'))}/{M.get('n_eps', '?')}" if M else "?" +print("# One-time TEST read vs TUNE (frozen tests; P/F = frozen rule acc>=0.70 & CI low>0.5; (few) = <3 eps or <20 pairs)\n") +print("Pairs/episodes (TUNE | TEST): " + "; ".join(f"{t} {counts('tune', s, k)} | {counts('test', s, k)}" for t, s, k in TESTS) + "\n") +for b in BUD: + print(f"\n## budget {b} (particles x seeds)\n") + print("| model | split | " + " | ".join(t for t, _, _ in TESTS) + " |") + print("|---|---|" + "---|" * len(TESTS)) + for m, lab in MODELS: + for s in ("tune", "test"): + print(f"| {lab} | {s.upper()} | " + " | ".join(cell(s, m, b, src, k) for _, src, k in TESTS) + " |") +# run 16: IQL rows (deterministic critic: one number for every budget). NEW = TUNE pick (status/real/iql_pick.json, +# rule fixed before the TEST read); OLD = issue-17 comparator. TUNE also lists the e5000 4-seed ensemble for reference. +PICK = json.load(open(ST / "iql_pick.json"))["pick"] +IQL = [(PICK, f"NEW IQL RSHAPED2 pick ({PICK})"), ("iqlR2_ens_e5000", "NEW IQL RSHAPED2 ens e5000 (TUNE ref)"), + ("iql_old_rprog_e1250", "OLD IQL RPROGRESS s0 e1250")] +def icell(split, name, src, key): + M = D[split][src].get(name, {}) + for k in key.split("."): + M = M.get(k, {}) if isinstance(M, dict) else {} + if not M or "acc" not in M: + return "-" + a, ci, n, e = M["acc"], M.get("ci", [float("nan")] * 2), M.get("n_pairs", M.get("n")), M.get("n_eps") + ok = a >= 0.70 and ci[0] > 0.5; few = (e or 0) < 3 or (n or 0) < 20 + return f"{a:.2f} [{ci[0]:.2f},{ci[1]:.2f}]{' P' if ok else ' F'}{' (few)' if few else ''}" +print("\n## IQL critics (deterministic: no particles/seeds, same number at every budget; A_hold is a tie by construction" + " for a first-action critic)\n") +print("| model | split | " + " | ".join(t for t, _, _ in TESTS) + " |") +print("|---|---|" + "---|" * len(TESTS)) +for n, lab in IQL: + for s in ("tune", "test"): + if s == "test" and "ens" in n and n != PICK: + continue + print(f"| {lab} | {s.upper()} | " + " | ".join(icell(s, n, src, k) for _, src, k in TESTS) + " |") diff --git a/rsm_rise/scripts/real/v7/payloads/enc_shard0.sh b/rsm_rise/scripts/real/v7/payloads/enc_shard0.sh new file mode 100644 index 0000000000000000000000000000000000000000..1a5b552608661649b74ae2e8d56fad594d4e63bb --- /dev/null +++ b/rsm_rise/scripts/real/v7/payloads/enc_shard0.sh @@ -0,0 +1,8 @@ +#!/usr/bin/env bash +# COOKV7_DINOWM: DINO encode (pooled + patch tokens) shard 0/8 of rsm_cooking_v7 (resumable per episode) +set -uo pipefail +ROOT=/proj/dmfexp/zwhong/rsm_rise +export TORCH_HOME="${TORCH_HOME:-$HOME/.cache/torch}" +echo "[payload] host=$(hostname) gpu=$CUDA_VISIBLE_DEVICES $(date -u)" +exec $ROOT/venv_rsm/bin/python $ROOT/scripts/real/v7/relabel_shard_tok.py --root $ROOT/data/real/rsm_cooking_v7 \ + --out $ROOT/cache/real_cooking_v7 --shard 0 --nshard 8 --cams global,wrist --crop-mode square --batch 256 diff --git a/rsm_rise/scripts/real/v7/payloads/enc_shard1.sh b/rsm_rise/scripts/real/v7/payloads/enc_shard1.sh new file mode 100644 index 0000000000000000000000000000000000000000..13ceb9c4f84c757377979176a9b16a2b30b0e5d7 --- /dev/null +++ b/rsm_rise/scripts/real/v7/payloads/enc_shard1.sh @@ -0,0 +1,8 @@ +#!/usr/bin/env bash +# COOKV7_DINOWM: DINO encode (pooled + patch tokens) shard 1/8 of rsm_cooking_v7 (resumable per episode) +set -uo pipefail +ROOT=/proj/dmfexp/zwhong/rsm_rise +export TORCH_HOME="${TORCH_HOME:-$HOME/.cache/torch}" +echo "[payload] host=$(hostname) gpu=$CUDA_VISIBLE_DEVICES $(date -u)" +exec $ROOT/venv_rsm/bin/python $ROOT/scripts/real/v7/relabel_shard_tok.py --root $ROOT/data/real/rsm_cooking_v7 \ + --out $ROOT/cache/real_cooking_v7 --shard 1 --nshard 8 --cams global,wrist --crop-mode square --batch 256 diff --git a/rsm_rise/scripts/real/v7/payloads/enc_shard2.sh b/rsm_rise/scripts/real/v7/payloads/enc_shard2.sh new file mode 100644 index 0000000000000000000000000000000000000000..545289dc4624769bd8f69d0ee8cca39fd3fcd0d0 --- /dev/null +++ b/rsm_rise/scripts/real/v7/payloads/enc_shard2.sh @@ -0,0 +1,8 @@ +#!/usr/bin/env bash +# COOKV7_DINOWM: DINO encode (pooled + patch tokens) shard 2/8 of rsm_cooking_v7 (resumable per episode) +set -uo pipefail +ROOT=/proj/dmfexp/zwhong/rsm_rise +export TORCH_HOME="${TORCH_HOME:-$HOME/.cache/torch}" +echo "[payload] host=$(hostname) gpu=$CUDA_VISIBLE_DEVICES $(date -u)" +exec $ROOT/venv_rsm/bin/python $ROOT/scripts/real/v7/relabel_shard_tok.py --root $ROOT/data/real/rsm_cooking_v7 \ + --out $ROOT/cache/real_cooking_v7 --shard 2 --nshard 8 --cams global,wrist --crop-mode square --batch 256 diff --git a/rsm_rise/scripts/real/v7/payloads/enc_shard3.sh b/rsm_rise/scripts/real/v7/payloads/enc_shard3.sh new file mode 100644 index 0000000000000000000000000000000000000000..0d1d67a4677e4599a538f8573900a366f94ea664 --- /dev/null +++ b/rsm_rise/scripts/real/v7/payloads/enc_shard3.sh @@ -0,0 +1,8 @@ +#!/usr/bin/env bash +# COOKV7_DINOWM: DINO encode (pooled + patch tokens) shard 3/8 of rsm_cooking_v7 (resumable per episode) +set -uo pipefail +ROOT=/proj/dmfexp/zwhong/rsm_rise +export TORCH_HOME="${TORCH_HOME:-$HOME/.cache/torch}" +echo "[payload] host=$(hostname) gpu=$CUDA_VISIBLE_DEVICES $(date -u)" +exec $ROOT/venv_rsm/bin/python $ROOT/scripts/real/v7/relabel_shard_tok.py --root $ROOT/data/real/rsm_cooking_v7 \ + --out $ROOT/cache/real_cooking_v7 --shard 3 --nshard 8 --cams global,wrist --crop-mode square --batch 256 diff --git a/rsm_rise/scripts/real/v7/payloads/enc_shard4.sh b/rsm_rise/scripts/real/v7/payloads/enc_shard4.sh new file mode 100644 index 0000000000000000000000000000000000000000..c884d1129c889a3b076181a522012d1253582a30 --- /dev/null +++ b/rsm_rise/scripts/real/v7/payloads/enc_shard4.sh @@ -0,0 +1,8 @@ +#!/usr/bin/env bash +# COOKV7_DINOWM: DINO encode (pooled + patch tokens) shard 4/8 of rsm_cooking_v7 (resumable per episode) +set -uo pipefail +ROOT=/proj/dmfexp/zwhong/rsm_rise +export TORCH_HOME="${TORCH_HOME:-$HOME/.cache/torch}" +echo "[payload] host=$(hostname) gpu=$CUDA_VISIBLE_DEVICES $(date -u)" +exec $ROOT/venv_rsm/bin/python $ROOT/scripts/real/v7/relabel_shard_tok.py --root $ROOT/data/real/rsm_cooking_v7 \ + --out $ROOT/cache/real_cooking_v7 --shard 4 --nshard 8 --cams global,wrist --crop-mode square --batch 256 diff --git a/rsm_rise/scripts/real/v7/payloads/enc_shard5.sh b/rsm_rise/scripts/real/v7/payloads/enc_shard5.sh new file mode 100644 index 0000000000000000000000000000000000000000..4ab55f3c29c1de244b4319a9c9ab23cedeb91f50 --- /dev/null +++ b/rsm_rise/scripts/real/v7/payloads/enc_shard5.sh @@ -0,0 +1,8 @@ +#!/usr/bin/env bash +# COOKV7_DINOWM: DINO encode (pooled + patch tokens) shard 5/8 of rsm_cooking_v7 (resumable per episode) +set -uo pipefail +ROOT=/proj/dmfexp/zwhong/rsm_rise +export TORCH_HOME="${TORCH_HOME:-$HOME/.cache/torch}" +echo "[payload] host=$(hostname) gpu=$CUDA_VISIBLE_DEVICES $(date -u)" +exec $ROOT/venv_rsm/bin/python $ROOT/scripts/real/v7/relabel_shard_tok.py --root $ROOT/data/real/rsm_cooking_v7 \ + --out $ROOT/cache/real_cooking_v7 --shard 5 --nshard 8 --cams global,wrist --crop-mode square --batch 256 diff --git a/rsm_rise/scripts/real/v7/payloads/enc_shard6.sh b/rsm_rise/scripts/real/v7/payloads/enc_shard6.sh new file mode 100644 index 0000000000000000000000000000000000000000..85d9fbdafdd3f56b39a2fa0558b65a0e89fd14b9 --- /dev/null +++ b/rsm_rise/scripts/real/v7/payloads/enc_shard6.sh @@ -0,0 +1,8 @@ +#!/usr/bin/env bash +# COOKV7_DINOWM: DINO encode (pooled + patch tokens) shard 6/8 of rsm_cooking_v7 (resumable per episode) +set -uo pipefail +ROOT=/proj/dmfexp/zwhong/rsm_rise +export TORCH_HOME="${TORCH_HOME:-$HOME/.cache/torch}" +echo "[payload] host=$(hostname) gpu=$CUDA_VISIBLE_DEVICES $(date -u)" +exec $ROOT/venv_rsm/bin/python $ROOT/scripts/real/v7/relabel_shard_tok.py --root $ROOT/data/real/rsm_cooking_v7 \ + --out $ROOT/cache/real_cooking_v7 --shard 6 --nshard 8 --cams global,wrist --crop-mode square --batch 256 diff --git a/rsm_rise/scripts/real/v7/payloads/enc_shard7.sh b/rsm_rise/scripts/real/v7/payloads/enc_shard7.sh new file mode 100644 index 0000000000000000000000000000000000000000..0dd95ba5c407fd26d9a6885e7fa8c9c3123207ac --- /dev/null +++ b/rsm_rise/scripts/real/v7/payloads/enc_shard7.sh @@ -0,0 +1,8 @@ +#!/usr/bin/env bash +# COOKV7_DINOWM: DINO encode (pooled + patch tokens) shard 7/8 of rsm_cooking_v7 (resumable per episode) +set -uo pipefail +ROOT=/proj/dmfexp/zwhong/rsm_rise +export TORCH_HOME="${TORCH_HOME:-$HOME/.cache/torch}" +echo "[payload] host=$(hostname) gpu=$CUDA_VISIBLE_DEVICES $(date -u)" +exec $ROOT/venv_rsm/bin/python $ROOT/scripts/real/v7/relabel_shard_tok.py --root $ROOT/data/real/rsm_cooking_v7 \ + --out $ROOT/cache/real_cooking_v7 --shard 7 --nshard 8 --cams global,wrist --crop-mode square --batch 256 diff --git a/rsm_rise/scripts/real/v7/push/upload_dino_features.sh b/rsm_rise/scripts/real/v7/push/upload_dino_features.sh new file mode 100644 index 0000000000000000000000000000000000000000..9ac105f701bf415a87189881046b0d5ca723ac4b --- /dev/null +++ b/rsm_rise/scripts/real/v7/push/upload_dino_features.sh @@ -0,0 +1,45 @@ +#!/usr/bin/env bash +#SBATCH --partition=cpu +#SBATCH --account=grp_runtime +#SBATCH --cpus-per-task=8 --mem=16G --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 +# Owner 2026-11-22: "where are those DINO feature variant? you should upload them too" -> v7/dino_features/ +set -euo pipefail +ROOT=/proj/dmfexp/zwhong/rsm_rise; JM=/proj/dmfexp/zwhong/jm/rsm_rise/cache/real_cooking_v7; LP=$ROOT/runs/v7_learnproj +E=$ROOT/runs/v7_push/dino_features; rm -rf $E; mkdir -p $E/common $E/A_frozen_gem $E/B_lora_proj $E/C_frozen_proj $E/probes +L(){ mkdir -p "$(dirname "$2")"; ln -sf "$(readlink -f "$1")" "$2"; } +for f in meta.npz PACK.json proprio.f32.npy act.f32.npy seg.i16.npy edge_from.i16.npy edge_to.i16.npy goal_reached.i8.npy \ + reached_state.i16.npy reward_shaped2.f32.npy reward_shaped2_w.f32.npy reward_shaped2_group.i8.npy LABELS_SHAPED2.json; do + L $JM/$f $E/common/$f; done +L /proj/dmfexp/zwhong/jm/rsm_rise/data/derived/cooking_v7_split.json $E/common/cooking_v7_split.json +L $JM/z.f16.npy $E/A_frozen_gem/z.f16.npy; L $JM/feat_stats.npz $E/A_frozen_gem/feat_stats.npz +for v in B_lora_proj:real_cooking_v7_dinorp C_frozen_proj:real_cooking_v7_dinoproj; do n=${v%%:*}; c=${v#*:} + L $ROOT/cache/$c/z.f16.npy $E/$n/z.f16.npy; L $ROOT/cache/$c/feat_stats.npz $E/$n/feat_stats.npz; L $ROOT/cache/$c/BUILD.json $E/$n/BUILD.json; done +for r in gem_c50 gem_c50_s1 attn_c50_k0 attn_c50_k01 attn_c50_k1 attn_c50_k1_s1 attn_c50_k10 ssm_c50_k1 v2_lora_k1; do + for f in ckpt_best.pt eval.json history.json splits.json feats.f16.npy DONE; do [ -e $LP/$r/$f ] && L $LP/$r/$f $E/probes/$r/$f; done; done +cat > $E/README.md <<'R' +# cooking v7: DINO feature variants (rsm_rise, 2026-11-21) +All arrays are per frame, 188,953 frames, in the frame order of common/meta.npz (episodes contiguous: ep_from/ep_to). +State fed to successor / hop / reward head = clip((cat[z, proprio] - mu) / max(sd, 0.01), -10, 10) with that variant's +feat_stats.npz (proprio = common/proprio.f32.npy, 10-d). Split: common/cooking_v7_split.json (+ TUNE/TEST lists in rsm_rise). +- A_frozen_gem/ frozen DINOv2 ViT-S/14, square crop 224, per camera (global, wrist) [CLS 384 | GeM(p=4) patches 384] -> 1536-d. + = the deployed v7 features (successors: v7/rsm_noaug, v7/rsm_ens20). +- B_lora_proj/ DINOv2 + LoRA r16 + learned projection P (reward-trained on reward_shaped2, keep-to-GeM lam 1) -> 1536-d; + encoder weights: v7/rsm_dinorp/encoder/ (= probes/v2_lora_k1/ckpt_best.pt). Successors: v7/rsm_dinorp. +- C_frozen_proj/ frozen DINOv2 patch tokens [514 x 384] -> learned attention-pool projection P (reward-trained, lam 0) -> 1536-d; + = probes/attn_c50_k0. Successors: v7/rsm_dinoproj. +- probes/ every projection-probe arm: /ckpt_best.pt (P + reward head), eval.json (TUNE/PVAL metrics), + feats.f16.npy (that P's features for all frames, where computed). gem_c50* = GeM baseline head; + attn_c50_k{0,01,1,10} = attention pooling with keep-to-GeM lam 0 / 0.1 / 1 / 10; ssm = spatial softmax; + v2_lora_k1 = the LoRA variant (B). +- common/ labels and metadata shared by all variants (reward_shaped2 = the shaped dense reward the heads use). +Raw patch tokens (70 GB, tok.f16.npy) are NOT uploaded; regenerate with rsm_rise scripts/real/v7/relabel_shard_tok.py. +R +cd $E; find -L . -type f ! -name SHA256SUMS -print0 | sort -z | xargs -0 sha256sum > SHA256SUMS +export HF_TOKEN=$(grep -oP '^HF_TOKEN_RSM_BUCKET=\K.*' $ROOT/.env) HF_HOME=$ROOT/.hf_cache HF_HUB_DISABLE_PROGRESS_BARS=1 +cd $ROOT; /u/zwhong/.local/bin/hf buckets sync $E hf://buckets/rsm-bucket/rsm-shared/v7/dino_features +V=$ROOT/runs/v7_push/dino_features_verify; rm -rf $V; mkdir -p $V +/u/zwhong/.local/bin/hf buckets sync hf://buckets/rsm-bucket/rsm-shared/v7/dino_features $V +(cd $V && sha256sum -c SHA256SUMS --quiet) && echo VERIFY_OK || { echo VERIFY_FAIL; exit 1; } +rm -rf $V diff --git a/rsm_rise/scripts/real/v7/push/upload_dwCxn.sh b/rsm_rise/scripts/real/v7/push/upload_dwCxn.sh new file mode 100644 index 0000000000000000000000000000000000000000..f0b26f30f92e380bd7dfd8303c6169fa3ebe4f7b --- /dev/null +++ b/rsm_rise/scripts/real/v7/push/upload_dwCxn.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +#SBATCH --partition=cpu +#SBATCH --account=grp_runtime +#SBATCH --cpus-per-task=4 --mem=8G --time=01:00:00 +#SBATCH --output=/proj/dmfexp/zwhong/rsm_rise/logs/slurm/%x.%j.out +set -euo pipefail +ROOT=/proj/dmfexp/zwhong/rsm_rise; E=$ROOT/runs/v7_push/dwCxn; rm -rf $E; mkdir -p $E +for d in $ROOT/runs/v7_fairc/dw/pooled_h3_xn03/s*; do mkdir -p $E/$(basename $d); for f in $d/ckpt_s*.pt $d/config.json $d/history.json; do [ -e $f ] && ln -s $(readlink -f $f) $E/$(basename $d)/; done; done +cd $E; find -L . -type f ! -name SHA256SUMS -print0 | sort -z | xargs -0 sha256sum > SHA256SUMS +export HF_TOKEN=$(grep -oP '^HF_TOKEN_RSM_BUCKET=\K.*' $ROOT/.env) HF_HOME=$ROOT/.hf_cache HF_HUB_DISABLE_PROGRESS_BARS=1 +cd $ROOT; /u/zwhong/.local/bin/hf buckets sync $E hf://buckets/rsm-bucket/rsm-shared/v7/fair_vs_C/dinowm/pooled_h3_xn03 +V=$ROOT/runs/v7_push/dwCxn_verify; rm -rf $V; mkdir -p $V; /u/zwhong/.local/bin/hf buckets sync hf://buckets/rsm-bucket/rsm-shared/v7/fair_vs_C/dinowm/pooled_h3_xn03 $V +(cd $V && sha256sum -c SHA256SUMS --quiet) && echo VERIFY_OK; rm -rf $V diff --git a/rsm_rise/scripts/real/v7/push/upload_iqlxn.sh b/rsm_rise/scripts/real/v7/push/upload_iqlxn.sh new file mode 100644 index 0000000000000000000000000000000000000000..348920ab3610b224433ac4faf3690706c3a07be2 --- /dev/null +++ b/rsm_rise/scripts/real/v7/push/upload_iqlxn.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +#SBATCH --partition=cpu +#SBATCH --account=grp_runtime +#SBATCH --cpus-per-task=4 --mem=8G --time=01:00:00 +#SBATCH --output=/proj/dmfexp/zwhong/rsm_rise/logs/slurm/%x.%j.out +set -euo pipefail +ROOT=/proj/dmfexp/zwhong/rsm_rise; E=$ROOT/runs/v7_push/iqlxn_C; rm -rf $E; mkdir -p $E +for d in $ROOT/runs/v7_fairc/iql/iqlxn_C_s*; do mkdir -p $E/$(basename $d); for f in $d/ckpt_s*.pt $d/config.json $d/history.jsonl; do [ -e $f ] && ln -s $(readlink -f $f) $E/$(basename $d)/; done; done +cd $E; find -L . -type f ! -name SHA256SUMS -print0 | sort -z | xargs -0 sha256sum > SHA256SUMS +export HF_TOKEN=$(grep -oP '^HF_TOKEN_RSM_BUCKET=\K.*' $ROOT/.env) HF_HOME=$ROOT/.hf_cache HF_HUB_DISABLE_PROGRESS_BARS=1 +cd $ROOT; /u/zwhong/.local/bin/hf buckets sync $E hf://buckets/rsm-bucket/rsm-shared/v7/fair_vs_C/iql +V=$ROOT/runs/v7_push/iqlxn_verify; rm -rf $V; mkdir -p $V; /u/zwhong/.local/bin/hf buckets sync hf://buckets/rsm-bucket/rsm-shared/v7/fair_vs_C/iql $V +(cd $V && sha256sum -c SHA256SUMS --quiet) && echo VERIFY_OK; rm -rf $V diff --git a/rsm_rise/scripts/real/v7/race_dinowm_v7.sbatch b/rsm_rise/scripts/real/v7/race_dinowm_v7.sbatch new file mode 100644 index 0000000000000000000000000000000000000000..094edc43c4465ec7968ebcefe92f34bdaf5df948 --- /dev/null +++ b/rsm_rise/scripts/real/v7/race_dinowm_v7.sbatch @@ -0,0 +1,11 @@ +#!/usr/bin/env bash +#SBATCH --partition=gpu-mid +#SBATCH --account=grp_runtime +#SBATCH --nodes=1 +#SBATCH --gpus=8 +#SBATCH --cpus-per-task=64 +#SBATCH --mem=400G +#SBATCH --time=1-00: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 +exec /proj/dmfexp/zwhong/rsm_rise/scripts/real/v7/race_dinowm_v7.sh slurm diff --git a/rsm_rise/scripts/real/v7/race_dinowm_v7.sh b/rsm_rise/scripts/real/v7/race_dinowm_v7.sh new file mode 100644 index 0000000000000000000000000000000000000000..abd1b214e318fe641d850e95291706b92553f716 --- /dev/null +++ b/rsm_rise/scripts/real/v7/race_dinowm_v7.sh @@ -0,0 +1,26 @@ +#!/usr/bin/env bash +# COOKV7_DINOWM full run submitted to BOTH LSF and Slurm (owner 2026-11-02: "also try launching on the slurm if we +# can't get the main lsf"). First job to start takes an atomic mkdir lock in OUT and trains; the twin exits 0. +# The holder touches the lock every 60 s; a lock untouched for 15 min is STALE (holder SIGKILLed/evicted) and is taken +# over -- the trainer resumes from OUT/ckpt.pt. usage: race_dinowm_v7.sh +# env: MICRO (default 1024/NPROC = one pass per step, no grad accumulation) +set -uo pipefail +ROOT=/proj/dmfexp/zwhong/rsm_rise +sched=$1; jid=${LSB_JOBID:-${SLURM_JOB_ID:-none}} +OUT=$ROOT/runs/real_cooking_v7/wm/dinowm; lock=$OUT/.run_lock; mkdir -p "$OUT" +[ -f "$OUT/DONE" ] && { echo "[race] already DONE"; exit 0; } +if ! mkdir "$lock" 2>/dev/null; then + if [ -z "$(find "$lock" -maxdepth 1 -mmin -15 2>/dev/null)" ]; then + echo "[race] STALE lock ($(cat $lock/owner 2>/dev/null)); $sched job $jid takes over" + rm -rf "$lock"; mkdir "$lock" || { echo "[race] lost the re-lock race"; exit 0; } + else + echo "[race] lock held by $(cat $lock/owner 2>/dev/null); $sched job $jid exits without training"; exit 0 + fi +fi +NPROC=$(nvidia-smi -L | wc -l) +MICRO=${MICRO:-$(( 1024 / NPROC ))} +echo "$sched $jid $(hostname) $(date -u +%FT%TZ) nproc=$NPROC micro=$MICRO" > $lock/owner +( while sleep 60; do touch "$lock/owner"; done ) & HB=$! +trap 'kill $HB 2>/dev/null; rm -rf "$lock"' EXIT +echo "[race] $sched job $jid won the lock: $(cat $lock/owner)" +OUT=$OUT NPROC=$NPROC CHUNK=50 bash $ROOT/scripts/real/v7/train_dinowm_v7.sh --micro "$MICRO" diff --git a/rsm_rise/scripts/real/v7/relabel_shard_tok.py b/rsm_rise/scripts/real/v7/relabel_shard_tok.py new file mode 100644 index 0000000000000000000000000000000000000000..5f0bb8f94d212e27d41fda670673d7b1aaa97847 --- /dev/null +++ b/rsm_rise/scripts/real/v7/relabel_shard_tok.py @@ -0,0 +1,66 @@ +#!/usr/bin/env python +"""COOKV7_DINOWM: sharded DINO encode of rsm_cooking_v7 that ALSO dumps patch tokens. + +Copy of scripts/real/v6/relabel_shard.py (v6 untouched). Same encoder / transform / decode as +scripts/real/relabel_dino_lerobot.py; one dinov2_vits14 forward per frame yields BOTH + _shards/ep__.f32.npy pooled [L,768] fp32 = [CLS | GeM(patches)] (byte-identical maths to + relabel_dino_lerobot.encode_u8, so relabel_merge.py builds z.f16.npy + exactly as for v6) + _shards/ep__.tok.f16.npy tokens [L,257,384] fp16 = [CLS, 256 patches row-major 16x16] + (x_norm_clstoken / x_norm_patchtokens, same fp32 forward) +Episodes i with i % nshard == shard. Skips episodes whose both files exist (resumable). +""" +import argparse, json, sys, time +from pathlib import Path +import numpy as np, torch +sys.path.insert(0, "/proj/dmfexp/zwhong/rsm_rise/scripts/real") +import relabel_dino_lerobot as R + +ap = argparse.ArgumentParser() +ap.add_argument("--root", required=True); ap.add_argument("--out", required=True) +ap.add_argument("--shard", type=int, required=True); ap.add_argument("--nshard", type=int, required=True) +ap.add_argument("--cams", default="global,wrist"); ap.add_argument("--crop-mode", default="square") +ap.add_argument("--batch", type=int, default=256) +a = ap.parse_args() +root = Path(a.root); sd = Path(a.out) / "_shards"; sd.mkdir(parents=True, exist_ok=True) +info = json.loads((root / "meta/info.json").read_text()) +n_ep, cs, dp, vp_t = int(info["total_episodes"]), int(info["chunks_size"]), info["data_path"], info["video_path"] +import pyarrow.parquet as pq +dev = "cuda" +model = R.load_dino(dev); tf = R.DinoTransform(a.crop_mode).to(dev) +cams = a.cams.split(",") + + +@torch.no_grad() +def encode_u8_tok(imgs_u8, batch): + """Same maths as R.encode_u8, plus the raw [CLS|patches] tokens.""" + pooled, toks = [], [] + for i in range(0, len(imgs_u8), batch): + x = torch.from_numpy(np.ascontiguousarray(imgs_u8[i:i + batch])).to(dev) + x = x.float().div_(255.0).clamp_(0.0, 1.0).permute(0, 3, 1, 2) + x = tf(x) + f = model.forward_features(x) + cls, pt = f["x_norm_clstoken"], f["x_norm_patchtokens"] + assert pt.shape[1] == R.N_PATCH and pt.shape[2] == R.D_TOK, pt.shape + pooled.append(torch.cat([cls, R.gem_pool(pt)], -1).float().cpu()) + toks.append(torch.cat([cls[:, None], pt], 1).half().cpu()) + return torch.cat(pooled).numpy(), torch.cat(toks).numpy() + + +mine = [i for i in range(n_ep) if i % a.nshard == a.shard] +t0 = time.time(); nf = 0 +for k, i in enumerate(mine): + L = pq.read_metadata(root / dp.format(episode_chunk=i // cs, episode_index=i)).num_rows + for c in cams: + f = sd / f"ep_{i:06d}_{c}.f32.npy"; ft = sd / f"ep_{i:06d}_{c}.tok.f16.npy" + if f.exists() and ft.exists(): + continue + vp = root / vp_t.format(episode_chunk=i // cs, video_key=R.CAM_KEYS[c], episode_index=i) + imgs = R.decode_mp4(vp, expect=L) + z, tok = encode_u8_tok(imgs, a.batch) + assert z.shape == (L, 768) and tok.shape == (L, 257, 384), (z.shape, tok.shape) + np.save(str(ft) + ".tmp.npy", tok); Path(str(ft) + ".tmp.npy").rename(ft) + np.save(str(f) + ".tmp.npy", z); Path(str(f) + ".tmp.npy").rename(f) + nf += L + print(f"[shard {a.shard}] {k+1}/{len(mine)} eps, {nf} frames, {nf/(time.time()-t0):.0f} f/s", flush=True) +print(f"[shard {a.shard}] DONE {len(mine)} eps in {time.time()-t0:.0f}s", flush=True) diff --git a/rsm_rise/scripts/real/v7/restore_code_snapshot.sh b/rsm_rise/scripts/real/v7/restore_code_snapshot.sh new file mode 100644 index 0000000000000000000000000000000000000000..203be48b9742d3f6bfb2ded8240d2d1810562687 --- /dev/null +++ b/rsm_rise/scripts/real/v7/restore_code_snapshot.sh @@ -0,0 +1,15 @@ +#!/usr/bin/env bash +# COOKV7_DINOWM: rebuild a PRIVATE pinned copy of the archived gen_q_rsm worktree (rsm_rise_data @462db4a + +# its uncommitted.patch + small.tar.zst) under rsm_rise/code/gen_q_rsm_snap_20261030. Does NOT touch the gen_q +# git repo (no worktree add): uses `git archive` (read-only) and plain tar/patch. +set -euo pipefail +G=/proj/dmfexp/zwhong/projs/issue_resolver_richardrl/gen_q +A=/archive/dmfexp/zwhong/worktrees_20261030/projs/issue_resolver_richardrl/gen_q_rsm +D=/proj/dmfexp/zwhong/rsm_rise/code/gen_q_rsm_snap_20261030 +[ -f $D/RESTORED_OK ] && { echo "already restored"; exit 0; } +rm -rf $D.tmp; mkdir -p $D.tmp +git -C $G archive 462db4a0e4cd377f3f2e13528ee39ed4365673e1 | tar -x -C $D.tmp +cd $D.tmp && git apply --binary --unsafe-paths --directory=. $A/uncommitted.patch 2>&1 || patch -p1 < $A/uncommitted.patch +tar -C $D.tmp -xf $A/small.tar.zst --zstd +ls $D.tmp/rsm_libero/train_rsm_dwm.py +mv $D.tmp $D; date -u > $D/RESTORED_OK; echo "[restore] OK $(du -sh $D | cut -f1)" diff --git a/rsm_rise/scripts/real/v7/reward2/eval_reward2.py b/rsm_rise/scripts/real/v7/reward2/eval_reward2.py new file mode 100644 index 0000000000000000000000000000000000000000..f545844619c0d290dc66be800fff64274d35c524 --- /dev/null +++ b/rsm_rise/scripts/real/v7/reward2/eval_reward2.py @@ -0,0 +1,228 @@ +#!/usr/bin/env python +"""V7_REWARD2 step 2b: held-out evaluation of the shaped action-conditioned reward heads (train_reward2.py) vs the +old R-progress head (progress_augc_h50_ps_s0 'rew', r = sigmoid(R/25)), plus a chain_ar scorer smoke test. +Selection: lowest TUNE weighted Huber among ACTION-conditioned runs (act != none). TEST reported once. +Writes status/real/v7_reward2_eval.{json,md}.""" +import json, sys, time, os +from pathlib import Path +import numpy as np +import torch, torch.nn.functional as F +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import rsm_scorer_ar as AR +from scipy.stats import spearmanr, rankdata + +JM = Path("/proj/dmfexp/zwhong/jm/rsm_rise"); C = JM / "cache/real_cooking_v7" +RUNS = Path("/proj/dmfexp/zwhong/rsm_rise/runs/v7_reward2") +OUT = Path("/proj/dmfexp/zwhong/rsm_rise/status/real") +SUCC = JM / "export/v7/rsm_ens20/progress_augc_h50_ps_s0/ckpt_s20000.pt" +HOP = JM / "export/v7/hop/gauss_h50_ps_s1/policy_s120000.pt" +FS = JM / "export/v7/rsm_ens20/feat_stats.npz" +torch.set_num_threads(int(os.environ.get("SLURM_CPUS_PER_TASK", "8"))) +rng = np.random.default_rng(0) + + +def auc(s, y): + s, y = np.asarray(s, float), np.asarray(y, bool); P, N = y.sum(), (~y).sum() + if P == 0 or N == 0: return None + r = rankdata(s); return float((r[y].sum() - P * (P + 1) / 2) / (P * N)) + + +def sp(a, b): return float(spearmanr(a, b).correlation) + + +# ------------------------------------------------------------------ data +st = np.load(FS); mu = st["mu"].astype(np.float32); sd = np.maximum(st["sd"].astype(np.float32), float(st["sd_floor"])) +zc = float(st["z_clip"]) +z = np.load(C / "z.f16.npy", mmap_mode="r"); pr = np.load(C / "proprio.f32.npy", mmap_mode="r") +act_raw = np.load(C / "act.f32.npy") +meta = np.load(C / "meta.npz"); ef, et = meta["ep_from"], meta["ep_to"]; n_ep = len(ef) +y = np.load(C / "reward_shaped2.f32.npy"); grp = np.load(C / "reward_shaped2_group.i8.npy") +efr, eto = np.load(C / "edge_from.i16.npy"), np.load(C / "edge_to.i16.npy"); seg = np.load(C / "seg.i16.npy") +split = json.load(open(JM / "data/derived/cooking_v7_split.json"))["episodes"] +tt = json.load(open(JM / "data/derived/cooking_v7_tune_test.json")) +fin = np.array([int(split[str(i)]["final_state"]) for i in range(n_ep)]) +train_eps = [i for i in range(n_ep) if split[str(i)]["split"] == "train"] +SETS = {"TUNE": sorted(tt["tune"]), "TEST": sorted(tt["test"])} +SETS["HELDOUT"] = sorted(SETS["TUNE"] + SETS["TEST"]) +SETS["TRAIN40"] = sorted(rng.choice(train_eps, 40, replace=False).tolist()) # in-sample reference +need = sorted(set(sum(SETS.values(), []))) +rows = np.concatenate([np.arange(ef[e], et[e]) for e in need]); pos = {r: i for i, r in enumerate(rows)} +X = np.clip((np.concatenate([np.asarray(z[rows], np.float32), np.asarray(pr[rows], np.float32)], 1) - mu) / sd, -zc, zc) +X = torch.from_numpy(X.astype(np.float32)) +row_ep = np.repeat(np.arange(n_ep), et - ef) + + +def chunk_raw(rr, CL=50): + fr = np.minimum(rr[:, None] + np.arange(CL)[None], et[row_ep[rr]][:, None] - 1) + return torch.from_numpy(act_raw[fr].reshape(len(rr), -1).astype(np.float32)) + + +A_log = chunk_raw(rows) # raw logged chunk [R, 500] + +# ------------------------------------------------------------------ old head (state-only, sigmoid(R/25)) +ck = torch.load(SUCC, map_location="cpu", weights_only=False); sdh = ck["rew"] +lin = sorted({int(k.split(".")[1]) for k in sdh if k.startswith("net.")}) +Ws = [(sdh[f"net.{i}.weight"].float(), sdh[f"net.{i}.bias"].float()) for i in lin] +temb = sdh["task.weight"][0].float() if "task.weight" in sdh else \ + F.linear(sdh["task.E"][0].float(), sdh["task.proj.weight"].float(), sdh["task.proj.bias"].float()) + + +@torch.no_grad() +def old_head(x): + h = torch.cat([x, temb.expand(len(x), -1)], -1) + for j, (W, b) in enumerate(Ws): + h = F.linear(h, W, b); h = F.silu(h) if j < len(Ws) - 1 else h + return torch.sigmoid(h.squeeze(-1) / 25.0) + + +def batched(fn, *ts, bs=8192): + return torch.cat([fn(*[t[i:i + bs] for t in ts]) for i in range(0, len(ts[0]), bs)]).numpy() + + +# ------------------------------------------------------------------ metrics +def metrics(pred_all): + out = {} + for nm, eps in SETS.items(): + rr = np.concatenate([np.arange(ef[e], et[e]) for e in eps]); ix = np.array([pos[r] for r in rr]) + p, lab, g = pred_all[ix], y[rr], grp[rr] + m = {"n_eps": len(eps), "frames": int(len(rr)), "spearman_vs_label": sp(p, lab), + "frame_auc_G7_vs_FAIL": auc(p[g != 0], g[g != 0] == 1), + "frame_auc_nonfail_vs_FAIL": auc(p, g != 2)} + pr_ = {} + for rt in sorted(set(meta["ep_route"][eps].tolist())): + es = [e for e in eps if meta["ep_route"][e] == rt] + r2 = np.concatenate([np.arange(ef[e], et[e]) for e in es]); i2 = np.array([pos[r] for r in r2]) + pr_[str(meta["ep_path"][es[0]])] = {"n": len(es), "pred_mean": float(pred_all[i2].mean()), + "label_mean": float(y[r2].mean()), + "pred_last50": float(np.mean([pred_all[[pos[r] for r in range(et[e] - 50, et[e])]].mean() for e in es]))} + m["per_route"] = pr_ + for K in (50, 150, "all"): + sc = [] + for e in eps: + lo = ef[e] if K == "all" else max(ef[e], et[e] - K) + sc.append(pred_all[[pos[r] for r in range(lo, et[e])]].mean()) + sc = np.array(sc); f = fin[eps] + for dn, (S, Fl) in {"goal7": ({7}, {5, 6}), "prog": ({3, 8, 7}, {5, 6})}.items(): + k = np.isin(f, list(S | Fl)) + m[f"ep_auc_{dn}_last{K}"] = auc(sc[k], np.isin(f[k], list(S))) + m[f"n_{dn}"] = [int(np.isin(f, list(S)).sum()), int(np.isin(f, list(Fl)).sum())] + # branch point: segments FROM state 2, 2->3 (pos) vs 2->6 (neg); first K frames of the segment + br = {} + for K in (25, 50, 150): + sc, lab_s, yl, fr_p, fr_y = [], [], [], [], [] + for e in eps: + a0 = ef[e]; s_ = seg[a0:et[e]] + for kk in np.unique(s_): + ii = a0 + np.where(s_ == kk)[0] + if efr[ii[0]] != 2 or eto[ii[0]] not in (3, 6): continue + ii = ii[:K]; pp = pred_all[[pos[r] for r in ii]] + sc.append(pp.mean()); lab_s.append(eto[ii[0]] == 3); yl.append(y[ii].mean()) + fr_p += pp.tolist(); fr_y += [eto[ii[0]] == 3] * len(ii) + br[f"first{K}"] = {"n_23": int(np.sum(lab_s)), "n_26": int(len(lab_s) - np.sum(lab_s)), + "ep_auc": auc(sc, lab_s), "frame_auc": auc(fr_p, fr_y), + "label_ep_auc": auc(yl, lab_s), + "mean_23": float(np.mean([s for s, l in zip(sc, lab_s) if l])) if np.sum(lab_s) else None, + "mean_26": float(np.mean([s for s, l in zip(sc, lab_s) if not l])) if len(lab_s) > np.sum(lab_s) else None} + m["branch_2to3_vs_2to6"] = br + out[nm] = m + return out + + +res = {"selection_rule": "lowest TUNE weighted Huber (ckpt_best) among runs with act != none", "runs": {}} +old = batched(old_head, X); res["old_head"] = metrics(old) +print("[eval] old head done", flush=True) +cands = [] +for d in sorted(RUNS.glob("*/history.json")): + h = json.load(open(d)); name = d.parent.name; b = h["best"] + head = AR.ActRewardHead(d.parent / "ckpt_best.pt") + p = batched(lambda x, a: head(x, a), X, A_log) + res["runs"][name] = {"config": h["config"], "best_tune": b, "logged_action": metrics(p)} + if h["config"]["act"] != "none": + cands.append((b["tune_whuber"], name)) + print("[eval] run", name, "tune_whuber", round(b["tune_whuber"], 4), flush=True) +sel = min(cands)[1]; res["selected"] = sel +print("[eval] selected", sel, flush=True) + +# ------------------------------------------------------------------ hop actions (what the planner feeds r2) +m = AR._load_rsm_scorer() +hop, _ = m.load_hop_head(str(HOP), X.shape[1], 1, "cpu", feat_sd=sd) +head = AR.ActRewardHead(RUNS / sel / "ckpt_best.pt") +tk = lambda n: torch.zeros(n, dtype=torch.long) +with torch.no_grad(): + A_mean = torch.cat([hop.sample_eps(X[i:i + 8192], tk(len(X[i:i + 8192])), torch.zeros(len(X[i:i + 8192]), hop.d_act)) + for i in range(0, len(X), 8192)]) + g = torch.Generator().manual_seed(1) + A_smp = torch.cat([hop.sample_eps(X[i:i + 8192], tk(len(X[i:i + 8192])), + torch.randn(len(X[i:i + 8192]), hop.d_act, generator=g)) for i in range(0, len(X), 8192)]) +res["selected_hop_mean_action"] = metrics(batched(lambda x, a: head(x, a), X, A_mean)) +res["selected_hop_sample_action"] = metrics(batched(lambda x, a: head(x, a), X, A_smp)) +# action sensitivity on held-out states: within-state sd over 16 hop samples vs across-state sd +ho = np.concatenate([np.arange(ef[e], et[e]) for e in SETS["HELDOUT"]]); pick = rng.choice(ho, 512, replace=False) +ix = torch.tensor([pos[r] for r in pick]); xs = X[ix] +with torch.no_grad(): + vals = torch.stack([head(xs, hop.sample_eps(xs, tk(len(xs)), torch.randn(len(xs), hop.d_act, generator=g))) + for _ in range(16)], 1).numpy() + v_log = head(xs, A_log[ix]).numpy() +res["action_sensitivity"] = {"n_states": 512, "within_state_sd_mean": float(vals.std(1).mean()), + "across_state_sd": float(vals.mean(1).std()), + "logged_minus_hopmean_abs_mean": float(np.abs(v_log - vals.mean(1)).mean())} +print("[eval] hop-action metrics done", json.dumps(res["action_sensitivity"]), flush=True) + +# ------------------------------------------------------------------ chain_ar scorer smoke (CPU, 4 TUNE states) +smoke = {} +try: + t0 = time.time() + kw = dict(backend="mlp", ckpt=str(SUCC), hop_ckpt=str(HOP), state=None, mode="chain", beta=0.99, gamma=0.995, + n_particles=16, score_kind="prob", temperature=25.0, chain_tail_eps=1e-3, device="cpu") + from types import SimpleNamespace + kw["state"] = SimpleNamespace(d=X.shape[1], sd=torch.from_numpy(sd).float(), normalize=None) + sc_ar = AR.build_rsm_scorer_ar(str(RUNS / sel / "ckpt_best.pt"), **kw) + sc_old = m.RSMScorer(**kw) + tune_rows = np.concatenate([np.arange(ef[e], et[e]) for e in SETS["TUNE"]]) + st_rows = rng.choice(tune_rows, 4, replace=False) + for r in st_rows: + x = X[pos[r]][None] + with torch.no_grad(): + A = torch.cat([A_log[pos[r]][None], hop.sample_eps(x.expand(15, -1), tk(15), torch.randn(15, hop.d_act, generator=g))]) + qa = sc_ar.score(x, A, seed=0); qa = np.asarray(sc_ar.last_q.cpu(), float) + qo = sc_old.score(x, A, seed=0); qo = np.asarray(sc_old.last_q.cpu(), float) + smoke[int(r)] = {"route": str(meta["ep_path"][row_ep[r]]), "label": float(y[r]), + "q_ar": qa.round(4).tolist(), "q_old_prob": qo.round(4).tolist(), + "finite": bool(np.isfinite(qa).all()), "spearman_ar_vs_old": sp(qa, qo), + "chain_stats": {k: v for k, v in (sc_ar.backend.last_chain_stats or {}).items() + if k in ("hops_mean", "capped_frac", "cap", "p_cont", "goal_action")}} + smoke["sec"] = time.time() - t0 +except Exception as e: + import traceback; traceback.print_exc(); smoke["error"] = repr(e) +res["scorer_smoke"] = smoke +json.dump(res, open(OUT / "v7_reward2_eval.json", "w"), indent=1, default=float) + + +# ------------------------------------------------------------------ md +def row(nm, M): + def f(v): return "nan" if v is None else f"{v:.3f}" + return (f"| {nm} | {f(M['spearman_vs_label'])} | {f(M['frame_auc_G7_vs_FAIL'])} | {f(M['ep_auc_goal7_last150'])} | " + f"{f(M['ep_auc_prog_last150'])} | {f(M['branch_2to3_vs_2to6']['first50']['ep_auc'])} " + f"(n {M['branch_2to3_vs_2to6']['first50']['n_23']}/{M['branch_2to3_vs_2to6']['first50']['n_26']}) | " + f"{f(M['branch_2to3_vs_2to6']['first50']['frame_auc'])} |") + + +L = [f"# V7_REWARD2 held-out eval (selected: {sel})", "", + "Columns: Spearman(pred, shaped label) | frame AUC G7-vs-FAIL | episode AUC goal7 (last150) | episode AUC prog (last150) |" + " branch 2->3 vs 2->6 episode AUC, first 50 frames of the segment from 2 | same, frame AUC", ""] +for split_nm in ("TUNE", "TEST", "HELDOUT", "TRAIN40"): + L += [f"## {split_nm}", "", "| head | spearman | fAUC G7/F | AUC goal7 | AUC prog | branch epAUC | branch fAUC |", + "|---|---|---|---|---|---|---|", row("OLD R-progress sigmoid(R/25)", res["old_head"][split_nm])] + for nm, rr in res["runs"].items(): + L.append(row(nm + (" **(sel)**" if nm == sel else ""), rr["logged_action"][split_nm])) + L.append(row(sel + " hop-mean action", res["selected_hop_mean_action"][split_nm])) + L.append(row(sel + " hop-sample action", res["selected_hop_sample_action"][split_nm])) + L.append("") +L += ["## per-route mean predicted reward (HELDOUT, selected, logged action) vs label mean; old head prob", "", + "| route | n | pred | label | pred last50 | old prob |", "|---|---|---|---|---|---|"] +for k, v in res["runs"][sel]["logged_action"]["HELDOUT"]["per_route"].items(): + o = res["old_head"]["HELDOUT"]["per_route"][k] + L.append(f"| {k} | {v['n']} | {v['pred_mean']:.3f} | {v['label_mean']:.3f} | {v['pred_last50']:.3f} | {o['pred_mean']:.3f} |") +L += ["", "action sensitivity: " + json.dumps(res["action_sensitivity"]), "", "scorer smoke: " + json.dumps(smoke)[:3000]] +open(OUT / "v7_reward2_eval.md", "w").write("\n".join(L) + "\n") +print("\n".join(L)) diff --git a/rsm_rise/scripts/real/v7/reward2/eval_reward2_cmp.py b/rsm_rise/scripts/real/v7/reward2/eval_reward2_cmp.py new file mode 100644 index 0000000000000000000000000000000000000000..83dff124f60b34fae67231746e7bd158f1d943fe --- /dev/null +++ b/rsm_rise/scripts/real/v7/reward2/eval_reward2_cmp.py @@ -0,0 +1,103 @@ +"""V7_REWARD2 run 2: (a) re-score every reward head on ONE common TUNE criterion -- the group-balanced weighted Huber +(weights of LABELS_SHAPED2: PROG 0.484, G7 4.24, FAIL 1.44), because history.json's 'tune_whuber' used each run's OWN +weights (unit weights for c50_unw), which made run-1's selection compare unlike quantities; (b) per-group MAE on +TUNE/TEST; (c) chain_ar scorer smoke (fixed stats schema) for c50_bal_s0, c50_bal_s1, c50_unw. +Writes status/real/v7_reward2_cmp.{json,md}.""" +import json, os, sys, time +from pathlib import Path +import numpy as np, torch +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import rsm_scorer_ar as AR +from scipy.stats import spearmanr + +JM = Path("/proj/dmfexp/zwhong/jm/rsm_rise"); C = JM / "cache/real_cooking_v7" +RUNS = Path("/proj/dmfexp/zwhong/rsm_rise/runs/v7_reward2"); OUT = Path("/proj/dmfexp/zwhong/rsm_rise/status/real") +SUCC = JM / "export/v7/rsm_ens20/progress_augc_h50_ps_s0/ckpt_s20000.pt" +HOP = JM / "export/v7/hop/gauss_h50_ps_s1/policy_s120000.pt" +FS = JM / "export/v7/rsm_ens20/feat_stats.npz" +torch.set_num_threads(int(os.environ.get("SLURM_CPUS_PER_TASK", "8"))) +st = np.load(FS); mu = st["mu"].astype(np.float32); sd = np.maximum(st["sd"].astype(np.float32), float(st["sd_floor"])) +zc = float(st["z_clip"]) +z = np.load(C / "z.f16.npy", mmap_mode="r"); pr = np.load(C / "proprio.f32.npy", mmap_mode="r") +act_raw = np.load(C / "act.f32.npy", mmap_mode="r") +meta = np.load(C / "meta.npz"); ef, et = meta["ep_from"], meta["ep_to"]; n_ep = len(ef) +y = np.load(C / "reward_shaped2.f32.npy"); grp = np.load(C / "reward_shaped2_group.i8.npy") +LW = json.load(open(C / "LABELS_SHAPED2.json"))["weights"] +GW = np.array([LW["PROG(->1/2/3/8)"], LW["G7(->7)"], LW["FAIL(->5/6)"]], np.float32) +tt = json.load(open(JM / "data/derived/cooking_v7_tune_test.json")) +SETS = {"TUNE": sorted(tt["tune"]), "TEST": sorted(tt["test"])} +row_ep = np.repeat(np.arange(n_ep), et - ef) +res = {"criterion": "TUNE group-balanced weighted Huber(delta 1), weights " + json.dumps(LW), "runs": {}} +data = {} +for nm, eps in SETS.items(): + rr = np.concatenate([np.arange(ef[e], et[e]) for e in eps]) + X = np.clip((np.concatenate([np.asarray(z[rr], np.float32), np.asarray(pr[rr], np.float32)], 1) - mu) / sd, -zc, zc) + fr = np.minimum(rr[:, None] + np.arange(50)[None], et[row_ep[rr]][:, None] - 1) + A = np.asarray(act_raw[fr.ravel()], np.float32).reshape(len(rr), -1) + data[nm] = (torch.from_numpy(X), torch.from_numpy(A), y[rr], grp[rr]) +for d in sorted(RUNS.glob("*/history.json")): + name = d.parent.name; head = AR.ActRewardHead(d.parent / "ckpt_best.pt"); r = {} + for nm, (X, A, lab, g) in data.items(): + with torch.no_grad(): + p = torch.cat([head(X[i:i + 8192], A[i:i + 8192]) for i in range(0, len(X), 8192)]).numpy() + e = p - lab; ae = np.abs(e); hub = np.where(ae < 1, 0.5 * e * e, ae - 0.5); w = GW[g] + r[nm] = {"whuber_bal": float((hub * w).sum() / w.sum()), "huber": float(hub.mean()), + "mae_PROG": float(ae[g == 0].mean()), "mae_G7": float(ae[g == 1].mean()), + "mae_FAIL": float(ae[g == 2].mean()), "mae_goal_frames": float(ae[lab >= 9.999].mean()), + "bias_G7": float(e[g == 1].mean()), "spearman": float(spearmanr(p, lab).correlation)} + res["runs"][name] = {"act": json.load(open(d))["config"]["act"], + "weights": json.load(open(d))["config"]["weights"], **r} + print("[cmp]", name, json.dumps(r["TUNE"]), flush=True) +cands = sorted((v["TUNE"]["whuber_bal"], k) for k, v in res["runs"].items() if v["act"] != "none") +res["ranking_tune"] = cands; res["selected_common_criterion"] = cands[0][1] +print("[cmp] ranking", cands, flush=True) + +# ---- chain_ar smoke +m = AR._load_rsm_scorer() +from types import SimpleNamespace +kw = dict(backend="mlp", ckpt=str(SUCC), hop_ckpt=str(HOP), mode="chain", beta=0.99, gamma=0.995, + n_particles=16, score_kind="prob", temperature=25.0, chain_tail_eps=1e-3, device="cpu", + state=SimpleNamespace(d=data["TUNE"][0].shape[1], sd=torch.from_numpy(sd).float(), normalize=None)) +smoke = {} +X, A, lab, g = data["TUNE"] +rng = np.random.default_rng(0); pick = rng.choice(len(X), 6, replace=False) +hop, _ = m.load_hop_head(str(HOP), X.shape[1], 1, "cpu", feat_sd=sd) +gen = torch.Generator().manual_seed(0) +sc_old = m.RSMScorer(**kw) +for hn in ("c50_bal_s0", "c50_bal_s1", "c50_unw"): + try: + t0 = time.time(); sc = AR.build_rsm_scorer_ar(str(RUNS / hn / "ckpt_best.pt"), **kw); out = [] + for i in pick: + x = X[i][None] + with torch.no_grad(): + Ac = torch.cat([A[i][None], hop.sample_eps(x.expand(15, -1), torch.zeros(15, dtype=torch.long), + torch.randn(15, hop.d_act, generator=gen))]) + sc.score(x, Ac, seed=0); qa = np.asarray(sc.last_q.cpu(), float) + sc_old.score(x, Ac, seed=0); qo = np.asarray(sc_old.last_q.cpu(), float) + out.append({"label": float(lab[i]), "group": int(g[i]), "q_ar_mean": float(qa.mean()), + "q_ar_range": float(qa.max() - qa.min()), "q_old_mean": float(qo.mean()), + "finite": bool(np.isfinite(qa).all()), + "spearman_ar_vs_old": float(spearmanr(qa, qo).correlation)}) + smoke[hn] = {"states": out, "sec": time.time() - t0, "chain_hops": sc.chain_hop_summary(), + "all_finite": all(o["finite"] for o in out), + "corr_qar_vs_label": float(spearmanr([o["q_ar_mean"] for o in out], [o["label"] for o in out]).correlation)} + print("[cmp] smoke", hn, "ok", round(time.time() - t0, 1), "s", flush=True) + except Exception as e: + import traceback; traceback.print_exc(); smoke[hn] = {"error": repr(e)} +res["scorer_smoke"] = smoke +json.dump(res, open(OUT / "v7_reward2_cmp.json", "w"), indent=1, default=float) +f = lambda v: f"{v:.4f}" +L = ["# V7_REWARD2 reward-head comparison on a common TUNE criterion", "", res["criterion"], "", + "| run | act | w | TUNE wHuber_bal | TUNE Huber | TUNE MAE PROG/G7/FAIL | TUNE MAE goal frames | TEST wHuber_bal | TEST MAE G7 | TEST spearman |", + "|---|---|---|---|---|---|---|---|---|---|"] +for k, v in sorted(res["runs"].items(), key=lambda kv: kv[1]["TUNE"]["whuber_bal"]): + T, S = v["TUNE"], v["TEST"] + L.append(f"| {k} | {v['act']} | {v['weights']} | {f(T['whuber_bal'])} | {f(T['huber'])} | {f(T['mae_PROG'])}/{f(T['mae_G7'])}/{f(T['mae_FAIL'])} | " + f"{f(T['mae_goal_frames'])} | {f(S['whuber_bal'])} | {f(S['mae_G7'])} | {S['spearman']:.4f} |") +L += ["", f"selected (common criterion, act != none): **{res['selected_common_criterion']}**", "", "## chain_ar scorer smoke", ""] +for hn, s in smoke.items(): + if "error" in s: L.append(f"- {hn}: ERROR {s['error']}"); continue + L.append(f"- {hn}: all finite {s['all_finite']}, {s['sec']:.1f}s, Spearman(Q_ar mean, label) over 6 states " + f"{s['corr_qar_vs_label']:.3f}; per state (label, Q_ar mean, Q_ar range over 16 cands, rho vs old): " + + "; ".join(f"({o['label']:.2f}, {o['q_ar_mean']:.2f}, {o['q_ar_range']:.3f}, {o['spearman_ar_vs_old']:.2f})" for o in s["states"])) +open(OUT / "v7_reward2_cmp.md", "w").write("\n".join(L) + "\n"); print("\n".join(L)) diff --git a/rsm_rise/scripts/real/v7/reward2/iql_payloads/cooking_v7_rw_RSHAPED2__S0AidqlPSt09__s0.sh b/rsm_rise/scripts/real/v7/reward2/iql_payloads/cooking_v7_rw_RSHAPED2__S0AidqlPSt09__s0.sh new file mode 100644 index 0000000000000000000000000000000000000000..e44f39fe8bac1dece74a1206e38fbd85320a45f4 --- /dev/null +++ b/rsm_rise/scripts/real/v7/reward2/iql_payloads/cooking_v7_rw_RSHAPED2__S0AidqlPSt09__s0.sh @@ -0,0 +1,16 @@ +#!/usr/bin/env bash +ROOT=/proj/dmfexp/zwhong/jm/rsm_rise +source /proj/dmfexp/zwhong/rsm_rise/wandb_env.sh +export RSM_HDF5_FILTER_KEY=train # plan split: mask/train only (TUNE/TEST = mask/valid held out) +if ls $ROOT/runs/cooking_v7_rw_RSHAPED2/policy/S0AidqlPSt09_seed0/*/*/models/model_epoch_5000.pth >/dev/null 2>&1; then + echo "[v7iql] SKIP cooking_v7_rw_RSHAPED2 S0AidqlPSt09 s0 -- epoch 5000 exists"; exit 0; fi +echo "[v7iql] RUN cooking_v7_rw_RSHAPED2 S0AidqlPSt09 s0 $(date -u) host=$(hostname) gpu=${CUDA_VISIBLE_DEVICES:-?}" +RSM_NUM_DATA_WORKERS=${RSM_NUM_DATA_WORKERS:-0} bash /proj/dmfexp/zwhong/rsm_rise/scripts/real/v7/reward2/run_train_r2.sh cooking_v7_rw_RSHAPED2 S0AidqlPSt09 0 \ + training.spectral_norm_policy=False training.policy_bottleneck_beta=0.0 \ + training.action_augmentation=False training.advanced_augmentation=False \ + training.critic_only=True training.vf_quantile=0.9 training.num_epochs=5000 exp.save_interval=1250 training.cache_mode=all +rc=$? +cfg=$(ls -t $ROOT/runs/cooking_v7_rw_RSHAPED2/policy/S0AidqlPSt09_seed0/*/*/config.json 2>/dev/null | head -1) +got=$(python3 -c "import json,sys;c=json.load(open(sys.argv[1]));a=c['algo'];print(a['vf_quantile'],a.get('critic_only'),c['train']['hdf5_filter_key'])" "$cfg" 2>/dev/null) +[ "$got" = "0.9 True train" ] || { echo "[v7iql] FATAL config says '$got' (want '0.9 True train') $cfg"; exit 90; } +echo "[v7iql] config OK $got rc=$rc"; exit $rc diff --git a/rsm_rise/scripts/real/v7/reward2/iql_payloads/cooking_v7_rw_RSHAPED2__S0AidqlPSt09__s1.sh b/rsm_rise/scripts/real/v7/reward2/iql_payloads/cooking_v7_rw_RSHAPED2__S0AidqlPSt09__s1.sh new file mode 100644 index 0000000000000000000000000000000000000000..4b182a05842de680d524edb520726853ea044c21 --- /dev/null +++ b/rsm_rise/scripts/real/v7/reward2/iql_payloads/cooking_v7_rw_RSHAPED2__S0AidqlPSt09__s1.sh @@ -0,0 +1,16 @@ +#!/usr/bin/env bash +ROOT=/proj/dmfexp/zwhong/jm/rsm_rise +source /proj/dmfexp/zwhong/rsm_rise/wandb_env.sh +export RSM_HDF5_FILTER_KEY=train # plan split: mask/train only (TUNE/TEST = mask/valid held out) +if ls $ROOT/runs/cooking_v7_rw_RSHAPED2/policy/S0AidqlPSt09_seed1/*/*/models/model_epoch_5000.pth >/dev/null 2>&1; then + echo "[v7iql] SKIP cooking_v7_rw_RSHAPED2 S0AidqlPSt09 s1 -- epoch 5000 exists"; exit 0; fi +echo "[v7iql] RUN cooking_v7_rw_RSHAPED2 S0AidqlPSt09 s1 $(date -u) host=$(hostname) gpu=${CUDA_VISIBLE_DEVICES:-?}" +RSM_NUM_DATA_WORKERS=${RSM_NUM_DATA_WORKERS:-0} bash /proj/dmfexp/zwhong/rsm_rise/scripts/real/v7/reward2/run_train_r2.sh cooking_v7_rw_RSHAPED2 S0AidqlPSt09 1 \ + training.spectral_norm_policy=False training.policy_bottleneck_beta=0.0 \ + training.action_augmentation=False training.advanced_augmentation=False \ + training.critic_only=True training.vf_quantile=0.9 training.num_epochs=5000 exp.save_interval=1250 training.cache_mode=all +rc=$? +cfg=$(ls -t $ROOT/runs/cooking_v7_rw_RSHAPED2/policy/S0AidqlPSt09_seed1/*/*/config.json 2>/dev/null | head -1) +got=$(python3 -c "import json,sys;c=json.load(open(sys.argv[1]));a=c['algo'];print(a['vf_quantile'],a.get('critic_only'),c['train']['hdf5_filter_key'])" "$cfg" 2>/dev/null) +[ "$got" = "0.9 True train" ] || { echo "[v7iql] FATAL config says '$got' (want '0.9 True train') $cfg"; exit 90; } +echo "[v7iql] config OK $got rc=$rc"; exit $rc diff --git a/rsm_rise/scripts/real/v7/reward2/iql_payloads/cooking_v7_rw_RSHAPED2__S0AidqlPSt09__s2.sh b/rsm_rise/scripts/real/v7/reward2/iql_payloads/cooking_v7_rw_RSHAPED2__S0AidqlPSt09__s2.sh new file mode 100644 index 0000000000000000000000000000000000000000..e7651ebcd81097db7eff558645ad068e954edabe --- /dev/null +++ b/rsm_rise/scripts/real/v7/reward2/iql_payloads/cooking_v7_rw_RSHAPED2__S0AidqlPSt09__s2.sh @@ -0,0 +1,16 @@ +#!/usr/bin/env bash +ROOT=/proj/dmfexp/zwhong/jm/rsm_rise +source /proj/dmfexp/zwhong/rsm_rise/wandb_env.sh +export RSM_HDF5_FILTER_KEY=train # plan split: mask/train only (TUNE/TEST = mask/valid held out) +if ls $ROOT/runs/cooking_v7_rw_RSHAPED2/policy/S0AidqlPSt09_seed2/*/*/models/model_epoch_5000.pth >/dev/null 2>&1; then + echo "[v7iql] SKIP cooking_v7_rw_RSHAPED2 S0AidqlPSt09 s2 -- epoch 5000 exists"; exit 0; fi +echo "[v7iql] RUN cooking_v7_rw_RSHAPED2 S0AidqlPSt09 s2 $(date -u) host=$(hostname) gpu=${CUDA_VISIBLE_DEVICES:-?}" +RSM_NUM_DATA_WORKERS=${RSM_NUM_DATA_WORKERS:-0} bash /proj/dmfexp/zwhong/rsm_rise/scripts/real/v7/reward2/run_train_r2.sh cooking_v7_rw_RSHAPED2 S0AidqlPSt09 2 \ + training.spectral_norm_policy=False training.policy_bottleneck_beta=0.0 \ + training.action_augmentation=False training.advanced_augmentation=False \ + training.critic_only=True training.vf_quantile=0.9 training.num_epochs=5000 exp.save_interval=1250 training.cache_mode=all +rc=$? +cfg=$(ls -t $ROOT/runs/cooking_v7_rw_RSHAPED2/policy/S0AidqlPSt09_seed2/*/*/config.json 2>/dev/null | head -1) +got=$(python3 -c "import json,sys;c=json.load(open(sys.argv[1]));a=c['algo'];print(a['vf_quantile'],a.get('critic_only'),c['train']['hdf5_filter_key'])" "$cfg" 2>/dev/null) +[ "$got" = "0.9 True train" ] || { echo "[v7iql] FATAL config says '$got' (want '0.9 True train') $cfg"; exit 90; } +echo "[v7iql] config OK $got rc=$rc"; exit $rc diff --git a/rsm_rise/scripts/real/v7/reward2/iql_payloads/cooking_v7_rw_RSHAPED2__S0AidqlPSt09__s3.sh b/rsm_rise/scripts/real/v7/reward2/iql_payloads/cooking_v7_rw_RSHAPED2__S0AidqlPSt09__s3.sh new file mode 100644 index 0000000000000000000000000000000000000000..98bcc56eea232a5252b94d219bd8f2c9844df2ae --- /dev/null +++ b/rsm_rise/scripts/real/v7/reward2/iql_payloads/cooking_v7_rw_RSHAPED2__S0AidqlPSt09__s3.sh @@ -0,0 +1,16 @@ +#!/usr/bin/env bash +ROOT=/proj/dmfexp/zwhong/jm/rsm_rise +source /proj/dmfexp/zwhong/rsm_rise/wandb_env.sh +export RSM_HDF5_FILTER_KEY=train # plan split: mask/train only (TUNE/TEST = mask/valid held out) +if ls $ROOT/runs/cooking_v7_rw_RSHAPED2/policy/S0AidqlPSt09_seed3/*/*/models/model_epoch_5000.pth >/dev/null 2>&1; then + echo "[v7iql] SKIP cooking_v7_rw_RSHAPED2 S0AidqlPSt09 s3 -- epoch 5000 exists"; exit 0; fi +echo "[v7iql] RUN cooking_v7_rw_RSHAPED2 S0AidqlPSt09 s3 $(date -u) host=$(hostname) gpu=${CUDA_VISIBLE_DEVICES:-?}" +RSM_NUM_DATA_WORKERS=${RSM_NUM_DATA_WORKERS:-0} bash /proj/dmfexp/zwhong/rsm_rise/scripts/real/v7/reward2/run_train_r2.sh cooking_v7_rw_RSHAPED2 S0AidqlPSt09 3 \ + training.spectral_norm_policy=False training.policy_bottleneck_beta=0.0 \ + training.action_augmentation=False training.advanced_augmentation=False \ + training.critic_only=True training.vf_quantile=0.9 training.num_epochs=5000 exp.save_interval=1250 training.cache_mode=all +rc=$? +cfg=$(ls -t $ROOT/runs/cooking_v7_rw_RSHAPED2/policy/S0AidqlPSt09_seed3/*/*/config.json 2>/dev/null | head -1) +got=$(python3 -c "import json,sys;c=json.load(open(sys.argv[1]));a=c['algo'];print(a['vf_quantile'],a.get('critic_only'),c['train']['hdf5_filter_key'])" "$cfg" 2>/dev/null) +[ "$got" = "0.9 True train" ] || { echo "[v7iql] FATAL config says '$got' (want '0.9 True train') $cfg"; exit 90; } +echo "[v7iql] config OK $got rc=$rc"; exit $rc diff --git a/rsm_rise/scripts/real/v7/reward2/iql_r2_manifest.py b/rsm_rise/scripts/real/v7/reward2/iql_r2_manifest.py new file mode 100644 index 0000000000000000000000000000000000000000..b323e2e25953ad9682cae20336acb166dd7095c7 --- /dev/null +++ b/rsm_rise/scripts/real/v7/reward2/iql_r2_manifest.py @@ -0,0 +1,56 @@ +#!/usr/bin/env python +"""V7_REWARD2 IQL eval: write a V7_MANIFEST-format json (entries kind=iql, stream=V7_IQL) that jm's +scripts/real/v7_junction/iql_columns.py reads via --manifest, so the jm harness is pointed at the RSHAPED2 run dirs +without editing any jm file. Entries: + * iql_v7_RSHAPED2_t09_s_e for seed in --seeds whose model_epoch_.pth exists (missing seeds skipped); + * the frozen comparator iql_v7_RPROGRESS_t09_s0_e1250 (always; fatal if missing). +A checkpoint modified < --min-age s ago is treated as missing (could still be being written by the trainer). +Prints the RSHAPED2 names (space separated) on stdout's last line; usage: iql_r2_manifest.py """ +import argparse, glob, json, os, sys, time + +R = "/proj/dmfexp/zwhong/jm/rsm_rise" +NORM = f"{R}/data/derived/cooking_v7_action_norm.json" +COMPARATOR = "iql_v7_RPROGRESS_t09_s0_e1250" + + +def find(label, seed, epoch, min_age): + base = f"{R}/runs/cooking_v7_rw_{label}/policy/S0AidqlPSt09_seed{seed}" + hits = sorted(glob.glob(base + f"/*/models/model_epoch_{epoch}.pth") + glob.glob(base + f"/*/*/models/model_epoch_{epoch}.pth")) + hits = [h for h in hits if time.time() - os.path.getmtime(h) >= min_age] + return hits[-1] if hits else None + + +def entry(label, seed, epoch, path): + return {"kind": "iql", "stream": "V7_IQL", "name": f"iql_v7_{label}_t09_s{seed}_e{epoch}", "label": label, + "vf_quantile": 0.9, "seed": seed, "epoch": epoch, "path": path, "action_norm": NORM} + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("epoch", type=int) + ap.add_argument("out") + ap.add_argument("--seeds", default="0,1,2,3") + ap.add_argument("--min-age", type=float, default=120.0) + a = ap.parse_args() + ents = [] + for s in [int(x) for x in a.seeds.split(",")]: + p = find("RSHAPED2", s, a.epoch, a.min_age) + if p is None: + print(f"[r2man] SKIP RSHAPED2 s{s} e{a.epoch}: no checkpoint", file=sys.stderr) + continue + ents.append(entry("RSHAPED2", s, a.epoch, p)) + cp = find("RPROGRESS", 0, 1250, 0) + assert cp, "comparator checkpoint RPROGRESS t09 s0 e1250 missing" + ents.append(entry("RPROGRESS", 0, 1250, cp)) + assert ents[-1]["name"] == COMPARATOR + os.makedirs(os.path.dirname(os.path.abspath(a.out)), exist_ok=True) + tmp = a.out + ".tmp" + json.dump({"stream": "V7_REWARD2_IQL", "epoch": a.epoch, "comparator": COMPARATOR, "entries": ents}, open(tmp, "w"), indent=1) + os.replace(tmp, a.out) + for e in ents: + print(f"[r2man] {e['name']} {e['path']}", file=sys.stderr) + print(" ".join(e["name"] for e in ents if e["label"] == "RSHAPED2")) + + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/real/v7/reward2/iql_r2_summary.py b/rsm_rise/scripts/real/v7/reward2/iql_r2_summary.py new file mode 100644 index 0000000000000000000000000000000000000000..eaa36b1ea8907f1357346aa843fb44c405ff4d2c --- /dev/null +++ b/rsm_rise/scripts/real/v7/reward2/iql_r2_summary.py @@ -0,0 +1,53 @@ +#!/usr/bin/env python +"""V7_REWARD2 IQL eval: side-by-side table, RSHAPED2 critics vs the frozen comparator iql_v7_RPROGRESS_t09_s0_e1250. +Junction rows use the iql_freeze.py rule (per junction J0/J2: mean over the 3 draws; worseM2 = min_J M2, worseM1 = min_J M1) +read from ensemble_metrics.py outputs; value-AUC rows from iql_value_auc.py. The jm TUNE freeze row of the comparator +(status/real/v7_junction/iql_freeze.json) is copied in as a reference (our TUNE comparator column reads jm's own parts, +so the two must agree). usage: iql_r2_summary.py --tune T.json --test S.json --auc A.json --out O.json""" +import argparse, json, os + +FREEZE = "/proj/dmfexp/zwhong/jm/rsm_rise/status/real/v7_junction/iql_freeze.json" + + +def jrows(path): + if not path or not os.path.exists(path): + return {} + res = json.load(open(path))["res"]; out = {} + for key in sorted({k for J in res.values() for k in J}): + m = {J: (res[J][key]["mean"]["M1"], res[J][key]["mean"]["M2"]) for J in res if key in res[J]} + out[key] = {"worseM2": min(v[1] for v in m.values()), "worseM1": min(v[0] for v in m.values()), + **{f"{J}_M1": v[0] for J, v in m.items()}, **{f"{J}_M2": v[1] for J, v in m.items()}} + return out + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--tune"); ap.add_argument("--test"); ap.add_argument("--auc"); ap.add_argument("--out", required=True) + a = ap.parse_args() + fr = json.load(open(FREEZE)); ref = [r for r in fr["table"] if r[0] == fr["comparator"]][0] + out = {"comparator": fr["comparator"], + "jm_freeze_tune_row": {"worseM2": ref[1], "worseM1": ref[2], **{f"J{j}_M1": v[0] for j, v in ref[3].items()}, + **{f"J{j}_M2": v[1] for j, v in ref[3].items()}}, + "junction": {"tune": jrows(a.tune), "test": jrows(a.test)}, "value_auc": {}} + if a.auc and os.path.exists(a.auc): + for n, c in json.load(open(a.auc))["critics"].items(): + out["value_auc"][n] = {sp: {h: {k: c[sp][h][k] for k in ("auc_goal_vs_fail", "auc_prog_vs_fail", "spearman_frame", + "spearman_within_ep_mean", "branch_2_auc_3_vs_6")} + for h in ("V", "Q")} for sp in ("tune", "test", "tune+test")} + tmp = a.out + ".tmp"; json.dump(out, open(tmp, "w"), indent=1); os.replace(tmp, a.out) + f = lambda x: " - " if x is None else f"{x:.3f}" + for sp in ("tune", "test"): + print(f"== junction {sp} (worseM2 worseM1 | J0 M1 M2 | J2 M1 M2)") + for k, r in out["junction"][sp].items(): + print(f"{k:42s} {f(r['worseM2'])} {f(r['worseM1'])} | {f(r.get('J0_M1'))} {f(r.get('J0_M2'))} | {f(r.get('J2_M1'))} {f(r.get('J2_M2'))}") + print(f"jm freeze TUNE row {out['comparator']}: {out['jm_freeze_tune_row']}") + for sp in ("tune", "test"): + print(f"== value AUC {sp} V: goal/fail prog/fail rho branch2 || Q: same") + for n, c in out["value_auc"].items(): + v, q = c[sp]["V"], c[sp]["Q"] + print(f"{n:34s} " + " ".join(f(v[k]) for k in ("auc_goal_vs_fail", "auc_prog_vs_fail", "spearman_frame", "branch_2_auc_3_vs_6")) + + " || " + " ".join(f(q[k]) for k in ("auc_goal_vs_fail", "auc_prog_vs_fail", "spearman_frame", "branch_2_auc_3_vs_6"))) + + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/real/v7/reward2/iql_value_auc.py b/rsm_rise/scripts/real/v7/reward2/iql_value_auc.py new file mode 100644 index 0000000000000000000000000000000000000000..79c9fb6cc327f0e96a3acfccbc49cc6132937bc1 --- /dev/null +++ b/rsm_rise/scripts/real/v7/reward2/iql_value_auc.py @@ -0,0 +1,159 @@ +#!/usr/bin/env python +"""V7_REWARD2 IQL eval (b): per-episode value AUC of IQL critics on the TUNE and TEST episodes of cooking v7. + +No per-episode V/Q AUC of the IQL critics existed in jm (only the junction-harness M1/M2 columns), so this computes it. +Critic loading = the deploy path used by the junction harness (jm scripts/real/v7_iql_score.py IQLV7 -> rise_stack +IDQLScorer -> robomimic FileUtils.policy_from_checkpoint; obs = CURRENT frame from the raw v7 hdf5, built with +rise_stack.obs.make_obs/obs_key exactly as IQLV7.obs_from_hdf5 + rm_obs_single do, only batched over frames). +Per frame t of every TUNE/TEST episode: + V(s_t) = nets["vf"] (the expectile value head) + Q(s_t, a_t) = min_k critic_target_k(s_t, norm(actions_raw[t])) (deploy score of the logged action) +Frame alignment: demo with attrs episode_index = ep <-> cache frames [ep_from[ep], ep_to[ep]); checked per episode +(length and annot/r_progress == cache reward_progress, the same check make_iql_view.py recorded in +status/real/v7_reward2_iql_view.json). Per-frame values are cached in --values-dir/.npz (resumable). +Metrics per split (tune, test, tune+test), for V and Q: + auc_goal_vs_fail : episode score = mean of the last 150 frames; final_state 7 (pos) vs 5/6 (neg) + auc_prog_vs_fail : same score; final_state 3/8/7 (pos) vs 5/6 (neg) (final_state 1 is in neither class) + spearman_frame : pooled frame-level Spearman vs cache reward_shaped2 (+ mean within-episode Spearman) + branch_2 : segments with edge_from == 2, segment score = mean over its first 50 frames, 2->3 (pos) vs 2->6 (neg) +usage: iql_value_auc.py --manifest M.json --out auc.json --values-dir DIR [--names a,b]""" +import argparse, json, os, sys +import numpy as np +from scipy.stats import rankdata, spearmanr + +R = "/proj/dmfexp/zwhong/jm/rsm_rise" +sys.path.insert(0, f"{R}/scripts/real") +C = f"{R}/cache/real_cooking_v7" +HDF5 = f"{R}/data/raw/cooking_v7_expert_suboptimal.hdf5" +TT = f"{R}/data/derived/cooking_v7_tune_test.json" +SPLIT = f"{R}/data/derived/cooking_v7_split.json" +LAST, FIRST, BS = 150, 50, 256 + + +def auc(s, y): + s = np.asarray(s, np.float64); y = np.asarray(y).astype(bool) + n1, n0 = int(y.sum()), int((~y).sum()) + if n1 == 0 or n0 == 0: + return None + r = rankdata(s) + return float((r[y].sum() - n1 * (n1 + 1) / 2.0) / (n1 * n0)) + + +def episodes(): + tt = json.load(open(TT)); sp = json.load(open(SPLIT))["episodes"] + m = np.load(f"{C}/meta.npz") + eps = sorted(set(tt["tune"]) | set(tt["test"])) + return tt, {e: int(sp[str(e)]["final_state"]) for e in eps}, m["ep_from"].astype(np.int64), m["ep_to"].astype(np.int64), eps + + +def compute_values(entry, eps, a, b, out): + import h5py, torch + from v7_iql_score import IQLV7 + from rise_stack import obs as _obs + torch.set_num_threads(int(os.environ.get("OMP_NUM_THREADS", "8"))) + q = IQLV7(entry["path"], action_norm=entry["action_norm"], hdf5=HDF5, device="cpu") + sc, an = q.sc, q.an + assert abs(sc.vf_quantile - entry["vf_quantile"]) < 1e-6, (sc.vf_quantile, entry) + algo, keys, OU = sc.algo, sc.keys, sc.ObsUtils + rp = np.load(f"{C}/reward_progress.f32.npy", mmap_mode="r") + V, Q = {}, {} + with h5py.File(HDF5, "r") as f: + d = f["data"] + demo_of = {int(d[k].attrs["episode_index"]): k for k in d} + for e in eps: + g = d[demo_of[e]]; T = g["actions_raw"].shape[0] + assert T == b[e] - a[e], (e, T, b[e] - a[e]) + assert np.array_equal(g["annot/r_progress"][()].astype(np.float32), np.asarray(rp[a[e]:b[e]])), f"r_progress mismatch ep {e}" + go = g["obs"] + ag, wr, st = go["agentview_image"][()], go["robot0_eye_in_hand_image"][()], go["ee_state"][()] + act = an.norm(g["actions_raw"][()].astype(np.float32)).astype(np.float32) + v_ep, q_ep = [], [] + for s0 in range(0, T, BS): + idx = range(s0, min(T, s0 + BS)) + obs_l = [_obs.make_obs({"global": ag[t], "wrist": wr[t]}, st[t], an.gripper_thresh, + images84={"global": ag[t], "wrist": wr[t]}, t=t) for t in idx] + ob = {} + for k in keys: + x = torch.from_numpy(np.stack([_obs.obs_key(o, k) for o in obs_l])).float() + if OU.key_is_obs_modality(k, "rgb"): + x = OU.process_obs(x, obs_modality="rgb") + ob[k] = x + with torch.no_grad(): + ac = torch.from_numpy(act[s0:s0 + len(obs_l)]) + v_ep.append(algo.nets["vf"](obs_dict=ob).reshape(-1).numpy()) + qs = torch.cat([c(obs_dict=ob, acts=ac) for c in algo.nets["critic_target"]], 1) + q_ep.append(qs.min(1)[0].numpy()) + V[e], Q[e] = np.concatenate(v_ep), np.concatenate(q_ep) + print(f"[vauc] {entry['name']} ep {e} T={T} V[-1]={V[e][-1]:.3f}", flush=True) + blob = {"eps": np.array(eps), "path": np.array(entry["path"])} + for e in eps: + blob[f"V_{e}"], blob[f"Q_{e}"] = V[e].astype(np.float32), Q[e].astype(np.float32) + tmp = f"{out}.{os.getpid()}.tmp.npz"; np.savez(tmp, **blob); os.replace(tmp, out) + + +def metrics(vals, eps_split, fs, a, b, lab, ef, et, sg): + res = {} + for head in ("V", "Q"): + x = {e: vals[f"{head}_{e}"].astype(np.float64) for e in eps_split} + sc = {e: float(x[e][-LAST:].mean()) for e in eps_split} + fail = [e for e in eps_split if fs[e] in (5, 6)] + goal = [e for e in eps_split if fs[e] == 7] + prog = [e for e in eps_split if fs[e] in (3, 8, 7)] + g_e = goal + fail; p_e = prog + fail + pooled_s = np.concatenate([x[e] for e in eps_split]); pooled_l = np.concatenate([lab[a[e]:b[e]] for e in eps_split]) + within = [spearmanr(x[e], lab[a[e]:b[e]])[0] for e in eps_split if np.ptp(lab[a[e]:b[e]]) > 0] + seg_s, seg_y = [], [] + for e in eps_split: + s_, f_, t_ = sg[a[e]:b[e]], ef[a[e]:b[e]], et[a[e]:b[e]] + for k in np.unique(s_): + w = np.flatnonzero(s_ == k) + if f_[w[0]] == 2 and t_[w[0]] in (3, 6): + seg_s.append(float(x[e][w[:FIRST]].mean())); seg_y.append(int(t_[w[0]]) == 3) + res[head] = { + "auc_goal_vs_fail": auc([sc[e] for e in g_e], [fs[e] == 7 for e in g_e]), "n_goal": len(goal), "n_fail": len(fail), + "auc_prog_vs_fail": auc([sc[e] for e in p_e], [fs[e] in (3, 8, 7) for e in p_e]), "n_prog": len(prog), + "spearman_frame": float(spearmanr(pooled_s, pooled_l)[0]), "spearman_within_ep_mean": float(np.nanmean(within)), + "n_frames": int(len(pooled_s)), + "branch_2_auc_3_vs_6": auc(seg_s, seg_y), "n_seg_2to3": int(sum(seg_y)), "n_seg_2to6": int(len(seg_y) - sum(seg_y)), + "branch_2_mean_3": float(np.mean([s for s, y in zip(seg_s, seg_y) if y])) if any(seg_y) else None, + "branch_2_mean_6": float(np.mean([s for s, y in zip(seg_s, seg_y) if not y])) if not all(seg_y) else None, + "ep_score_by_final_state": {str(k): float(np.mean([sc[e] for e in eps_split if fs[e] == k])) + for k in sorted({fs[e] for e in eps_split})}, + } + return res + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--manifest", required=True) + ap.add_argument("--out", required=True) + ap.add_argument("--values-dir", required=True) + ap.add_argument("--names", default="") + A = ap.parse_args() + ents = json.load(open(A.manifest))["entries"] + if A.names: + keep = set(A.names.split(",")); ents = [e for e in ents if e["name"] in keep] + tt, fs, a, b, eps = episodes() + os.makedirs(A.values_dir, exist_ok=True) + lab = np.load(f"{C}/reward_shaped2.f32.npy").astype(np.float64) + ef, et, sg = np.load(f"{C}/edge_from.i16.npy"), np.load(f"{C}/edge_to.i16.npy"), np.load(f"{C}/seg.i16.npy") + out = {"manifest": A.manifest, "last": LAST, "first": FIRST, "splits": {"tune": tt["tune"], "test": tt["test"]}, "critics": {}} + for e in ents: + vp = os.path.join(A.values_dir, f"{e['name']}.npz") + if os.path.exists(vp) and str(np.load(vp)["path"]) == e["path"]: + print(f"[vauc] reuse {vp}", flush=True) + else: + compute_values(e, eps, a, b, vp) + vals = dict(np.load(vp)) + out["critics"][e["name"]] = {"path": e["path"], "epoch": e["epoch"], "label": e["label"], **{ + sp: metrics(vals, eps_sp, fs, a, b, lab, ef, et, sg) + for sp, eps_sp in (("tune", tt["tune"]), ("test", tt["test"]), ("tune+test", sorted(tt["tune"] + tt["test"])))}} + m = out["critics"][e["name"]] + print(f"[vauc] {e['name']} " + " | ".join( + f"{sp} V goal {m[sp]['V']['auc_goal_vs_fail']} prog {m[sp]['V']['auc_prog_vs_fail']} rho {m[sp]['V']['spearman_frame']:.3f} br {m[sp]['V']['branch_2_auc_3_vs_6']}" + for sp in ("tune", "test")), flush=True) + tmp = f"{A.out}.{os.getpid()}.tmp"; json.dump(out, open(tmp, "w"), indent=1); os.replace(tmp, A.out) + + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/real/v7/reward2/make_iql_view.py b/rsm_rise/scripts/real/v7/reward2/make_iql_view.py new file mode 100644 index 0000000000000000000000000000000000000000..0e063e6638986c917b3242553312fd48e1cbd5c4 --- /dev/null +++ b/rsm_rise/scripts/real/v7/reward2/make_iql_view.py @@ -0,0 +1,51 @@ +#!/usr/bin/env python +"""V7_REWARD2 step 3a: robomimic view data/derived/rw/cooking_v7_rw_RSHAPED2.hdf5 (jm tree) for the IQL retrain. +Same ExternalLink construction as convert_cooking_v7_hdf5.build_view (every member except `rewards` links into the +raw v7 hdf5), rewards = reward_shaped2 (make_labels.py) * SCALE with SCALE = 0.1, i.e. in [-0.1, +1.0] +(the RPROGRESS critic saw 0/1 per frame; the scale keeps Q in the same range, the ranking is scale-invariant). +Alignment checks per demo (cache episode = demo attr episode_index): annot/r_progress == cache reward_progress +(proves frame alignment) and len == cache episode length. Refuses to overwrite an existing view.""" +import json, os, uuid +import h5py, numpy as np +R = "/proj/dmfexp/zwhong/jm/rsm_rise" +C = f"{R}/cache/real_cooking_v7" +SRC = f"{R}/data/raw/cooking_v7_expert_suboptimal.hdf5" +DST = f"{R}/data/derived/rw/cooking_v7_rw_RSHAPED2.hdf5" +SCALE = 0.1 +assert not os.path.exists(DST), f"{DST} exists -- refusing to overwrite" +r2 = np.load(f"{C}/reward_shaped2.f32.npy"); rp = np.load(f"{C}/reward_progress.f32.npy") +m = np.load(f"{C}/meta.npz"); a, b = m["ep_from"].astype(np.int64), m["ep_to"].astype(np.int64) +tmp = DST + ".tmp" +stats = dict(n=0, frames=0, min=1e9, max=-1e9, mismatch=[]) +with h5py.File(SRC, "r") as f, h5py.File(tmp, "w") as g: + for k, v in f.attrs.items(): g.attrs[k] = v + d = f["data"]; gd = g.create_group("data") + for k, v in d.attrs.items(): gd.attrs[k] = v + gd.attrs["reward_type"] = ("RSHAPED2 (V7_REWARD2, owner 2026-11-20): 0.1 x shaped progress label; levels 0->0, 1/2->1, " + "3->2, 8->3, goal 7->+10, failure 5/6->-1, linear within segments") + gd.attrs["dataset_id"] = str(uuid.uuid5(uuid.NAMESPACE_URL, "rsm_rise/" + os.path.basename(DST))) + for k in f: + if k != "data": f.copy(f[k], g, name=k) + for k in d: + gk = gd.create_group(k) + for ak, av_ in d[k].attrs.items(): gk.attrs[ak] = av_ + for mem in d[k]: + if mem == "rewards": continue + gk[mem] = h5py.ExternalLink(os.path.abspath(SRC), f"/data/{k}/{mem}") + ep = int(d[k].attrs["episode_index"]) + T = d[k]["actions"].shape[0] + ann = d[k]["annot/r_progress"][()].astype(np.float32) + ok = (T == b[ep] - a[ep]) and np.array_equal(ann, rp[a[ep]:b[ep]]) + if not ok: stats["mismatch"].append([k, ep, int(T), int(b[ep] - a[ep])]) + r = r2[a[ep]:b[ep]].astype(np.float64) * SCALE + assert len(r) == T and np.isfinite(r).all() + gk.create_dataset("rewards", data=r) + stats["n"] += 1; stats["frames"] += T; stats["min"] = min(stats["min"], r.min()); stats["max"] = max(stats["max"], r.max()) +assert not stats["mismatch"], stats["mismatch"][:5] +os.replace(tmp, DST) +with h5py.File(DST, "r") as f: + masks = {k: len(f["mask"][k][()]) for k in f["mask"].keys()} + k0 = sorted(f["data"].keys())[0]; _ = f["data"][k0]["actions"].shape # resolves the ExternalLink +stats.update(masks=masks, scale=SCALE, dst=DST, PASS=True) +json.dump(stats, open("/proj/dmfexp/zwhong/rsm_rise/status/real/v7_reward2_iql_view.json", "w"), indent=1, default=float) +print(json.dumps(stats, indent=1, default=float)) diff --git a/rsm_rise/scripts/real/v7/reward2/make_labels.py b/rsm_rise/scripts/real/v7/reward2/make_labels.py new file mode 100644 index 0000000000000000000000000000000000000000..2f9734945b5939453f480f065518cddffd88841a --- /dev/null +++ b/rsm_rise/scripts/real/v7/reward2/make_labels.py @@ -0,0 +1,120 @@ +#!/usr/bin/env python +"""V7_REWARD2 step 1 (owner 2026-11-20): shaped, monotone per-frame reward labels for cooking v7. + +Progress level L (route graph of data/real/rsm_cooking_v7/meta/collection/task.json): + state 0 -> 0 ; states 1, 2 -> 1 ; state 3 -> 2 ; state 8 -> 3 ; GOAL 7 -> +10 ; failure 5/6 -> -1. +Within a segment a->b of n frames (cache seg.i16 / edge_from / edge_to), frame j (0..n-1) gets + v_j = L(a) + (L(b) - L(a)) * (j + 1) / n +so the arrival frame (goal_reached=1, the segment's last frame) carries exactly L(b) and the next segment +starts just above it: monotone increasing along a progress route, linear down to -1 on a failure segment, +and the transition into 7 ramps 3 -> +10 with the goal frame itself = +10. +Loss weights (group-balanced on TRAIN frames, 3 groups by segment destination): + G7 = segments ending in 7 ; PROG = segments ending in 1/2/3/8 ; FAIL = segments ending in 5/6 + w_g = N_train / (3 * N_g,train) (so every group carries 1/3 of the total weight; mean w = 1 on train) +Writes NEW files only (refuses to overwrite) into the jm v7 cache: + reward_shaped2.f32.npy, reward_shaped2_w.f32.npy, reward_shaped2_group.i8.npy (0 PROG, 1 G7, 2 FAIL), + LABELS_SHAPED2.json ; plot status/real/v7_reward2_labels.png ; summary status/real/v7_reward2_labels.json +""" +import json, os, sys +from pathlib import Path +import numpy as np + +C = Path("/proj/dmfexp/zwhong/jm/rsm_rise/cache/real_cooking_v7") +SPLIT = Path("/proj/dmfexp/zwhong/jm/rsm_rise/data/derived/cooking_v7_split.json") +TT = Path("/proj/dmfexp/zwhong/jm/rsm_rise/data/derived/cooking_v7_tune_test.json") +OUT = Path("/proj/dmfexp/zwhong/rsm_rise/status/real") +LEVEL = {0: 0.0, 1: 1.0, 2: 1.0, 3: 2.0, 8: 3.0, 7: 10.0, 5: -1.0, 6: -1.0} +FORCE = "--force" in sys.argv + +meta = np.load(C / "meta.npz") +ef, et = np.load(C / "edge_from.i16.npy"), np.load(C / "edge_to.i16.npy") +seg = np.load(C / "seg.i16.npy"); gr = np.load(C / "goal_reached.i8.npy") +N = len(ef) +split = json.load(open(SPLIT))["episodes"]; tt = json.load(open(TT)) +n_ep = len(meta["ep_from"]); assert len(split) == n_ep +sp = np.array([split[str(i)]["split"] for i in range(n_ep)]) +tune, test = set(tt["tune"]), set(tt["test"]) +role = np.array(["train" if sp[i] == "train" else ("tune" if i in tune else ("test" if i in test else "valid?")) + for i in range(n_ep)]) +assert (role == "valid?").sum() == 0, "valid episode not in tune/test" + +r = np.full(N, np.nan, np.float32); grp = np.full(N, -1, np.int8); row_role = np.empty(N, object) +for i in range(n_ep): + a0, b0 = int(meta["ep_from"][i]), int(meta["ep_to"][i]) + row_role[a0:b0] = role[i] + s = seg[a0:b0] + for k in np.unique(s): + idx = a0 + np.where(s == k)[0] + assert np.all(np.diff(idx) == 1), f"ep {i} seg {k} not contiguous" + fa, fb = int(ef[idx[0]]), int(et[idx[0]]) + assert np.all(ef[idx] == fa) and np.all(et[idx] == fb), f"ep {i} seg {k} mixed edges" + n = len(idx) + r[idx] = LEVEL[fa] + (LEVEL[fb] - LEVEL[fa]) * (np.arange(n) + 1) / n + grp[idx] = 1 if fb == 7 else (2 if fb in (5, 6) else 0) +assert np.isfinite(r).all() and (grp >= 0).all() +# goal frames = +10 exactly +gf = (gr == 1) & (et == 7) +assert np.allclose(r[gf], 10.0), r[gf][:5] + +tr = row_role == "train" +cnt = {g: int(((grp == g) & tr).sum()) for g in (0, 1, 2)} +wg = {g: tr.sum() / (3.0 * cnt[g]) for g in (0, 1, 2)} +w = np.array([wg[int(g)] for g in grp], np.float32) + +outs = {"reward_shaped2.f32.npy": r, "reward_shaped2_w.f32.npy": w, "reward_shaped2_group.i8.npy": grp} +for fn, arr in outs.items(): + p = C / fn + if p.exists() and not FORCE: + old = np.load(p) + assert old.shape == arr.shape and np.array_equal(old, arr), f"{p} exists with different content" + print("[labels] exists, identical:", p) + else: + np.save(p, arr); print("[labels] wrote", p, arr.shape, arr.dtype) + +# ------------------------------------------------------------------ summary +GN = {0: "PROG(->1/2/3/8)", 1: "G7(->7)", 2: "FAIL(->5/6)"} +edges = np.array([-1.5, -0.5, 0.0001, 0.5, 1.0001, 1.5, 2.0001, 2.5, 3.0001, 5, 7.5, 9.9999, 10.0001]) +hist, _ = np.histogram(r, bins=edges) +per_route = {} +for rt in sorted(set(meta["ep_route"].tolist())): + eps = np.where(meta["ep_route"] == rt)[0] + rows = np.concatenate([np.arange(meta["ep_from"][e], meta["ep_to"][e]) for e in eps]) + first = [float(r[meta["ep_from"][e]]) for e in eps]; last = [float(r[meta["ep_to"][e] - 1]) for e in eps] + mono = all(np.all(np.diff(r[meta["ep_from"][e]:meta["ep_to"][e]]) >= -1e-6) for e in eps) + per_route[int(rt)] = {"path": str(meta["ep_path"][eps[0]]), "n_eps": int(len(eps)), "frames": int(len(rows)), + "mean": float(r[rows].mean()), "min": float(r[rows].min()), "max": float(r[rows].max()), + "first_frame_mean": float(np.mean(first)), "last_frame_mean": float(np.mean(last)), + "monotone_nondecreasing_all_eps": bool(mono), + "group_frames": {GN[g]: int((grp[rows] == g).sum()) for g in (0, 1, 2)}} +summ = {"level": {str(k): v for k, v in LEVEL.items()}, + "interp": "v_j = L(a) + (L(b)-L(a))*(j+1)/n within each segment a->b of n frames", + "N": int(N), "mean": float(r.mean()), "frac_pos": float((r > 0).mean()), "frac_neg": float((r < 0).mean()), + "n_goal_frames": int(gf.sum()), + "hist_edges": edges.tolist(), "hist_counts": hist.tolist(), + "train_group_frames": {GN[g]: cnt[g] for g in (0, 1, 2)}, + "weights": {GN[g]: float(wg[g]) for g in (0, 1, 2)}, + "weight_rule": "w_g = N_train/(3 N_g,train): each destination group carries 1/3 of the train loss weight", + "roles_frames": {k: int((row_role == k).sum()) for k in ("train", "tune", "test")}, + "per_route": per_route} +if not (C / "LABELS_SHAPED2.json").exists() or FORCE: + json.dump(summ, open(C / "LABELS_SHAPED2.json", "w"), indent=1) +json.dump(summ, open(OUT / "v7_reward2_labels.json", "w"), indent=1) +print(json.dumps(summ, indent=1)) + +import matplotlib; matplotlib.use("Agg") +import matplotlib.pyplot as plt +fig, ax = plt.subplots(1, 2, figsize=(13, 4.6)) +cols = plt.cm.tab10(np.arange(10)) +for rt, d in per_route.items(): + eps = np.where(meta["ep_route"] == rt)[0][:3] + for j, e in enumerate(eps): + y = r[meta["ep_from"][e]:meta["ep_to"][e]] + ax[0].plot(np.arange(len(y)) / max(len(y) - 1, 1), y, color=cols[rt], lw=1.2, alpha=0.8, + label=f"route {rt}: {d['path']}" if j == 0 else None) +ax[0].set_xlabel("episode time (normalised)"); ax[0].set_ylabel("shaped reward label") +ax[0].set_title("per-route label profiles (3 episodes per route)"); ax[0].legend(fontsize=7, loc="upper left") +ax[0].grid(alpha=0.3) +ax[1].hist(r, bins=np.linspace(-1.05, 10.05, 112), color="0.35"); ax[1].set_yscale("log") +ax[1].set_xlabel("label"); ax[1].set_ylabel("frames (log)"); ax[1].set_title(f"label histogram, N={N}") +fig.tight_layout(); fig.savefig(OUT / "v7_reward2_labels.png", dpi=110) +print("[labels] plot", OUT / "v7_reward2_labels.png") diff --git a/rsm_rise/scripts/real/v7/reward2/payloads/rew2_a0_bal.sh b/rsm_rise/scripts/real/v7/reward2/payloads/rew2_a0_bal.sh new file mode 100644 index 0000000000000000000000000000000000000000..af13b4c41d43b93ee1e01659b7722e8c2d1052fe --- /dev/null +++ b/rsm_rise/scripts/real/v7/reward2/payloads/rew2_a0_bal.sh @@ -0,0 +1,4 @@ +#!/usr/bin/env bash +cd /proj/dmfexp/zwhong/rsm_rise +echo "[r2 payload] a0_bal $(date -u) host=$(hostname) gpu=${CUDA_VISIBLE_DEVICES:-?}" +exec /proj/dmfexp/zwhong/rsm_rise/venv_rsm/bin/python scripts/real/v7/reward2/train_reward2.py --out /proj/dmfexp/zwhong/rsm_rise/runs/v7_reward2/a0_bal --act a0 diff --git a/rsm_rise/scripts/real/v7/reward2/payloads/rew2_c50_bal_adrop02.sh b/rsm_rise/scripts/real/v7/reward2/payloads/rew2_c50_bal_adrop02.sh new file mode 100644 index 0000000000000000000000000000000000000000..dc50ed6c408da82d1ec86fd0b207568a5bf4c15a --- /dev/null +++ b/rsm_rise/scripts/real/v7/reward2/payloads/rew2_c50_bal_adrop02.sh @@ -0,0 +1,4 @@ +#!/usr/bin/env bash +cd /proj/dmfexp/zwhong/rsm_rise +echo "[r2 payload] c50_bal_adrop02 $(date -u) host=$(hostname) gpu=${CUDA_VISIBLE_DEVICES:-?}" +exec /proj/dmfexp/zwhong/rsm_rise/venv_rsm/bin/python scripts/real/v7/reward2/train_reward2.py --out /proj/dmfexp/zwhong/rsm_rise/runs/v7_reward2/c50_bal_adrop02 --act chunk50 --act_drop 0.2 diff --git a/rsm_rise/scripts/real/v7/reward2/payloads/rew2_c50_bal_s0.sh b/rsm_rise/scripts/real/v7/reward2/payloads/rew2_c50_bal_s0.sh new file mode 100644 index 0000000000000000000000000000000000000000..485996522c0096f089672d1632f68b402d1ddaf2 --- /dev/null +++ b/rsm_rise/scripts/real/v7/reward2/payloads/rew2_c50_bal_s0.sh @@ -0,0 +1,4 @@ +#!/usr/bin/env bash +cd /proj/dmfexp/zwhong/rsm_rise +echo "[r2 payload] c50_bal_s0 $(date -u) host=$(hostname) gpu=${CUDA_VISIBLE_DEVICES:-?}" +exec /proj/dmfexp/zwhong/rsm_rise/venv_rsm/bin/python scripts/real/v7/reward2/train_reward2.py --out /proj/dmfexp/zwhong/rsm_rise/runs/v7_reward2/c50_bal_s0 --act chunk50 --seed 0 diff --git a/rsm_rise/scripts/real/v7/reward2/payloads/rew2_c50_bal_s1.sh b/rsm_rise/scripts/real/v7/reward2/payloads/rew2_c50_bal_s1.sh new file mode 100644 index 0000000000000000000000000000000000000000..26897f19e14429b766f268f6a9971868c14ecbb3 --- /dev/null +++ b/rsm_rise/scripts/real/v7/reward2/payloads/rew2_c50_bal_s1.sh @@ -0,0 +1,4 @@ +#!/usr/bin/env bash +cd /proj/dmfexp/zwhong/rsm_rise +echo "[r2 payload] c50_bal_s1 $(date -u) host=$(hostname) gpu=${CUDA_VISIBLE_DEVICES:-?}" +exec /proj/dmfexp/zwhong/rsm_rise/venv_rsm/bin/python scripts/real/v7/reward2/train_reward2.py --out /proj/dmfexp/zwhong/rsm_rise/runs/v7_reward2/c50_bal_s1 --act chunk50 --seed 1 diff --git a/rsm_rise/scripts/real/v7/reward2/payloads/rew2_c50_bal_w1024do01.sh b/rsm_rise/scripts/real/v7/reward2/payloads/rew2_c50_bal_w1024do01.sh new file mode 100644 index 0000000000000000000000000000000000000000..fe4fd1dd2934781b11008fabb6120b397fd14c9d --- /dev/null +++ b/rsm_rise/scripts/real/v7/reward2/payloads/rew2_c50_bal_w1024do01.sh @@ -0,0 +1,4 @@ +#!/usr/bin/env bash +cd /proj/dmfexp/zwhong/rsm_rise +echo "[r2 payload] c50_bal_w1024do01 $(date -u) host=$(hostname) gpu=${CUDA_VISIBLE_DEVICES:-?}" +exec /proj/dmfexp/zwhong/rsm_rise/venv_rsm/bin/python scripts/real/v7/reward2/train_reward2.py --out /proj/dmfexp/zwhong/rsm_rise/runs/v7_reward2/c50_bal_w1024do01 --act chunk50 --width 1024 --dropout 0.1 diff --git a/rsm_rise/scripts/real/v7/reward2/payloads/rew2_c50_bal_xn01.sh b/rsm_rise/scripts/real/v7/reward2/payloads/rew2_c50_bal_xn01.sh new file mode 100644 index 0000000000000000000000000000000000000000..ac5a1e2bce3945c70061f69daaf244348296f238 --- /dev/null +++ b/rsm_rise/scripts/real/v7/reward2/payloads/rew2_c50_bal_xn01.sh @@ -0,0 +1,4 @@ +#!/usr/bin/env bash +cd /proj/dmfexp/zwhong/rsm_rise +echo "[r2 payload] c50_bal_xn01 $(date -u) host=$(hostname) gpu=${CUDA_VISIBLE_DEVICES:-?}" +exec /proj/dmfexp/zwhong/rsm_rise/venv_rsm/bin/python scripts/real/v7/reward2/train_reward2.py --out /proj/dmfexp/zwhong/rsm_rise/runs/v7_reward2/c50_bal_xn01 --act chunk50 --x_noise 0.1 diff --git a/rsm_rise/scripts/real/v7/reward2/payloads/rew2_c50_unw.sh b/rsm_rise/scripts/real/v7/reward2/payloads/rew2_c50_unw.sh new file mode 100644 index 0000000000000000000000000000000000000000..6432d2e0a15ebb543ea989ee50f77bef62e47b07 --- /dev/null +++ b/rsm_rise/scripts/real/v7/reward2/payloads/rew2_c50_unw.sh @@ -0,0 +1,4 @@ +#!/usr/bin/env bash +cd /proj/dmfexp/zwhong/rsm_rise +echo "[r2 payload] c50_unw $(date -u) host=$(hostname) gpu=${CUDA_VISIBLE_DEVICES:-?}" +exec /proj/dmfexp/zwhong/rsm_rise/venv_rsm/bin/python scripts/real/v7/reward2/train_reward2.py --out /proj/dmfexp/zwhong/rsm_rise/runs/v7_reward2/c50_unw --act chunk50 --weights none diff --git a/rsm_rise/scripts/real/v7/reward2/payloads/rew2_none_bal.sh b/rsm_rise/scripts/real/v7/reward2/payloads/rew2_none_bal.sh new file mode 100644 index 0000000000000000000000000000000000000000..35e8b98ab62fc415cb89039dc7b6105b21f12745 --- /dev/null +++ b/rsm_rise/scripts/real/v7/reward2/payloads/rew2_none_bal.sh @@ -0,0 +1,4 @@ +#!/usr/bin/env bash +cd /proj/dmfexp/zwhong/rsm_rise +echo "[r2 payload] none_bal $(date -u) host=$(hostname) gpu=${CUDA_VISIBLE_DEVICES:-?}" +exec /proj/dmfexp/zwhong/rsm_rise/venv_rsm/bin/python scripts/real/v7/reward2/train_reward2.py --out /proj/dmfexp/zwhong/rsm_rise/runs/v7_reward2/none_bal --act none diff --git a/rsm_rise/scripts/real/v7/reward2/rsm_scorer_ar.py b/rsm_rise/scripts/real/v7/reward2/rsm_scorer_ar.py new file mode 100644 index 0000000000000000000000000000000000000000..fcb9ddd6e4483e127ef3c043da565a90f0633317 --- /dev/null +++ b/rsm_rise/scripts/real/v7/reward2/rsm_scorer_ar.py @@ -0,0 +1,248 @@ +"""V7_REWARD2: NEW scorer option "chain_ar" -- the coin-terminated beta chain read out with an ACTION-CONDITIONED, +regression reward head r2(x, a) (train_reward2.py) instead of the successor's state-only membership head. + +Nothing in rsm_scorer.py is modified. build_rsm_scorer_ar(...) constructs the stock RSMScorer (mlp backend, mode +"chain") and re-classes ITS backend instance to MLPBackendAR, whose q() differs from MLPBackend.q() only when an r2 +head is attached and mode == "chain": + + per particle (identical coins / CRN noise / pruning as rsm_scorer._q_chain_logit): + walk N ~ coin(p = (gamma-beta)/(gamma(1-beta))) hops; at each hop z <- flow sample, a <- hop head(z, eps_k) + GOAL READ at the frozen node: z_g = flow sample(z, a); a_g = hop head(z_g, eps_goal) <-- NEW: the read needs + an action, taken from the SAME hop/continuation policy the chain already uses + (eps_goal is one extra CRN draw per particle, shared across candidates; + goal_action="hop_mean" uses eps=0, i.e. the Gaussian hop head's mean chunk) + value = r2(z_g, norm(a_g)) (no sigmoid / temperature: r2 is a regression on the shaped label) + Q = mean over particles of value ~ E[ r2 at a Geom(1-gamma) frame offset ] (the chain's discounted-occupancy read) +The tuple contract of MLPBackend.q is kept: (Q, Q, [lcb], stats-on-instance) -- the "logit" slot carries Q too, so +score_kind "prob" or "logit" rank identically. + +CONTRACT for rsm_real (see status/real/V7_REWARD2.md "scorer contract"): + checkpoint (torch.save dict) keys: + rew2 : state_dict of Rew2MLP (net.{0,2,..}.weight/bias; SiLU between Linear layers) + arch : {d_x: 1546, d_a: 500 (chunk50) | 10 (a0) | 0, act: "chunk50"|"a0"|"none", chunk: 50|1, adim: 10, + width, depth, dropout, input: "cat(x_zscored[1546], a_norm_flat[d_a])"} + act_norm : {min[10], max[10], rule: a_n = 2 (a - min)/(max - min) - 1} (== cooking_v7_action_norm.json) + feat_stats: path of the feat_stats.npz used for x (byte-identical to export/v7/rsm_ens20/feat_stats.npz) + inputs: x = clip((feat - mu)/max(sd, 0.01), -10, 10), feat = [DINO z 1536 | proprio 10] -- exactly the successor's + state; a = RAW absolute-pose action chunk [50 x 10] flattened time-major (the successor/hop-head layout), + normalised by act_norm inside the head wrapper; for act=a0 only the first 10 dims are used. + hop head: required (the goal read samples a_g from it); it emits RAW chunks of the successor's d_act (500). +""" +from __future__ import annotations +import importlib.util, os, sys +import numpy as np +import torch +import torch.nn as nn + +SNAP = "/proj/dmfexp/zwhong/rsm_rise/code/gen_q_rsm_snap_20261030" +RSM_SCORER_PY = os.environ.get( + "RSM_SCORER_PY", f"{SNAP}/rsm_rise/pipeline/code/rise_robomimic/robomimic/algo/rsm_scorer.py") +os.environ.setdefault("RSM_LIBERO_DIR", f"{SNAP}/rsm_libero") + + +def _load_rsm_scorer(): + if "rsm_scorer_stock" in sys.modules: + return sys.modules["rsm_scorer_stock"] + spec = importlib.util.spec_from_file_location("rsm_scorer_stock", RSM_SCORER_PY) + m = importlib.util.module_from_spec(spec); sys.modules["rsm_scorer_stock"] = m; spec.loader.exec_module(m) + return m + + +class Rew2MLP(nn.Module): + def __init__(self, d_x, d_a, width, depth, dropout=0.0): + super().__init__() + L, d = [], d_x + d_a + for _ in range(depth): + L += [nn.Linear(d, width), nn.SiLU()] + ([nn.Dropout(dropout)] if dropout > 0 else []) + d = width + L += [nn.Linear(d, 1)] + self.net = nn.Sequential(*L); self.d_a = d_a + + def forward(self, x, a=None): + h = x if self.d_a == 0 else torch.cat([x, a], -1) + return self.net(h).squeeze(-1) + + +class ActRewardHead(nn.Module): + """r2(x, a_raw_flat) with the action normalisation and chunk slicing folded in.""" + + def __init__(self, path, device="cpu"): + super().__init__() + ck = torch.load(path, map_location="cpu", weights_only=False) + ar = ck["arch"]; self.arch = ar + self.net = Rew2MLP(ar["d_x"], ar["d_a"], ar["width"], ar["depth"], ar.get("dropout", 0.0)) + self.net.load_state_dict(ck["rew2"]); self.net.eval() + for p in self.net.parameters(): + p.requires_grad_(False) + self.register_buffer("amin", torch.tensor(ck["act_norm"]["min"], dtype=torch.float32)) + self.register_buffer("amax", torch.tensor(ck["act_norm"]["max"], dtype=torch.float32)) + self.adim, self.d_a = int(ar["adim"]), int(ar["d_a"]) + self.to(device) + + def norm_chunk(self, a_raw_flat): + if self.d_a == 0: + return None + a = a_raw_flat.float().reshape(a_raw_flat.shape[0], -1, self.adim) + a = 2 * (a - self.amin) / (self.amax - self.amin) - 1 + return a.reshape(a.shape[0], -1)[:, :self.d_a] + + @torch.no_grad() + def forward(self, x, a_raw_flat): + return self.net(x.float(), self.norm_chunk(a_raw_flat)) + + +# RSM_PAIRTEST run 9 (hop-count sweep): opt-in instrumentation, no effect on Q. If env HOPSTAT_DIR is set, every +# chain_ar call records per-particle hop counts, the z-scored-state RMS at the last hop node (before the goal read) and +# at the goal-read sample, plus the start-state RMS; dumped as one npz per process at exit. +_HOPSTAT = {"hops": [], "z_last": [], "z_goal": [], "z_start": [], "cap": [], "beta": [], "vraw": []} # run 13: + vraw = per-particle reward read BEFORE any clamp +def _hopstat_dump(): + d = os.environ.get("HOPSTAT_DIR") + if not d or not _HOPSTAT["hops"]: + return + os.makedirs(d, exist_ok=True) + tag = os.environ.get("HOPSTAT_TAG", "x") + np.savez(os.path.join(d, f"hopstat_{tag}_{os.getpid()}.npz"), argv=np.array(" ".join(sys.argv)), + **{k: np.concatenate([np.ravel(np.asarray(v)) for v in vs]) if vs else np.zeros(0) for k, vs in _HOPSTAT.items()}) +import atexit as _atexit +_atexit.register(_hopstat_dump) + + +def q_chain_value_ar(m, enc_z, a_chunk, task, *, rew2, flow, rms, pol, beta, gamma, cap=None, n_particles=16, + flow_steps=8, max_rows=None, tail_eps=None, goal_action="hop_sample", return_particles=False, + seed=None, value_clip=None): + """Same walk as m._q_chain_logit (sampled path), r2 read with a hop-head action at the goal state.""" + sample_future = m._rsm_modules()[1].sample_future + dev = enc_z.device + _HS = bool(os.environ.get("HOPSTAT_DIR")) + B, D = enc_z.shape + n = int(n_particles) + tail_eps = m.CHAIN_TAIL_EPS if tail_eps is None else float(tail_eps) + max_rows = m.MAX_ROWS if max_rows is None else int(max_rows) + p_cont = m.chain_continuation_p(beta, gamma) + L = int(m.chain_cap(beta, gamma, tail_eps) if cap is None else cap) + if pol is None: + raise RuntimeError("chain_ar needs a hop head: the goal read samples its action from it") + g = None + if seed is not None: + g = torch.Generator(device=dev); g.manual_seed(int(seed)) + rnd = lambda *s: torch.randn(*s, device=dev, generator=g) + x0s = [rnd(n, D) for _ in range(L + 1)] + epss = [rnd(n, int(pol.d_act)) for _ in range(L)] if L >= 1 else [] + coins = torch.rand(L, n, device=dev, generator=g) if L >= 1 else None + eps_goal = rnd(n, int(pol.d_act)) # NEW draw, after the stock ones (stock CRN unchanged) + if goal_action == "hop_mean": + eps_goal = torch.zeros_like(eps_goal) + cand_per = max(1, max_rows // n); part_per = n if n <= max_rows else max_rows + q_out = torch.empty(B, n, device=dev, dtype=torch.float32) + hops_out = torch.zeros(B, n, device=dev, dtype=torch.int32) + capped_out = torch.zeros(B, n, device=dev, dtype=torch.bool) + for b0 in range(0, B, cand_per): + b1 = min(B, b0 + cand_per); nb = b1 - b0 + for p0 in range(0, n, part_per): + p1 = min(n, p0 + part_per); npp = p1 - p0; R = nb * npp + z = enc_z[b0:b1].repeat_interleave(npp, 0) + a = a_chunk[b0:b1].repeat_interleave(npp, 0) + tk = task[b0:b1].repeat_interleave(npp, 0) + bq = torch.full((R,), float(beta), device=dev) + pid = torch.arange(p0, p1, device=dev).repeat(nb) + alive = torch.ones(R, dtype=torch.bool, device=dev) + hops = torch.zeros(R, dtype=torch.int32, 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] + z_new = sample_future(flow, z[idx], a[idx], tk[idx], bq[idx], rms, flow_steps, n=1, x0=x0s[k][sub]) + a_new = pol.sample_eps(z_new, tk[idx], epss[k][sub]) + z = z.index_copy(0, idx, z_new); a = a.index_copy(0, idx, a_new) + hops = hops.index_add(0, idx, torch.ones_like(idx, dtype=torch.int32)) + if _HS: + z_last_rms = z.float().pow(2).mean(1).sqrt() + z = sample_future(flow, z, a, tk, bq, rms, flow_steps, n=1, x0=x0s[L][pid]) + if _HS: + _HOPSTAT["hops"].append(hops.cpu().numpy()); _HOPSTAT["z_last"].append(z_last_rms.cpu().numpy()) + _HOPSTAT["z_goal"].append(z.float().pow(2).mean(1).sqrt().cpu().numpy()) + _HOPSTAT["z_start"].append(enc_z[b0:b1].float().pow(2).mean(1).sqrt().cpu().numpy()) + _HOPSTAT["cap"].append([L]); _HOPSTAT["beta"].append([float(beta)]) + a_g = pol.sample_eps(z, tk, eps_goal[pid]) + v = rew2(z, a_g).float() + if _HS: + _HOPSTAT["vraw"].append(v.detach().cpu().numpy().ravel()) + if value_clip is not None: # RSM_PAIRTEST run 5 fix: deep chain nodes drift off-manifold (NN dist 30 -> + v = v.clamp(*value_clip) # 350 by hop 7) and the unbounded regression extrapolates to -15; clamp to + # the training-label range ([-1, 10] for reward_shaped2) + q_out[b0:b1, p0:p1] = torch.nan_to_num(v, nan=0.0).view(nb, npp) + hops_out[b0:b1, p0:p1] = hops.view(nb, npp) + capped_out[b0:b1, p0:p1] = alive.view(nb, npp) + hf = hops_out.float() + capped_frac = float(capped_out.float().mean()) + exp_hops = hf[~capped_out].mean() if (~capped_out).any() else torch.tensor(float("nan")) + levels_run = int(hf.sum()) + B * n # hop levels + one goal read per row + # same key set as rsm_scorer._q_chain_logit's stats, so RSMScorer._accum_chain_stats / chain_hop_summary work + stats = {"mode": "chain_ar", "beta": float(beta), "gamma": float(gamma), "p_cont": p_cont, "cap": L, + "tail_eps": float(tail_eps), "tail_prob_at_cap": p_cont ** L, "n_particles": n, + "goal_action": goal_action, + "E_hops_expected": p_cont / (1.0 - p_cont) if p_cont < 1.0 else float("inf"), + "E_beta_reads_expected": 1.0 / (1.0 - p_cont) if p_cont < 1.0 else float("inf"), + "L_star_tab_discounts": (1.0 - beta) / (1.0 - gamma), + "frame_offset_mean_expected": gamma / (1.0 - gamma), + "hops_mean": float(hf.mean()), "hops_median": float(hf.median()), + "hops_p90": float(hf.flatten().quantile(0.90)), "hops_mean_expired": float(exp_hops), + "capped_frac": capped_frac, "absorbed_frac": 0.0, "expired_frac": 1.0 - capped_frac, + "absorbed_note": "reference chain has no absorbing event; termination is the coin or the cap", + "levels_run": levels_run, "levels_per_row": levels_run / max(B * n, 1), + "cap_binding": bool(capped_frac * n >= 2.0 or float(hf.mean()) > 0.9 * max(L, 1))} + out = [q_out.mean(1), q_out.mean(1)] + if return_particles: + out.append(q_out) + out.append(stats) + return tuple(out) + + +def make_backend_ar_class(m): + class MLPBackendAR(m.MLPBackend): + rew2 = None + goal_action = "hop_sample" + value_clip = None + + def q(self, z, a, *, mode, depth, beta, gamma, n_particles, flow_steps, return_logit=False, + temperature=None, return_lcb=None, return_problog=False, return_trace=False): + if self.rew2 is None or mode != "chain": + return super().q(z, a, mode=mode, depth=depth, beta=beta, gamma=gamma, n_particles=n_particles, + flow_steps=flow_steps, return_logit=return_logit, temperature=temperature, + return_lcb=return_lcb, return_problog=return_problog, return_trace=return_trace) + if return_problog or return_trace: + raise RuntimeError("chain_ar supports score_kind prob/logit/conformal_lcb only") + task = torch.zeros(z.shape[0], dtype=torch.long, device=z.device) + out = list(q_chain_value_ar(m, z, a, task, rew2=self.rew2, flow=self.flow, rms=self.rms, pol=self.hop, + beta=beta, gamma=gamma, cap=getattr(self, "chain_cap_override", None), + n_particles=n_particles, flow_steps=flow_steps, max_rows=self.max_rows, + tail_eps=getattr(self, "chain_tail_eps", m.CHAIN_TAIL_EPS), + goal_action=self.goal_action, return_particles=return_lcb is not None, + seed=getattr(self, "chain_seed", None), value_clip=self.value_clip)) + q, ql = out.pop(0), out.pop(0) + res = [q, ql] + if return_lcb is not None: + res.append(m._particle_quantile(out.pop(0), return_lcb)) + self.last_chain_stats = out.pop(0) + return tuple(res) if (return_logit or return_lcb is not None) else q + return MLPBackendAR + + +def build_rsm_scorer_ar(rew2_ckpt, *, goal_action="hop_sample", value_clip=None, **rsm_kwargs): + """rsm_kwargs = the stock RSMScorer kwargs (backend="mlp", ckpt=, hop_ckpt=, feat_stats=, mode="chain", beta=, + gamma=, n_particles=, score_kind="prob", ...). Returns the stock scorer with its backend switched to chain_ar.""" + m = _load_rsm_scorer() + rsm_kwargs.setdefault("backend", "mlp"); rsm_kwargs.setdefault("mode", "chain") + if rsm_kwargs["backend"] != "mlp" or rsm_kwargs["mode"] != "chain": + raise ValueError("chain_ar is defined for backend=mlp, mode=chain only") + sc = m.RSMScorer(**rsm_kwargs) + be = sc.backend + be.__class__ = make_backend_ar_class(m) + be.rew2 = ActRewardHead(rew2_ckpt, device=be.device) + be.goal_action = goal_action + be.value_clip = value_clip + if be.rew2.arch["d_x"] != be.d_z: + raise RuntimeError(f"r2 reads {be.rew2.arch['d_x']}-d states, successor latent is {be.d_z}-d") + return sc diff --git a/rsm_rise/scripts/real/v7/reward2/run_cmp.sh b/rsm_rise/scripts/real/v7/reward2/run_cmp.sh new file mode 100644 index 0000000000000000000000000000000000000000..371869d6d27400ab62646d1402ad1d6f02288d83 --- /dev/null +++ b/rsm_rise/scripts/real/v7/reward2/run_cmp.sh @@ -0,0 +1,11 @@ +#!/usr/bin/env bash +#SBATCH --job-name=rr_cpu_v7r2_cmp +#SBATCH --partition=cpu +#SBATCH --account=grp_runtime +#SBATCH --nodes=1 --ntasks=1 --cpus-per-task=16 +#SBATCH --mem=96G +#SBATCH --time=02:00:00 +#SBATCH --output=/proj/dmfexp/zwhong/rsm_rise/logs/slurm/rr_cpu_v7r2_cmp.%j.out +#SBATCH --error=/proj/dmfexp/zwhong/rsm_rise/logs/slurm/rr_cpu_v7r2_cmp.%j.err +cd /proj/dmfexp/zwhong/rsm_rise +/proj/dmfexp/zwhong/rsm_rise/venv_rsm/bin/python scripts/real/v7/reward2/eval_reward2_cmp.py diff --git a/rsm_rise/scripts/real/v7/reward2/run_eval.sh b/rsm_rise/scripts/real/v7/reward2/run_eval.sh new file mode 100644 index 0000000000000000000000000000000000000000..97efdbdc21ea5f2b6d325fa8c1c8152814cc255f --- /dev/null +++ b/rsm_rise/scripts/real/v7/reward2/run_eval.sh @@ -0,0 +1,11 @@ +#!/usr/bin/env bash +#SBATCH --job-name=rr_cpu_v7r2_eval +#SBATCH --partition=cpu +#SBATCH --account=grp_runtime +#SBATCH --nodes=1 --ntasks=1 --cpus-per-task=16 +#SBATCH --mem=96G +#SBATCH --time=02:00:00 +#SBATCH --output=/proj/dmfexp/zwhong/rsm_rise/logs/slurm/rr_cpu_v7r2_eval.%j.out +#SBATCH --error=/proj/dmfexp/zwhong/rsm_rise/logs/slurm/rr_cpu_v7r2_eval.%j.err +cd /proj/dmfexp/zwhong/rsm_rise +/proj/dmfexp/zwhong/rsm_rise/venv_rsm/bin/python scripts/real/v7/reward2/eval_reward2.py diff --git a/rsm_rise/scripts/real/v7/reward2/run_eval_sf.sh b/rsm_rise/scripts/real/v7/reward2/run_eval_sf.sh new file mode 100644 index 0000000000000000000000000000000000000000..44962bb6f9a78d11d41da58870def912c210b199 --- /dev/null +++ b/rsm_rise/scripts/real/v7/reward2/run_eval_sf.sh @@ -0,0 +1,22 @@ +#!/usr/bin/env bash +#SBATCH --partition=cpu +#SBATCH --account=grp_runtime +#SBATCH --nodes=1 --ntasks=1 --cpus-per-task=32 +#SBATCH --mem=96G +#SBATCH --time=10: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 +# RSM_PAIRTEST run 6: SELF-FORCED r2 head (runs/v7_reward2_sf/) in the rsm_real#17 chain on the frozen v7 +# successor; A/B (errmode 16x8) + C (pairtest_v3 16x2/16x8/64x4), TUNE only. CLIP=1 -> arc (clamp [-1,10]), 0 -> ar. +# usage: SF=main_s0 CLIP=1 sbatch -J rr_cpu_evsf_ run_eval_sf.sh +set -uo pipefail +export PAIRTEST_VERSION=pairtest_v3 +cd /proj/dmfexp/zwhong/rsm_rise +PY=/proj/dmfexp/zwhong/rsm_rise/venv_rsm/bin/python; S=scripts/real/v7/pairtest +ck=runs/v7_reward2_sf/$SF/ckpt_best.pt; [ -f $ck ] || { echo "no $ck"; exit 1; } +k=$([ "${CLIP:-1}" = 1 ] && echo arc || echo ar); t=sf_${SF}_$k +$PY $S/errmode_test.py --stage score --split tune --seeds 8 --model ${t}_16x8=$k:$ck,np=16 +$PY $S/pairtest.py --stage score --split tune --seeds 2 --model ${t}=$k:$ck,np=16 +$PY $S/pairtest.py --stage score --split tune --seeds 8 --model ${t}_np16s8=$k:$ck,np=16 +$PY $S/pairtest.py --stage score --split tune --seeds 4 --model ${t}_np64s4=$k:$ck,np=64 +echo "[ev_sf] done $(date -u)" diff --git a/rsm_rise/scripts/real/v7/reward2/run_eval_sf2.sh b/rsm_rise/scripts/real/v7/reward2/run_eval_sf2.sh new file mode 100644 index 0000000000000000000000000000000000000000..f7621df53aff0fa4bc355221d41ef2f5365e5dda --- /dev/null +++ b/rsm_rise/scripts/real/v7/reward2/run_eval_sf2.sh @@ -0,0 +1,23 @@ +#!/usr/bin/env bash +#SBATCH --partition=cpu +#SBATCH --account=grp_runtime +#SBATCH --nodes=1 --ntasks=1 --cpus-per-task=32 +#SBATCH --mem=96G +#SBATCH --time=10: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 +# RSM_PAIRTEST run 7: r2-family head HEAD (runs/v7_reward2_sf//ckpt_best.pt), clamped chain (arc), optional +# successor SUCC (default = frozen v7) and chain tail eps TAIL (depth cap; 0.42 -> 4 hops, 0.65 -> 2 hops). +# A/B (errmode 16x8) + C (pairtest_v3 16x2/16x8/64x4), TUNE only. usage: HEAD=d1 TAG=x [SUCC=ck] [TAIL=0.42] sbatch ... +set -uo pipefail +export PAIRTEST_VERSION=pairtest_v3 +cd /proj/dmfexp/zwhong/rsm_rise +PY=/proj/dmfexp/zwhong/rsm_rise/venv_rsm/bin/python; S=scripts/real/v7/pairtest +ck=runs/v7_reward2_sf/$HEAD/ckpt_best.pt; [ -f $ck ] || { echo "no $ck"; exit 1; } +ex=""; [ -n "${SUCC:-}" ] && ex="$ex,succ=$SUCC"; [ -n "${TAIL:-}" ] && ex="$ex,tail=$TAIL" +t=sf2_${TAG} +$PY $S/errmode_test.py --stage score --split tune --seeds 8 --model ${t}_16x8=arc:$ck,np=16$ex +$PY $S/pairtest.py --stage score --split tune --seeds 2 --model ${t}=arc:$ck,np=16$ex +$PY $S/pairtest.py --stage score --split tune --seeds 8 --model ${t}_np16s8=arc:$ck,np=16$ex +$PY $S/pairtest.py --stage score --split tune --seeds 4 --model ${t}_np64s4=arc:$ck,np=64$ex +echo "[ev_sf2] done $(date -u)" diff --git a/rsm_rise/scripts/real/v7/reward2/run_iql_eval.sh b/rsm_rise/scripts/real/v7/reward2/run_iql_eval.sh new file mode 100644 index 0000000000000000000000000000000000000000..970bb1022e9fe628e95e42cef42239ac408b57f8 --- /dev/null +++ b/rsm_rise/scripts/real/v7/reward2/run_iql_eval.sh @@ -0,0 +1,60 @@ +#!/usr/bin/env bash +#SBATCH --job-name=rr_cpu_v7r2_iqleval +#SBATCH --partition=cpu +#SBATCH --account=grp_runtime +#SBATCH --nodes=1 --ntasks=1 --cpus-per-task=16 +#SBATCH --mem=48G +#SBATCH --time=03:00:00 +#SBATCH --output=/proj/dmfexp/zwhong/rsm_rise/logs/slurm/rr_cpu_v7r2_iqleval.%j.out +#SBATCH --error=/proj/dmfexp/zwhong/rsm_rise/logs/slurm/rr_cpu_v7r2_iqleval.%j.err +# V7_REWARD2 IQL eval: RSHAPED2 t09 critics (seeds 0..3, those with a model_epoch_.pth; missing seeds skipped) vs the +# frozen comparator iql_v7_RPROGRESS_t09_s0_e1250, on TUNE and TEST, CPU only (critics run on CPU as in jm v7iqlcol_ep.sh). +# (a) jm junction harness, unmodified: iql_columns.py --manifest + ensemble_metrics.py (= v7iqlcol_ep.sh with +# SPLIT=tune / SPLIT=test; no leaderboard append). TUNE comparator column = jm's own v7iql_e1250_parts (read only); +# TEST comparator column is scored once into $OUT/junction/test_cmp_parts (flock, shared by all epochs). +# (b) iql_value_auc.py: per-episode V/Q AUCs, frame Spearman vs reward_shaped2, branch-2 test (parallel with (a)). +# usage: sbatch scripts/real/v7/reward2/run_iql_eval.sh outputs: status/real/v7_reward2_iql/ +set -o pipefail # no -u: jm scripts/env.sh + wandb_env.sh are not -u clean +EP=${1:?epoch} +R=/proj/dmfexp/zwhong/jm/rsm_rise +V7J=$R/scripts/real/v7_junction +D=$R/data/derived/v7_junction +S=/proj/dmfexp/zwhong/rsm_rise/scripts/real/v7/reward2 +OUT=/proj/dmfexp/zwhong/rsm_rise/status/real/v7_reward2_iql +CMP=iql_v7_RPROGRESS_t09_s0_e1250 +CMP_TUNE_PARTS=$R/status/real/v7_junction/v7iql_e1250_parts +cd $R; source scripts/env.sh; PY=$R/env/bin/python +mkdir -p $OUT/junction $OUT/values /proj/dmfexp/zwhong/rsm_rise/logs/slurm +echo "[r2iql] e$EP host=$(hostname) job=${SLURM_JOB_ID:-na} $(date -u)" +MAN=$OUT/manifest_e${EP}.json +NEW=$($PY $S/iql_r2_manifest.py $EP $MAN | tail -1) || exit 3 +[ -n "$NEW" ] || { echo "[r2iql] no RSHAPED2 checkpoint at e$EP -- nothing to do"; exit 4; } +NEWC=$(echo $NEW | tr ' ' ','); echo "[r2iql] critics: $NEW (+ $CMP)" + +# (b) value AUC, background (8 threads); flock so concurrent epoch jobs do not both compute the comparator's values +( OMP_NUM_THREADS=8 MKL_NUM_THREADS=8 flock $OUT/values/.lock $PY $S/iql_value_auc.py --manifest $MAN \ + --out $OUT/auc_e${EP}.json --values-dir $OUT/values ) > $OUT/auc_e${EP}.log 2>&1 & +PID_AUC=$! + +# (a) junction harness, TUNE then TEST (8 threads, set inside iql_columns.py) +rc=0 +for SP in tune test; do + SETS=$D/v7${SP}_d0.npz,$D/v7${SP}_d1.npz,$D/v7${SP}_d2.npz + PT=$OUT/junction/${SP}_e${EP}_parts + $PY $V7J/iql_columns.py --sets $SETS --parts $PT --epoch $EP --names $NEWC --manifest $MAN || { rc=1; continue; } + if [ $SP = tune ]; then CPT=$CMP_TUNE_PARTS + else CPT=$OUT/junction/test_cmp_parts + flock $OUT/junction/.test_cmp.lock $PY $V7J/iql_columns.py --sets $SETS --parts $CPT --epoch 1250 --names $CMP --manifest $MAN || { rc=1; continue; } + fi + ENS=(); MEM="" + for n in $NEW; do ENS+=(--ens $n=$PT:$n); MEM+=",$PT:$n"; done + [ $(echo $NEW | wc -w) -gt 1 ] && ENS+=(--ens iql_v7_RSHAPED2_t09_ens_e${EP}=${MEM#,}) + ENS+=(--ens $CMP=$CPT:$CMP) + $PY $V7J/ensemble_metrics.py --sets $SETS --out $OUT/junction/${SP}_e${EP}_metrics.json "${ENS[@]}" || rc=2 +done + +wait $PID_AUC || { echo "[r2iql] value AUC failed, see $OUT/auc_e${EP}.log"; rc=$((rc+10)); } +tail -n 3 $OUT/auc_e${EP}.log +$PY $S/iql_r2_summary.py --tune $OUT/junction/tune_e${EP}_metrics.json --test $OUT/junction/test_e${EP}_metrics.json \ + --auc $OUT/auc_e${EP}.json --out $OUT/summary_e${EP}.json +echo "[r2iql] done rc=$rc $(date -u)"; exit $rc diff --git a/rsm_rise/scripts/real/v7/reward2/run_iqlview.sh b/rsm_rise/scripts/real/v7/reward2/run_iqlview.sh new file mode 100644 index 0000000000000000000000000000000000000000..75c5b70a13812c657f594416c74194565da5a696 --- /dev/null +++ b/rsm_rise/scripts/real/v7/reward2/run_iqlview.sh @@ -0,0 +1,11 @@ +#!/usr/bin/env bash +#SBATCH --job-name=rr_cpu_v7r2_iqlview +#SBATCH --partition=cpu +#SBATCH --account=grp_runtime +#SBATCH --nodes=1 --ntasks=1 --cpus-per-task=8 +#SBATCH --mem=32G +#SBATCH --time=00:30:00 +#SBATCH --output=/proj/dmfexp/zwhong/rsm_rise/logs/slurm/rr_cpu_v7r2_iqlview.%j.out +#SBATCH --error=/proj/dmfexp/zwhong/rsm_rise/logs/slurm/rr_cpu_v7r2_iqlview.%j.err +cd /proj/dmfexp/zwhong/rsm_rise +/proj/dmfexp/zwhong/rsm_rise/venv_rsm/bin/python scripts/real/v7/reward2/make_iql_view.py diff --git a/rsm_rise/scripts/real/v7/reward2/run_labels.sh b/rsm_rise/scripts/real/v7/reward2/run_labels.sh new file mode 100644 index 0000000000000000000000000000000000000000..93a51a4afd951a8693778c96a8289340159aa91f --- /dev/null +++ b/rsm_rise/scripts/real/v7/reward2/run_labels.sh @@ -0,0 +1,11 @@ +#!/usr/bin/env bash +#SBATCH --job-name=rr_cpu_v7r2_labels +#SBATCH --partition=cpu +#SBATCH --account=grp_runtime +#SBATCH --nodes=1 --ntasks=1 --cpus-per-task=8 +#SBATCH --mem=32G +#SBATCH --time=00:30:00 +#SBATCH --output=/proj/dmfexp/zwhong/rsm_rise/logs/slurm/rr_cpu_v7r2_labels.%j.out +#SBATCH --error=/proj/dmfexp/zwhong/rsm_rise/logs/slurm/rr_cpu_v7r2_labels.%j.err +cd /proj/dmfexp/zwhong/rsm_rise +/proj/dmfexp/zwhong/rsm_rise/venv_rsm/bin/python scripts/real/v7/reward2/make_labels.py diff --git a/rsm_rise/scripts/real/v7/reward2/run_train_r2.sh b/rsm_rise/scripts/real/v7/reward2/run_train_r2.sh new file mode 100644 index 0000000000000000000000000000000000000000..25bdee664daa4b2d7860b380e39c46a85e478ccd --- /dev/null +++ b/rsm_rise/scripts/real/v7/reward2/run_train_r2.sh @@ -0,0 +1,337 @@ +#!/usr/bin/env bash +# RISE training runner. usage: run_train.sh [extra hydra overrides...] +# task : square_expert_play | mug_expert_suboptimal | square_expert_suboptimal +# cell : S0A (flagship) | S0B (use_bc=True) | S3H1 (use_bc=True on successful episodes only, no kNN augmentation) +# | S3H1aug (S3H1 + their kNN augmentation ON) | S3H1plain/S0Bplain (the PAPER's BC/BCU: +# plain diffusion policy, no augmentation, no spectral norm, no bottleneck) | smoke_* +# Checkpoints: $ROOT/runs//policy/_seed///models/model_epoch_*.pth +set -uo pipefail +# The whole script body is a function so bash parses it completely before running anything: +# editing this file while a job is running it is then safe (bash otherwise reads scripts incrementally). +main() { + ROOT=/proj/dmfexp/zwhong/jm/rsm_rise + source $ROOT/scripts/env.sh + # V7_REWARD2: W&B to richardrl/rsm_rise only (brief rule 4); keep jm ROOT semantics + source /proj/dmfexp/zwhong/rsm_rise/wandb_env.sh; export RSM_RISE_ROOT=$ROOT + task=$1; cell=$2; seed=$3; shift 3 + case $task in + square_expert_play) tcfg=square; data=$ROOT/data/raw/square_expert_play.hdf5 ;; + mug_expert_suboptimal) tcfg=mug; data=$ROOT/data/raw/mug_expert_suboptimal.hdf5 ;; # raw file lacks next_obs -> derived _nextobs copy (below) + square_expert_suboptimal) tcfg=square_suboptimal; data=$ROOT/data/raw/square_expert_suboptimal.hdf5 ;; + # additional ("winning configuration") tasks -- do not launch until the orchestrator says so + threading_expert_play) tcfg=threading; data=$ROOT/data/raw/threading_expert_play.hdf5 ;; + two_piece_expert_play) tcfg=piece_assembly; data=$ROOT/data/raw/two_piece_expert_play.hdf5 ;; + two_piece_expert_play_tipping) tcfg=piece_assembly; data=$ROOT/data/raw/two_piece_expert_play_tipping.hdf5 ;; # no tipping-specific config in _experiments/; coverage config (lambda 0.1, T 0.08) + two_piece_expert_suboptimal) tcfg=piece_assembly_suboptimal; data=$ROOT/data/raw/two_piece_expert_suboptimal.hdf5 ;; + # paper-regime variant of square suboptimal (orchestrator 15:38): Table IV used 20 expert + 80 suboptimal + # episodes and NO augmentation (T=0); dataset built by scripts/build_square_sub_paper.py (seed 0 subsample). + square_sub_paper) tcfg=square_suboptimal; data=$ROOT/data/derived/square_sub_paper.hdf5 ;; + # square_sub_paper2: the SAME Table IV amounts (20 expert + 80 suboptimal) but with the 20 experts drawn from + # the PLAY file. The suboptimal file's own reward-1 episodes train BC to ~61 % against the paper's 8.0, while + # the play file's experts train to ~3 %, which brackets it -- the two pools share no initial state and differ in + # length and action magnitude, so they are different demo sources (runs/_diag/expert_overlap.json). + square_sub_paper2) tcfg=square_suboptimal; data=$ROOT/data/derived/square_sub_paper2.hdf5 ;; + # square_sub_20100: the released suboptimal task with its expert pool cut to 20 (all 100 suboptimal kept), so + # the only change from square_expert_suboptimal is how many demonstrations the policy sees. + square_sub_20100) tcfg=square_suboptimal; data=$ROOT/data/derived/square_sub_20100.hdf5 ;; + # Table IV subsampled variants of the other released files (orchestrator instruction 17:16, from the RISE + # authors): fixed seed-0 subsamples built by scripts/build_paper_variant.py; key lists in data/derived/.json. + threading_paper) tcfg=threading; data=$ROOT/data/derived/threading_paper.hdf5 ;; # 200 play + 200 of 250 expert, T 0.08 + mug_paper) tcfg=mug; data=$ROOT/data/derived/mug_paper.hdf5 ;; # 20 expert + 85 of 100 suboptimal, T 0.05 + piecesub_paper) tcfg=piece_assembly_suboptimal; data=$ROOT/data/derived/piecesub_paper.hdf5 ;; # 10 of 20 expert + 100 suboptimal, T 0.0 (augmentation off below) + piecetip_paper) tcfg=piece_assembly; data=$ROOT/data/derived/piecetip_paper.hdf5 ;; # 200 expert + 104 tipped + 199 of 400 flat play, T 0.08 + # rsm_rise #267: MimicGen-GENERATED variants, built in the EVAL env so that the expert and the + # play halves share ONE action space. Task 1 of #267 showed that in the released mug/threading + # files the expert half is MimicGen (6-DoF, |a| to 1.0, robot init noise sigma 0.02) while the + # play half is human teleop (roll/pitch identically 0, |a| <= 0.625, one fixed robot init) -- + # the two rows that collapse are exactly the two heterogeneous files. These task names are NEW, + # so nothing existing is overwritten. + # mug_mgen : 20 released experts + 104 MimicGen MugCleanup_D0 successes (r=1) + # + 100 MimicGen failures (r=0); built by scripts/tmp/i267/build_mgen_dataset.py + # threading_mgen : MimicGen Threading_RSMCov (= robomimic_threading_coverage init distribution) + mug_mgen) tcfg=mug; data=$ROOT/data/derived/mug_mgen.hdf5 ;; + threading_mgen) tcfg=threading; data=$ROOT/data/derived/threading_mgen.hdf5 ;; + # rsm_rise #263: REAL FR3 cooking play data (HF jmarangola/rsm_cooking_v5 -> scripts/real/convert_cooking_hdf5.py). + # Provenance reward: episodes ending in state {3,4} = expert (r=1 every frame), {5,6} = suboptimal (r=0). + # 148 expert + 100 suboptimal = 248 episodes, 181 530 frames, 84x84 full-FOV images, next_obs included. + cooking_v5_expert_suboptimal) tcfg=cooking; data=$ROOT/data/raw/cooking_v5_expert_suboptimal.hdf5 ;; + # REWARD_MATRIX (gen_q#280 / rsm_real#2, 2026-09-23): reward-relabelled VIEWS of the cooking file. + # Same demos, frames, actions and observations -- every demo member except `rewards` is an h5py + # ExternalLink back into data/raw/cooking_v5_expert_suboptimal.hdf5, which is opened read-only and + # NEVER modified -- and `rewards` carries the named reward head instead of the shipped one. Built and + # asserted frame-for-frame against cache/real_cooking_v5/meta.npz by scripts/real/make_reward_hdf5.py + # (1.1 MB per head, no data duplicated). Task name = cooking_v5_rw_, so every head gets its own + # runs/ tree and no existing cell is overwritten. These cells exist so the IQL critic is trained on the + # SAME label as the RSM cell it is compared against; without them the two scorers read different rewards. + cooking_v5_rw_*) tcfg=cooking; data=$ROOT/data/derived/rw/${task}.hdf5 + [ -f "$data" ] || { echo "missing relabelled dataset $data -- run scripts/real/make_reward_hdf5.py"; exit 2; } ;; + # V6_IQL (plan T5, 2026-10-15): rsm_cooking_v6 views, RFINAL (edge_to==7) / RPROGRESS (edge_to in {3,7}); ExternalLinks + # into data/raw/cooking_v6_expert_suboptimal.hdf5, built by scripts/real/convert_cooking_v6_hdf5.py. + cooking_v6_rw_*) tcfg=cooking; data=$ROOT/data/derived/rw/${task}.hdf5 + [ -f "$data" ] || { echo "missing v6 view $data -- run scripts/real/convert_cooking_v6_hdf5.py"; exit 2; } ;; + # V7_IQL (2026-10-28): rsm_cooking_v7 views, RFINAL (edge_to==7) / RPROGRESS (edge_to in {3,8,7}; 8 = pickup-ready cooking + # state); ExternalLinks into data/raw/cooking_v7_expert_suboptimal.hdf5, built by scripts/real/convert_cooking_v7_hdf5.py. + cooking_v7_rw_*) tcfg=cooking; data=$ROOT/data/derived/rw/${task}.hdf5 + [ -f "$data" ] || { echo "missing v7 view $data -- run scripts/real/convert_cooking_v7_hdf5.py"; exit 2; } ;; + *) echo "unknown task $task"; exit 2 ;; + esac + # raw files that lack next_obs use the derived copy (built by scripts/make_derived_datasets.py as a CPU job) + nx=$ROOT/data/derived/${task}_nextobs.hdf5; [ -f "$nx" ] && data=$nx + taskov=() + # Table IV regime: no action augmentation of any kind, for EVERY cell of this task. + case $task in + square_sub_paper|square_sub_paper2|square_sub_20100|piecesub_paper) taskov+=(training.action_augmentation=False training.advanced_augmentation=False) ;; + esac + # BASE_TOPUP (gen_q#287) path (D), 2026-09-25. A cell whose family name ends `dinod` instead of `dino` + # is the SAME recipe as its live-DINO twin -- byte-for-byte the same case arm below, because the recipe + # is matched on $rcell (the name with `dinod` -> `dino`) -- with ONE change: the observation is the + # PRECOMPUTED 1545-d pooled DINO state from data/derived/_dinostate.hdf5 (= cache//z.f16.npy + # + proprio, z-scored by feat_stats -- exactly what rsm_scorer.PooledDinoState feeds every RSM / IFQL / + # DINO-WM / DF number at eval time), fed as a low_dim key with NO encoder at all. The frozen ViT then + # runs ZERO times per epoch, which is the only lever that shortens a single ~43 GPU-h critic run + # (owner priority 2026-09-25 22:00 UTC). + # * `training.use_dino_features=False` is CORRECT here and not a contradiction: there is no image to + # encode, so there is no encoder to swap. The DINO features arrive through the dataset. + # * NOT bit-identical to the live `*dino*` arm: (D)'s state is z-scored by feat_stats while the live + # path feeds the critic MLP raw 1536-d features. (D) is the representation the owner asked for + # ("the SAME precomputed DINOv2 features RSM reads"), so it keeps its OWN family name and never + # pools with the live cells. + # * `train_robomimic.py:536` copies low_dim_keys into `train.proprio_keys`, so `dino_state` also + # becomes a "proprio" key for robomimic's neighbour machinery. Verified harmless for these cells: + # `proprio_keys` is read ONLY by SequenceDataset._extract_proprio_state_for_distance, called only + # from the advanced/mask augmentation builders, and every `*dinod*` cell in flight has + # action_augmentation=False and advanced_augmentation=False (mask_augmentation defaults False). + # A `*dinod*` cell that ever turns augmentation ON must revisit this. + # BASE_TOPUP (gen_q#287) FAST CRITIC PATH, 2026-09-26 (owner 05:00 UTC "IDQL is just IQL with a scalar + # head -- why is it so slow?"). A cell family ending `dinodq` is path (D) PLUS critic-only: + # * `algo.critic_only=True` -> no diffusion-actor loss, no actor update. The flagship never reads + # this run's actor (the proposer is the fixed published PIXEL actor from another checkpoint), and the + # critic's gradients are unchanged by construction: _compute_critic_loss/_update_critic never read + # the actor and the advantage weights are .detach()ed (robomimic/algo/idql.py). + # * `training.action_augmentation=False advanced_augmentation=False` + `algo.critic_skip_even_epochs=True` + # wherever the RELEASED recipe had augmentation ON. This is the step that makes path (D) LEGAL for the + # 15 aug-ON runs that blocked it in run 4: RISE's critic NEVER trains on the kNN-augmented rows + # (`critic_skip = using_augmented and not critic_on_augmented`, released `critic_on_augmented=False`), + # so the augmentation pool -- which path (D) cannot build, having no images for its distance space -- + # only ever fed the ACTOR. Dropping it changes nothing the critic sees, and skipping the even epochs + # keeps the critic update COUNT at the released 250k while still checkpointing at epoch 5000, which + # the table loader requires (critic epoch == proposer epoch). + # * Aug-OFF tasks (square_sub_20100 by regime, threading's S0Aidql by cell) must NOT get + # critic_skip_even_epochs: their released critic already updates every epoch (500k / 50k). + # New family name -> its own runs/ tree and its own arm key `critic:dino(Dq)` (verdict_table.py + # _critic_arm_label), so it can never pool with the live `critic:dino` column or with `critic:dino(D)`. + pathd=0; pathdq=0 + case $cell in + *dinodq*) pathd=1; pathdq=1; rcell=${cell//dinodq/dino} ;; + *dinod*) pathd=1; rcell=${cell//dinod/dino} ;; + *) rcell=$cell ;; + esac + cellov=() + case $rcell in + # rsm_rise CRITIC_DINO (gen_q fairness fix #1, 2026-09-25). Identical to S0A / S0Aidql in every + # hyper-parameter, data file, reward, epoch count and seed -- the ONLY change is the observation + # ENCODER: frozen DINOv2 ViT-S/14 [CLS | GeM(patch)] per camera instead of the from-scratch + # ResNet18Conv + SpatialSoftmax, i.e. exactly the features the RSM / DINO-WM / DF / IFQL scorers + # consume (train_robomimic.py also drops the 76x76 CropRandomizer under this flag so the field of + # view matches cache// as well). NEW family names -> new runs//policy/ trees, so no + # faithful-RISE checkpoint or table number is ever overwritten. The critic is what we want; the + # actor is co-trained because robomimic's IDQL has no critic-only entry point -- which costs the + # critic nothing: _compute_critic_loss/_update_critic (robomimic/algo/idql.py:330-345) never read + # the actor, and the actor's advantage weights are .detach()ed. + # ORDER: these patterns CONTAIN "S0A", and bash `case` is first-match-wins, so they must come first + # (the same trap that made S0Bplain silently train as S0B -- see the note below). + # CRITIC_DINO run 3 (2026-09-25): `num_epochs=500`. Threading is the ONLY flagship row whose pinned + # proposer is the IDQL policy at epoch 500 (status/fairaudit/proposer.json) and the loader requires + # `critic epoch == policy epoch`, so epochs 501-5000 of this cell can never be read by any cell in the + # table. The cap is EXACT, not a shortcut: `algo.optim_params.*.learning_rate.epoch_schedule` is `[]` + # for critic, vf and policy, so `lr_scheduler_from_optim_params` returns None and the learning rate is + # constant -- nothing in the optimisation depends on the horizon, and the epoch-500 weights are + # bit-identical to those of a 5000-epoch run with the same seed. Saves ~133 GPU-h (3 seeds x 4500 + # epochs x 0.59 min). `RSM_CRITICDINO_FULL_EPOCHS=1` restores 5000 if a later row ever needs them. + # gen_q#287 deliverable 3 (gamma sweeps for the critics), 2026-09-26. These arms MUST stay ABOVE the + # plain *S0Adino* / *S0Aidqldino* arms: the case matches top-down, so `S0Adinog0p95` would otherwise be + # swallowed by `*S0Adino*` and silently train at the default algo.discount=0.99 under a name that claims + # 0.95. Each arm is the plain recipe PLUS one key -- `algo.discount` (iql_config.py:37, default 0.99 = + # deliverable 1's run) -- so the gamma is reproducible from the CELL NAME alone, which is what the arm key + # in the tables is derived from. Nothing else in the released recipe changes. + *S0Aidqldinog0p95*) cellov+=(training.use_dino_features=True training.action_augmentation=False + training.advanced_augmentation=False training.spectral_norm_policy=False + training.policy_bottleneck_beta=0.0 training.discount_rate=0.95) + [ "${RSM_CRITICDINO_FULL_EPOCHS:-0}" = "1" ] || cellov+=(training.num_epochs=500) ;; + *S0Aidqldinog0p98*) cellov+=(training.use_dino_features=True training.action_augmentation=False + training.advanced_augmentation=False training.spectral_norm_policy=False + training.policy_bottleneck_beta=0.0 training.discount_rate=0.98) + [ "${RSM_CRITICDINO_FULL_EPOCHS:-0}" = "1" ] || cellov+=(training.num_epochs=500) ;; + *S0Aidqldinog0p995*) cellov+=(training.use_dino_features=True training.action_augmentation=False + training.advanced_augmentation=False training.spectral_norm_policy=False + training.policy_bottleneck_beta=0.0 training.discount_rate=0.995) + [ "${RSM_CRITICDINO_FULL_EPOCHS:-0}" = "1" ] || cellov+=(training.num_epochs=500) ;; + # gen_q#287 deliverable 3b (EXPECTILE sweep, owner 2026-09-26 04:30Z), added 2026-09-26 run 15. Same + # placement rule as the gamma arms: these patterns CONTAIN `S0Adino` / `S0Aidqldino`, so they must stay + # ABOVE them or bash's first-match-wins would train them at the released tau=0.9 under a name claiming + # 0.5/0.7. One key only -- `algo.vf_quantile` (idql_config.py:111, released 0.9; the expectile of the + # V regression, idql.py:451-454), already plumbed from `training.vf_quantile` + # (train_robomimic.py:571), so nothing else in the recipe moves. tau=0.5 is the behaviour-value + # variant, i.e. the same estimand RSM's beta-recursion estimates. + *S0Aidqldinot0p5*) cellov+=(training.use_dino_features=True training.action_augmentation=False + training.advanced_augmentation=False training.spectral_norm_policy=False + training.policy_bottleneck_beta=0.0 training.vf_quantile=0.5) + [ "${RSM_CRITICDINO_FULL_EPOCHS:-0}" = "1" ] || cellov+=(training.num_epochs=500) ;; + *S0Aidqldinot0p7*) cellov+=(training.use_dino_features=True training.action_augmentation=False + training.advanced_augmentation=False training.spectral_norm_policy=False + training.policy_bottleneck_beta=0.0 training.vf_quantile=0.7) + [ "${RSM_CRITICDINO_FULL_EPOCHS:-0}" = "1" ] || cellov+=(training.num_epochs=500) ;; + *S0Adinot0p5*) cellov+=(training.use_dino_features=True training.vf_quantile=0.5) ;; + *S0Adinot0p7*) cellov+=(training.use_dino_features=True training.vf_quantile=0.7) ;; + *S0Adinog0p95*) cellov+=(training.use_dino_features=True training.discount_rate=0.95) ;; + *S0Adinog0p98*) cellov+=(training.use_dino_features=True training.discount_rate=0.98) ;; + *S0Adinog0p995*) cellov+=(training.use_dino_features=True training.discount_rate=0.995) ;; + *S0Aidqldino*) cellov+=(training.use_dino_features=True training.action_augmentation=False + training.advanced_augmentation=False training.spectral_norm_policy=False + training.policy_bottleneck_beta=0.0) + [ "${RSM_CRITICDINO_FULL_EPOCHS:-0}" = "1" ] || cellov+=(training.num_epochs=500) ;; + *S0Adino*) cellov+=(training.use_dino_features=True) ;; + *S0A*) ;; + # CASE ORDER (2026-09-21). bash `case` is FIRST MATCH WINS, and `S0Bplain` CONTAINS `S0B`, so it used + # to match the `*S0B*` arm and never reach the plain arm below: it kept RISE's augmentation, spectral + # norm and bottleneck, making it identical to `S0B` except for RNG while being reported as the paper's + # plain BCU. Found by gen_q#265 noticing an `S0Bplain` log that contained a 570-row augmentation pool, + # which a plain cell cannot build; confirmed by the built configs matching `S0B` on all nine recipe keys + # across three tasks. `S3H1plain` was never affected (it matches neither `*S0A*` nor `*S0B*`). The + # plain arm now comes FIRST. Any family name that is a superstring of another family's pattern must be + # ordered ahead of it. + # BASE_TOPUP (gen_q#287, 2026-09-25). The paper's BC / BCU baselines with DINOv2 conditioning, i.e. + # the SAME plain recipe as `S3H1plain` / `S0Bplain` (no augmentation, no spectral norm, no bottleneck, + # same epochs / lr / batch / diffusion policy head) with the ONLY change being the observation encoder: + # `training.use_dino_features=True`, which swaps robomimic's ResNet for a FROZEN dinov2_vits14 and -- + # via the CRITIC_DINO patch at train_robomimic.py:542 -- drops the 76x76 CropRandomizer, so the features + # are the full-84x84-frame features `cache//z.f16.npy` holds (measured parity vs the cache: + # cos_min 0.9999887, mean|diff| 0.0060, the residual being the cache's fp16 storage -- + # status/criticdino/FEATPARITY.md). Owner ask, 2026-09-25 ~20:10 UTC: "the baselines should all have + # dino input features". + # CASE ORDER: `S3H1plaindino` CONTAINS `S3H1plain` and `S0Bplaindino` CONTAINS `S0Bplain`, and bash + # `case` is FIRST MATCH WINS -- so these arms MUST stay above the plain arm below, exactly the trap + # documented for `S0Bplain` vs `S0B`. + *S3H1plaindino*|*S0Bplaindino*) + cellov+=(training.use_bc=True training.action_augmentation=False training.advanced_augmentation=False + training.spectral_norm_policy=False training.policy_bottleneck_beta=0.0 + training.use_dino_features=True) + case $rcell in *S3H1plaindino*) data=$ROOT/data/derived/${task}_expert.hdf5 ;; esac ;; + *S3H1plain*|*S0Bplain*) # THE PAPER'S ACTUAL BASELINES (RISE Sec. V, verbatim): BC is "the standard + # imitation learning paradigm, with a diffusion policy trained on only the expert dataset D_E"; + # BCU "is similar to behavior cloning, but on the union"; and IDQL is "the method RISE builds off + # of, WITHOUT ANY DATA AUGMENTATION OR LIPSCHITZ PENALTY". So augmentation and the spectral-norm + # Lipschitz penalty are RISE's own ingredients and the BC/BCU baselines carry NEITHER. These cells + # are plain: no augmentation, no spectral norm, no bottleneck. S3H1plain = expert only, S0Bplain = union. + cellov+=(training.use_bc=True training.action_augmentation=False training.advanced_augmentation=False + training.spectral_norm_policy=False training.policy_bottleneck_beta=0.0) + case $rcell in *S3H1plain*) data=$ROOT/data/derived/${task}_expert.hdf5 ;; esac ;; + *S0B*) cellov+=(training.use_bc=True) ;; + *S3H1aug*) # BC on the expert demos with RISE's OWN augmentation left ON (their square.py has + # action_augmentation=True, advanced_augmentation=True, distance_threshold .15, num_neighbors 15). + # Our S3H1 disables both; this cell is the faithful-to-their-recipe control (2026-09-19, user request). + cellov+=(training.use_bc=True) + data=$ROOT/data/derived/${task}_expert.hdf5 ;; + *S3H1*) cellov+=(training.use_bc=True training.action_augmentation=False training.advanced_augmentation=False) + data=$ROOT/data/derived/${task}_expert.hdf5 ;; + *) echo "unknown cell $cell (expected it to contain S0A, S0B or S3H1)"; exit 2 ;; + esac + if [ "$pathd" = "1" ]; then + dd=$ROOT/data/derived/${task}_dinostate.hdf5 + [ -f "$dd" ] || { echo "missing path-(D) dataset $dd -- run scripts/basetopup/build_dinostate_hdf5.py $task"; exit 2; } + data=$dd + cellov+=(training.use_dino_features=False "training.rgb_keys=[]" + "training.low_dim_keys=[dino_state,robot0_eef_pos,robot0_eef_quat,robot0_gripper_qpos]") + echo "[run_train] path (D): cell=$cell recipe=$rcell data=$data obs=dino_state(1545)+3 proprio keys, no encoder" + # the critic-only half of the fast path (see the comment above the `case $cell` that set pathdq). + # Appended LAST so it wins over taskov/cellov (run_train.sh:297 orders logov taskov cellov "$@"). + if [ "$pathdq" = "1" ]; then + cellov+=(training.critic_only=True training.action_augmentation=False training.advanced_augmentation=False) + skipeven=1 + case $task in square_sub_paper|square_sub_paper2|square_sub_20100|piecesub_paper) skipeven=0 ;; esac + case $cell in *S0Aidqldinodq*) skipeven=0 ;; esac + [ "$skipeven" = "1" ] && cellov+=(training.critic_skip_even_epochs=True) + echo "[run_train] path (Dq) critic-only: actor loss OFF, augmentation OFF, critic_skip_even_epochs=$skipeven" + fi + fi + name=${task}_${cell}_s${seed} + outdir=$ROOT/runs/$task/policy/${cell}_seed${seed} + mkdir -p $outdir + if [ -n "${RSM_WANDB_ENTITY:-}" ]; then + export RSM_WANDB_RUN_NAME="${task}/${cell}_seed${seed}" RSM_WANDB_GROUP="$task" # W&B run name (read by robomimic's DataLogger) + logov=(exp.entity=$RSM_WANDB_ENTITY exp.project=$RSM_WANDB_PROJECT "exp.format_strings=[stdout,tensorboard,wandb]") + echo "[run_train] W&B on: entity=$RSM_WANDB_ENTITY project=$RSM_WANDB_PROJECT run=$RSM_WANDB_RUN_NAME dir=$WANDB_DIR" + else + logov=("exp.format_strings=[stdout,tensorboard]") + fi + # rsm_rise 20:15: ROLLING RESUME CHECKPOINT for the slow S0A (IQL) cells. An S0A epoch costs ~0.34 min, so the + # released save_interval of 500 epochs is ~2.9 h of work, while the preemptable queue evicts a job every ~1-2 h + # -> such a cell can restart forever and never write a checkpoint (two_piece_expert_play S0A seed 1: 13 h wall, + # 5 restarts, 0 checkpoints). The trainer now also writes ONE extra checkpoint every RSM_ROLLING_EVERY epochs + # into $outdir/rolling/, keeping only the newest file (nothing in the every-500 series is ever deleted -- + # orchestrator 13:26). Cost: one checkpoint of disk per cell. RSM_ROLLING_EVERY=0 disables. + # rsm_rise 2026-09-19 03:20 UTC: rolling checkpoints are now enabled for EVERY cell, not just S0A, and are + # additionally driven by WALL-CLOCK time (RSM_ROLLING_SECONDS). Reason: the wandb-429 crash loop (fixed in + # sim_pipeline/utils/logger.py, but restarts still happen from preemption) gave some cells a mean time to + # failure of 13-35 min, shorter than the time to reach the next epoch multiple -- so they resumed from the + # same checkpoint forever and made zero net progress. Observed livelocked: mug_expert_suboptimal S0A s0 + # (7 resumes from epoch 2500, an S0A cell that DID have RSM_ROLLING_EVERY=100 and still never reached a + # multiple of 100), square_sub_paper S3H1 s0 (7x from 2000) and s2 (7x from 3000) -- S3H1 cells, which had + # rolling disabled entirely. 900 s bounds the loss at 15 min per restart for every cell regardless of its + # epoch rate, and costs one extra 3 GB file per cell (only the newest is kept). + export RSM_ROLLING_EVERY=${RSM_ROLLING_EVERY:-100} + export RSM_ROLLING_SECONDS=${RSM_ROLLING_SECONDS:-900} + # rsm_rise 2026-09-19 08:50 UTC: PER-CELL override, so a livelocked cell can be rescued WITHOUT killing its + # (running, GPU-holding) job. The wrapper is re-exec'd from disk on every LSF rerun (bsub -r), so dropping + # EVERY=25 + # SECONDS=300 + # into $outdir/rolling_conf takes effect at the cell's next eviction. Rationale: the two 224 G tipping S0B + # cells spend ~29 min of every ~39 min preemption cycle re-running "SequenceDataset: caching get_item calls" + # (189 372 frames), leaving ~10 min = ~68 epochs of training -- under BOTH the 900 s clock and the 100-epoch + # multiple, so they resumed from the same rolling checkpoint forever (s1 pinned at 4507, s2 at 4700). + # Deliberately per-cell, not a new global default: at 25 epochs a 3 GB checkpoint is rewritten every ~3.5 min, + # which is real I/O on a 96 %-full filesystem and is only worth paying for cells that are actually livelocked. + if [ -f "$outdir/rolling_conf" ]; then + while IFS='=' read -r k v; do + case $k in EVERY) export RSM_ROLLING_EVERY=$v ;; SECONDS) export RSM_ROLLING_SECONDS=$v ;; esac + done < "$outdir/rolling_conf" + echo "[run_train] rolling_conf override from $outdir/rolling_conf" + fi + export RSM_ROLLING_DIR=$outdir/rolling + # resume: if this cell already has checkpoints (job rerun / resubmission after a crash), continue from the latest + # one -- the every-500 series AND the rolling file, whichever is further along + last=$(ls $outdir/*/*/models/model_epoch_*.pth $outdir/rolling/model_epoch_*.pth 2>/dev/null | awk -F'model_epoch_' '{split($2,a,"."); print a[1], $0}' | sort -n | tail -1 | cut -d' ' -f2-) + if [ -n "$last" ]; then + export RSM_RESUME_CKPT=$last + [ -f $outdir/wandb_run_id ] && export RSM_WANDB_RUN_ID=$(cat $outdir/wandb_run_id) + echo "[run_train] RESUMING from $last (wandb id ${RSM_WANDB_RUN_ID:-none})" + fi + export RSM_WANDB_RUN_ID_FILE=$outdir/wandb_run_id + # GPU-utilisation mitigation (orchestrator 15:52): robomimic's DataLoader defaults to num_data_workers=0, so the + # single process alternates load (~25 % of epoch time) and train. RSM_NUM_DATA_WORKERS>0 is read by + # sim_pipeline/training/train_robomimic.py and changes NO training semantics (same sampler/seed/batches). + export RSM_NUM_DATA_WORKERS=${RSM_NUM_DATA_WORKERS:-0} + echo "[run_train] RSM_NUM_DATA_WORKERS=$RSM_NUM_DATA_WORKERS" + # rsm_rise 2026-09-19 04:20: print the rolling-checkpoint config, so a later run can tell from the LOG + # alone whether a live process was launched before or after the 03:12 wall-clock patch (the vars are exported + # by the bash that was parsed at dispatch, so an old process keeps the old behaviour until LSF re-dispatches). + echo "[run_train] RSM_ROLLING_EVERY=$RSM_ROLLING_EVERY RSM_ROLLING_SECONDS=$RSM_ROLLING_SECONDS RSM_ROLLING_DIR=$RSM_ROLLING_DIR" + cd $RISE_CODE + # RSM_PRINT_OVERRIDES=1: print the composed hydra override list and exit 0 without training. Pure shell, + # so the cell dispatch (which arm matched, which flags it added, in which order) can be checked on the + # login node before a GPU pack is spent on it. (BASE_TOPUP gen_q#287 run 11.) + if [ "${RSM_PRINT_OVERRIDES:-0}" = "1" ]; then + printf '[run_train] OVERRIDES task=%s cell=%s rcell=%s seed=%s data=%s\n' "$task" "$cell" "$rcell" "$seed" "$data" + for o in "${taskov[@]}" "${cellov[@]}" "$@"; do printf ' %s\n' "$o"; done + exit 0 + fi + echo "[run_train] host=$(hostname) job=${LSB_JOBID:-none} task=$task cell=$cell seed=$seed data=$data"; nvidia-smi -L 2>/dev/null + date +%s > $outdir/start_epoch_time + python scripts/train_robomimic.py -cn iql_diffusion +training=$tcfg data.dataset_path=$data \ + name=$name exp.logdir=$outdir exp.seed=$seed "${logov[@]}" "${taskov[@]}" "${cellov[@]}" "$@" + rc=$? + echo "[run_train] exit=$rc $(date)" + exit $rc +} +main "$@" +exit $? diff --git a/rsm_rise/scripts/real/v7/reward2/sf2_payloads/sf_d1_rp_s2_qaux0_rr0_s0.sh b/rsm_rise/scripts/real/v7/reward2/sf2_payloads/sf_d1_rp_s2_qaux0_rr0_s0.sh new file mode 100644 index 0000000000000000000000000000000000000000..29daeb78dfcd89dd0cfd3e2525c9660bc23471b6 --- /dev/null +++ b/rsm_rise/scripts/real/v7/reward2/sf2_payloads/sf_d1_rp_s2_qaux0_rr0_s0.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +cd /proj/dmfexp/zwhong/rsm_rise +echo "[sf2 payload] d1_rp_s2_qaux0_rr0_s0 $(date -u) host=$(hostname) gpu=${CUDA_VISIBLE_DEVICES:-?}" +[ -f runs/v7_reward2_sf/d1_rp_s2_qaux0_rr0_s0/ckpt_best.pt ] && { echo exists; exit 0; } +exec /proj/dmfexp/zwhong/rsm_rise/venv_rsm/bin/python scripts/real/v7/reward2/train_reward2_sf.py --out /proj/dmfexp/zwhong/rsm_rise/runs/v7_reward2_sf/d1_rp_s2_qaux0_rr0_s0 --depth 1 --succ_ckpt /proj/dmfexp/zwhong/rsm_rise/runs/real_cooking_v7/rsm_rpred/s2_qaux0_rr0_s0/ckpt_s40000.pt diff --git a/rsm_rise/scripts/real/v7/reward2/sf2_payloads/sf_d1_rp_s2_qaux1_rr0_s0.sh b/rsm_rise/scripts/real/v7/reward2/sf2_payloads/sf_d1_rp_s2_qaux1_rr0_s0.sh new file mode 100644 index 0000000000000000000000000000000000000000..a9a2ed075b78e9162e5ce1b8bf2723b907f3ea0c --- /dev/null +++ b/rsm_rise/scripts/real/v7/reward2/sf2_payloads/sf_d1_rp_s2_qaux1_rr0_s0.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +cd /proj/dmfexp/zwhong/rsm_rise +echo "[sf2 payload] d1_rp_s2_qaux1_rr0_s0 $(date -u) host=$(hostname) gpu=${CUDA_VISIBLE_DEVICES:-?}" +[ -f runs/v7_reward2_sf/d1_rp_s2_qaux1_rr0_s0/ckpt_best.pt ] && { echo exists; exit 0; } +exec /proj/dmfexp/zwhong/rsm_rise/venv_rsm/bin/python scripts/real/v7/reward2/train_reward2_sf.py --out /proj/dmfexp/zwhong/rsm_rise/runs/v7_reward2_sf/d1_rp_s2_qaux1_rr0_s0 --depth 1 --succ_ckpt /proj/dmfexp/zwhong/rsm_rise/runs/real_cooking_v7/rsm_rpred/s2_qaux1_rr0_s0/ckpt_s40000.pt diff --git a/rsm_rise/scripts/real/v7/reward2/sf2_payloads/sf_d1_rp_s2_qaux1_rr1_s0.sh b/rsm_rise/scripts/real/v7/reward2/sf2_payloads/sf_d1_rp_s2_qaux1_rr1_s0.sh new file mode 100644 index 0000000000000000000000000000000000000000..e0958507bb3f6993ce3a7c28b2404cc5cd9b4450 --- /dev/null +++ b/rsm_rise/scripts/real/v7/reward2/sf2_payloads/sf_d1_rp_s2_qaux1_rr1_s0.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +cd /proj/dmfexp/zwhong/rsm_rise +echo "[sf2 payload] d1_rp_s2_qaux1_rr1_s0 $(date -u) host=$(hostname) gpu=${CUDA_VISIBLE_DEVICES:-?}" +[ -f runs/v7_reward2_sf/d1_rp_s2_qaux1_rr1_s0/ckpt_best.pt ] && { echo exists; exit 0; } +exec /proj/dmfexp/zwhong/rsm_rise/venv_rsm/bin/python scripts/real/v7/reward2/train_reward2_sf.py --out /proj/dmfexp/zwhong/rsm_rise/runs/v7_reward2_sf/d1_rp_s2_qaux1_rr1_s0 --depth 1 --succ_ckpt /proj/dmfexp/zwhong/rsm_rise/runs/real_cooking_v7/rsm_rpred/s2_qaux1_rr1_s0/ckpt_s40000.pt diff --git a/rsm_rise/scripts/real/v7/reward2/sf2_payloads/sf_d1_rp_s2_qaux1_rr1_s1.sh b/rsm_rise/scripts/real/v7/reward2/sf2_payloads/sf_d1_rp_s2_qaux1_rr1_s1.sh new file mode 100644 index 0000000000000000000000000000000000000000..16ecf9248b5ae84defe87d35b7ff52dfa3f15e9b --- /dev/null +++ b/rsm_rise/scripts/real/v7/reward2/sf2_payloads/sf_d1_rp_s2_qaux1_rr1_s1.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +cd /proj/dmfexp/zwhong/rsm_rise +echo "[sf2 payload] d1_rp_s2_qaux1_rr1_s1 $(date -u) host=$(hostname) gpu=${CUDA_VISIBLE_DEVICES:-?}" +[ -f runs/v7_reward2_sf/d1_rp_s2_qaux1_rr1_s1/ckpt_best.pt ] && { echo exists; exit 0; } +exec /proj/dmfexp/zwhong/rsm_rise/venv_rsm/bin/python scripts/real/v7/reward2/train_reward2_sf.py --out /proj/dmfexp/zwhong/rsm_rise/runs/v7_reward2_sf/d1_rp_s2_qaux1_rr1_s1 --depth 1 --succ_ckpt /proj/dmfexp/zwhong/rsm_rise/runs/real_cooking_v7/rsm_rpred/s2_qaux1_rr1_s1/ckpt_s40000.pt diff --git a/rsm_rise/scripts/real/v7/reward2/sf2_payloads/sf_d1_rp_s2_qaux5_rr1_s0.sh b/rsm_rise/scripts/real/v7/reward2/sf2_payloads/sf_d1_rp_s2_qaux5_rr1_s0.sh new file mode 100644 index 0000000000000000000000000000000000000000..ec963f804c6e269975a6cba15da7191d4857a99c --- /dev/null +++ b/rsm_rise/scripts/real/v7/reward2/sf2_payloads/sf_d1_rp_s2_qaux5_rr1_s0.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +cd /proj/dmfexp/zwhong/rsm_rise +echo "[sf2 payload] d1_rp_s2_qaux5_rr1_s0 $(date -u) host=$(hostname) gpu=${CUDA_VISIBLE_DEVICES:-?}" +[ -f runs/v7_reward2_sf/d1_rp_s2_qaux5_rr1_s0/ckpt_best.pt ] && { echo exists; exit 0; } +exec /proj/dmfexp/zwhong/rsm_rise/venv_rsm/bin/python scripts/real/v7/reward2/train_reward2_sf.py --out /proj/dmfexp/zwhong/rsm_rise/runs/v7_reward2_sf/d1_rp_s2_qaux5_rr1_s0 --depth 1 --succ_ckpt /proj/dmfexp/zwhong/rsm_rise/runs/real_cooking_v7/rsm_rpred/s2_qaux5_rr1_s0/ckpt_s40000.pt diff --git a/rsm_rise/scripts/real/v7/reward2/sf2_payloads/sf_d1_s1.sh b/rsm_rise/scripts/real/v7/reward2/sf2_payloads/sf_d1_s1.sh new file mode 100644 index 0000000000000000000000000000000000000000..56c9436b8535680e73fcdad19eccd409976b4b6f --- /dev/null +++ b/rsm_rise/scripts/real/v7/reward2/sf2_payloads/sf_d1_s1.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +cd /proj/dmfexp/zwhong/rsm_rise +echo "[sf2 payload] d1_s1 $(date -u) host=$(hostname) gpu=${CUDA_VISIBLE_DEVICES:-?}" +[ -f runs/v7_reward2_sf/d1_s1/ckpt_best.pt ] && { echo exists; exit 0; } +exec /proj/dmfexp/zwhong/rsm_rise/venv_rsm/bin/python scripts/real/v7/reward2/train_reward2_sf.py --out /proj/dmfexp/zwhong/rsm_rise/runs/v7_reward2_sf/d1_s1 --depth 1 --seed 1 diff --git a/rsm_rise/scripts/real/v7/reward2/sf2_payloads/sf_d2.sh b/rsm_rise/scripts/real/v7/reward2/sf2_payloads/sf_d2.sh new file mode 100644 index 0000000000000000000000000000000000000000..97c28ba4409131d6c85a02b12c9241065ca3cbee --- /dev/null +++ b/rsm_rise/scripts/real/v7/reward2/sf2_payloads/sf_d2.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +cd /proj/dmfexp/zwhong/rsm_rise +echo "[sf2 payload] d2 $(date -u) host=$(hostname) gpu=${CUDA_VISIBLE_DEVICES:-?}" +[ -f runs/v7_reward2_sf/d2/ckpt_best.pt ] && { echo exists; exit 0; } +exec /proj/dmfexp/zwhong/rsm_rise/venv_rsm/bin/python scripts/real/v7/reward2/train_reward2_sf.py --out /proj/dmfexp/zwhong/rsm_rise/runs/v7_reward2_sf/d2 --depth 2 diff --git a/rsm_rise/scripts/real/v7/reward2/sf2_payloads/sf_d3.sh b/rsm_rise/scripts/real/v7/reward2/sf2_payloads/sf_d3.sh new file mode 100644 index 0000000000000000000000000000000000000000..6f18acf951a7ba44ea2f1c15e0b6e9f03869f67f --- /dev/null +++ b/rsm_rise/scripts/real/v7/reward2/sf2_payloads/sf_d3.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +cd /proj/dmfexp/zwhong/rsm_rise +echo "[sf2 payload] d3 $(date -u) host=$(hostname) gpu=${CUDA_VISIBLE_DEVICES:-?}" +[ -f runs/v7_reward2_sf/d3/ckpt_best.pt ] && { echo exists; exit 0; } +exec /proj/dmfexp/zwhong/rsm_rise/venv_rsm/bin/python scripts/real/v7/reward2/train_reward2_sf.py --out /proj/dmfexp/zwhong/rsm_rise/runs/v7_reward2_sf/d3 --depth 3 diff --git a/rsm_rise/scripts/real/v7/reward2/sf3_payloads/sf_hn_r1.sh b/rsm_rise/scripts/real/v7/reward2/sf3_payloads/sf_hn_r1.sh new file mode 100644 index 0000000000000000000000000000000000000000..6fb106f78c6cbaa20949810748a0998a36089cd0 --- /dev/null +++ b/rsm_rise/scripts/real/v7/reward2/sf3_payloads/sf_hn_r1.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +cd /proj/dmfexp/zwhong/rsm_rise +echo "[sf3 payload] hn_r1 $(date -u) host=$(hostname) gpu=${CUDA_VISIBLE_DEVICES:-?}" +[ -f runs/v7_reward2_sf/hn_r1/ckpt_best.pt ] && { echo exists; exit 0; } +exec /proj/dmfexp/zwhong/rsm_rise/venv_rsm/bin/python scripts/real/v7/reward2/train_reward2_sf.py --out /proj/dmfexp/zwhong/rsm_rise/runs/v7_reward2_sf/hn_r1 --depth 1 --hn_rank 1 diff --git a/rsm_rise/scripts/real/v7/reward2/sf3_payloads/sf_hn_w1.sh b/rsm_rise/scripts/real/v7/reward2/sf3_payloads/sf_hn_w1.sh new file mode 100644 index 0000000000000000000000000000000000000000..c3bf82c4f1c48f7d6d43076150ae1716c02906e9 --- /dev/null +++ b/rsm_rise/scripts/real/v7/reward2/sf3_payloads/sf_hn_w1.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +cd /proj/dmfexp/zwhong/rsm_rise +echo "[sf3 payload] hn_w1 $(date -u) host=$(hostname) gpu=${CUDA_VISIBLE_DEVICES:-?}" +[ -f runs/v7_reward2_sf/hn_w1/ckpt_best.pt ] && { echo exists; exit 0; } +exec /proj/dmfexp/zwhong/rsm_rise/venv_rsm/bin/python scripts/real/v7/reward2/train_reward2_sf.py --out /proj/dmfexp/zwhong/rsm_rise/runs/v7_reward2_sf/hn_w1 --depth 1 --hn_w 1 diff --git a/rsm_rise/scripts/real/v7/reward2/sf3_payloads/sf_hn_w1_r1.sh b/rsm_rise/scripts/real/v7/reward2/sf3_payloads/sf_hn_w1_r1.sh new file mode 100644 index 0000000000000000000000000000000000000000..155d009c97907e83321645e44645a7db6a697390 --- /dev/null +++ b/rsm_rise/scripts/real/v7/reward2/sf3_payloads/sf_hn_w1_r1.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +cd /proj/dmfexp/zwhong/rsm_rise +echo "[sf3 payload] hn_w1_r1 $(date -u) host=$(hostname) gpu=${CUDA_VISIBLE_DEVICES:-?}" +[ -f runs/v7_reward2_sf/hn_w1_r1/ckpt_best.pt ] && { echo exists; exit 0; } +exec /proj/dmfexp/zwhong/rsm_rise/venv_rsm/bin/python scripts/real/v7/reward2/train_reward2_sf.py --out /proj/dmfexp/zwhong/rsm_rise/runs/v7_reward2_sf/hn_w1_r1 --depth 1 --hn_w 1 --hn_rank 1 diff --git a/rsm_rise/scripts/real/v7/reward2/sf3_payloads/sf_hn_w1_r1_s1.sh b/rsm_rise/scripts/real/v7/reward2/sf3_payloads/sf_hn_w1_r1_s1.sh new file mode 100644 index 0000000000000000000000000000000000000000..536ce85900dd4f4b49295a3e055bf69b7a7c67ae --- /dev/null +++ b/rsm_rise/scripts/real/v7/reward2/sf3_payloads/sf_hn_w1_r1_s1.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +cd /proj/dmfexp/zwhong/rsm_rise +echo "[sf3 payload] hn_w1_r1_s1 $(date -u) host=$(hostname) gpu=${CUDA_VISIBLE_DEVICES:-?}" +[ -f runs/v7_reward2_sf/hn_w1_r1_s1/ckpt_best.pt ] && { echo exists; exit 0; } +exec /proj/dmfexp/zwhong/rsm_rise/venv_rsm/bin/python scripts/real/v7/reward2/train_reward2_sf.py --out /proj/dmfexp/zwhong/rsm_rise/runs/v7_reward2_sf/hn_w1_r1_s1 --depth 1 --hn_w 1 --hn_rank 1 --seed 1 diff --git a/rsm_rise/scripts/real/v7/reward2/sf3_payloads/sf_hn_w1_s1.sh b/rsm_rise/scripts/real/v7/reward2/sf3_payloads/sf_hn_w1_s1.sh new file mode 100644 index 0000000000000000000000000000000000000000..cb2aa44f3670b3403c010ea1431c9f803f808336 --- /dev/null +++ b/rsm_rise/scripts/real/v7/reward2/sf3_payloads/sf_hn_w1_s1.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +cd /proj/dmfexp/zwhong/rsm_rise +echo "[sf3 payload] hn_w1_s1 $(date -u) host=$(hostname) gpu=${CUDA_VISIBLE_DEVICES:-?}" +[ -f runs/v7_reward2_sf/hn_w1_s1/ckpt_best.pt ] && { echo exists; exit 0; } +exec /proj/dmfexp/zwhong/rsm_rise/venv_rsm/bin/python scripts/real/v7/reward2/train_reward2_sf.py --out /proj/dmfexp/zwhong/rsm_rise/runs/v7_reward2_sf/hn_w1_s1 --depth 1 --hn_w 1 --seed 1 diff --git a/rsm_rise/scripts/real/v7/reward2/sf3_payloads/sf_hn_w1_thr.sh b/rsm_rise/scripts/real/v7/reward2/sf3_payloads/sf_hn_w1_thr.sh new file mode 100644 index 0000000000000000000000000000000000000000..e4c1abd015abe428dc1906693f972466e8512280 --- /dev/null +++ b/rsm_rise/scripts/real/v7/reward2/sf3_payloads/sf_hn_w1_thr.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +cd /proj/dmfexp/zwhong/rsm_rise +echo "[sf3 payload] hn_w1_thr $(date -u) host=$(hostname) gpu=${CUDA_VISIBLE_DEVICES:-?}" +[ -f runs/v7_reward2_sf/hn_w1_thr/ckpt_best.pt ] && { echo exists; exit 0; } +exec /proj/dmfexp/zwhong/rsm_rise/venv_rsm/bin/python scripts/real/v7/reward2/train_reward2_sf.py --out /proj/dmfexp/zwhong/rsm_rise/runs/v7_reward2_sf/hn_w1_thr --depth 1 --hn_w 1 --hn_thr 0.482 diff --git a/rsm_rise/scripts/real/v7/reward2/sf3_payloads/sf_hn_w1_thr1.sh b/rsm_rise/scripts/real/v7/reward2/sf3_payloads/sf_hn_w1_thr1.sh new file mode 100644 index 0000000000000000000000000000000000000000..d36e6f92ad153217a39fc032baf42b8863844cfa --- /dev/null +++ b/rsm_rise/scripts/real/v7/reward2/sf3_payloads/sf_hn_w1_thr1.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +cd /proj/dmfexp/zwhong/rsm_rise +echo "[sf3 payload] hn_w1_thr1 $(date -u) host=$(hostname) gpu=${CUDA_VISIBLE_DEVICES:-?}" +[ -f runs/v7_reward2_sf/hn_w1_thr1/ckpt_best.pt ] && { echo exists; exit 0; } +exec /proj/dmfexp/zwhong/rsm_rise/venv_rsm/bin/python scripts/real/v7/reward2/train_reward2_sf.py --out /proj/dmfexp/zwhong/rsm_rise/runs/v7_reward2_sf/hn_w1_thr1 --depth 1 --hn_w 1 --hn_thr 1.0 diff --git a/rsm_rise/scripts/real/v7/reward2/sf3_payloads/sf_hn_w3.sh b/rsm_rise/scripts/real/v7/reward2/sf3_payloads/sf_hn_w3.sh new file mode 100644 index 0000000000000000000000000000000000000000..9adc19c5bc18cd8848210c43574d93a937931e2f --- /dev/null +++ b/rsm_rise/scripts/real/v7/reward2/sf3_payloads/sf_hn_w3.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +cd /proj/dmfexp/zwhong/rsm_rise +echo "[sf3 payload] hn_w3 $(date -u) host=$(hostname) gpu=${CUDA_VISIBLE_DEVICES:-?}" +[ -f runs/v7_reward2_sf/hn_w3/ckpt_best.pt ] && { echo exists; exit 0; } +exec /proj/dmfexp/zwhong/rsm_rise/venv_rsm/bin/python scripts/real/v7/reward2/train_reward2_sf.py --out /proj/dmfexp/zwhong/rsm_rise/runs/v7_reward2_sf/hn_w3 --depth 1 --hn_w 3 diff --git a/rsm_rise/scripts/real/v7/reward2/sf_payloads/sf_adrop0.sh b/rsm_rise/scripts/real/v7/reward2/sf_payloads/sf_adrop0.sh new file mode 100644 index 0000000000000000000000000000000000000000..2df352e556470bffd406e3725cb849a7d810aaa9 --- /dev/null +++ b/rsm_rise/scripts/real/v7/reward2/sf_payloads/sf_adrop0.sh @@ -0,0 +1,4 @@ +#!/usr/bin/env bash +cd /proj/dmfexp/zwhong/rsm_rise +echo "[sf payload] adrop0 $(date -u) host=$(hostname) gpu=${CUDA_VISIBLE_DEVICES:-?}" +exec /proj/dmfexp/zwhong/rsm_rise/venv_rsm/bin/python scripts/real/v7/reward2/train_reward2_sf.py --out /proj/dmfexp/zwhong/rsm_rise/runs/v7_reward2_sf/adrop0 --act_drop 0 diff --git a/rsm_rise/scripts/real/v7/reward2/sf_payloads/sf_d1.sh b/rsm_rise/scripts/real/v7/reward2/sf_payloads/sf_d1.sh new file mode 100644 index 0000000000000000000000000000000000000000..08283e02ad72b49e2ba277b34f277a87cef9421e --- /dev/null +++ b/rsm_rise/scripts/real/v7/reward2/sf_payloads/sf_d1.sh @@ -0,0 +1,4 @@ +#!/usr/bin/env bash +cd /proj/dmfexp/zwhong/rsm_rise +echo "[sf payload] d1 $(date -u) host=$(hostname) gpu=${CUDA_VISIBLE_DEVICES:-?}" +exec /proj/dmfexp/zwhong/rsm_rise/venv_rsm/bin/python scripts/real/v7/reward2/train_reward2_sf.py --out /proj/dmfexp/zwhong/rsm_rise/runs/v7_reward2_sf/d1 --depth 1 diff --git a/rsm_rise/scripts/real/v7/reward2/sf_payloads/sf_main_s0.sh b/rsm_rise/scripts/real/v7/reward2/sf_payloads/sf_main_s0.sh new file mode 100644 index 0000000000000000000000000000000000000000..2a84dfa69cb5d526be79f3fcd420c96174f1d194 --- /dev/null +++ b/rsm_rise/scripts/real/v7/reward2/sf_payloads/sf_main_s0.sh @@ -0,0 +1,4 @@ +#!/usr/bin/env bash +cd /proj/dmfexp/zwhong/rsm_rise +echo "[sf payload] main_s0 $(date -u) host=$(hostname) gpu=${CUDA_VISIBLE_DEVICES:-?}" +exec /proj/dmfexp/zwhong/rsm_rise/venv_rsm/bin/python scripts/real/v7/reward2/train_reward2_sf.py --out /proj/dmfexp/zwhong/rsm_rise/runs/v7_reward2_sf/main_s0 --seed 0 diff --git a/rsm_rise/scripts/real/v7/reward2/sf_payloads/sf_main_s1.sh b/rsm_rise/scripts/real/v7/reward2/sf_payloads/sf_main_s1.sh new file mode 100644 index 0000000000000000000000000000000000000000..b69aa8db7424d525c929ccf74f58d8bae6771bd7 --- /dev/null +++ b/rsm_rise/scripts/real/v7/reward2/sf_payloads/sf_main_s1.sh @@ -0,0 +1,4 @@ +#!/usr/bin/env bash +cd /proj/dmfexp/zwhong/rsm_rise +echo "[sf payload] main_s1 $(date -u) host=$(hostname) gpu=${CUDA_VISIBLE_DEVICES:-?}" +exec /proj/dmfexp/zwhong/rsm_rise/venv_rsm/bin/python scripts/real/v7/reward2/train_reward2_sf.py --out /proj/dmfexp/zwhong/rsm_rise/runs/v7_reward2_sf/main_s1 --seed 1 diff --git a/rsm_rise/scripts/real/v7/reward2/sf_payloads/sf_main_s2.sh b/rsm_rise/scripts/real/v7/reward2/sf_payloads/sf_main_s2.sh new file mode 100644 index 0000000000000000000000000000000000000000..2fe555e867a75f5487ef8b38518fc36386e98bd6 --- /dev/null +++ b/rsm_rise/scripts/real/v7/reward2/sf_payloads/sf_main_s2.sh @@ -0,0 +1,4 @@ +#!/usr/bin/env bash +cd /proj/dmfexp/zwhong/rsm_rise +echo "[sf payload] main_s2 $(date -u) host=$(hostname) gpu=${CUDA_VISIBLE_DEVICES:-?}" +exec /proj/dmfexp/zwhong/rsm_rise/venv_rsm/bin/python scripts/real/v7/reward2/train_reward2_sf.py --out /proj/dmfexp/zwhong/rsm_rise/runs/v7_reward2_sf/main_s2 --seed 2 diff --git a/rsm_rise/scripts/real/v7/reward2/sf_payloads/sf_sfonly.sh b/rsm_rise/scripts/real/v7/reward2/sf_payloads/sf_sfonly.sh new file mode 100644 index 0000000000000000000000000000000000000000..73b1a17a8cce61ef6b1f42027e5c61f3cfb0e7a6 --- /dev/null +++ b/rsm_rise/scripts/real/v7/reward2/sf_payloads/sf_sfonly.sh @@ -0,0 +1,4 @@ +#!/usr/bin/env bash +cd /proj/dmfexp/zwhong/rsm_rise +echo "[sf payload] sfonly $(date -u) host=$(hostname) gpu=${CUDA_VISIBLE_DEVICES:-?}" +exec /proj/dmfexp/zwhong/rsm_rise/venv_rsm/bin/python scripts/real/v7/reward2/train_reward2_sf.py --out /proj/dmfexp/zwhong/rsm_rise/runs/v7_reward2_sf/sfonly --w_tf 0 diff --git a/rsm_rise/scripts/real/v7/reward2/sf_payloads/sf_uniform.sh b/rsm_rise/scripts/real/v7/reward2/sf_payloads/sf_uniform.sh new file mode 100644 index 0000000000000000000000000000000000000000..5c31edf1d98de34269376a9df160ee0a83c174bf --- /dev/null +++ b/rsm_rise/scripts/real/v7/reward2/sf_payloads/sf_uniform.sh @@ -0,0 +1,4 @@ +#!/usr/bin/env bash +cd /proj/dmfexp/zwhong/rsm_rise +echo "[sf payload] uniform $(date -u) host=$(hostname) gpu=${CUDA_VISIBLE_DEVICES:-?}" +exec /proj/dmfexp/zwhong/rsm_rise/venv_rsm/bin/python scripts/real/v7/reward2/train_reward2_sf.py --out /proj/dmfexp/zwhong/rsm_rise/runs/v7_reward2_sf/uniform --depth_w uniform diff --git a/rsm_rise/scripts/real/v7/reward2/sf_payloads/sf_wsf3.sh b/rsm_rise/scripts/real/v7/reward2/sf_payloads/sf_wsf3.sh new file mode 100644 index 0000000000000000000000000000000000000000..fcbe34e330150a531c4c47594a02a04b17f62a4d --- /dev/null +++ b/rsm_rise/scripts/real/v7/reward2/sf_payloads/sf_wsf3.sh @@ -0,0 +1,4 @@ +#!/usr/bin/env bash +cd /proj/dmfexp/zwhong/rsm_rise +echo "[sf payload] wsf3 $(date -u) host=$(hostname) gpu=${CUDA_VISIBLE_DEVICES:-?}" +exec /proj/dmfexp/zwhong/rsm_rise/venv_rsm/bin/python scripts/real/v7/reward2/train_reward2_sf.py --out /proj/dmfexp/zwhong/rsm_rise/runs/v7_reward2_sf/wsf3 --w_sf 3 diff --git a/rsm_rise/scripts/real/v7/reward2/slurm_pack_local.sh b/rsm_rise/scripts/real/v7/reward2/slurm_pack_local.sh new file mode 100644 index 0000000000000000000000000000000000000000..779d1d40bc304768ef3e616c88c2783b14d4d90a --- /dev/null +++ b/rsm_rise/scripts/real/v7/reward2/slurm_pack_local.sh @@ -0,0 +1,101 @@ +#!/usr/bin/env bash +# V7_REWARD2 copy of scripts/slurm_gpu_pack.sh with LOCAL sbatch (ssh slurm is refused on login5). slurm_pack_local.sh [payload.sh ...] +# +# SLURM twin of scripts/bsub_gpu_pack.sh (2026-09-23). Blue Vela also has a SLURM controller, reachable from this +# node only through the user-owned sshd on login1 (`ssh slurm`, see ~/.ssh/config). One job holds a whole 8-GPU +# node and runs one payload per GPU. /proj is visible on the SLURM side, so payload paths need no staging. +# +# Partitions (sinfo): gpu-mid (default), gpu-low, gpu-debug, gpu-high (DO NOT USE -- owner instruction), gpu-long +# (inactive), cpu. env: SL_PART (gpu-mid), SL_GPUS (8), SL_TIME (08:00:00), SL_MEM (0 = all node memory). +set -uo pipefail +ROOT=/proj/dmfexp/zwhong/rsm_rise +name=$1; shift +P=${SL_PART:-gpu-mid} +case "$P" in *high*) echo "refusing gpu-high (owner instruction)"; exit 2;; esac +G=${SL_GPUS:-8} +[ "$G" -ge 4 ] || { echo "refusing a $G-GPU job (CLAUDE.md: never 1-GPU; use 4 or 8)"; exit 3; } +case "${SL_QOS:-}" in *high*) echo "refusing *high* QOS (owner instruction)"; exit 2;; esac +n=$#; [ "$n" -ge 1 ] || { echo "usage: slurm_gpu_pack.sh ..."; exit 2; } +[ "$n" -le "$G" ] || { echo "$n payloads for $G GPUs -- split the call"; exit 2; } +# ORCH run 43 (2026-09-23 05:20Z): jobs 37079/37080/37082 all "COMPLETED" in 0 s doing NOTHING because the +# payloads were passed as ROOT-relative paths and the batch script ran them from sbatch's cwd. Resolve every +# payload to an absolute path HERE and refuse to submit if one is missing, so that can never recur silently. +abs=() +for p in "$@"; do + case "$p" in + /*) q=$p ;; + *) q=$ROOT/$p ;; + esac + [ -f "$q" ] || { echo "payload not found: $p (resolved $q) -- refusing to submit $name"; exit 2; } + abs+=("$q") +done +set -- "${abs[@]}" +mkdir -p "$ROOT/logs/slurm" "$ROOT/status/packs" +sb=$ROOT/status/packs/${name}.slurm.$$.sh +{ + echo '#!/usr/bin/env bash' + echo "#SBATCH --job-name=$name" + echo "#SBATCH --partition=$P" + echo "#SBATCH --account=grp_runtime" + # SL_QOS (PI05_RISE run 50, 2026-09-24 20:30Z): gpu-mid runs under QOS grp_runtime_medium, whose + # gres/gpu=128 account-wide cap our own fleet saturates -- 42215/42216 sat PEND "QOSGrpGRES" while + # SEVEN gpu-mid nodes were idle. gpu-low is the SAME node set with AllowQos=burst, and burst has no + # GrpTRES/MaxTRES/MaxWall at all (0 GPUs in use fleet-wide when checked). So SL_PART=gpu-low + # SL_QOS=burst is a free lane for restart-safe eval packs. Cost: PriorityTier 5 vs gpu-mid's 16384 + # and Priority=0, i.e. first to be preempted (PreemptMode=REQUEUE) -- fine for payloads that skip a + # cell whose JSON exists, NOT for a long training that restarts from zero. Unset => unchanged. + [ -n "${SL_QOS:-}" ] && echo "#SBATCH --qos=${SL_QOS}" + echo "#SBATCH --gres=gpu:$G" + # SL_CPUS (BETA_CHAIN run 27, 2026-09-24 06:25Z): cpus-per-task defaulted to 8*G, i.e. 64 on an 8-GPU + # pack. Every gpu-mid node was "mix" (GPUs free, 4-28 CPUs idle), so a whole-node-sized CPU ask could + # not place while the GPUs it wanted sat free. Eval payloads are single-process, so allow a smaller + # ask. Unset => 8*G exactly as before, so no existing caller changes. + echo "#SBATCH --nodes=1 --ntasks=1 --cpus-per-task=${SL_CPUS:-$(( 8 * G ))}" + echo "#SBATCH --mem=${SL_MEM:-0}" + echo "#SBATCH --time=${SL_TIME:-08:00:00}" + echo "#SBATCH --requeue" + # SL_EXCLUDE (gen_q#274 run 51-main, 2026-09-25). A bad GPU node costs a WHOLE pack: every payload + # on it fails, and because the payloads are self-skipping-on-existing-JSON a requeue lands them back + # on the same node and fails again. p1-r04-n2 has done this repeatedly (recorded as an open item in + # status/NEW_BASELINES_DONE since run 47). DEFAULT-ON with that node named, because the failure mode + # is silent -- a caller who does not know to exclude it is exactly the caller who loses the pack. + # SL_EXCLUDE="" explicitly clears it (e.g. to re-test whether the node is healthy again); + # SL_EXCLUDE= replaces it. Printed to stderr on every submission so it is never invisible. + _ex="${SL_EXCLUDE-p1-r04-n2}" + if [ -n "$_ex" ]; then + echo "#SBATCH --exclude=$_ex" + fi + # SL_DEP (audit run 5, 2026-09-23): optional sbatch --dependency spec, e.g. SL_DEP=afterany:37167. + # Lets a relaunch of cells another job is still writing queue BEHIND that job instead of racing it + # on the same output JSON. Empty by default, so no existing caller changes behaviour. + [ -n "${SL_DEP:-}" ] && echo "#SBATCH --dependency=${SL_DEP}" + echo "#SBATCH --output=$ROOT/logs/slurm/${name}.%j.out" + echo "#SBATCH --error=$ROOT/logs/slurm/${name}.%j.err" + echo "cd $ROOT || exit 9" + echo 'echo "[slurm-pack] host=$(hostname) job=${SLURM_JOB_ID:-none} gpus='"$G"' payloads='"$n"' $(date -u)"' + echo 'nvidia-smi --query-gpu=index,name --format=csv,noheader || true' + echo 'declare -A PID2SLOT' + i=0 + for p in "$@"; do + echo "CUDA_VISIBLE_DEVICES=$i bash '$p' > $ROOT/logs/slurm/${name}.slot$i.\${SLURM_JOB_ID:-0}.out 2>&1 &" + echo "PID2SLOT[\$!]=$i" + i=$((i+1)) + done + echo 'rc_bad=0' + echo 'for pid in "${!PID2SLOT[@]}"; do wait "$pid"; rc=$?; s=${PID2SLOT[$pid]};' + echo ' echo "[slurm-pack] slot$s exit=$rc"; [ "$rc" -eq 0 ] || rc_bad=$((rc_bad+1)); done' + echo 'echo "[slurm-pack] all payloads finished $(date -u) failed_slots=$rc_bad"' + echo 'exit $(( rc_bad > 0 ? 1 : 0 ))' +} > "$sb" +chmod +x "$sb" +# SL_TESTONLY=1 (PI05_RISE run 50): validate the submission with `sbatch --test-only` -- checks the +# partition/QOS/GRES combination is ACCEPTED and reports when it would start, WITHOUT queuing a job. +# Used to confirm a gpu-low/burst route before cancelling a pending gpu-mid copy, so the work is moved +# and never duplicated (two runners of one cell race on the same parts/*.npz -- run 49). +if [ -n "${SL_TESTONLY:-}" ]; then + sbatch --test-only "$sb" + exit $? +fi +echo "[slurm_gpu_pack] node exclude list: '${SL_EXCLUDE-p1-r04-n2}'" \ + "(SL_EXCLUDE=\"\" to clear, SL_EXCLUDE= to replace)" >&2 +sbatch "$sb" diff --git a/rsm_rise/scripts/real/v7/reward2/train_reward2.py b/rsm_rise/scripts/real/v7/reward2/train_reward2.py new file mode 100644 index 0000000000000000000000000000000000000000..2e4e3d551fe9fc108df5646a40d4f3efcc5a039a --- /dev/null +++ b/rsm_rise/scripts/real/v7/reward2/train_reward2.py @@ -0,0 +1,193 @@ +#!/usr/bin/env python +"""V7_REWARD2 step 2: standalone action-conditioned reward head r(x, a) on the FROZEN v7 successor features. + +The v7 successor (progress_augc_h50_ps_s0) uses the identity encoder: its latent IS the z-scored state + x = clip((feat - mu) / max(sd, 0.01), -10, 10), feat = [DINO z (1536) | proprio (10)] (feat_stats.npz) +so "frozen successor features" = x; the script asserts enc_kind == identity and n_pr == 0 from the ckpt. +Action input (--act chunk50): the next 50 logged actions (padded by repeating the last, exactly as the +successor's data._chunk_at), each normalised with the v7 action norm a_n = 2 (a - min)/(max - min) - 1, +flattened to 500-d. --act a0: first action only (10-d). --act none: state-only ablation. +Target: reward_shaped2.f32.npy (make_labels.py). Loss: weighted Huber (delta 1) with reward_shaped2_w. +TRAIN episodes only; TUNE (cooking_v7_tune_test.json) for selection = lowest TUNE weighted Huber; TEST untouched here. +Checkpoint keys: {"rew2": state_dict, "arch": {...}, "act_norm": {"min","max"}, "config": vars(args), "tune": metrics} +""" +import argparse, json, os, time +from pathlib import Path +import numpy as np +import torch, torch.nn as nn, torch.nn.functional as F + +JM = Path("/proj/dmfexp/zwhong/jm/rsm_rise") +C = Path(__import__("os").environ.get("RR_V7_CACHE", str(JM / "cache/real_cooking_v7"))) # V7_LEARNPROJ env override (default unchanged) +p = argparse.ArgumentParser() +p.add_argument("--out", required=True) +p.add_argument("--act", default="chunk50", choices=["chunk50", "a0", "none"]) +p.add_argument("--chunk", type=int, default=50) +p.add_argument("--weights", default="balanced", choices=["balanced", "none"]) +p.add_argument("--width", type=int, default=512) +p.add_argument("--depth", type=int, default=2) +p.add_argument("--dropout", type=float, default=0.0) +p.add_argument("--x_noise", type=float, default=0.0) +p.add_argument("--act_drop", type=float, default=0.0, help="prob of zeroing the whole action input per row") +p.add_argument("--steps", type=int, default=20000) +p.add_argument("--batch", type=int, default=4096) +p.add_argument("--lr", type=float, default=3e-4) +p.add_argument("--wd", type=float, default=1e-4) +p.add_argument("--huber", type=float, default=1.0) +p.add_argument("--eval_every", type=int, default=1000) +p.add_argument("--seed", type=int, default=0) +# RSM_PAIRTEST run 17 (A_logged diagnosis): explicit "hover at a success meta-state" negatives. Off by default. +p.add_argument("--hover_margin", type=float, default=0.0, help="TRAIN rows on segments leaving 3/8 whose 50-chunk max ee " + "displacement is in the lowest 5%% for that stage (frames >= 50 before the episode end) get label y - margin") +p.add_argument("--hold_aug", type=float, default=0.0, help="prob per row (edge_from in 3/8) of replacing the chunk by " + "a_t repeated (go to the commanded pose and stay) with label y - hover_margin") +p.add_argument("--succ_ckpt", default=str(JM / "export/v7/rsm_ens20/progress_augc_h50_ps_s0/ckpt_s20000.pt")) +args = p.parse_args() +out = Path(args.out); out.mkdir(parents=True, exist_ok=True) +if (out / "DONE").exists(): + print("[r2] DONE exists, skip", out); raise SystemExit(0) +torch.manual_seed(args.seed); np.random.seed(args.seed) +dev = "cuda" + +ck = torch.load(args.succ_ckpt, map_location="cpu", weights_only=False) +enc_kind = ck.get("enc_kind", ck["config"].get("enc", "mlp")); n_pr = int(ck.get("n_pr", 0) or 0) +print("[r2] successor enc_kind", enc_kind, "n_pr", n_pr, "d_in", ck.get("d_in"), "d_act", ck.get("d_act"), flush=True) +assert enc_kind == "identity" and n_pr == 0, "successor features are not the identity z-scored state" +del ck + +st = np.load(C / "feat_stats.npz") +mu, sd, zc = st["mu"].astype(np.float32), np.maximum(st["sd"].astype(np.float32), float(st["sd_floor"])), float(st["z_clip"]) +z = np.load(C / "z.f16.npy"); pr = np.load(C / "proprio.f32.npy") +feat = np.concatenate([z.astype(np.float32), pr], 1); del z +X = np.clip((feat - mu) / sd, -zc, zc).astype(np.float32); del feat +an = json.load(open(JM / "data/derived/cooking_v7_action_norm.json")) +amin, amax = np.array(an["action_min"], np.float32), np.array(an["action_max"], np.float32) +act = 2 * (np.load(C / "act.f32.npy") - amin) / (amax - amin) - 1 +meta = np.load(C / "meta.npz"); ep_from, ep_to = meta["ep_from"], meta["ep_to"] +N = len(X); row_ep = np.repeat(np.arange(len(ep_from)), ep_to - ep_from) +y = np.load(C / "reward_shaped2.f32.npy"); w = np.load(C / "reward_shaped2_w.f32.npy") +grp = np.load(C / "reward_shaped2_group.i8.npy") +if args.weights == "none": + w = np.ones_like(w) +split = json.load(open(JM / "data/derived/cooking_v7_split.json"))["episodes"] +tt = json.load(open(JM / "data/derived/cooking_v7_tune_test.json")) +train_eps = np.array([i for i in range(len(ep_from)) if split[str(i)]["split"] == "train"]) +tune_eps = np.array(sorted(tt["tune"])) +assert not set(train_eps) & set(tt["tune"]) and not set(train_eps) & set(tt["test"]) +rows_of = lambda eps: np.concatenate([np.arange(ep_from[e], ep_to[e]) for e in eps]) +tr_rows, tu_rows = rows_of(train_eps), rows_of(tune_eps) +print(f"[r2] N={N} train rows {len(tr_rows)} ({len(train_eps)} eps) tune rows {len(tu_rows)} ({len(tune_eps)} eps)", flush=True) + +hov_stage = np.zeros(N, bool) +if args.hover_margin > 0: + e_from = np.load(C / "edge_from.i16.npy").astype(np.int64); ar = np.load(C / "act.f32.npy", mmap_mode="r") + y = y.copy(); ep_end = ep_to[row_ep]; hov_stage = np.isin(e_from, [3, 8]) + for s_ in (3, 8): + cand = tr_rows[(e_from[tr_rows] == s_) & (tr_rows <= ep_end[tr_rows] - 50)] + fr = np.minimum(cand[:, None] + np.arange(50)[None], ep_end[cand][:, None] - 1) + P3 = np.asarray(ar[fr.ravel(), :3]).reshape(len(cand), 50, 3) + dc = np.linalg.norm(P3 - P3[:, :1], axis=2).max(1); hv = cand[dc <= np.percentile(dc, 5)] + y[hv] -= args.hover_margin + print(f"[r2] hover negatives stage {s_}: {len(hv)} TRAIN rows, label -{args.hover_margin}", flush=True) +hov_g = torch.from_numpy(hov_stage).to(dev) +Xg = torch.from_numpy(X).to(dev); Ag = torch.from_numpy(act.astype(np.float32)).to(dev) +yg = torch.from_numpy(y).to(dev); wg = torch.from_numpy(w).to(dev) +epto_g = torch.from_numpy(ep_to[row_ep]).to(dev) +CL = args.chunk if args.act == "chunk50" else 1 +d_a = 0 if args.act == "none" else CL * act.shape[1] + + +def act_in(idx): + if args.act == "none": + return None + fr = idx[:, None] + torch.arange(CL, device=dev)[None, :] + fr = torch.minimum(fr, epto_g[idx][:, None] - 1) + return Ag[fr].reshape(len(idx), -1) + + +class Rew2(nn.Module): + def __init__(self, d_x, d_a, width, depth, dropout): + super().__init__() + L, d = [], d_x + d_a + for _ in range(depth): + L += [nn.Linear(d, width), nn.SiLU()] + ([nn.Dropout(dropout)] if dropout > 0 else []) + d = width + L += [nn.Linear(d, 1)] + self.net = nn.Sequential(*L); self.d_a = d_a + + def forward(self, x, a=None): + h = x if self.d_a == 0 else torch.cat([x, a], -1) + return self.net(h).squeeze(-1) + + +model = Rew2(X.shape[1], d_a, args.width, args.depth, args.dropout).to(dev) +opt = torch.optim.AdamW(model.parameters(), lr=args.lr, weight_decay=args.wd) +sched = torch.optim.lr_scheduler.CosineAnnealingLR(opt, args.steps) +tr_g = torch.from_numpy(tr_rows).to(dev); tu_g = torch.from_numpy(tu_rows).to(dev) + + +@torch.no_grad() +def predict(rows_g): + model.eval(); outs = [] + for i in range(0, len(rows_g), 16384): + idx = rows_g[i:i + 16384]; outs.append(model(Xg[idx], act_in(idx))) + model.train(); return torch.cat(outs) + + +def spearman(a, b): + from scipy.stats import spearmanr + return float(spearmanr(a, b).correlation) + + +def auc(s, lab): + from scipy.stats import rankdata + s, lab = np.asarray(s, float), np.asarray(lab, bool); P, Nn = lab.sum(), (~lab).sum() + if P == 0 or Nn == 0: return float("nan") + rk = rankdata(s); return float((rk[lab].sum() - P * (P + 1) / 2) / (P * Nn)) + + +def tune_metrics(): + pr_ = predict(tu_g); yt, wt = yg[tu_g], wg[tu_g] + hub = F.huber_loss(pr_, yt, reduction="none", delta=args.huber) + pn, yn, gn = pr_.cpu().numpy(), yt.cpu().numpy(), grp[tu_rows] + m = {"tune_whuber": float((hub * wt).sum() / wt.sum()), "tune_huber": float(hub.mean()), + "tune_mae": float((pr_ - yt).abs().mean()), "tune_spearman": spearman(pn, yn), + "tune_frame_auc_G7_vs_FAIL": auc(pn[gn != 0], gn[gn != 0] == 1)} + for g, nm in ((0, "PROG"), (1, "G7"), (2, "FAIL")): + m[f"tune_mae_{nm}"] = float(np.abs(pn[gn == g] - yn[gn == g]).mean()) + return m + + +hist, best, t0 = [], None, time.time() +for step in range(1, args.steps + 1): + idx = tr_g[torch.randint(len(tr_g), (args.batch,), device=dev)] + x = Xg[idx] + if args.x_noise > 0: + x = x + args.x_noise * torch.randn_like(x) + a = act_in(idx) + if a is not None and args.act_drop > 0: + a = a * (torch.rand(len(a), 1, device=dev) >= args.act_drop).float() + yt = yg[idx] + if args.hold_aug > 0 and a is not None: + hm = hov_g[idx] & (torch.rand(len(idx), device=dev) < args.hold_aug) + if hm.any(): + a = a.clone(); a[hm] = Ag[idx[hm]].repeat(1, CL); yt = yt.clone(); yt[hm] = yt[hm] - args.hover_margin + loss = (F.huber_loss(model(x, a), yt, reduction="none", delta=args.huber) * wg[idx]).sum() / wg[idx].sum() + opt.zero_grad(set_to_none=True); loss.backward(); opt.step(); sched.step() + if step % args.eval_every == 0 or step == args.steps: + m = tune_metrics(); m.update(step=step, train_loss=float(loss), sec=time.time() - t0); hist.append(m) + print("[r2]", json.dumps({k: (round(v, 4) if isinstance(v, float) else v) for k, v in m.items()}), flush=True) + blob = {"rew2": model.state_dict(), + "arch": {"kind": "Rew2MLP", "d_x": int(X.shape[1]), "d_a": int(d_a), "act": args.act, "chunk": CL, + "adim": int(act.shape[1]), "width": args.width, "depth": args.depth, "act_fn": "SiLU", + "dropout": args.dropout, "input": "cat(x_zscored[1546], a_norm_flat[d_a])", + "output": "shaped reward (regression, no squashing)"}, + "act_norm": {"min": amin.tolist(), "max": amax.tolist(), + "rule": "a_n = 2 (a - min)/(max - min) - 1, per dim, raw absolute-pose actions"}, + "feat_stats": str(C / "feat_stats.npz"), "labels": "reward_shaped2.f32.npy", + "config": vars(args), "tune": m, "step": step} + torch.save(blob, out / "ckpt_last.pt") + if best is None or m["tune_whuber"] < best["tune_whuber"]: + best = m; torch.save(blob, out / "ckpt_best.pt") +json.dump({"history": hist, "best": best, "config": vars(args)}, open(out / "history.json", "w"), indent=1) +open(out / "DONE", "w").write(json.dumps(best)) +print("[r2] DONE best", json.dumps(best), flush=True) diff --git a/rsm_rise/scripts/real/v7/reward2/train_reward2_sf.py b/rsm_rise/scripts/real/v7/reward2/train_reward2_sf.py new file mode 100644 index 0000000000000000000000000000000000000000..8d488f6607cba8518937866a2648aee79bf763f1 --- /dev/null +++ b/rsm_rise/scripts/real/v7/reward2/train_reward2_sf.py @@ -0,0 +1,316 @@ +#!/usr/bin/env python +"""RSM_PAIRTEST run 6 (owner 2026-11-20 08:05Z): SELF-FORCED reward head on the FROZEN v7 successor (variant a). + +The chain read-out (rsm_scorer_ar.q_chain_value_ar) evaluates r2(z_g, a_g) at SUCCESSOR-GENERATED nodes z_g, with +a_g taken from the hop head. The r2 heads of train_reward2.py only ever saw real frames with logged chunks (teacher +forcing); chain nodes drift off-manifold with hop count (run 5: NN dist 31 -> 347 by hop 7) where the regression +extrapolates. Here the head is trained on the states the read-out actually feeds it: + + bank (built once per run, on GPU, frozen successor + frozen hop head, rsm_real#17 settings beta 0.99, 8 flow steps): + t ~ uniform TRAIN row; z_0 = x_t; a_0 = logged chunk at t (raw); row_0 = t + for d = 1..D: z_d = sample_future(flow, z_{d-1}, a_{d-1}, beta) (the chain hop / goal read) + row_d = truncated_geometric_future(row_{d-1}, ep_end, beta) (the REAL future the successor + is fit to, same sampler as data.py) + a_d = hop.sample_eps(z_d, eps_d) (the read action / next hop action) + sample (z_d, a_d, label = reward_shaped2[row_d], depth d) + The label is the shaped reward of the paired real future: r(z_d) regressed on it is unbiased in expectation + for E[r(future) | s, a, depth] (the hop policy stands in for the logged continuation at d >= 2). + depth weights (--depth_w read): P(read at depth d) of the coin chain, (1-p) p^(d-1), tail mass on d = D, + p = (gamma - beta)/(gamma (1 - beta)) = 0.80 at beta .99 / gamma .998; --depth_w uniform: equal. + loss = w_tf * balanced Huber(real frame, logged chunk) [== train_reward2 c50_bal_adrop02] + + w_sf * balanced Huber(bank node, hop action, paired real-future label) (balance weights of the label row) +Selection on TUNE: tune_sf_huber (bank built from TUNE rows, same procedure) + tune_whuber (real frames), sum. +Checkpoint layout == train_reward2.py (Rew2MLP 'rew2' + arch + act_norm), so rsm_scorer_ar / pairtest 'ar:'/'arc:' +specs load it unchanged. +""" +import argparse, json, os, sys, time +from pathlib import Path +from types import SimpleNamespace +import numpy as np +import torch, torch.nn as nn, torch.nn.functional as F + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import rsm_scorer_ar as AR + +JM = Path("/proj/dmfexp/zwhong/jm/rsm_rise") +C = JM / "cache/real_cooking_v7" +p = argparse.ArgumentParser() +p.add_argument("--out", required=True) +p.add_argument("--succ_ckpt", default=str(JM / "export/v7/rsm_ens20/progress_augc_h50_ps_s0/ckpt_s20000.pt")) +p.add_argument("--hop_ckpt", default=str(JM / "export/v7/hop/gauss_h50_ps_s1/policy_s120000.pt")) +p.add_argument("--beta", type=float, default=0.99) +p.add_argument("--gamma", type=float, default=0.998) +p.add_argument("--flow_steps", type=int, default=8) +p.add_argument("--depth", type=int, default=12, help="max chain depth D in the bank") +p.add_argument("--depth_w", default="read", choices=["read", "uniform"]) +p.add_argument("--bank_rows", type=int, default=150000) +p.add_argument("--tune_bank_rows", type=int, default=20000) +p.add_argument("--w_tf", type=float, default=1.0) +p.add_argument("--w_sf", type=float, default=1.0) +p.add_argument("--width", type=int, default=512) +p.add_argument("--depth_mlp", type=int, default=2) +p.add_argument("--act_drop", type=float, default=0.2) +p.add_argument("--steps", type=int, default=20000) +p.add_argument("--batch", type=int, default=4096) +p.add_argument("--lr", type=float, default=3e-4) +p.add_argument("--wd", type=float, default=1e-4) +p.add_argument("--huber", type=float, default=1.0) +p.add_argument("--eval_every", type=int, default=1000) +p.add_argument("--seed", type=int, default=0) +p.add_argument("--bank_cache", default="", help="reuse a bank npz (same succ/hop/beta/depth) if it exists") +# run 8 (H8): counterfactual hard negatives on first-hop successor samples (TRAIN only) +p.add_argument("--hn_w", type=float, default=0.0, help="weight of the hard-negative regression term (0 = off)") +p.add_argument("--hn_rank", type=float, default=0.0, help="weight of the hard-negative ranking term") +p.add_argument("--hn_thr", type=float, default=float("inf"), help="max proprio-z distance of the failure partner") +p.add_argument("--hn_stride", type=int, default=2) +p.add_argument("--hn_samples", type=int, default=4, help="successor samples per hard-negative pair") +args = p.parse_args() +out = Path(args.out); out.mkdir(parents=True, exist_ok=True) +if (out / "DONE").exists(): + print("[sf] DONE exists, skip", out); raise SystemExit(0) +torch.manual_seed(args.seed); np.random.seed(args.seed) +dev = "cuda" +t_start = time.time() + +st = np.load(C / "feat_stats.npz") +mu, sd, zc = st["mu"].astype(np.float32), np.maximum(st["sd"].astype(np.float32), float(st["sd_floor"])), float(st["z_clip"]) +z = np.load(C / "z.f16.npy"); pr = np.load(C / "proprio.f32.npy") +feat = np.concatenate([z.astype(np.float32), pr], 1); del z +X = np.clip((feat - mu) / sd, -zc, zc).astype(np.float32); del feat +an = json.load(open(JM / "data/derived/cooking_v7_action_norm.json")) +amin, amax = np.array(an["action_min"], np.float32), np.array(an["action_max"], np.float32) +act_raw = np.load(C / "act.f32.npy").astype(np.float32) +act = 2 * (act_raw - amin) / (amax - amin) - 1 +meta = np.load(C / "meta.npz"); ep_from, ep_to = meta["ep_from"], meta["ep_to"] +N = len(X); row_ep = np.repeat(np.arange(len(ep_from)), ep_to - ep_from) +y = np.load(C / "reward_shaped2.f32.npy"); w = np.load(C / "reward_shaped2_w.f32.npy") +split = json.load(open(JM / "data/derived/cooking_v7_split.json"))["episodes"] +tt = json.load(open(JM / "data/derived/cooking_v7_tune_test.json")) +train_eps = np.array([i for i in range(len(ep_from)) if split[str(i)]["split"] == "train"]) +tune_eps = np.array(sorted(tt["tune"])) +assert not set(train_eps) & set(tt["tune"]) and not set(train_eps) & set(tt["test"]) +rows_of = lambda eps: np.concatenate([np.arange(ep_from[e], ep_to[e]) for e in eps]) +tr_rows, tu_rows = rows_of(train_eps), rows_of(tune_eps) +CL, ADIM = 50, act.shape[1] +print(f"[sf] N={N} train rows {len(tr_rows)} tune rows {len(tu_rows)}", flush=True) + +# ---------------------------------------------------------------- frozen successor + hop head (scorer loaders) +m = AR._load_rsm_scorer() +sc = m.RSMScorer(backend="mlp", ckpt=args.succ_ckpt, hop_ckpt=args.hop_ckpt, mode="chain", beta=args.beta, + gamma=args.gamma, n_particles=16, score_kind="prob", temperature=25.0, chain_tail_eps=1e-3, + device=dev, state=SimpleNamespace(d=X.shape[1], sd=torch.from_numpy(sd).float(), normalize=None)) +be = sc.backend +sample_future = m._rsm_modules()[1].sample_future +assert be.d_z == X.shape[1], "successor latent must be the identity z-scored state" +p_cont = m.chain_continuation_p(args.beta, args.gamma) +print(f"[sf] successor d_z {be.d_z} d_act {be.d_act} chunk {be.chunk}; hop d_act {be.hop.d_act}; p_cont {p_cont:.4f}", + flush=True) + + +def trunc_geom(rows, beta, rng): + hi = ep_to[row_ep[rows]] + length = hi - rows; log_d = np.log(beta) + fm = np.maximum(1.0 - np.exp(length * log_d), 1e-12) + off = np.ceil(np.log1p(-rng.random(len(rows)) * fm) / log_d).astype(np.int64) - 1 + return rows + np.clip(off, 0, length - 1) + + +def raw_chunk(rows): + fr = np.minimum(rows[:, None] + np.arange(CL)[None], ep_to[row_ep[rows]][:, None] - 1) + return act_raw[fr.ravel()].reshape(len(rows), -1) + + +@torch.no_grad() +def build_bank(pool, n_rows, seed, tag): + """returns dict z [n*D,1546] f16, a [n*D,500] f16 (NORMALISED, head input), lab, wlab, depth, row.""" + rng = np.random.default_rng(seed); g = torch.Generator(device=dev); g.manual_seed(seed) + t0 = time.time(); D = args.depth; bs = 4096 + Z = np.zeros((n_rows * D, X.shape[1]), np.float16); A = np.zeros((n_rows * D, CL * ADIM), np.float16) + ROW = np.zeros(n_rows * D, np.int64); DEP = np.zeros(n_rows * D, np.int8) + rows0 = rng.choice(pool, n_rows) + for b0 in range(0, n_rows, bs): + r = rows0[b0:b0 + bs]; nb = len(r) + zc_ = be.latent(torch.from_numpy(X[r]).to(dev)) + a = torch.from_numpy(raw_chunk(r)).to(dev) + tk = torch.zeros(nb, dtype=torch.long, device=dev); bq = torch.full((nb,), args.beta, device=dev) + row = r.copy() + for d in range(1, D + 1): + zc_ = sample_future(be.flow, zc_, a, tk, bq, be.rms, args.flow_steps, n=1, + x0=torch.randn(nb, X.shape[1], device=dev, generator=g)) + row = trunc_geom(row, args.beta, rng) + a = be.hop.sample_eps(zc_, tk, torch.randn(nb, be.hop.d_act, device=dev, generator=g)).float() + an_ = (2 * (a.reshape(nb, -1, ADIM) - torch.from_numpy(amin).to(dev)) / + torch.from_numpy(amax - amin).to(dev) - 1).reshape(nb, -1) + sl = np.arange(nb) * D + (d - 1) + b0 * D + Z[sl] = zc_.half().cpu().numpy(); A[sl] = an_.half().cpu().numpy(); ROW[sl] = row; DEP[sl] = d + if (b0 // bs) % 10 == 0: + print(f"[sf] bank {tag} {b0 + nb}/{n_rows} {time.time() - t0:.0f}s", flush=True) + bank = dict(z=Z, a=A, row=ROW, depth=DEP) + # drift diagnostics: |z| by depth + nz = np.linalg.norm(Z[:200000].astype(np.float32), axis=1); dd = DEP[:200000] + print(f"[sf] bank {tag} done {time.time() - t0:.0f}s; |z| by depth " + + " ".join(f"{d}:{nz[dd == d].mean():.1f}" for d in range(1, D + 1)), flush=True) + return bank + + +bank_path = Path(args.bank_cache) if args.bank_cache else out / "bank.npz" +if bank_path.exists(): + B_ = dict(np.load(bank_path)); print("[sf] bank loaded", bank_path, flush=True) + bank = {k[3:]: v for k, v in B_.items() if k.startswith("tr_")}; tbank = {k[3:]: v for k, v in B_.items() if k.startswith("tu_")} +else: + bank = build_bank(tr_rows, args.bank_rows, 1000 + args.seed, "train") + tbank = build_bank(tu_rows, args.tune_bank_rows, 2000 + args.seed, "tune") + if args.bank_cache: + tmp = str(bank_path) + ".tmp.npz" + np.savez(tmp, **{"tr_" + k: v for k, v in bank.items()}, **{"tu_" + k: v for k, v in tbank.items()}) + os.replace(tmp, bank_path) +del sc + +# ---------------------------------------------------------------- H8 hard-negative bank +HN = None +if args.hn_w > 0 or args.hn_rank > 0: + e_from = np.load(C / "edge_from.i16.npy").astype(np.int64); e_to = np.load(C / "edge_to.i16.npy").astype(np.int64) + fin = np.array([split[str(i)]["final_state"] for i in range(len(ep_from))]) + good_tr = train_eps[np.isin(fin[train_eps], [3, 8, 7])] + ancr = np.concatenate([np.arange(ep_from[e], ep_to[e], args.hn_stride) for e in good_tr]) + ancr = ancr[np.isin(e_to[ancr], [1, 2, 3, 8, 7])] + failr = tr_rows[np.isin(e_to[tr_rows], [5, 6])] + prT = pr[tr_rows].astype(np.float64); pmu, psd = prT.mean(0), np.maximum(prT.std(0), 1e-3) + pz = lambda r_: torch.from_numpy(((pr[r_] - pmu) / psd).astype(np.float32)).to(dev) + part = np.full(len(ancr), -1, np.int64); dist = np.full(len(ancr), np.inf, np.float32) + for s0 in np.unique(e_from[ancr]): + w_ = np.flatnonzero(e_from[ancr] == s0); pool = failr[e_from[failr] == s0] + if len(pool) == 0: + pool = failr + Pp = pz(pool) + for i in range(0, len(w_), 4096): + dd = torch.cdist(pz(ancr[w_[i:i + 4096]]), Pp); v_, j_ = dd.min(1) + part[w_[i:i + 4096]] = pool[j_.cpu().numpy()]; dist[w_[i:i + 4096]] = v_.cpu().numpy() + keep = dist < args.hn_thr + print(f"[sf] HN anchors {len(ancr)} kept {int(keep.sum())} (thr {args.hn_thr}); dist pct " + f"{np.percentile(dist, [5, 25, 50, 75, 95]).round(3).tolist()}", flush=True) + ancr, part = ancr[keep], part[keep] + rng_h = np.random.default_rng(3000 + args.seed); gh = torch.Generator(device=dev); gh.manual_seed(3000 + args.seed) + K = args.hn_samples; nA = len(ancr) + ZP = np.zeros((nA * K, X.shape[1]), np.float16); ZF = np.zeros_like(ZP) + AP = np.zeros((nA * K, CL * ADIM), np.float16); AF = np.zeros_like(AP); LP = np.zeros(nA * K, np.int64); LF = np.zeros(nA * K, np.int64) + amin_g, arng_g = torch.from_numpy(amin).to(dev), torch.from_numpy(amax - amin).to(dev) + nrm = lambda a_, nb_: (2 * (a_.reshape(nb_, -1, ADIM) - amin_g) / arng_g - 1).reshape(nb_, -1) + with torch.no_grad(): + for b0 in range(0, nA, 1024): + r = np.repeat(ancr[b0:b0 + 1024], K); q = np.repeat(part[b0:b0 + 1024], K); nb = len(r) + z0 = be.latent(torch.from_numpy(X[r]).to(dev)); tk = torch.zeros(nb, dtype=torch.long, device=dev) + bq = torch.full((nb,), args.beta, device=dev); x0 = torch.randn(nb, X.shape[1], device=dev, generator=gh) + ep_ = torch.randn(nb, be.hop.d_act, device=dev, generator=gh) + sl = slice(b0 * K, b0 * K + nb) + for nm, rows_, Zs, As in (("p", r, ZP, AP), ("f", q, ZF, AF)): + zh = sample_future(be.flow, z0, torch.from_numpy(raw_chunk(rows_)).to(dev), tk, bq, be.rms, args.flow_steps, + n=1, x0=x0.clone()) + ah = be.hop.sample_eps(zh, tk, ep_).float() + Zs[sl] = zh.half().cpu().numpy(); As[sl] = nrm(ah, nb).half().cpu().numpy() + LP[sl] = trunc_geom(r, args.beta, rng_h); LF[sl] = trunc_geom(q, args.beta, rng_h) + HN = dict(zp=torch.from_numpy(ZP).to(dev), zf=torch.from_numpy(ZF).to(dev), ap=torch.from_numpy(AP).to(dev), + af=torch.from_numpy(AF).to(dev), lp=torch.from_numpy(LP).to(dev), lf=torch.from_numpy(LF).to(dev)) + print(f"[sf] HN bank {nA}x{K}; label mean prog {y[LP].mean():.3f} fail {y[LF].mean():.3f}; " + f"frac lp>lf {(y[LP] > y[LF]).mean():.3f}", flush=True) + +D = args.depth +if args.depth_w == "read": + dw = np.array([(1 - p_cont) * p_cont ** (d - 1) for d in range(1, D + 1)]); dw[-1] += p_cont ** D +else: + dw = np.ones(D) / D +print("[sf] depth weights", np.round(dw, 4).tolist(), flush=True) + +Xg = torch.from_numpy(X).to(dev); Ag = torch.from_numpy(act.astype(np.float32)).to(dev) +yg = torch.from_numpy(y).to(dev); wg = torch.from_numpy(w).to(dev) +epto_g = torch.from_numpy(ep_to[row_ep]).to(dev) + + +def to_g(bk): + return dict(z=torch.from_numpy(bk["z"]).to(dev), a=torch.from_numpy(bk["a"]).to(dev), + row=torch.from_numpy(bk["row"]).to(dev), dw=torch.from_numpy(dw[bk["depth"].astype(np.int64) - 1]).float().to(dev), + depth=bk["depth"]) + + +Bg, Tg = to_g(bank), to_g(tbank) +# sample bank nodes with prob proportional to the depth weight (each depth has the same count) +samp_p = Bg["dw"] / Bg["dw"].sum() + + +def act_in(idx): + fr = torch.minimum(idx[:, None] + torch.arange(CL, device=dev)[None, :], epto_g[idx][:, None] - 1) + return Ag[fr].reshape(len(idx), -1) + + +model = AR.Rew2MLP(X.shape[1], CL * ADIM, args.width, args.depth_mlp, 0.0).to(dev) +opt = torch.optim.AdamW(model.parameters(), lr=args.lr, weight_decay=args.wd) +sched = torch.optim.lr_scheduler.CosineAnnealingLR(opt, args.steps) +tr_g = torch.from_numpy(tr_rows).to(dev); tu_g = torch.from_numpy(tu_rows).to(dev) + + +def hub(pred, lab, wt): + return (F.huber_loss(pred, lab, reduction="none", delta=args.huber) * wt).sum() / wt.sum() + + +@torch.no_grad() +def tune_metrics(): + model.eval(); m_ = {} + P = torch.cat([model(Xg[tu_g[i:i + 16384]], act_in(tu_g[i:i + 16384])) for i in range(0, len(tu_g), 16384)]) + m_["tune_whuber"] = float(hub(P, yg[tu_g], wg[tu_g])); m_["tune_mae"] = float((P - yg[tu_g]).abs().mean()) + Ps = torch.cat([model(Tg["z"][i:i + 16384].float(), Tg["a"][i:i + 16384].float()) for i in range(0, len(Tg["z"]), 16384)]) + lab = yg[Tg["row"]]; wl = wg[Tg["row"]] * Tg["dw"] + m_["tune_sf_whuber"] = float(hub(Ps, lab, wl)) + dep = Tg["depth"] + for d in (1, 2, 4, 8, D): + k = torch.from_numpy(dep == d).to(dev) + if k.any(): + m_[f"tune_sf_mae_d{d}"] = float((Ps[k] - lab[k]).abs().mean()) + m_["tune_sf_pred_min"] = float(Ps.min()); m_["tune_sf_pred_p1"] = float(Ps.quantile(0.01)) + m_["tune_sel"] = m_["tune_whuber"] + m_["tune_sf_whuber"] + model.train(); return m_ + + +hist, best, t0 = [], None, time.time() +for step in range(1, args.steps + 1): + loss = torch.zeros((), device=dev) + if args.w_tf > 0: + idx = tr_g[torch.randint(len(tr_g), (args.batch,), device=dev)] + a = act_in(idx) + if args.act_drop > 0: + a = a * (torch.rand(len(a), 1, device=dev) >= args.act_drop).float() + loss = loss + args.w_tf * hub(model(Xg[idx], a), yg[idx], wg[idx]) + if args.w_sf > 0: + j = torch.multinomial(samp_p, args.batch, replacement=True) + a = Bg["a"][j].float() + if args.act_drop > 0: + a = a * (torch.rand(len(a), 1, device=dev) >= args.act_drop).float() + lr_ = Bg["row"][j] + loss = loss + args.w_sf * hub(model(Bg["z"][j].float(), a), yg[lr_], wg[lr_]) + if HN is not None: + j = torch.randint(len(HN["lp"]), (args.batch // 2,), device=dev) + rp = model(HN["zp"][j].float(), HN["ap"][j].float()); rf = model(HN["zf"][j].float(), HN["af"][j].float()) + lp_, lf_ = HN["lp"][j], HN["lf"][j] + if args.hn_w > 0: + loss = loss + args.hn_w * 0.5 * (hub(rp, yg[lp_], wg[lp_]) + hub(rf, yg[lf_], wg[lf_])) + if args.hn_rank > 0: + dl = yg[lp_] - yg[lf_]; mk = (dl.abs() > 0.5).float() + loss = loss + args.hn_rank * (F.softplus(-(rp - rf) * torch.sign(dl)) * mk).sum() / mk.sum().clamp_min(1) + opt.zero_grad(set_to_none=True); loss.backward(); opt.step(); sched.step() + if step % args.eval_every == 0 or step == args.steps: + m_ = tune_metrics(); m_.update(step=step, train_loss=float(loss), sec=time.time() - t0); hist.append(m_) + print("[sf]", json.dumps({k: (round(v, 4) if isinstance(v, float) else v) for k, v in m_.items()}), flush=True) + blob = {"rew2": model.state_dict(), + "arch": {"kind": "Rew2MLP", "d_x": int(X.shape[1]), "d_a": int(CL * ADIM), "act": "chunk50", "chunk": CL, + "adim": int(ADIM), "width": args.width, "depth": args.depth_mlp, "act_fn": "SiLU", + "dropout": 0.0, "input": "cat(x_zscored[1546], a_norm_flat[d_a])", + "output": "shaped reward (regression, no squashing); SELF-FORCED on successor nodes"}, + "act_norm": {"min": amin.tolist(), "max": amax.tolist(), + "rule": "a_n = 2 (a - min)/(max - min) - 1, per dim, raw absolute-pose actions"}, + "feat_stats": str(C / "feat_stats.npz"), "labels": "reward_shaped2.f32.npy", + "config": vars(args), "tune": m_, "step": step} + torch.save(blob, out / "ckpt_last.pt") + if best is None or m_["tune_sel"] < best["tune_sel"]: + best = m_; torch.save(blob, out / "ckpt_best.pt") +json.dump({"history": hist, "best": best, "config": vars(args)}, open(out / "history.json", "w"), indent=1) +open(out / "DONE", "w").write(json.dumps(best)) +print(f"[sf] DONE total {time.time() - t_start:.0f}s best", json.dumps(best), flush=True) diff --git a/rsm_rise/scripts/real/v7/rpred/payloads/p0_main_s0.sh b/rsm_rise/scripts/real/v7/rpred/payloads/p0_main_s0.sh new file mode 100644 index 0000000000000000000000000000000000000000..1f61f9c973843b9149a9763658e7a8935c7fb0c1 --- /dev/null +++ b/rsm_rise/scripts/real/v7/rpred/payloads/p0_main_s0.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +set -uo pipefail +bash /proj/dmfexp/zwhong/rsm_rise/scripts/real/v7/rpred/train_one.sh s2_qaux1_rr1 0 40000 --reward-npy /proj/dmfexp/zwhong/rsm_rise/data/derived/v7_rpred/reward_shaped2_01.f32.npy --reward-mode soft --reward-loss bce --weight-npy /proj/dmfexp/zwhong/jm/rsm_rise/cache/real_cooking_v7/reward_shaped2_w.f32.npy --w-qaux 1.0 --w-rrank 1.0 diff --git a/rsm_rise/scripts/real/v7/rpred/payloads/p1_main_s1.sh b/rsm_rise/scripts/real/v7/rpred/payloads/p1_main_s1.sh new file mode 100644 index 0000000000000000000000000000000000000000..84e7394d1689e362d1e312a8ab0ad9b90138e103 --- /dev/null +++ b/rsm_rise/scripts/real/v7/rpred/payloads/p1_main_s1.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +set -uo pipefail +bash /proj/dmfexp/zwhong/rsm_rise/scripts/real/v7/rpred/train_one.sh s2_qaux1_rr1 1 40000 --reward-npy /proj/dmfexp/zwhong/rsm_rise/data/derived/v7_rpred/reward_shaped2_01.f32.npy --reward-mode soft --reward-loss bce --weight-npy /proj/dmfexp/zwhong/jm/rsm_rise/cache/real_cooking_v7/reward_shaped2_w.f32.npy --w-qaux 1.0 --w-rrank 1.0 diff --git a/rsm_rise/scripts/real/v7/rpred/payloads/p2_main_s2.sh b/rsm_rise/scripts/real/v7/rpred/payloads/p2_main_s2.sh new file mode 100644 index 0000000000000000000000000000000000000000..f0b11b80c84d92cc9a4a523585dba470ac1cd838 --- /dev/null +++ b/rsm_rise/scripts/real/v7/rpred/payloads/p2_main_s2.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +set -uo pipefail +bash /proj/dmfexp/zwhong/rsm_rise/scripts/real/v7/rpred/train_one.sh s2_qaux1_rr1 2 40000 --reward-npy /proj/dmfexp/zwhong/rsm_rise/data/derived/v7_rpred/reward_shaped2_01.f32.npy --reward-mode soft --reward-loss bce --weight-npy /proj/dmfexp/zwhong/jm/rsm_rise/cache/real_cooking_v7/reward_shaped2_w.f32.npy --w-qaux 1.0 --w-rrank 1.0 diff --git a/rsm_rise/scripts/real/v7/rpred/payloads/p3_qaux_only.sh b/rsm_rise/scripts/real/v7/rpred/payloads/p3_qaux_only.sh new file mode 100644 index 0000000000000000000000000000000000000000..5ae1cdbb5a066133b9c7c37871109fc395a6f24b --- /dev/null +++ b/rsm_rise/scripts/real/v7/rpred/payloads/p3_qaux_only.sh @@ -0,0 +1,4 @@ +#!/usr/bin/env bash +set -uo pipefail +bash /proj/dmfexp/zwhong/rsm_rise/scripts/real/v7/rpred/train_one.sh s2_qaux1_rr0 0 40000 --reward-npy /proj/dmfexp/zwhong/rsm_rise/data/derived/v7_rpred/reward_shaped2_01.f32.npy --reward-mode soft --reward-loss bce --weight-npy /proj/dmfexp/zwhong/jm/rsm_rise/cache/real_cooking_v7/reward_shaped2_w.f32.npy --w-qaux 1.0 --w-rrank 0 +bash /proj/dmfexp/zwhong/rsm_rise/scripts/real/v7/rpred/train_one.sh s2_qaux1_rr0 1 40000 --reward-npy /proj/dmfexp/zwhong/rsm_rise/data/derived/v7_rpred/reward_shaped2_01.f32.npy --reward-mode soft --reward-loss bce --weight-npy /proj/dmfexp/zwhong/jm/rsm_rise/cache/real_cooking_v7/reward_shaped2_w.f32.npy --w-qaux 1.0 --w-rrank 0 diff --git a/rsm_rise/scripts/real/v7/rpred/payloads/p4_rr_only.sh b/rsm_rise/scripts/real/v7/rpred/payloads/p4_rr_only.sh new file mode 100644 index 0000000000000000000000000000000000000000..56c0da2cd2b92b3fbfbf02402eb49f7f92c84859 --- /dev/null +++ b/rsm_rise/scripts/real/v7/rpred/payloads/p4_rr_only.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +set -uo pipefail +bash /proj/dmfexp/zwhong/rsm_rise/scripts/real/v7/rpred/train_one.sh s2_qaux0_rr1 0 40000 --reward-npy /proj/dmfexp/zwhong/rsm_rise/data/derived/v7_rpred/reward_shaped2_01.f32.npy --reward-mode soft --reward-loss bce --weight-npy /proj/dmfexp/zwhong/jm/rsm_rise/cache/real_cooking_v7/reward_shaped2_w.f32.npy --w-qaux 0 --w-rrank 1.0 diff --git a/rsm_rise/scripts/real/v7/rpred/payloads/p5_plain_s2.sh b/rsm_rise/scripts/real/v7/rpred/payloads/p5_plain_s2.sh new file mode 100644 index 0000000000000000000000000000000000000000..6372be8235b58370ca7d2bd76e2175efa6da9ae9 --- /dev/null +++ b/rsm_rise/scripts/real/v7/rpred/payloads/p5_plain_s2.sh @@ -0,0 +1,4 @@ +#!/usr/bin/env bash +set -uo pipefail +bash /proj/dmfexp/zwhong/rsm_rise/scripts/real/v7/rpred/train_one.sh s2_qaux0_rr0 0 40000 --reward-npy /proj/dmfexp/zwhong/rsm_rise/data/derived/v7_rpred/reward_shaped2_01.f32.npy --reward-mode soft --reward-loss bce --weight-npy /proj/dmfexp/zwhong/jm/rsm_rise/cache/real_cooking_v7/reward_shaped2_w.f32.npy --w-qaux 0 --w-rrank 0 +bash /proj/dmfexp/zwhong/rsm_rise/scripts/real/v7/rpred/train_one.sh s2_qaux0_rr0 1 40000 --reward-npy /proj/dmfexp/zwhong/rsm_rise/data/derived/v7_rpred/reward_shaped2_01.f32.npy --reward-mode soft --reward-loss bce --weight-npy /proj/dmfexp/zwhong/jm/rsm_rise/cache/real_cooking_v7/reward_shaped2_w.f32.npy --w-qaux 0 --w-rrank 0 diff --git a/rsm_rise/scripts/real/v7/rpred/payloads/p6_prog_qaux.sh b/rsm_rise/scripts/real/v7/rpred/payloads/p6_prog_qaux.sh new file mode 100644 index 0000000000000000000000000000000000000000..439dac87f7448edbca6377259231e657484d22c3 --- /dev/null +++ b/rsm_rise/scripts/real/v7/rpred/payloads/p6_prog_qaux.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +set -uo pipefail +bash /proj/dmfexp/zwhong/rsm_rise/scripts/real/v7/rpred/train_one.sh prog_qaux1_rr1 0 40000 --reward-npy /proj/dmfexp/zwhong/jm/rsm_rise/cache/real_cooking_v7/reward_progress.f32.npy --reward-mode dense --reward-loss bce --w-qaux 1.0 --w-rrank 1.0 diff --git a/rsm_rise/scripts/real/v7/rpred/payloads/p7_qaux5.sh b/rsm_rise/scripts/real/v7/rpred/payloads/p7_qaux5.sh new file mode 100644 index 0000000000000000000000000000000000000000..05ad761ea4d466d07d7b0a27698e412ed435fda2 --- /dev/null +++ b/rsm_rise/scripts/real/v7/rpred/payloads/p7_qaux5.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +set -uo pipefail +bash /proj/dmfexp/zwhong/rsm_rise/scripts/real/v7/rpred/train_one.sh s2_qaux5_rr1 0 40000 --reward-npy /proj/dmfexp/zwhong/rsm_rise/data/derived/v7_rpred/reward_shaped2_01.f32.npy --reward-mode soft --reward-loss bce --weight-npy /proj/dmfexp/zwhong/jm/rsm_rise/cache/real_cooking_v7/reward_shaped2_w.f32.npy --w-qaux 5.0 --w-rrank 1.0 diff --git a/rsm_rise/scripts/real/v7/rpred/run_eval_qaux.sh b/rsm_rise/scripts/real/v7/rpred/run_eval_qaux.sh new file mode 100644 index 0000000000000000000000000000000000000000..01113aea4cf572ffdbb4a39fee0630f7c6ea668d --- /dev/null +++ b/rsm_rise/scripts/real/v7/rpred/run_eval_qaux.sh @@ -0,0 +1,23 @@ +#!/usr/bin/env bash +#SBATCH --partition=cpu +#SBATCH --account=grp_runtime +#SBATCH --nodes=1 --ntasks=1 --cpus-per-task=32 +#SBATCH --mem=96G +#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 +# RSM_PAIRTEST run 6: qaux ONE-SHOT Q (no chain) of the reward-predictive successors on C (pairtest_v3) and A/B +# (errmode), TUNE only. usage: STEP=20000 RUNS="a b" sbatch -J rr_cpu_qaux run_eval_qaux.sh +set -uo pipefail +export PAIRTEST_VERSION=pairtest_v3 +cd /proj/dmfexp/zwhong/rsm_rise +PY=/proj/dmfexp/zwhong/rsm_rise/venv_rsm/bin/python; S=scripts/real/v7/pairtest +for RUN in $RUNS; do + ck=runs/real_cooking_v7/rsm_rpred/$RUN/ckpt_s$STEP.pt; [ -f $ck ] || { echo "no $ck"; continue; } + for B in 0.99 0.998; do + t=qx_${RUN}_k$((STEP/1000))_b${B#0.} + $PY $S/pairtest.py --stage score --split tune --seeds 1 --model ${t}=qaux:$B,succ=$ck + $PY $S/errmode_test.py --stage score --split tune --seeds 1 --model ${t}=qaux:$B,succ=$ck + done +done +echo "[qaux] done $(date -u)" diff --git a/rsm_rise/scripts/real/v7/rpred/run_eval_rpred.sh b/rsm_rise/scripts/real/v7/rpred/run_eval_rpred.sh new file mode 100644 index 0000000000000000000000000000000000000000..2b159a926296129a5e93db8ccf496b61d78be51a --- /dev/null +++ b/rsm_rise/scripts/real/v7/rpred/run_eval_rpred.sh @@ -0,0 +1,23 @@ +#!/usr/bin/env bash +#SBATCH --partition=cpu +#SBATCH --account=grp_runtime +#SBATCH --nodes=1 --ntasks=1 --cpus-per-task=32 +#SBATCH --mem=96G +#SBATCH --time=10: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 +# One reward-predictive successor run (rsm_rpred/) at ckpt_s$STEP: C = frozen pairtest_v3 TUNE at 16x2 / 16x8 / 64x4, +# then A/B = frozen errmode tests (errmode_test.py) at 16x8. Read-out = rsm_real#17 chain with the run's OWN reward head +# (T=25 as deployed). Resumable (pairtest caches per model, errmode caches per minute). +# usage: RUN=s2_qaux1_rr1_s0 STEP=20000 sbatch -J rr_cpu_ev_ run_eval_rpred.sh +set -uo pipefail +export PAIRTEST_VERSION=pairtest_v3 +cd /proj/dmfexp/zwhong/rsm_rise +PY=/proj/dmfexp/zwhong/rsm_rise/venv_rsm/bin/python; S=scripts/real/v7/pairtest +ck=runs/real_cooking_v7/rsm_rpred/$RUN/ckpt_s$STEP.pt; [ -f $ck ] || { echo "no $ck"; exit 1; } +t=rp_${RUN}_k$((STEP/1000)) +$PY $S/pairtest.py --stage score --split tune --seeds 2 --model ${t}_np16s2=old,succ=$ck,np=16 +$PY $S/pairtest.py --stage score --split tune --seeds 8 --model ${t}_np16s8=old,succ=$ck,np=16 +$PY $S/errmode_test.py --stage score --split tune --seeds 8 --model ${t}_16x8=old,succ=$ck,np=16 +$PY $S/pairtest.py --stage score --split tune --seeds 4 --model ${t}_np64s4=old,succ=$ck,np=64 +echo "[ev_rpred] done $(date -u)" diff --git a/rsm_rise/scripts/real/v7/rpred/run_pairtest_rpred.sh b/rsm_rise/scripts/real/v7/rpred/run_pairtest_rpred.sh new file mode 100644 index 0000000000000000000000000000000000000000..7dede81b4324bde5253ca517147dd99e691e633e --- /dev/null +++ b/rsm_rise/scripts/real/v7/rpred/run_pairtest_rpred.sh @@ -0,0 +1,26 @@ +#!/usr/bin/env bash +#SBATCH --job-name=rr_cpu_pt_rpred +#SBATCH --partition=cpu +#SBATCH --account=grp_runtime +#SBATCH --nodes=1 --ntasks=1 --cpus-per-task=32 +#SBATCH --mem=96G +#SBATCH --time=08:00:00 +#SBATCH --output=/proj/dmfexp/zwhong/rsm_rise/logs/slurm/rr_cpu_pt_rpred.%j.out +#SBATCH --error=/proj/dmfexp/zwhong/rsm_rise/logs/slurm/rr_cpu_pt_rpred.%j.err +# Frozen pairtest_v3 on TUNE for the reward-predictive successors (rsm_rpred/*), at checkpoint step $STEP +# (default 20000), with the same hop head and rsm_real#17 read-out as v7_old. Budgets: 16x2 (deployed +# setting), 64x4 (finalist), 16x8 (128 rollouts). v7_old rows already exist for all three budgets. +# Usage: STEP=20000 sbatch run_pairtest_rpred.sh +set -uo pipefail +export PAIRTEST_VERSION=pairtest_v3 +STEP=${STEP:-20000} +cd /proj/dmfexp/zwhong/rsm_rise +PY=/proj/dmfexp/zwhong/rsm_rise/venv_rsm/bin/python; S=scripts/real/v7/pairtest +for d in runs/real_cooking_v7/rsm_rpred/*_s*; do + ck=$d/ckpt_s$STEP.pt; [ -f $ck ] || { echo "skip $d (no ckpt_s$STEP)"; continue; } + t=rp_$(basename $d)_k$((STEP/1000)) + $PY $S/pairtest.py --stage score --split tune --seeds 2 --model ${t}_np16s2=old,succ=$ck,np=16 + $PY $S/pairtest.py --stage score --split tune --seeds 8 --model ${t}_np16s8=old,succ=$ck,np=16 + $PY $S/pairtest.py --stage score --split tune --seeds 4 --model ${t}_np64s4=old,succ=$ck,np=64 +done +echo "[pt_rpred] done $(date -u)" diff --git a/rsm_rise/scripts/real/v7/rpred/train_one.sh b/rsm_rise/scripts/real/v7/rpred/train_one.sh new file mode 100644 index 0000000000000000000000000000000000000000..7d1db408fdb51e64560c2ba36fce8c55f6fcb435 --- /dev/null +++ b/rsm_rise/scripts/real/v7/rpred/train_one.sh @@ -0,0 +1,28 @@ +#!/usr/bin/env bash +# train_one.sh +# RSM_PAIRTEST reward-predictive successor (v7 cooking). Base = progress_augc_h50_ps_s0 recipe exactly +# (chunk 50, beta 0.95-0.998, identity enc, plan-split contrastive kNN aug, same split), + the tag's extra args. +# Resumable: train_rsm --resume 1 continues from $OUT/ckpt.pt; DONE_ marks completion. +set -uo pipefail +tag=$1; seed=$2; steps=$3; shift 3 +JM=/proj/dmfexp/zwhong/jm/rsm_rise; RR=/proj/dmfexp/zwhong/rsm_rise +OUT=$RR/runs/real_cooking_v7/rsm_rpred/${tag}_s${seed} +[ -f $OUT/DONE_$steps ] && { echo "already done $OUT ($steps)"; exit 0; } +mkdir -p $OUT +source $RR/wandb_env.sh +export PYTHONPATH=/proj/dmfexp/zwhong/jm/gen_q_v7/rsm_libero${PYTHONPATH:+:$PYTHONPATH} +cd $RR/code/rsm_libero_rpred +echo "[payload] $tag s$seed steps $steps host $(hostname) gpu ${CUDA_VISIBLE_DEVICES:-?} $(date -u)" +$RR/venv_rsm/bin/python train_rsm.py --cache $JM/cache/real_cooking_v7 --out $OUT \ + --enc identity --append-proprio 0 \ + --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 4096 --lr 3e-4 --ema 0.995 --steps $steps --save-every 10000 --eval-every 5000 \ + --eval-minmse-n 16 --eval-nnl1-k 16 --eval-nnl1-b 256 --sample-clip 10 --in-ram 1 --chunk 50 --seed $seed \ + --flow-norm 1 --x-noise 0 --flow-dropout 0.1 --wd 0.1 --val-eps-json $JM/data/derived/cooking_v7_split.json \ + --action-augment 0.03 --augment-mode contrastive --augment-table $JM/data/derived/v7_augsucc/aug_knn_ee_plansplit.npz \ + --augment-neighbors 15 --augment-frac-cap 0.25 \ + --wandb-entity richardrl --wandb-project rsm_rise --wandb-name real_cooking_v7/rsm_rpred/${tag}_s${seed} \ + "$@" +rc=$? +[ -f $OUT/ckpt_s$steps.pt ] && touch $OUT/DONE_$steps +echo "[payload] $tag s$seed exit rc=$rc $(date -u)" diff --git a/rsm_rise/scripts/real/v7/smoke4_micro256.sh b/rsm_rise/scripts/real/v7/smoke4_micro256.sh new file mode 100644 index 0000000000000000000000000000000000000000..fb260874f8b7c9ea79cf66471f91c4fbdf907c00 --- /dev/null +++ b/rsm_rise/scripts/real/v7/smoke4_micro256.sh @@ -0,0 +1,14 @@ +#!/usr/bin/env bash +# COOKV7_DINOWM: can 4 GPUs hold batch 1024 with NO grad accumulation (256 rows/GPU in one pass)? +# 200 steps, chunk 50, --micro 256 (overrides 128); samples GPU memory with nvidia-smi every 2 s. +set -uo pipefail +ROOT=/proj/dmfexp/zwhong/rsm_rise +OUT=$ROOT/runs/real_cooking_v7/wm/_smoke4_m256; mkdir -p $OUT +nvidia-smi --query-gpu=index,memory.used,memory.total --format=csv,noheader,nounits -l 2 > $OUT/gpumem.csv & +SMI=$! +OUT=$OUT CHUNK=50 NPROC=4 WBNAME=real_cooking_v7/DINOWM_smoke4_m256 \ + bash $ROOT/scripts/real/v7/train_dinowm_v7.sh --steps 200 --eval-every 100 --save-every 200 --wandb-mode disabled --micro 256 +rc=$? +kill $SMI 2>/dev/null +echo "[smoke4] rc=$rc peak GPU MiB per index:"; awk -F', ' '{if($2>m[$1])m[$1]=$2; t=$3} END{for(i in m) print "gpu"i, m[i], "/", t}' $OUT/gpumem.csv +exit $rc diff --git a/rsm_rise/scripts/real/v7/smoke_v7.sh b/rsm_rise/scripts/real/v7/smoke_v7.sh new file mode 100644 index 0000000000000000000000000000000000000000..966eb44da5a8eb48d2248666779e39d474e6ab2c --- /dev/null +++ b/rsm_rise/scripts/real/v7/smoke_v7.sh @@ -0,0 +1,10 @@ +#!/usr/bin/env bash +# COOKV7_DINOWM smoke on 8 GPUs (DDP): 500 steps at chunk 50 (v6 flagship) then chunk 8 (recipe default). +set -uo pipefail +ROOT=/proj/dmfexp/zwhong/rsm_rise +[ -f $ROOT/cache/real_cooking_v7/tokens/VALIDATION_TOK.json ] || { echo "token cache missing"; exit 3; } +for c in 50 8; do + OUT=$ROOT/runs/real_cooking_v7/wm/_smoke_c$c CHUNK=$c NPROC=8 WBNAME=real_cooking_v7/DINOWM_smoke_c$c \ + bash $ROOT/scripts/real/v7/train_dinowm_v7.sh --steps 500 --eval-every 250 --save-every 500 --wandb-mode disabled +done +echo "[smoke] done $(date -u)" diff --git a/rsm_rise/scripts/real/v7/stove/build_anchors.py b/rsm_rise/scripts/real/v7/stove/build_anchors.py new file mode 100644 index 0000000000000000000000000000000000000000..fc601d21d17c17bb75bb02a26377ddc95e0dfc84 --- /dev/null +++ b/rsm_rise/scripts/real/v7/stove/build_anchors.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python +"""V7_STOVE step 1+2 (model-free, written BEFORE any scoring): post-grasp anchors + the PAN/STOVE/OTHER endpoint labeller. + +Episodes: routes 0->1->3, 0->1 (PAN class) and 0->5 (STOVE class) from data/derived/cooking_v7_split.json; TUNE = the +frozen tune list, TRAIN = split 'train'. TEST is never touched. +Grasp / place (proprio gripper width = proprio[:, 9], metres; open = 0.069, closed on tomato 0.02-0.048 on TRAIN): + t_grasp = first frame with gripper < CLOSE (0.060) + t_release = first frame after t_grasp with gripper > OPEN (0.065) (hysteresis; the place) +Anchors: t_grasp, t_grasp+5, ... < t_release (stride 5). tsg = t - t_grasp, frac = tsg / (t_release - t_grasp). +Coincidence: PAN-episode anchor whose nearest TRAIN 0->5 frame (all frames, pairtest_v3 space = z-scored 10-d proprio) is closer than the + frozen pairtest_v3 threshold (p50 of TRAIN within-route NN distances = 0.4777). +Labeller (endpoint = xyz of the chunk's LAST (50th) action; absolute EE target, metres): + reference = TRAIN carry frames [t_grasp, t_release + 5] of PAN episodes (routes 0->1->3 / 0->1, the 0->1 segment only) + and of STOVE episodes (0->5). d_pan / d_stove = distance from the endpoint to the nearest reference frame of each class. + PAN if d_stove - d_pan > MARGIN (2 cm) and d_pan < FAR (5 cm) + STOVE if d_pan - d_stove > MARGIN and d_stove < FAR + OTHER otherwise (shared carry prefix where both routes coincide, or off-distribution endpoint). + Secondary ARR rule (the brief's literal one): PAN_arr / STOVE_arr if the endpoint lies within R_ARR (4 cm) of a TRAIN + release (arrival) point of that class and further than R_ARR from every arrival point of the other. +Sanity check: the labeller on every TUNE+TRAIN anchor's LOGGED 50-chunk (pan episodes must never be STOVE, etc.). +""" +import json, sys +from pathlib import Path +import numpy as np + +JM = Path("/proj/dmfexp/zwhong/jm/rsm_rise"); C = JM / "cache/real_cooking_v7" +ROOT = Path("/proj/dmfexp/zwhong/rsm_rise"); OUT = ROOT / "runs/v7_stove"; ST = ROOT / "status/real" +CLOSE, OPEN, STRIDE, CH = 0.060, 0.065, 5, 50 +MARGIN, FAR, R_ARR = 0.02, 0.05, 0.04 +PAN_R, STOVE_R = {(0, 1, 3), (0, 1)}, {(0, 5)} +THR_COINC = 0.47774171829223633 +LAB = {0: "OTHER", 1: "PAN", 2: "STOVE"} + + +def grasp_release(g): + cl = np.flatnonzero(g < CLOSE) + if not len(cl): + return None + tg = int(cl[0]); op = np.flatnonzero(g[tg:] > OPEN) + return (tg, tg + int(op[0])) if len(op) else None + + +def mindist(Q, P, bs=4096): + out = np.empty(len(Q)); arg = np.empty(len(Q), np.int64) + for i in range(0, len(Q), bs): + d = np.sqrt(((Q[i:i + bs, None, :] - P[None]) ** 2).sum(-1)); out[i:i + bs] = d.min(1); arg[i:i + bs] = d.argmin(1) + return out, arg + + +class Labeller: + def __init__(self, ref): + self.Pp, self.Ps, self.Ap, self.As = ref["ref_pan"], ref["ref_stove"], ref["arr_pan"], ref["arr_stove"] + + def __call__(self, end): # end [N,3] -> (label [N] in {0,1,2}, arr label, d_pan, d_stove) + dp, _ = mindist(end, self.Pp); ds, _ = mindist(end, self.Ps) + lab = np.zeros(len(end), np.int8) + lab[(ds - dp > MARGIN) & (dp < FAR)] = 1; lab[(dp - ds > MARGIN) & (ds < FAR)] = 2 + ap, _ = mindist(end, self.Ap); as_, _ = mindist(end, self.As) + arr = np.zeros(len(end), np.int8); arr[(ap < R_ARR) & (as_ > R_ARR)] = 1; arr[(as_ < R_ARR) & (ap > R_ARR)] = 2 + return lab, arr, dp, ds + + +def main(): + sys.path.insert(0, str(ROOT / "scripts/real/v7/pairtest")) + import pairtest as PT + info = {int(k): v for k, v in json.load(open(JM / "data/derived/cooking_v7_split.json"))["episodes"].items()} + tune = sorted(int(e) for e in json.load(open(JM / "data/derived/cooking_v7_tune_test.json"))["tune"]) + m = np.load(C / "meta.npz"); ef, et = m["ep_from"].astype(np.int64), m["ep_to"].astype(np.int64) + pr = np.load(C / "proprio.f32.npy", mmap_mode="r"); act = np.load(C / "act.f32.npy", mmap_mode="r") + edge_from = np.load(C / "edge_from.i16.npy", mmap_mode="r") + # proprio == observation.state check against the issue-17 junction anchors (built from the parquet) + A0 = np.load(JM / "data/derived/v7_junction/anchors_v7_tune_d0.npz") + rows0 = ef[A0["anchor_ep"]] + A0["anchor_frame"]; chk = float(np.abs(np.asarray(pr[rows0]) - A0["anchor_state"]).max()) + assert chk < 1e-5, chk + rep = {"rule": __doc__, "proprio_vs_parquet_state_maxdiff": chk, "episodes": {}} + A = {k: [] for k in ("row", "ep", "frame", "split", "cls", "tsg", "carry", "frac", "tg", "tr")} + ref = {"ref_pan": [], "ref_stove": [], "arr_pan": [], "arr_stove": []} + for e, v in sorted(info.items()): + path = tuple(v["path"]); sp = "tune" if e in tune else ("train" if v["split"] == "train" else None) + if sp is None or (path not in PAN_R and path not in STOVE_R): + continue + g = np.asarray(pr[ef[e]:et[e], 9]); gr = grasp_release(g) + cls = 1 if path in PAN_R else 2 + if gr is None: + rep["episodes"][e] = {"split": sp, "path": path, "skipped": "no grasp/release"}; continue + tg, tr = gr + if cls == 1: # the 0->1 segment must contain the place + s = np.flatnonzero(np.asarray(edge_from[ef[e]:et[e]]) != 0); seg_end = int(s[0]) if len(s) else et[e] - ef[e] + assert tr < seg_end, (e, tr, seg_end) + rep["episodes"][e] = {"split": sp, "path": path, "t_grasp": tg, "t_release": tr, "len": int(et[e] - ef[e])} + if sp == "train": + key = "pan" if cls == 1 else "stove" + ref["ref_" + key].append(np.asarray(pr[ef[e] + tg: ef[e] + min(tr + 6, et[e] - ef[e]), :3])) + ref["arr_" + key].append(np.asarray(pr[ef[e] + tr, :3])[None]) + for t in range(tg, tr, STRIDE): + A["row"].append(ef[e] + t); A["ep"].append(e); A["frame"].append(t); A["split"].append(sp); A["cls"].append(cls) + A["tsg"].append(t - tg); A["carry"].append(tr - tg); A["frac"].append((t - tg) / (tr - tg)); A["tg"].append(tg); A["tr"].append(tr) + ref = {k: np.concatenate(v).astype(np.float64) for k, v in ref.items()} + A = {k: np.asarray(v) for k, v in A.items()} + rows = A["row"].astype(np.int64); n = len(rows) + # logged chunk (frames past the episode end repeat the last action) + row_ep_end = et[A["ep"]] + idx = np.minimum(rows[:, None] + np.arange(CH)[None], row_ep_end[:, None] - 1) + own = np.asarray(act[idx.reshape(-1)]).reshape(n, CH, -1).astype(np.float32) + L = Labeller(ref) + lab, arr, dp, ds = L(own[:, -1, :3].astype(np.float64)) + # coincidence (pan anchors vs TRAIN stove frames, pairtest feature space) + # pairtest_v3 space: 10-d proprio z-scored with the frozen TRAIN mu/sd of runs/pairtest/pairs_v3_tune.json + PJ = json.load(open(ROOT / "runs/pairtest/pairs_v3_tune.json")); assert abs(PJ["thresholds"]["p50"] - THR_COINC) < 1e-9 + pmu, psd = np.asarray(PJ["proprio_mu"]), np.asarray(PJ["proprio_sd"]) + px = lambda r: ((np.asarray(pr[np.asarray(r, np.int64)], np.float64) - pmu) / psd).astype(np.float32) + stove_rows = np.concatenate([np.arange(ef[e], et[e]) for e, v in info.items() if v["split"] == "train" and tuple(v["path"]) in STOVE_R]) + cd = np.full(n, np.inf); cj = np.full(n, -1) + pan = np.flatnonzero(A["cls"] == 1) + d, j = PT.nn_dist(px(rows[pan]), px(stove_rows)); cd[pan] = d; cj[pan] = stove_rows[j] + OUT.mkdir(parents=True, exist_ok=True) + np.savez(OUT / "anchors.npz", anchor_row=rows, anchor_ep=A["ep"], anchor_frame=A["frame"], split=A["split"], cls=A["cls"], + tsg=A["tsg"], carry=A["carry"], frac=A["frac"], t_grasp=A["tg"], t_release=A["tr"], + anchor_state=np.asarray(pr[rows]).astype(np.float32), own_act=own, own_lab=lab, own_arr=arr, own_dpan=dp, own_dstove=ds, + coinc_dist=cd, coinc_row=cj, **ref) + # report + def cnt(mask, x): + return {LAB[k]: int(((x == k) & mask).sum()) for k in (0, 1, 2)} + S = {} + for sp in ("tune", "train"): + for c, cn in ((1, "pan"), (2, "stove")): + mk = (A["split"] == sp) & (A["cls"] == c) + S[f"{sp}_{cn}"] = {"anchors": int(mk.sum()), "eps": int(len(np.unique(A["ep"][mk]))), + "own_label": cnt(mk, lab), "own_arr": cnt(mk, arr), + "own_label_late(frac>=.5)": cnt(mk & (A["frac"] >= .5), lab)} + if c == 1: + S[f"{sp}_{cn}"]["coincident"] = int((mk & (cd < THR_COINC)).sum()) + S[f"{sp}_{cn}"]["coincident_eps"] = int(len(np.unique(A["ep"][mk & (cd < THR_COINC)]))) + S[f"{sp}_{cn}"]["coinc_dist_pct"] = np.percentile(cd[mk], [5, 25, 50]).round(3).tolist() + rep["summary"] = S + rep["ref_sizes"] = {k: int(len(v)) for k, v in ref.items()} + rep["arr_centroids"] = {k: ref[k].mean(0).round(3).tolist() for k in ("arr_pan", "arr_stove")} + rep["sanity_pass"] = bool(S["tune_pan"]["own_label"]["STOVE"] == 0 and S["tune_stove"]["own_label"]["PAN"] == 0) + json.dump(rep, open(OUT / "anchors.json", "w"), indent=1, default=lambda o: o if not isinstance(o, tuple) else list(o)) + print(json.dumps({k: rep[k] for k in ("proprio_vs_parquet_state_maxdiff", "summary", "ref_sizes", "arr_centroids", "sanity_pass")}, indent=1)) + + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/real/v7/stove/diag.py b/rsm_rise/scripts/real/v7/stove/diag.py new file mode 100644 index 0000000000000000000000000000000000000000..51007cdce6058b0dcce90af935d1403004d27e6d --- /dev/null +++ b/rsm_rise/scripts/real/v7/stove/diag.py @@ -0,0 +1,114 @@ +#!/usr/bin/env python +"""V7_STOVE ranking diagnostic for an RSM read-out (default: DEFAULT = c50 head, b.99 g.995). +For TUNE pan-episode anchors that have both a PAN and a STOVE candidate: take the read-out's best PAN and best STOVE +candidate, draw P=64 first-read successor futures z_f ~ succ(. | s, a; beta) and + (1) the head read v = r2(z_f, a_hop(z_f)) (the chain's goal read, unclamped and clamped), + (2) the nearest TRAIN frame of z_f (z space, every 3rd TRAIN frame): its PHASE -- + pan_carry / pan_placed (0->1 segment after release, i.e. ~state 1) / pan_later (1->3...) / + stove_carry / stove_placed (0->5 after release = state 5) / pre_grasp / other_route. +Also the head's calibration on REAL TRAIN frames by phase (logged chunk and hop-sampled action). +usage: diag.py [--ro default] -> runs/v7_stove/diag_.json""" +import argparse, json, os, sys +from pathlib import Path +import numpy as np, torch + +ROOT = Path("/proj/dmfexp/zwhong/rsm_rise"); OUT = ROOT / "runs/v7_stove" +sys.path.insert(0, str(ROOT / "scripts/real/v7/stove")) +from score_rsm import PT, RO, load_samples +from build_anchors import grasp_release, PAN_R, STOVE_R +JM = Path("/proj/dmfexp/zwhong/jm/rsm_rise"); C = JM / "cache/real_cooking_v7" +PH = ["pre_grasp", "pan_carry", "pan_placed", "pan_later", "stove_carry", "stove_placed", "other_route"] + + +def phases(info, ef, et, pr, edge_from): + ph = np.full(int(et.max()), 6, np.int8) + for e, v in info.items(): + path = tuple(v["path"]); a, b = ef[e], et[e] + if path not in PAN_R and path not in STOVE_R: + continue + gr = grasp_release(np.asarray(pr[a:b, 9])); ph[a:b] = 0 + if gr is None: + continue + tg, tr = gr + if path in PAN_R: + s = np.flatnonzero(np.asarray(edge_from[a:b]) != 0); se = int(s[0]) if len(s) else b - a + ph[a + tg:a + tr] = 1; ph[a + tr:a + se] = 2; ph[a + se:b] = 3 + else: + ph[a + tg:a + tr] = 4; ph[a + tr:b] = 5 + return ph + + +def main(): + ap = argparse.ArgumentParser(); ap.add_argument("--ro", default="default"); ap.add_argument("--P", type=int, default=64) + a = ap.parse_args(); os.chdir(ROOT); torch.set_num_threads(int(os.environ.get("SLURM_CPUS_PER_TASK", "16"))) + A, S, _ = load_samples(); L = np.load(OUT / "cand_labels.npz")["lab"] + Z = np.load(OUT / f"q_{a.ro}_tune.npz"); idx, Q = Z["idx"], Z["q"] + info = {int(k): v for k, v in json.load(open(JM / "data/derived/cooking_v7_split.json"))["episodes"].items()} + m = np.load(C / "meta.npz"); ef, et = m["ep_from"].astype(np.int64), m["ep_to"].astype(np.int64) + pr = np.load(C / "proprio.f32.npy", mmap_mode="r"); act = np.load(C / "act.f32.npy", mmap_mode="r") + ph = phases(info, ef, et, pr, np.load(C / "edge_from.i16.npy", mmap_mode="r")) + F = PT.Feat(); kind, sc = PT.build_scorer(RO[a.ro], F.sd, 1546); be = sc.backend + import rsm_scorer_ar as AR + sf = AR._load_rsm_scorer()._rsm_modules()[1].sample_future + tr_eps = [e for e, v in info.items() if v["split"] == "train"] + rows = np.concatenate([np.arange(ef[e], et[e], 3) for e in tr_eps]) + zt = [] + with torch.no_grad(): + for i in range(0, len(rows), 4096): + zt.append(torch.as_tensor(sc._inputs(sc.as_state(torch.from_numpy(F.x(rows[i:i + 4096]))))).float()) + zt = torch.cat(zt); ztn = (zt * zt).sum(1) + print("[diag] train pool", zt.shape, flush=True) + + def nn_phase(zf): + d2 = (zf * zf).sum(1)[:, None] + ztn[None] - 2 * zf @ zt.T + j = d2.argmin(1).numpy(); return ph[rows[j]], np.sqrt(d2.min(1).values.clamp_min(0).numpy()) + + tk = lambda n: torch.zeros(n, dtype=torch.long) + beta = float(sc.beta); g = torch.Generator().manual_seed(0) + rec = {"PAN": {"v": [], "vc": [], "ph": [], "d": [], "q": []}, "STOVE": {"v": [], "vc": [], "ph": [], "d": [], "q": []}} + pan_both = [k for k in range(len(idx)) if A["cls"][idx[k]] == 1 and (L[idx[k]] == 1).any() and (L[idx[k]] == 2).any()] + for k in pan_both: + i = idx[k]; x = torch.from_numpy(F.x(A["anchor_row"][i:i + 1])) + z0 = torch.as_tensor(sc._inputs(sc.as_state(x))).float() + for cls, lv in (("PAN", 1), ("STOVE", 2)): + c = int(np.argmax(np.where(L[i] == lv, Q[k], -np.inf))) + ac = sc._flat_chunk(torch.from_numpy(S[i, c:c + 1].astype(np.float32))).float() + with torch.no_grad(): + zf = sf(be.flow, z0.repeat(a.P, 1), ac.repeat(a.P, 1), tk(a.P), torch.full((a.P,), beta), be.rms, sc.flow_steps, + n=1, x0=torch.randn(a.P, z0.shape[1], generator=g)) + ag = be.hop.sample_eps(zf, tk(a.P), torch.randn(a.P, int(be.hop.d_act), generator=g)) + v = be.rew2(zf, ag).float().view(-1) if getattr(be, "rew2", None) is not None else torch.full((a.P,), float("nan")) + p, d = nn_phase(zf) + R = rec[cls]; R["v"].append(v.numpy()); R["vc"].append(v.clamp(-1, 10).numpy()); R["ph"].append(p); R["d"].append(d); R["q"].append(Q[k, c]) + if len(rec["PAN"]["q"]) % 10 == 0: + print(f"[diag] {len(rec['PAN']['q'])}/{len(pan_both)}", flush=True) + res = {"ro": a.ro, "n_anchors": len(pan_both), "beta_first_read": beta} + for cls, R in rec.items(): + if not R["v"]: + continue + v, vc, p, d = (np.stack(R[x]) for x in ("v", "vc", "ph", "d")) + res[cls] = {"Q_mean": float(np.mean(R["q"])), "head_read_mean": float(v.mean()), "head_read_clamped_mean": float(vc.mean()), + "head_read_pct": np.percentile(v, [10, 50, 90]).round(3).tolist(), + "future_nn_phase_frac": {PH[j]: float((p == j).mean()) for j in range(7)}, + "future_nn_dist_p50": float(np.median(d))} + # head calibration on REAL TRAIN frames by phase (every 3rd frame; logged chunk + hop action) + if getattr(be, "rew2", None) is not None: + cal = {} + ridx = np.minimum(rows[:, None] + np.arange(50)[None], et[np.searchsorted(ef, rows, side="right") - 1][:, None] - 1) + for j in range(7): + w = np.flatnonzero(ph[rows] == j) + if len(w) == 0: + continue + w = w[np.linspace(0, len(w) - 1, min(len(w), 3000)).astype(int)] + al = sc._flat_chunk(torch.from_numpy(np.asarray(act[ridx[w].reshape(-1)]).reshape(len(w), 50, -1))).float() + with torch.no_grad(): + vl = be.rew2(zt[w], al).float().view(-1).numpy() + vh = be.rew2(zt[w], be.hop.sample_eps(zt[w], tk(len(w)), torch.randn(len(w), int(be.hop.d_act), generator=g))).float().view(-1).numpy() + cal[PH[j]] = {"n": int(len(w)), "logged_mean": float(vl.mean()), "logged_pct": np.percentile(vl, [10, 50, 90]).round(3).tolist(), + "hop_mean": float(vh.mean())} + res["head_calibration_train_frames"] = cal + json.dump(res, open(OUT / f"diag_{a.ro}.json", "w"), indent=1); print(json.dumps(res, indent=1)) + + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/real/v7/stove/metrics.py b/rsm_rise/scripts/real/v7/stove/metrics.py new file mode 100644 index 0000000000000000000000000000000000000000..e8dc9560c199b202d77ae2ffaed6b042df23efa5 --- /dev/null +++ b/rsm_rise/scripts/real/v7/stove/metrics.py @@ -0,0 +1,121 @@ +#!/usr/bin/env python +"""V7_STOVE metrics: candidate labels (build_anchors.Labeller on the 50th-action xyz), coverage, ranking per read-out. +Writes runs/v7_stove/metrics.json and status/real/v7_stove_table.md.""" +import json, sys +from pathlib import Path +import numpy as np + +ROOT = Path("/proj/dmfexp/zwhong/rsm_rise"); OUT = ROOT / "runs/v7_stove" +sys.path.insert(0, str(ROOT / "scripts/real/v7/stove")) +from build_anchors import Labeller, THR_COINC +ROS = ["default", "sf_cap1", "i17", "iql_new", "iql17"] + + +def boot(vals, eps, n=2000, seed=0): + vals, eps = np.asarray(vals, float), np.asarray(eps) + if len(vals) == 0: + return [float("nan")] * 2 + rng = np.random.default_rng(seed); ue = np.unique(eps); by = {e: vals[eps == e] for e in ue}; r = [] + for _ in range(n): + s = rng.choice(ue, len(ue)); r.append(np.concatenate([by[e] for e in s]).mean()) + return [float(np.percentile(r, 2.5)), float(np.percentile(r, 97.5))] + + +def main(): + A = dict(np.load(OUT / "anchors.npz")); n = len(A["anchor_row"]) + S = np.zeros((n, 128, 50, 10), np.float16); have = np.zeros(n, bool) + for k in range(8): + f = OUT / f"samples.part{k}.npz" + if f.exists(): + z = np.load(f); S[z["idx"]] = z["samples"]; have[z["idx"]] = True + L = Labeller(A) + w = np.flatnonzero(have) + lab = np.full((n, 128), -1, np.int8); arr = np.full((n, 128), -1, np.int8) + l, ar, _, _ = L(S[w, :, -1, :3].astype(np.float64).reshape(-1, 3)) + lab[w] = l.reshape(len(w), 128); arr[w] = ar.reshape(len(w), 128) + np.savez(OUT / "cand_labels.npz", lab=lab, arr=arr) + res = {"n_anchors": int(n), "n_sampled": int(have.sum()), "coverage": {}, "ranking": {}} + early = A["frac"] < 0.5; coinc = A["coinc_dist"] < THR_COINC + groups = {} + for sp in ("tune", "train"): + for c, cn in ((1, "pan"), (2, "stove")): + base = (A["split"] == sp) & (A["cls"] == c) & have + groups[f"{sp}_{cn}"] = base; groups[f"{sp}_{cn}_early"] = base & early; groups[f"{sp}_{cn}_late"] = base & ~early + if c == 1: + groups[f"{sp}_{cn}_coinc"] = base & coinc + for g, mk in groups.items(): + if mk.sum() == 0: + res["coverage"][g] = {"n": 0}; continue + for nm, LL in (("lab", lab), ("arr", arr)): + x = LL[mk]; ep = A["anchor_ep"][mk] + res["coverage"].setdefault(g, {"n": int(mk.sum()), "eps": int(len(np.unique(ep)))})[nm] = { + "any_pan": float((x == 1).any(1).mean()), "any_pan_ci": boot((x == 1).any(1), ep), + "any_stove": float((x == 2).any(1).mean()), + "frac_pan": float((x == 1).mean()), "frac_stove": float((x == 2).mean()), "frac_other": float((x == 0).mean()), + "frac_pan_ci": boot((x == 1).mean(1), ep), + "frac_pan_pct": np.percentile((x == 1).mean(1), [10, 25, 50, 75, 90]).round(3).tolist(), + "own_logged_label": {k: int((A["own_lab"][mk] == v).sum()) for k, v in (("OTHER", 0), ("PAN", 1), ("STOVE", 2))}} + for ro in ROS: + for sub in ("tune", "trainpan2"): + f = OUT / f"q_{ro}_{sub}.npz" + if not f.exists(): + continue + z = np.load(f); idx, q = z["idx"], z["q"] + for g, mk in groups.items(): + if not g.startswith("tune" if sub == "tune" else "train_pan"): + continue + sel = np.flatnonzero(mk[idx]) + if len(sel) == 0: + continue + ii = idx[sel]; Q = q[sel] + for nm, LL in (("lab", lab), ("arr", arr)): + x = LL[ii]; ep = A["anchor_ep"][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) + gap = (bp - bs)[both]; win = np.where(gap > 0, 1.0, np.where(gap == 0, 0.5, 0.0)) + # rank of the best PAN candidate among all 128 (0 = top) where a PAN exists + hp = (x == 1).any(1); rk = (Q[hp] > bp[hp][:, None]).sum(1) + # mean Q of PAN vs STOVE candidates (within-anchor), where both exist + mp = np.array([Q[k][x[k] == 1].mean() - Q[k][x[k] == 2].mean() for k in np.flatnonzero(both)]) + sdq = Q.std(1) + r = {"n": int(len(ii)), "eps": int(len(np.unique(ep))), + "top1_pan": float((top == 1).mean()), "top1_pan_ci": boot(top == 1, ep), + "top1_stove": float((top == 2).mean()), "top1_stove_ci": boot(top == 2, ep), "top1_other": float((top == 0).mean()), + "random_pan": float((x == 1).mean()), "random_stove": float((x == 2).mean()), + "n_both": int(both.sum()), "eps_both": int(len(np.unique(ep[both]))), + "bestpan_gt_beststove": float(win.mean()) if both.any() else None, + "bestpan_gt_beststove_ci": boot(win, ep[both]) if both.any() else None, + "gap_best_pct": np.percentile(gap, [10, 25, 50, 75, 90]).round(4).tolist() if both.any() else None, + "gap_best_over_sdQ_median": float(np.median(gap / np.maximum(sdq[both], 1e-9))) if both.any() else None, + "gap_meanpan_minus_meanstove_median": float(np.median(mp)) if both.any() else None, + "meanpan_gt_meanstove": float((mp > 0).mean()) if both.any() else None, + "bestpan_rank_median": float(np.median(rk)) if hp.any() else None, + "sdQ_median": float(np.median(sdq))} + res["ranking"].setdefault(ro, {}).setdefault(g, {})[nm] = r + json.dump(res, open(OUT / "metrics.json", "w"), indent=1) + # compact table + T = ["| read-out | n anch/eps | top-1 PAN | top-1 STOVE | random PAN / STOVE | both: bestPAN>bestSTOVE [CI] (n/eps) | gap p50 | early top1 P/S | late top1 P/S |", + "|---|---|---|---|---|---|---|---|---|"] + for ro in ROS: + R = res["ranking"].get(ro, {}) + if "tune_pan" not in R: + continue + r, e, la = R["tune_pan"]["lab"], R.get("tune_pan_early", {}).get("lab", {}), R.get("tune_pan_late", {}).get("lab", {}) + f = lambda v: "-" if v is None else f"{v:.2f}" + T.append(f"| {ro} | {r['n']}/{r['eps']} | {f(r['top1_pan'])} [{f(r['top1_pan_ci'][0])},{f(r['top1_pan_ci'][1])}] | {f(r['top1_stove'])} | " + f"{f(r['random_pan'])} / {f(r['random_stove'])} | {f(r['bestpan_gt_beststove'])} " + f"[{f((r['bestpan_gt_beststove_ci'] or [None])[0])},{f((r['bestpan_gt_beststove_ci'] or [None, None])[1])}] ({r['n_both']}/{r['eps_both']}) | " + f"{f((r['gap_best_pct'] or [None]*5)[2])} | {f(e.get('top1_pan'))}/{f(e.get('top1_stove'))} | {f(la.get('top1_pan'))}/{f(la.get('top1_stove'))} |") + cv = res["coverage"] + C = ["| anchors | n/eps | >=1 PAN cand | >=1 STOVE cand | mean frac PAN / STOVE / OTHER | logged chunk label P/S/O |", "|---|---|---|---|---|---|"] + for g in ("tune_pan", "tune_pan_early", "tune_pan_late", "tune_stove", "train_pan", "train_pan_early", "train_pan_late", "train_stove"): + if cv.get(g, {}).get("n", 0) == 0: + continue + x = cv[g]["lab"]; o = x["own_logged_label"] + C.append(f"| {g} | {cv[g]['n']}/{cv[g]['eps']} | {x['any_pan']:.2f} | {x['any_stove']:.2f} | {x['frac_pan']:.2f} / {x['frac_stove']:.2f} / {x['frac_other']:.2f} | {o['PAN']}/{o['STOVE']}/{o['OTHER']} |") + open(ROOT / "status/real/v7_stove_table.md", "w").write("## Coverage (labeller `lab`)\n" + "\n".join(C) + "\n\n## Ranking (TUNE pan-episode anchors, `lab`)\n" + "\n".join(T) + "\n") + print("\n".join(C)); print(); print("\n".join(T)) + + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/real/v7/stove/probe_geom.py b/rsm_rise/scripts/real/v7/stove/probe_geom.py new file mode 100644 index 0000000000000000000000000000000000000000..56c2cac82c4a94693b20ceaa300c61d05cdcbce5 --- /dev/null +++ b/rsm_rise/scripts/real/v7/stove/probe_geom.py @@ -0,0 +1,22 @@ +import numpy as np, json +J='/proj/dmfexp/zwhong/jm/rsm_rise'; C=J+'/cache/real_cooking_v7' +m=np.load(C+'/meta.npz'); sp={int(k):v for k,v in json.load(open(J+'/data/derived/cooking_v7_split.json'))['episodes'].items()} +p=np.load(C+'/proprio.f32.npy',mmap_mode='r'); ef=np.load(C+'/edge_from.i16.npy') +CL,OP=0.06,0.065 +allg=[] +for path in [(0,1,3),(0,1),(0,5)]: + rows=[] + for e,v in sp.items(): + if tuple(v['path'])!=path or v['split']!='train': continue + a,b=m['ep_from'][e],m['ep_to'][e]; g=np.asarray(p[a:b,9]); allg.append(g) + cl=np.flatnonzero(gOP) + if len(op)==0: print('norelease',e,path,b-a,tg); continue + tr=tg+op[0]; s=np.flatnonzero(ef[a:b]!=0); se=s[0] if len(s) else b-a + rows.append((e,tg,tr,b-a,se,np.asarray(p[a+tr,:3]),g[tg:tr].min(),g[tg:tr].max(), np.asarray(p[a+tg,:3]))) + R=lambda i: np.array([r[i] for r in rows]) + print(path,len(rows),'dur p10/50/90',np.percentile(R(2)-R(1),[10,50,90]),'grasp t p50',np.median(R(1)),'release-segend p50',np.median(R(2)-R(4))) + print(' place xyz mean',R(5).mean(0).round(3),'sd',R(5).std(0).round(3),' grasp xyz',R(8).mean(0).round(3),R(8).std(0).round(3)) + print(' carry grip min p10/50/90', np.percentile(R(6),[10,50,90]).round(4),'max',np.percentile(R(7),[50,90,100]).round(4)) +g=np.concatenate(allg); h,b=np.histogram(g,bins=np.arange(0,0.075,0.0025)); print(list(zip(b.round(4).tolist(),h.tolist()))) diff --git a/rsm_rise/scripts/real/v7/stove/run_cpu.sh b/rsm_rise/scripts/real/v7/stove/run_cpu.sh new file mode 100644 index 0000000000000000000000000000000000000000..2af7b739da5297413e8151589d889844102d58cc --- /dev/null +++ b/rsm_rise/scripts/real/v7/stove/run_cpu.sh @@ -0,0 +1,14 @@ +#!/usr/bin/env bash +#SBATCH --partition=cpu +#SBATCH --account=grp_runtime +#SBATCH --nodes=1 --ntasks=1 --cpus-per-task=16 +#SBATCH --mem=16G +#SBATCH --time=04: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_STOVE generic CPU runner: run_cpu.sh +set -uo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +echo "[v7_stove] $(hostname) ${SLURM_JOB_ID:-} $* $(date -u)" +"$@" diff --git a/rsm_rise/scripts/real/v7/stove/run_iql.sh b/rsm_rise/scripts/real/v7/stove/run_iql.sh new file mode 100644 index 0000000000000000000000000000000000000000..5ccce0830445d69623bb77a5074fd561c4041bb7 --- /dev/null +++ b/rsm_rise/scripts/real/v7/stove/run_iql.sh @@ -0,0 +1,4 @@ +#!/usr/bin/env bash +# RISE env wrapper for score_iql.py +cd /proj/dmfexp/zwhong/jm/rsm_rise; source scripts/env.sh +exec /proj/dmfexp/zwhong/jm/rsm_rise/env/bin/python /proj/dmfexp/zwhong/rsm_rise/scripts/real/v7/stove/score_iql.py "$@" diff --git a/rsm_rise/scripts/real/v7/stove/sample.py b/rsm_rise/scripts/real/v7/stove/sample.py new file mode 100644 index 0000000000000000000000000000000000000000..cd27f25dd88ac280a11fdd0d2102cf8574745d47 --- /dev/null +++ b/rsm_rise/scripts/real/v7/stove/sample.py @@ -0,0 +1,71 @@ +#!/usr/bin/env python +"""V7_STOVE: 128 pi0.5 proposer chunks per post-grasp anchor (robot proposer = knn3v7 @30000, N=128, chunk 50), +the exact batched path of jm scripts/real/v7_junction/p1_coverage_v7.py sample() (checked vs the sequential +OpenpiPolicy path on the first anchor of the shard). usage: run_env_openpi.sh sample.py --shard K/8""" +import argparse, os, sys, time +from pathlib import Path +import numpy as np + +JM = "/proj/dmfexp/zwhong/jm/rsm_rise"; sys.path.insert(0, f"{JM}/scripts/real"); sys.path.insert(0, f"{JM}/scripts/real/v7_junction") +OUT = Path("/proj/dmfexp/zwhong/rsm_rise/runs/v7_stove") +CFG = "pi05_cooking_sn0p1_knn0p03_ft50_v7_s0" +CKPT = f"{JM}/runs/openpi/checkpoints/{CFG}/sn0p1_knn0p03_s0_ft50_v7/30000" + + +def main(): + ap = argparse.ArgumentParser(); ap.add_argument("--shard", required=True); ap.add_argument("--n", type=int, default=128) + ap.add_argument("--batch", type=int, default=32); ap.add_argument("--seed", type=int, default=0) + a = ap.parse_args(); si, sk = (int(x) for x in a.shard.split("/")) + fn = OUT / f"samples.part{si}.npz" + if fn.exists(): + print("[sample] exists", fn); return + import jax + from p1_coverage_v7 import decode_mp4 + from twin_rollout import OpenpiPolicy, PROMPT + from openpi.models import model as _model + A = np.load(OUT / "anchors.npz") + order = np.lexsort((A["anchor_frame"], A["anchor_ep"], A["split"] != "tune")) # TUNE first, by episode + sel = np.array_split(order, sk)[si] + ep, fr, stt = A["anchor_ep"], A["anchor_frame"], A["anchor_state"] + t0 = time.time(); pol = OpenpiPolicy(CFG, CKPT, a.seed); p = pol.policy; Hm, Dm = pol.H, pol.D + print(f"[sample] shard {si}/{sk}: {len(sel)} anchors, loaded in {time.time()-t0:.0f}s", flush=True) + + def batched(obs, noise): + inputs = p._input_transform(jax.tree.map(lambda x: x, obs)); outs = [] + for b0 in range(0, len(noise), a.batch): + nb = noise[b0:b0 + a.batch] + inp = jax.tree.map(lambda x: np.repeat(np.asarray(x)[None], len(nb), 0), inputs) + o = _model.Observation.from_dict(jax.tree.map(jax.numpy.asarray, inp)) + p._rng, r = jax.random.split(p._rng) + act = np.asarray(p._sample_actions(r, o, noise=jax.numpy.asarray(nb), **dict(p._sample_kwargs))) + st = np.asarray(inputs["state"]) + for k in range(len(nb)): + outs.append(np.asarray(p._output_transform({"state": st, "actions": act[k]})["actions"])[:50, :10]) + return np.stack(outs) + + rng = np.random.default_rng(a.seed + 1000 * si) + S = np.zeros((len(sel), a.n, 50, 10), np.float32); check = None; cache_ep = None; tl = time.time() + vr = Path(f"{JM}/data/real/rsm_cooking_v7/videos/chunk-000") + for k, i in enumerate(sel): + e, t = int(ep[i]), int(fr[i]) + if e != cache_ep: + frames = (decode_mp4(vr / f"observation.images.global/episode_{e:06d}.mp4"), + decode_mp4(vr / f"observation.images.wrist/episode_{e:06d}.mp4")); cache_ep = e + obs = {"observation/image": frames[0][t], "observation/wrist_image": frames[1][t], + "observation/state": stt[i].astype(np.float32), "prompt": PROMPT} + noise = rng.standard_normal((a.n, Hm, Dm)).astype(np.float32) + S[k] = batched(obs, noise) + if check is None: + seq = np.stack([np.asarray(p.infer(obs, noise=noise[q])["actions"])[:50, :10] for q in range(4)]) + check = float(np.abs(seq - S[k, :4]).max()); print(f"[sample] batched-vs-sequential max|diff| {check:.2e}", flush=True) + if check > 0.02: + raise SystemExit("batched path disagrees with OpenpiPolicy") + if k % 20 == 0: + el = time.time() - tl; print(f"[sample] {k+1}/{len(sel)} ep{e} t{t} {el:.0f}s eta {el/(k+1)*(len(sel)-k-1):.0f}s", flush=True) + np.savez_compressed(fn, samples=S.astype(np.float16), idx=sel, anchor_row=A["anchor_row"][sel], check_maxdiff=np.float32(check), + gen_s=np.float32(time.time() - tl), ckpt=CKPT) + print("[sample] wrote", fn, flush=True) + + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/real/v7/stove/sample_pack.sbatch b/rsm_rise/scripts/real/v7/stove/sample_pack.sbatch new file mode 100644 index 0000000000000000000000000000000000000000..7d3b3901a95159973c3ed54e10eaf357ceaa296f --- /dev/null +++ b/rsm_rise/scripts/real/v7/stove/sample_pack.sbatch @@ -0,0 +1,23 @@ +#!/usr/bin/env bash +#SBATCH --partition=gpu-mid +#SBATCH --account=grp_runtime +#SBATCH --gres=gpu:8 +#SBATCH --nodes=1 --ntasks=1 --cpus-per-task=64 +#SBATCH --mem=0 +#SBATCH --time=03:00:00 +#SBATCH --requeue +#SBATCH --exclude=p1-r04-n2 +#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_STOVE: 128 pi0.5 (knn3v7@30k) samples per post-grasp anchor; 8 shards, one per GPU (no 1-GPU jobs). +cd /proj/dmfexp/zwhong/rsm_rise || exit 9 +echo "[stove-pack] $(hostname) ${SLURM_JOB_ID} $(date -u)"; nvidia-smi -L +S=/proj/dmfexp/zwhong/rsm_rise/scripts/real/v7/stove +declare -A P2S +for k in 0 1 2 3 4 5 6 7; do + CUDA_VISIBLE_DEVICES=$k XLA_PYTHON_CLIENT_MEM_FRACTION=0.8 bash /proj/dmfexp/zwhong/jm/rsm_rise/scripts/real/run_env_openpi.sh $S/sample.py --shard $k/8 \ + > logs/slurm/rr_gpu_stove_sample.slot$k.${SLURM_JOB_ID}.out 2>&1 & + P2S[$!]=$k +done +bad=0; for pid in "${!P2S[@]}"; do wait $pid; rc=$?; echo "slot${P2S[$pid]} exit=$rc"; [ $rc -eq 0 ] || bad=$((bad+1)); done +echo "[stove-pack] done $(date -u) failed=$bad"; exit $(( bad > 0 ? 1 : 0 )) diff --git a/rsm_rise/scripts/real/v7/stove/score_iql.py b/rsm_rise/scripts/real/v7/stove/score_iql.py new file mode 100644 index 0000000000000000000000000000000000000000..30e5c78a1a6fd0ff1b4cd3925b9ddedd97477591 --- /dev/null +++ b/rsm_rise/scripts/real/v7/stove/score_iql.py @@ -0,0 +1,61 @@ +#!/usr/bin/env python +"""V7_STOVE: IQL read-out on the 128 proposer candidates per post-grasp anchor = the deploy IDQLScorer rule +Q = min_k critic_target_k(obs(s_t), norm(chunk[0])) (loading/obs exactly as scripts/real/v7/pairtest/iql_pairs.py). +usage (RISE env): score_iql.py --ro iql_new|iql17 --subset tune|trainpan2""" +import argparse, os, sys +from pathlib import Path +import numpy as np + +R = "/proj/dmfexp/zwhong/jm/rsm_rise"; sys.path.insert(0, f"{R}/scripts/real") +C = f"{R}/cache/real_cooking_v7"; HDF5 = f"{R}/data/raw/cooking_v7_expert_suboptimal.hdf5" +NORM = f"{R}/data/derived/cooking_v7_action_norm.json" +OUT = Path("/proj/dmfexp/zwhong/rsm_rise/runs/v7_stove") +sys.path.insert(0, "/proj/dmfexp/zwhong/rsm_rise/scripts/real/v7/stove") +CK = {"iql_new": f"{R}/runs/cooking_v7_rw_RSHAPED2/policy/S0AidqlPSt09_seed2/cooking_v7_rw_RSHAPED2_S0AidqlPSt09_s2/20261120035346/models/model_epoch_5000.pth", + "iql17": f"{R}/runs/cooking_v7_rw_RPROGRESS/policy/S0AidqlPSt09_seed0/cooking_v7_rw_RPROGRESS_S0AidqlPSt09_s0/20261028200450/models/model_epoch_1250.pth"} + + +def main(): + ap = argparse.ArgumentParser(); ap.add_argument("--ro", required=True); ap.add_argument("--subset", required=True); ap.add_argument("--smoke", action="store_true") + a = ap.parse_args() + out = OUT / f"q_{a.ro}_{a.subset}.npz" + if out.exists(): + print("[iql] exists", out); return + import h5py, torch + from v7_iql_score import IQLV7 + from rise_stack import obs as _obs + from score_rsm import load_samples, subset # numpy-only helpers (score_rsm imports torch/pairtest lazily-safe) + torch.set_num_threads(int(os.environ.get("SLURM_CPUS_PER_TASK", "16"))) + A, S, have = load_samples(); idx = subset(A, a.subset) + if a.smoke: + idx = idx[:3]; S[idx] = (A["own_act"][idx][:, None] + np.random.default_rng(0).normal(0, .01, (3, 128, 50, 10)) * (np.arange(10) < 3)).astype(np.float16) + out = OUT / f"smoke_{a.ro}.npz" + assert a.smoke or have[idx].all() + qq = IQLV7(CK[a.ro], action_norm=NORM, hdf5=HDF5, device="cpu"); sc, an = qq.sc, qq.an + algo, keys, OU = sc.algo, sc.keys, sc.ObsUtils + m = np.load(f"{C}/meta.npz"); ef = m["ep_from"].astype(np.int64) + q = np.zeros((len(idx), 128)); ep = A["anchor_ep"][idx]; fr = A["anchor_frame"][idx] + with h5py.File(HDF5, "r") as f: + d = f["data"]; demo_of = {int(d[k].attrs["episode_index"]): k for k in d} + for e in np.unique(ep): + g = d[demo_of[int(e)]]; go = g["obs"]; w = np.flatnonzero(ep == e) + ag, wr, st = go["agentview_image"][()], go["robot0_eye_in_hand_image"][()], go["ee_state"][()] + for i in w: + t = int(fr[i]) + o = _obs.make_obs({"global": ag[t], "wrist": wr[t]}, st[t], an.gripper_thresh, images84={"global": ag[t], "wrist": wr[t]}, t=t) + ob = {} + for k in keys: + x = torch.from_numpy(np.stack([_obs.obs_key(o, k)] * 128)).float() + if OU.key_is_obs_modality(k, "rgb"): + x = OU.process_obs(x, obs_modality="rgb") + ob[k] = x + ac = torch.from_numpy(an.norm(S[idx[i], :, 0].astype(np.float32)).astype(np.float32)) + with torch.no_grad(): + qs = torch.cat([c(obs_dict=ob, acts=ac) for c in algo.nets["critic_target"]], 1) + q[i] = qs.min(1)[0].numpy() + print(f"[iql] {a.ro} ep {e}: {len(w)} anchors", flush=True) + np.savez(out, idx=idx, q=q, ckpt=CK[a.ro]); print("[iql] wrote", out) + + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/real/v7/stove/score_rsm.py b/rsm_rise/scripts/real/v7/stove/score_rsm.py new file mode 100644 index 0000000000000000000000000000000000000000..6faa6ace1d8172f687a074a721b67d00dfe4fa5c --- /dev/null +++ b/rsm_rise/scripts/real/v7/stove/score_rsm.py @@ -0,0 +1,69 @@ +#!/usr/bin/env python +"""V7_STOVE: score the 128 proposer candidates of each post-grasp anchor with a robot RSM read-out (one MC draw, seed 0, += the robot's 64x1 / 16x1). Resumable (partial npz every 25 anchors; CPU jobs here can be evicted). +usage: score_rsm.py --ro default|sf_cap1|i17 --subset tune|trainpan2""" +import argparse, os, sys, time +from pathlib import Path +import numpy as np, torch + +ROOT = Path("/proj/dmfexp/zwhong/rsm_rise"); OUT = ROOT / "runs/v7_stove" +sys.path.insert(0, str(ROOT / "scripts/real/v7/pairtest")); sys.path.insert(0, str(ROOT / "scripts/real/v7/reward2")) +os.environ.setdefault("PAIRTEST_VERSION", "pairtest_v3") +import pairtest as PT + +RO = {"default": "arc:runs/v7_reward2/c50_bal_adrop02/ckpt_best.pt,np=64,beta=0.99,gamma=0.995,tail=1e-3", + "sf_cap1": "arc:runs/v7_reward2_sf/d1/ckpt_best.pt,np=64,beta=0.99,gamma=0.998,tail=0.9", + "i17": "old,np=16,beta=0.99,gamma=0.998,tail=1e-3"} + + +def load_samples(): + A = dict(np.load(OUT / "anchors.npz")) + n = len(A["anchor_row"]); S = np.zeros((n, 128, 50, 10), np.float16); have = np.zeros(n, bool) + for k in range(8): + f = OUT / f"samples.part{k}.npz" + if f.exists(): + z = np.load(f); S[z["idx"]] = z["samples"]; have[z["idx"]] = True + return A, S, have + + +def subset(A, name): + if name == "tune": + return np.flatnonzero(A["split"] == "tune") + if name == "trainpan2": + w = np.flatnonzero((A["split"] == "train") & (A["cls"] == 1)); return w[::2] + raise ValueError(name) + + +def main(): + ap = argparse.ArgumentParser(); ap.add_argument("--ro", required=True); ap.add_argument("--subset", required=True); ap.add_argument("--smoke", action="store_true") + a = ap.parse_args(); os.chdir(ROOT) + torch.set_num_threads(int(os.environ.get("SLURM_CPUS_PER_TASK", "16"))) + out = OUT / f"q_{a.ro}_{a.subset}.npz" + if out.exists(): + print("[score] exists", out); return + A, S, have = load_samples(); idx = subset(A, a.subset) + if a.smoke: # 3 anchors, candidates = the logged chunk + 127 copies jittered by 1 cm; nothing written + idx = idx[:3]; S[idx] = (A["own_act"][idx][:, None] + np.random.default_rng(0).normal(0, .01, (3, 128, 50, 10)) * (np.arange(10) < 3)).astype(np.float16) + out = OUT / f"smoke_{a.ro}.npz" + assert a.smoke or have[idx].all(), "samples missing" + part = OUT / (f"smoke_{a.ro}.partial.npz" if a.smoke else f"q_{a.ro}_{a.subset}.partial.npz") + q = np.full((len(idx), 128), np.nan) + if part.exists(): + z = np.load(part); assert (z["idx"] == idx).all(); q = z["q"] + F = PT.Feat(); X = torch.from_numpy(F.x(A["anchor_row"][idx])) + kind, sc = PT.build_scorer(RO[a.ro], F.sd, X.shape[1]); assert kind == "rsm" + t0 = time.time(); done0 = int((~np.isnan(q[:, 0])).sum()) + for i in range(len(idx)): + if not np.isnan(q[i, 0]): + continue + Ai = torch.from_numpy(S[idx[i]].astype(np.float32)) + sc.score(X[i][None], Ai, seed=0); q[i] = np.asarray(sc.last_q.cpu(), float) + if i % 25 == 0 or i == len(idx) - 1: + np.savez(part, idx=idx, q=q) + el = time.time() - t0; nd = int((~np.isnan(q[:, 0])).sum()) - done0 + print(f"[score] {a.ro} {a.subset} {i+1}/{len(idx)} {el:.0f}s ({el/max(nd,1):.2f}s/anchor) q[0:3]={q[i,:3].round(3)}", flush=True) + np.savez(out, idx=idx, q=q, spec=RO[a.ro]); part.unlink(missing_ok=True); print("[score] wrote", out) + + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/real/v7/stove/smoke.sh b/rsm_rise/scripts/real/v7/stove/smoke.sh new file mode 100644 index 0000000000000000000000000000000000000000..1c848a98e0d89db88b649948df7a5b0803bcb725 --- /dev/null +++ b/rsm_rise/scripts/real/v7/stove/smoke.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +set -x +PY=/proj/dmfexp/zwhong/rsm_rise/venv_rsm/bin/python; S=/proj/dmfexp/zwhong/rsm_rise/scripts/real/v7/stove +for r in default sf_cap1 i17; do $PY $S/score_rsm.py --ro $r --subset tune --smoke; done +for r in iql_new iql17; do bash $S/run_iql.sh --ro $r --subset tune --smoke; done diff --git a/rsm_rise/scripts/real/v7/train_dinowm_v7.sh b/rsm_rise/scripts/real/v7/train_dinowm_v7.sh new file mode 100644 index 0000000000000000000000000000000000000000..5f8067b1c2b8a8715c7660bfe08c00006a03252a --- /dev/null +++ b/rsm_rise/scripts/real/v7/train_dinowm_v7.sh @@ -0,0 +1,38 @@ +#!/usr/bin/env bash +# COOKV7_DINOWM: the rsm_rise DINO-WM recipe (scripts/train_dinowm.sh, unmodified) on cache/real_cooking_v7. +# Architecture / optimiser / steps are EXACTLY train_dinowm.sh. Differences, all real-data knobs taken from the v6 RSM +# flagship (deployed RSM ENS20 = h50 family, scripts/real/v6/payloads/succ_progress_augc_h50_ps_s*.sh): +# CODE code/gen_q_rsm_snap_20261030/rsm_libero (code/gen_q worktree was archived 2026-10-30; pinned private copy +# + COOKV7 patch: --reward-npy / --val-eps-json / --wandb-tags in TokenRSMData, unset = bit-identical) +# --chunk ${CHUNK:-50} v6 flagship chunk 50 rows (~1.25 s at 40 Hz effective); v6 plain successors used 8 +# --beta-lo .95 --beta-hi .998 --beta-q .992 v6 successor band (D5 open). NOTE: latent_mse ignores beta (constant 0) +# --reward-npy reward_progress.f32.npy v6 flagship label (edge_to in {3,7}; D2 open) +# --val-eps-json data/derived/cooking_v7_split.json v6 flagship used the plan split +# usage: train_dinowm_v7.sh [extra train_rsm_dwm.py args] env: NPROC (8), OUT, CHUNK, RLABEL, SPLIT, WBNAME +set -uo pipefail +ROOT=/proj/dmfexp/zwhong/rsm_rise +TASK=real_cooking_v7 +source "$ROOT/wandb_env.sh" || true +PY="$ROOT/venv_rsm/bin/python" +NPROC=${NPROC:-8} +CODE=$ROOT/code/gen_q_rsm_snap_20261030/rsm_libero +OUT=${OUT:-$ROOT/runs/$TASK/wm/dinowm} +CHUNK=${CHUNK:-50} +RLABEL=${RLABEL:-$ROOT/cache/$TASK/reward_progress.f32.npy} +SPLIT=${SPLIT:-$ROOT/data/derived/cooking_v7_split.json} +WBNAME=${WBNAME:-$TASK/DINOWM} +mkdir -p "$OUT" +export OMP_NUM_THREADS=${OMP_NUM_THREADS:-8} +export PYTHONUNBUFFERED=1 +echo "[train_dinowm_v7] $(date) host=$(hostname) nproc=$NPROC out=$OUT chunk=$CHUNK label=$RLABEL split=$SPLIT extra='$*'" +echo "[train_dinowm_v7] gpus: $(nvidia-smi --query-gpu=name --format=csv,noheader 2>/dev/null | sort | uniq -c | tr '\n' ';')" +cd "$CODE" +"$PY" -m torch.distributed.run --standalone --nproc_per_node "$NPROC" train_rsm_dwm.py \ + --cache "$ROOT/cache/$TASK" --out "$OUT" --dynamics latent_mse \ + --depth 6 --heads 16 --dim-head 64 --mlp 2048 --dropout 0.1 \ + --chunk "$CHUNK" --beta-lo 0.95 --beta-hi 0.998 --beta-q 0.992 \ + --batch 1024 --micro 128 --lr 3e-4 --ema 0.995 --steps 100000 \ + --save-every 10000 --eval-every 2500 --eval-minmse-n 16 --compile 1 \ + --reward-mode dense --reward-loss bce --seed 0 --wandb-name "$WBNAME" --wandb-tags cooking_v7,dinowm \ + --reward-npy "$RLABEL" --val-eps-json "$SPLIT" "$@" +rc=$?; echo "[train_dinowm_v7] exit rc=$rc $(date -u)"; exit $rc diff --git a/rsm_rise/scripts/real/v7/v7_reward_heldout.py b/rsm_rise/scripts/real/v7/v7_reward_heldout.py new file mode 100644 index 0000000000000000000000000000000000000000..8bac731488ba9681c97382fd364734fcff5f6820 --- /dev/null +++ b/rsm_rise/scripts/real/v7/v7_reward_heldout.py @@ -0,0 +1,203 @@ +#!/usr/bin/env python +"""V7_REWARD_HELDOUT (owner 2026-11-20): does the cooking-v7 R-progress reward head, read out as +r = sigmoid(R(z)/T) with T=25 (jmarangola/rsm_real #17), separate the held-out states preceding +failures from those preceding successes? + +Read-only: loads the frozen ckpt + cache + split files, writes status/v7_reward_heldout.{json,md,png}. +Outcome definitions (final_state from cooking_v7_split.json): + goal7 : success = final 7, failure = final in {5,6} + prog : success = final in {3,8,7}, failure = final in {5,6} (R-progress positives) + splitnote: success = final in {1,3,4,7,8}, failure = {5,6} (split-file SUCCESS set) +""" +import json, sys +from pathlib import Path +import numpy as np +import torch +import torch.nn.functional as F + +JM = Path("/proj/dmfexp/zwhong/jm/rsm_rise") +CK = JM / "export/v7/rsm_ens20/progress_augc_h50_ps_s0/ckpt_s20000.pt" +FS = JM / "export/v7/rsm_ens20/feat_stats.npz" +C = JM / "cache/real_cooking_v7" +SPLIT = JM / "data/derived/cooking_v7_split.json" +TT = JM / "data/derived/cooking_v7_tune_test.json" +OUT = Path("/proj/dmfexp/zwhong/rsm_rise/status") +T = 25.0 +KS = [50, 150, "all"] +NB = 2000 +DEFS = {"goal7": ({7}, {5, 6}), "prog": ({3, 8, 7}, {5, 6}), "splitnote": ({1, 3, 4, 7, 8}, {5, 6})} +rng = np.random.default_rng(0) + + +def auc(s, y): + s = np.asarray(s, float); y = np.asarray(y, bool) + p, n = y.sum(), (~y).sum() + if p == 0 or n == 0: + return float("nan") + from scipy.stats import rankdata + r = rankdata(s) + return float((r[y].sum() - p * (p + 1) / 2) / (p * n)) + + +def ci(a): + a = np.asarray(a, float); a = a[np.isfinite(a)] + return [float(np.percentile(a, 2.5)), float(np.percentile(a, 97.5))] if len(a) else [None, None] + + +# ---------------------------------------------------------------- model +ck = torch.load(CK, map_location="cpu", weights_only=False) +cfg = ck.get("config", {}) +sd = ck["rew"] +print("[v7rh] ckpt keys", list(ck.keys()), "rew keys", {k: tuple(v.shape) for k, v in sd.items()}, flush=True) +print("[v7rh] cfg subset", {k: cfg.get(k) for k in ("chunk", "seed", "reward_npy", "enc", "d_lat", "proprio", + "val_frac", "split_json", "norm_pool")}, "d_in", ck.get("d_in"), + "d_lat", ck.get("d_lat"), flush=True) +lin = sorted({int(k.split(".")[1]) for k in sd if k.startswith("net.")}) +Ws = [(sd[f"net.{i}.weight"].float(), sd[f"net.{i}.bias"].float()) for i in lin] +if "task.weight" in sd: + temb = sd["task.weight"][0].float() +else: + temb = F.linear(sd["task.E"][0].float(), sd["task.proj.weight"].float(), sd["task.proj.bias"].float()) +if ck.get("enc"): + print("[v7rh] WARNING enc state_dict non-empty:", list(ck["enc"].keys())[:5], flush=True) + + +def R(x): # x [B, d_in] torch float + h = torch.cat([x, temb.expand(len(x), -1)], -1) + for j, (W, b) in enumerate(Ws): + h = F.linear(h, W, b) + if j < len(Ws) - 1: + h = F.silu(h) + return h.squeeze(-1) + + +# ---------------------------------------------------------------- data +st = np.load(FS) +mu, sdv, zc = st["mu"].astype(np.float32), st["sd"].astype(np.float32), float(st["z_clip"]) +st2 = np.load(C / "feat_stats.npz") +assert np.array_equal(st2["mu"], st["mu"]) and np.array_equal(st2["sd"], st["sd"]) +print(f"[v7rh] feat_stats sd min {sdv.min():.3g} (floor {float(st['sd_floor'])}), z_clip {zc}", flush=True) +z = np.load(C / "z.f16.npy", mmap_mode="r") +pp = np.load(C / "proprio.f32.npy", mmap_mode="r") +meta = np.load(C / "meta.npz") +ef_, et_ = meta["ep_from"], meta["ep_to"] +rp = np.load(C / "reward_progress.f32.npy", mmap_mode="r") +split = json.load(open(SPLIT))["episodes"] +tt = json.load(open(TT)) +n_ep = len(ef_) +assert len(split) == n_ep +valid = np.array([split[str(i)]["split"] == "valid" for i in range(n_ep)]) +fin = np.array([int(split[str(i)]["final_state"]) for i in range(n_ep)]) +route = np.array([int(split[str(i)]["route_index"]) for i in range(n_ep)]) +assert int(valid.sum()) == 40 and sorted(tt["tune"] + tt["test"]) == sorted(np.nonzero(valid)[0].tolist()) +ep_valid_meta = meta["ep_valid"] +print(f"[v7rh] meta.ep_valid==split valid: {bool(np.array_equal(ep_valid_meta, valid))} " + f"(meta {int(ep_valid_meta.sum())})", flush=True) + +# training reference: 40 train episodes with the SAME per-route counts as the held-out 40, seed 0 +train_ref = [] +for r in sorted(set(route.tolist())): + k = int((valid & (route == r)).sum()) + pool = np.nonzero((~valid) & (route == r))[0] + train_ref += sorted(rng.choice(pool, size=min(k, len(pool)), replace=False).tolist()) +SETS = {"TUNE": list(tt["tune"]), "TEST": list(tt["test"]), + "TUNE+TEST": sorted(tt["tune"] + tt["test"]), "TRAIN40": train_ref} + +need = sorted(set(sum(SETS.values(), []))) +per_ep = {} +with torch.no_grad(): + for e in need: + a, b = int(ef_[e]), int(et_[e]) + x = np.concatenate([np.asarray(z[a:b], np.float32), np.asarray(pp[a:b], np.float32)], -1) + x = np.clip((x - mu) / sdv, -zc, zc) + lg = R(torch.from_numpy(x)).numpy().astype(np.float64) + per_ep[e] = {"logit": lg, "r": 1 / (1 + np.exp(-lg / T)), "lab": np.asarray(rp[a:b], float)} +# sanity: in-sample frame AUC of the head vs its own R-progress label (all scored frames) +allr = np.concatenate([per_ep[e]["r"] for e in need]); alll = np.concatenate([per_ep[e]["lab"] for e in need]) +print(f"[v7rh] sanity: frame AUC(r vs reward_progress label) over scored eps = {auc(allr, alll > 0):.4f}", flush=True) + + +def lastk(e, K): + v = per_ep[e]["r"] + return v if K == "all" else v[-K:] + + +res = {"ckpt": str(CK), "T": T, "n_boot": NB, "defs": {k: [sorted(a), sorted(b)] for k, (a, b) in DEFS.items()}, + "train_ref_eps": train_ref, "sets": {}} +for sname, eps in SETS.items(): + eps = np.array(eps) + for dname, (S, Fl) in DEFS.items(): + ys = np.array([fin[e] in S for e in eps]); yf = np.array([fin[e] in Fl for e in eps]) + es, efl = eps[ys], eps[yf] + o = {"n_success": int(len(es)), "n_failure": int(len(efl)), "n_other": int(len(eps) - len(es) - len(efl)), + "other_final_states": sorted(set(int(fin[e]) for e in eps[~ys & ~yf])), "K": {}} + for K in KS: + ms = np.array([lastk(e, K).mean() for e in es]); mf = np.array([lastk(e, K).mean() for e in efl]) + d = {"mean_success": float(ms.mean()) if len(ms) else None, + "mean_failure": float(mf.mean()) if len(mf) else None} + if len(ms) and len(mf): + d["diff"] = float(ms.mean() - mf.mean()) + d["auc_episode"] = auc(np.r_[ms, mf], np.r_[np.ones(len(ms)), np.zeros(len(mf))]) + bs, bf, bd, ba = [], [], [], [] + for _ in range(NB): + s_ = ms[rng.integers(0, len(ms), len(ms))]; f_ = mf[rng.integers(0, len(mf), len(mf))] + bs.append(s_.mean()); bf.append(f_.mean()); bd.append(s_.mean() - f_.mean()) + ba.append(auc(np.r_[s_, f_], np.r_[np.ones(len(s_)), np.zeros(len(f_))])) + d.update(ci_success=ci(bs), ci_failure=ci(bf), ci_diff=ci(bd), ci_auc_episode=ci(ba)) + o["K"][str(K)] = d + # frame-level AUC within last 150 frames, CI by episode (cluster) bootstrap + if len(es) and len(efl): + fs = [lastk(e, 150) for e in es]; ff = [lastk(e, 150) for e in efl] + o["auc_frame_last150"] = auc(np.concatenate(fs + ff), + np.r_[np.ones(sum(map(len, fs))), np.zeros(sum(map(len, ff)))]) + ba = [] + for _ in range(NB): + s_ = [fs[i] for i in rng.integers(0, len(fs), len(fs))] + f_ = [ff[i] for i in rng.integers(0, len(ff), len(ff))] + ba.append(auc(np.concatenate(s_ + f_), np.r_[np.ones(sum(map(len, s_))), np.zeros(sum(map(len, f_)))])) + o["ci_auc_frame_last150"] = ci(ba) + o["n_frames_last150"] = [int(sum(map(len, fs))), int(sum(map(len, ff)))] + # per-episode table + o["episodes"] = [{"ep": int(e), "route": int(route[e]), "final": int(fin[e]), "len": int(len(per_ep[e]["r"])), + "mean_r_last50": float(lastk(e, 50).mean()), "mean_r_last150": float(lastk(e, 150).mean()), + "mean_r_all": float(per_ep[e]["r"].mean()), "mean_logit_all": float(per_ep[e]["logit"].mean())} + for e in eps if fin[e] in S or fin[e] in Fl] + res["sets"].setdefault(sname, {})[dname] = o + k150 = o["K"]["150"] + print(f"[v7rh] {sname:9s} {dname:9s} nS={o['n_success']:2d} nF={o['n_failure']:2d} nO={o['n_other']:2d} " + f"last150 S={k150.get('mean_success')} F={k150.get('mean_failure')} AUCep={k150.get('auc_episode')} " + f"CI={k150.get('ci_auc_episode')} AUCfr={o.get('auc_frame_last150')}", flush=True) + +# per-route mean r (held-out) for context +res["heldout_route_mean_r_all"] = {str(r): float(np.mean([per_ep[e]["r"].mean() for e in SETS["TUNE+TEST"] if route[e] == r])) + for r in sorted(set(route[SETS["TUNE+TEST"]].tolist()))} +json.dump(res, open(OUT / "v7_reward_heldout.json", "w"), indent=1) + +# ---------------------------------------------------------------- figure +import matplotlib +matplotlib.use("Agg") +import matplotlib.pyplot as plt +L = 400 +fig, axs = plt.subplots(2, 2, figsize=(11, 7), sharex=True, sharey=True) +for row, dname in enumerate(["goal7", "prog"]): + S, Fl = DEFS[dname] + for col, sname in enumerate(["TUNE+TEST", "TRAIN40"]): + ax = axs[row, col] + for lab, cls, colr in (("success", S, "#1f77b4"), ("failure", Fl, "#d62728")): + eps = [e for e in SETS[sname] if fin[e] in cls] + M = np.full((len(eps), L), np.nan) + for i, e in enumerate(eps): + v = per_ep[e]["r"][::-1][:L]; M[i, :len(v)] = v + x = np.arange(L) + m = np.nanmean(M, 0) + bo = np.array([np.nanmean(M[rng.integers(0, len(eps), len(eps))], 0) for _ in range(500)]) + lo, hi = np.nanpercentile(bo, 2.5, 0), np.nanpercentile(bo, 97.5, 0) + ax.plot(x, m, color=colr, label=f"{lab} (n={len(eps)})") + ax.fill_between(x, lo, hi, color=colr, alpha=0.2) + ax.invert_xaxis(); ax.set_title(f"{sname} | {dname} (S={sorted(S)} F={sorted(Fl)})", fontsize=9) + ax.legend(fontsize=8); ax.grid(alpha=0.3) + if row == 1: ax.set_xlabel("frames before episode end") + if col == 0: ax.set_ylabel(f"r = sigmoid(R(z)/{T:g})") +fig.suptitle("cooking-v7 R-progress head (progress_augc_h50_ps_s0 @20k): mean r aligned at episode end, 95% CI over episodes") +fig.tight_layout(); fig.savefig(OUT / "v7_reward_heldout.png", dpi=120) +print("[v7rh] DONE", flush=True) diff --git a/rsm_rise/scripts/real/v7_augrm/test_job.sh b/rsm_rise/scripts/real/v7_augrm/test_job.sh new file mode 100644 index 0000000000000000000000000000000000000000..0300486360c5be43efedbee74702451b3c81efbb --- /dev/null +++ b/rsm_rise/scripts/real/v7_augrm/test_job.sh @@ -0,0 +1,27 @@ +#!/usr/bin/env bash +# V7_AUGRM tests (CPU): rsm_libero pytest (existing + new removal test) and a 200-step smoke train of the v7 successor +# recipe (succ_progress_noaug_h50_ps_s0 argv, no aug) on the v7 cache, from the successor-remove-action-augment worktree. +set -uo pipefail +export OMP_NUM_THREADS=16 MKL_NUM_THREADS=16 MUJOCO_GL=disable WANDB_MODE=disabled +WT=/proj/dmfexp/zwhong/iris/gen_q_wt/successor-remove-action-augment/rsm_libero +PY=/proj/dmfexp/zwhong/rsm_rise/venv_rsm/bin/python +V7=/proj/dmfexp/zwhong/jm/rsm_rise +OUTD=/proj/dmfexp/zwhong/rsm_rise/status/real/v7_augrm; mkdir -p $OUTD +cd $WT +echo "== git $(git rev-parse --short HEAD) $(git status --short | wc -l) changed paths; host $(hostname) $(date -u)" +$PY -c "import pytest" 2>/dev/null || $PY -m pip install -q pytest +echo "== pytest (existing + removal test)" +$PY -m pytest -q -rs -s test_dwm.py test_lewm_port.py test_successor_no_action_augment.py 2>&1 | tee $OUTD/pytest.txt | tail -60 +echo "PYTEST_EXIT ${PIPESTATUS[0]}" +echo "== smoke train 200 steps (v7 recipe, no aug)" +SM=/proj/dmfexp/zwhong/rsm_rise/runs/_smoke_v7_augrm/progress_noaug_h50_ps_s0; rm -rf $SM; mkdir -p $SM +$PY train_rsm.py --cache $V7/cache/real_cooking_v7 --out $SM \ + --enc identity --append-proprio 0 --reward-mode dense --reward-loss bce --reward-npy $V7/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 4096 --lr 3e-4 --ema 0.995 --steps 200 --save-every 100 --eval-every 100 --eval-minmse-n 16 --eval-nnl1-k 16 --eval-nnl1-b 256 --sample-clip 10 --in-ram 1 --chunk 50 --seed 0 \ + --wandb-name real_cooking_v7/rsm_smoke/augrm --wandb-mode disabled --flow-norm 1 --x-noise 0 --flow-dropout 0.1 --wd 0.1 --val-eps-json $V7/data/derived/cooking_v7_split.json \ + 2>&1 | tee $OUTD/smoke_train.txt | grep -v "^\s*$" | tail -40 +echo "SMOKE_EXIT ${PIPESTATUS[0]}" +ls $SM +echo "== old-flag launch must fail" +$PY train_rsm.py --cache $V7/cache/real_cooking_v7 --out $SM.bad --action-augment 0.03 --augment-mode contrastive 2>&1 | tail -2; echo "OLDFLAG_EXIT ${PIPESTATUS[0]}" +echo "== done $(date -u)" diff --git a/rsm_rise/scripts/real/value_regression_bracket.py b/rsm_rise/scripts/real/value_regression_bracket.py new file mode 100644 index 0000000000000000000000000000000000000000..d1c997d9a441c4ff9135f79544010ff483e20670 --- /dev/null +++ b/rsm_rise/scripts/real/value_regression_bracket.py @@ -0,0 +1,391 @@ +"""SUCC_DEBUG run 19 (gen_q#277): THE BRACKET THE REWARD-LABEL SEARCH NEEDS, MODEL-FREE. + +H38/H40 killed the `dense` label (a per-episode constant by construction, data.py:317) and then +killed the node-2 SITE (a linear read-out of the anchor names the branch with 0 errors on 5,048 +held-out frames). Run 18's way forward was "a reward that varies WITHIN an episode", and LSF +1889156-9 is running Task 1 on the eight non-dense-reward checkpoints to find one. + +That search needs a bracket, and the bracket does not need a model. The quantity the planner +integrates is + V_beta(t) = E_{k ~ TruncGeom(beta, L)} [ r(s_{t+k}) ], L = ep_end - t, +with EXACTLY the k-distribution the trainer samples (data.py::truncated_geometric_future: k in +[0, L-1], k=0 ADMITTED, pmf (1-beta) beta^k / (1 - beta^L)). V_beta is computable in closed form +from the logged episode -- no sampling, no checkpoint -- by the reverse recursion + S(t) = r(t) + beta S(t+1), V_beta(t) = (1-beta) S(t) / (1 - beta^L). +So for EVERY candidate label we can ask, exhaustively and with no model in the loop, the two +questions that decide whether a successor model can earn its keep under that label: + + Q_A IS THE LABEL DEGENERATE? How well does the STAY-PUT read-out -- "the anchor's own + instantaneous reward r(t)" -- already equal V_beta(t)? R2_stay ~ 1 means mean-over- + successors is the anchor's own value and the test is vacuous, which is what `dense` does. + Q_B IS THE VALUE ALREADY IN THE ANCHOR? How well do an episode-held-out 1-NN and a ridge + read-out of the anchor FEATURE predict V_beta? R2 ~ 1 means a direct regression on s + already is the value function and the successor model is not load-bearing -- the H40 + failure mode generalised from a binary branch to a real-valued value. + +A label is USABLE for the RSM-as-value-function claim only if BOTH are far from 1. Every row +carries its brackets: CONST (predict the train mean, R2 = 0 by construction) below, and the total +variance decomposition (within-episode share of Var[V]) beside -- a label whose variance is all +BETWEEN episodes cannot be anything but an episode ID, which is the H40 trap. + +COST NOTE. The features, the kNN neighbour indices and the ridge Gram matrix depend only on the +anchors, NOT on the label, so they are computed ONCE and every label re-uses them (one extra +solve per label). Fifteen labels cost barely more than one. + +Reads only. No trainer, no checkpoint, nothing written outside --out. +""" +import argparse, json, os, sys, time +import numpy as np + +RSM = "/proj/dmfexp/zwhong/projs/issue_resolver_richardrl/gen_q_rsm/rsm_libero" +ROOT = "/proj/dmfexp/zwhong/rsm_rise" +sys.path.insert(0, RSM) +NODE = 2 + + +def knn_idx(Q, R, ep_q, ep_r, k, chunk=256): + """k nearest references per query, same-episode references masked out (episode-held-out).""" + nq = Q.shape[0] + rn = (R * R).sum(1) + I = np.empty((nq, k), np.int64); Dd = np.empty((nq, k), np.float32) + for i in range(0, nq, chunk): + q = Q[i:i + chunk] + d2 = rn[None, :] - 2.0 * (q @ R.T) + (q * q).sum(1)[:, None] + d2[ep_q[i:i + chunk][:, None] == ep_r[None, :]] = np.inf + part = np.argpartition(d2, k, axis=1)[:, :k] + pv = np.take_along_axis(d2, part, 1) + o = np.argsort(pv, axis=1) + I[i:i + chunk] = np.take_along_axis(part, o, 1) + Dd[i:i + chunk] = np.sqrt(np.maximum(np.take_along_axis(pv, o, 1), 0.0)) + return I, Dd + + +def value_exact(r, ep_from, ep_to, beta): + """V_beta(t) for every frame, closed form, the trainer's own truncated geometric.""" + V = np.zeros_like(r, dtype=np.float64) + for lo, hi in zip(ep_from, ep_to): + lo, hi = int(lo), int(hi) + n = hi - lo + if n <= 0: + continue + S = np.empty(n, np.float64) + acc = 0.0 + rr = r[lo:hi].astype(np.float64) + for j in range(n - 1, -1, -1): # S(t) = r(t) + beta S(t+1) + acc = rr[j] + beta * acc + S[j] = acc + L = np.arange(n, 0, -1, dtype=np.float64) # frames remaining INCLUDING self + V[lo:hi] = (1.0 - beta) * S / (1.0 - beta ** L) + return V.astype(np.float32) + + +def value_exact_capped(r, ep_from, ep_to, beta, eps): + """V(t) with the trainer's PER-ANCHOR beta cap: b_t = min(beta, eps**(1/L_t)). + + value_exact() above integrates the beta the SCORER asks for. data.py::sample (lines 459-462) + never uses that beta directly: it caps it per anchor so the truncated tail is a constant eps, + beta_cap = eps**(1/L), L = ep_end - t. With a per-anchor beta the scalar reverse recursion + S(t) = r(t) + b S(t+1) is no longer valid (it assumes ONE b along the whole path), so this does + the geometric sum explicitly per episode: + V(t) = (1-b_t)/(1-b_t**L_t) * sum_{k=0}^{L_t-1} b_t**k r(t+k). + O(n^2) per episode, ~1e8 flops over the corpus, seconds. + NOTE this still uses the TOP of the trainer's band; the trainer draws beta ~ U[beta_lo, b_hi], + so this is an upper bound on the horizon the trainer actually sees, not the band average. + """ + V = np.zeros_like(r, dtype=np.float64) + for lo, hi in zip(ep_from, ep_to): + lo, hi = int(lo), int(hi) + n = hi - lo + if n <= 0: + continue + rr = r[lo:hi].astype(np.float64) + L = np.arange(n, 0, -1, dtype=np.float64) # frames remaining INCLUDING self + b = np.minimum(beta, np.power(eps, 1.0 / np.maximum(L, 2.0))) + k = np.arange(n, dtype=np.float64) + W = np.power(b[:, None], k[None, :]) # W[t, k] = b_t**k + W[k[None, :] >= L[:, None]] = 0.0 # truncate at the episode end + # sum_k b_t**k r(t+k): r(t+k) = rr[t+k], so shift by building from a strided view + acc = np.zeros(n, np.float64) + for j in range(n): # j = k offset + acc[:n - j] += W[:n - j, j] * rr[j:] + V[lo:hi] = (1.0 - b) * acc / np.maximum(1.0 - np.power(b, L), 1e-12) + return V.astype(np.float32) + + +def value_exact_band(r, ep_from, ep_to, beta_lo, beta_hi, eps, q=8): + """V(t) AVERAGED OVER THE BETA BAND THE TRAINER ACTUALLY DRAWS FROM (data.py:459-462). + + value_exact_capped() above uses the TOP of the band, b_t = min(beta, eps**(1/L)). That is not + what the trainer regresses toward. data.py does, per anchor: + beta_cap = eps**(1/L) + beta_hi_eff= clip(beta_cap, beta_lo, beta_hi) <-- NOTE THE LOWER CLIP + beta ~ U[beta_lo, beta_hi_eff] + so (i) the realised beta is a uniform DRAW over a band, not a point, and (ii) an anchor whose + cap falls BELOW beta_lo is clipped back UP to beta_lo -- value_exact_capped's plain minimum + undershoots exactly those short-horizon anchors. Both are fixed here. + V_band(t) = E_u[ V_{b(t,u)}(t) ], b(t,u) = beta_lo + u*(beta_hi_eff(t)-beta_lo), u ~ U[0,1], + evaluated with a q-point midpoint rule in u (the integrand is smooth in b; --band-q doubles + as the convergence knob and the self-test checks q vs 2q). + Cost: q x value_exact_capped, O(q n^2) per episode, seconds. + """ + V = np.zeros_like(r, dtype=np.float64) + u = (np.arange(q, dtype=np.float64) + 0.5) / q # midpoint nodes in [0,1] + for lo, hi in zip(ep_from, ep_to): + lo, hi = int(lo), int(hi) + n = hi - lo + if n <= 0: + continue + rr = r[lo:hi].astype(np.float64) + L = np.arange(n, 0, -1, dtype=np.float64) # frames remaining INCLUDING self + cap = np.power(eps, 1.0 / np.maximum(L, 2.0)) + hi_eff = np.clip(cap, beta_lo, beta_hi) # data.py's clip, lower bound included + k = np.arange(n, dtype=np.float64) + past_end = k[None, :] >= L[:, None] + acc_band = np.zeros(n, np.float64) + for uu in u: + b = beta_lo + uu * (hi_eff - beta_lo) + W = np.power(b[:, None], k[None, :]) + W[past_end] = 0.0 + acc = np.zeros(n, np.float64) + for j in range(n): # j = k offset; r(t+k) = rr[t+k] + acc[:n - j] += W[:n - j, j] * rr[j:] + acc_band += (1.0 - b) * acc / np.maximum(1.0 - np.power(b, L), 1e-12) + V[lo:hi] = acc_band / q + return V.astype(np.float32) + + +def r2(pred, y, var): + return float(1.0 - np.mean((pred - y) ** 2) / max(var, 1e-12)) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--cache", default=f"{ROOT}/cache/real_cooking_v5") + ap.add_argument("--betas", default="0.95,0.99") + ap.add_argument("--seed", type=int, default=0, help="MUST match the training cells' --seed") + ap.add_argument("--chunk", type=int, default=8) + ap.add_argument("--k-success", type=int, default=10) + ap.add_argument("--ref-stride", type=int, default=8) + ap.add_argument("--train-query-stride", type=int, default=40) + ap.add_argument("--val-query-stride", type=int, default=2) + ap.add_argument("--knn-k", type=int, default=5) + ap.add_argument("--ridge-lam", type=float, default=10.0) + ap.add_argument("--cap-eps", type=float, default=0.0, + help="if >0, integrate V with the trainer's per-anchor beta cap " + "b_t=min(beta, cap_eps**(1/L)) (data.py:460, beta_trunc_eps). " + "0 = the scorer's beta, uncapped (the original behaviour).") + ap.add_argument("--band-lo", type=float, default=0.0, + help="if >0, integrate V over the trainer's BETA BAND instead of a point: " + "beta ~ U[band_lo, clip(cap_eps**(1/L), band_lo, beta)] (data.py:459-462). " + "Each --betas entry is then read as the cell's --beta-hi. Needs --cap-eps.") + ap.add_argument("--band-q", type=int, default=8, help="midpoint nodes for the band average") + ap.add_argument("--out", required=True) + a = ap.parse_args() + + from data import LiberoRSMData + t0 = time.time() + os.makedirs(os.path.dirname(os.path.abspath(a.out)) or ".", exist_ok=True) + d = LiberoRSMData(a.cache, chunk=a.chunk, k_success=a.k_success, seed=a.seed, + stratify_success=False, in_ram=True, reward_mode="dense") + N = int(np.max(d.ep_to)); D = int(d.feat_dim) + ef = np.load(f"{a.cache}/edge_from.i16.npy") + print(f"[vrb] N={N} D={D} train_eps={len(d.train_eps)} val_eps={len(d.val_eps)} " + f"({time.time()-t0:.0f}s)", flush=True) + + # ---- the label table ------------------------------------------------------------------- + labels = {} + succ = np.asarray(d.ep_success, bool) + r_dense = np.zeros(N, np.float32) + r_t40 = np.zeros(N, np.float32); r_t10 = np.zeros(N, np.float32) + r_soft = np.zeros(N, np.float32) + for i in np.where(succ)[0]: + lo, hi = int(d.ep_from[i]), int(d.ep_to[i]) + r_dense[lo:hi] = 1.0 + r_t40[max(lo, hi - 40):hi] = 1.0 + r_t10[max(lo, hi - 10):hi] = 1.0 + r_soft[lo:hi] = (0.98 ** np.arange(hi - lo - 1, -1, -1)).astype(np.float32) + labels["dense"] = r_dense; labels["terminal_k40"] = r_t40 + labels["terminal_k10"] = r_t10; labels["soft_g0.98"] = r_soft + for f in sorted(os.listdir(a.cache)): + if f.startswith("reward") and f.endswith(".f32.npy"): + v = np.load(os.path.join(a.cache, f)).astype(np.float32) + if v.shape[0] != N: + print(f"[vrb] SKIP {f}: len {v.shape[0]} != N {N}", flush=True); continue + labels[f[:-8]] = v + print(f"[vrb] labels: {sorted(labels)}", flush=True) + + # ---- anchor sets (shared by every label) ----------------------------------------------- + def rows_of(eps, stride): + rr = np.concatenate([np.arange(int(d.ep_from[e]), int(d.ep_to[e])) for e in sorted(eps)]) + ee = np.concatenate([np.full(int(d.ep_to[e]) - int(d.ep_from[e]), e, np.int64) + for e in sorted(eps)]) + return rr[::stride], ee[::stride] + + ref_rows, ref_ep = rows_of(d.train_eps, a.ref_stride) + trq_rows, trq_ep = rows_of(d.train_eps, a.train_query_stride) + vaq_rows, vaq_ep = rows_of(d.val_eps, a.val_query_stride) + Xr = d._feat(ref_rows).astype(np.float32) + Xq = {"train": d._feat(trq_rows).astype(np.float32), + "val": d._feat(vaq_rows).astype(np.float32)} + QR = {"train": (trq_rows, trq_ep), "val": (vaq_rows, vaq_ep)} + print(f"[vrb] refs {len(ref_rows)} | queries train {len(trq_rows)} val {len(vaq_rows)} " + f"({time.time()-t0:.0f}s)", flush=True) + + NN = {} + for s in ("train", "val"): + qr, qe = QR[s] + NN[s] = knn_idx(Xq[s], Xr, qe, ref_ep, a.knn_k) + print(f"[vrb] knn {s} done ({time.time()-t0:.0f}s)", flush=True) + + # ridge: Gram on the REFERENCE set, factorised once; per label only the RHS changes + Xc = np.concatenate([Xr, np.ones((len(Xr), 1), np.float32)], 1).astype(np.float64) + G = Xc.T @ Xc + a.ridge_lam * np.eye(Xc.shape[1]) + Gf = np.linalg.cholesky(G) + Xqc = {s: np.concatenate([Xq[s], np.ones((len(Xq[s]), 1), np.float32)], 1).astype(np.float64) + for s in ("train", "val")} + print(f"[vrb] gram factorised ({time.time()-t0:.0f}s)", flush=True) + + # ---- HORIZON ARITHMETIC, label-independent, the bracket every sparse label needs ------ + # The trainer caps beta per anchor so the truncated tail is a constant eps: + # beta_cap = eps**(1/L), L = ep_end - t (data.py::sample, beta_trunc_eps=0.02) + # so the reachable horizon from an anchor is set by L, NOT by the beta the scorer asks for. + # Under the capped truncated geometric the mean hop is + # E[k | khop {blk[f'beta{q}']['mean_hop_frames']:.0f} " + f"(cap {blk[f'beta{q}']['capped_frac']:.2f}, " + f"{blk[f'beta{q}']['hops_to_ep_end']:.1f} hops to end)" + for q in (0.95, 0.99, 0.999, 0.9995)), flush=True) + + out = {"cache": a.cache, "seed": a.seed, "N": N, "D": D, + "ref_stride": a.ref_stride, "train_query_stride": a.train_query_stride, + "val_query_stride": a.val_query_stride, "knn_k": a.knn_k, + "ridge_lam": a.ridge_lam, "horizon": hz, "cap_eps": a.cap_eps, + "band_lo": a.band_lo, "band_q": a.band_q, + "beta_semantics": ("band average E_{beta~U[band_lo, clip(cap_eps**(1/L),band_lo,beta)]}" + if a.band_lo > 0 else + ("top of the band, b=min(beta,cap_eps**(1/L))" if a.cap_eps > 0 + else "uncapped, the scorer's beta")), + "n_ref": int(len(ref_rows)), "n_q": {s: int(len(QR[s][0])) for s in QR}, + "k_dist": "TruncGeom(beta,L) k in [0,L-1], k=0 admitted, pmf (1-b)b^k/(1-b^L) " + "-- data.py::truncated_geometric_future, closed form (no sampling)", + "rows": []} + + for beta in [float(x) for x in a.betas.split(",")]: + if a.band_lo > 0: + if a.cap_eps <= 0: + raise SystemExit("--band-lo needs --cap-eps (the band's upper clip is the cap)") + Vs = {name: value_exact_band(r, d.ep_from, d.ep_to, a.band_lo, beta, a.cap_eps, + a.band_q) for name, r in labels.items()} + elif a.cap_eps > 0: + Vs = {name: value_exact_capped(r, d.ep_from, d.ep_to, beta, a.cap_eps) + for name, r in labels.items()} + else: + Vs = {name: value_exact(r, d.ep_from, d.ep_to, beta) for name, r in labels.items()} + + # ---- ARE THE LABELS THE SAME VALUE FUNCTION AT THE JUNCTION, UP TO SCALE? ---------- + # vrb_hibeta.json showed IDENTICAL node-2 R2_stay / R2_nn1 to 3 dp for labels whose + # node-2 Var[V] differs by five orders of magnitude (terminal_k10 1.7e-05 vs B_H400 + # 3.4e-02). R2 is scale-invariant, so that is exactly what V_a = c * V_b at the + # junction would produce -- and it would be a REAL property (every tail-supported + # label integrates the same geometric mass into the same final window), not a bug. + # This block decides which, with a number, before anything is written down. + qr_v = QR["val"][0] + m2v = ef[qr_v] == NODE + if m2v.sum() > 20: + nm = list(Vs.keys()) + M = np.stack([Vs[n][qr_v][m2v].astype(np.float64) for n in nm]) + sd = M.std(1) + ok = sd > 1e-12 + C = np.full((len(nm), len(nm)), np.nan) + if ok.sum() > 1: + C[np.ix_(ok, ok)] = np.corrcoef(M[ok]) + out.setdefault("node2_collinearity", {})[f"b{beta}"] = { + "labels": nm, "n": int(m2v.sum()), + "sd": [float(x) for x in sd], + "const_at_node2": [bool(x) for x in ~ok], + "corr": [[None if np.isnan(x) else round(float(x), 6) for x in row] for row in C]} + print(f"[vrb] COLLINEARITY b{beta} n={int(m2v.sum())} node-2 val anchors, " + f"{int(ok.sum())}/{len(nm)} labels non-constant", flush=True) + + for name, V in Vs.items(): + rec = {"label": name, "beta": beta} + # variance decomposition over TRAIN frames (all of them, not the strided set) + allr = np.concatenate([np.arange(int(d.ep_from[e]), int(d.ep_to[e])) + for e in sorted(d.train_eps)]) + alle = np.concatenate([np.full(int(d.ep_to[e]) - int(d.ep_from[e]), e, np.int64) + for e in sorted(d.train_eps)]) + Va = V[allr].astype(np.float64) + tot = float(Va.var()) + epm = np.zeros_like(Va) + for e in sorted(d.train_eps): + m = alle == e + epm[m] = Va[m].mean() + within = float(((Va - epm) ** 2).mean()) + rec["V_train_mean"] = float(Va.mean()); rec["V_train_var"] = tot + rec["within_ep_var_frac"] = float(within / max(tot, 1e-12)) + rec["r_frac_nonzero"] = float((labels[name] != 0).mean()) + + ymu = float(Va.mean()) + wr = np.linalg.solve(Gf.T, np.linalg.solve(Gf, Xc.T @ V[ref_rows].astype(np.float64))) + for s in ("train", "val"): + qr, qe = QR[s] + y = V[qr].astype(np.float64) + var = float(y.var()) + I, Dd = NN[s] + pred_nn1 = V[ref_rows[I[:, 0]]].astype(np.float64) + pred_nnk = V[ref_rows[I]].astype(np.float64).mean(1) + pred_rdg = Xqc[s] @ wr + pred_stay = labels[name][qr].astype(np.float64) + blk = {"n": int(len(qr)), "V_var": var, "V_mean": float(y.mean()), + "R2_const": r2(np.full_like(y, ymu), y, var), + "R2_stay": r2(pred_stay, y, var), + "R2_nn1": r2(pred_nn1, y, var), + f"R2_nn{a.knn_k}": r2(pred_nnk, y, var), + "R2_ridge": r2(pred_rdg, y, var), + "MAE_const": float(np.abs(y - ymu).mean()), + "MAE_stay": float(np.abs(pred_stay - y).mean()), + "MAE_nn1": float(np.abs(pred_nn1 - y).mean()), + "MAE_ridge": float(np.abs(pred_rdg - y).mean())} + # the same, restricted to node-2 (junction) anchors + m2 = ef[qr] == NODE + if m2.sum() > 20: + y2 = y[m2]; v2 = float(y2.var()) + blk["node2"] = {"n": int(m2.sum()), "V_var": v2, + "R2_stay": r2(pred_stay[m2], y2, v2), + "R2_nn1": r2(pred_nn1[m2], y2, v2), + "R2_ridge": r2(pred_rdg[m2], y2, v2)} + blk["nn1_dist_median"] = float(np.median(Dd[:, 0])) + rec[s] = blk + out["rows"].append(rec) + v = rec["val"] + print(f"[vrb] b{beta} {name:26s} within_var {rec['within_ep_var_frac']:.3f} | " + f"VAL R2 stay {v['R2_stay']:+.3f} nn1 {v['R2_nn1']:+.3f} " + f"ridge {v['R2_ridge']:+.3f} ({time.time()-t0:.0f}s)", flush=True) + + with open(a.out, "w") as f: + json.dump(out, f, indent=1) + print(f"[vrb] wrote {a.out} ({time.time()-t0:.0f}s)", flush=True) + + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/real/verify_ckpt_root.sh b/rsm_rise/scripts/real/verify_ckpt_root.sh new file mode 100644 index 0000000000000000000000000000000000000000..cf0f049963f41aa642c75136edc4a74c647f285c --- /dev/null +++ b/rsm_rise/scripts/real/verify_ckpt_root.sh @@ -0,0 +1,57 @@ +#!/usr/bin/env bash +# Verify the rise_stack QUICKSTART end-to-end against a LOCAL COPY of the public HF mirror: +# `rise_stack.check` (no data, no robot) for all three baselines, then a --ckpt-root replay run. +# LSF GPU payload -- never a login node. +set -uo pipefail +SRC=${SRC:-/proj/dmfexp/zwhong/projs/rsm_real} +RISE_ROOT=${RISE_ROOT:-/proj/dmfexp/zwhong/rsm_rise} +CKPTS=${CKPTS:-$RISE_ROOT/hf_ckpt_root} +OUT=${OUT:-$SRC/runs/rise_stack_ckptroot} +mkdir -p "$OUT" +REPO=$OUT/.snapshot +rsync -a --delete --exclude __pycache__ "$SRC/rise_stack" "$REPO/" || cp -r "$SRC/rise_stack" "$REPO/" + +echo "[verify] host=$(hostname) job=${LSB_JOBID:-none} ckpts=$CKPTS $(date -u)" +nvidia-smi -L 2>/dev/null +rc=0 + +# ---------------- RISE env: idql + rsm ------------------------------------------------------ +( source "$RISE_ROOT/scripts/env.sh" + export PYTHONPATH="$REPO:$RISE_ROOT/code/rise_robomimic:$RISE_ROOT/code/rise_code:${PYTHONPATH:-}" + export RSM_LIBERO_DIR=$RISE_ROOT/code/gen_q/rsm_libero TORCH_HOME=$RISE_ROOT/cache/torch + PY=$RISE_ROOT/env/bin/python + cd "$REPO" + for B in idql rsm; do + echo "=== [verify] check $B --ckpt-root ===" + set -x + $PY -m rise_stack.check --baseline $B --ckpt-root "$CKPTS" --n-cand 128 \ + --json-out "$OUT/check_$B.json" || exit 1 + set +x + done + echo "=== [verify] replay with --ckpt-root (idql, rsm) ===" + for B in idql rsm; do + set -x + $PY -m rise_stack.run --baseline $B --ckpt-root "$CKPTS" --env replay --episodes 2 \ + --n-cand 128 --horizon 8 --seed 0 --out "$OUT/replay_$B" || exit 1 + set +x + done +) || rc=1 + +# ---------------- openpi env: bc (pi0.5) ---------------------------------------------------- +( export OPENPI_DATA_HOME=$RISE_ROOT/.openpi_assets HF_LEROBOT_HOME=$RISE_ROOT/data/real/lerobot_home + export UV_CACHE_DIR=$RISE_ROOT/.uv_cache HF_HUB_OFFLINE=1 TOKENIZERS_PARALLELISM=false PYTHONUNBUFFERED=1 + export XLA_PYTHON_CLIENT_MEM_FRACTION=0.45 XLA_PYTHON_CLIENT_PREALLOCATE=false + export TORCH_HOME=$RISE_ROOT/cache/torch + export PYTHONPATH="$REPO:$RISE_ROOT/code/rise_robomimic:$RISE_ROOT/code/diffusion_policy:$RISE_ROOT/code/robosuite:$RISE_ROOT/code/mimicgen_environments:$RISE_ROOT/code/rise_code:${PYTHONPATH:-}" + PY=$RISE_ROOT/third_party/openpi/.venv/bin/python + cd "$REPO" + echo "=== [verify] check bc (pi0.5) --ckpt-root ===" + set -x + $PY -m rise_stack.check --baseline bc --variant openpi --ckpt-root "$CKPTS" --n-cand 16 \ + --json-out "$OUT/check_bc.json" || exit 1 + set +x +) || rc=1 + +echo "[verify] rc=$rc $(date -u)" +for f in "$OUT"/check_*.json; do [ -f "$f" ] && echo "--- $f" && cat "$f"; done +exit $rc diff --git a/rsm_rise/scripts/real/xl2x2_matched.py b/rsm_rise/scripts/real/xl2x2_matched.py new file mode 100644 index 0000000000000000000000000000000000000000..b3e1e0f20c6912bcf35ddb4bcfd07d470a9ecf27 --- /dev/null +++ b/rsm_rise/scripts/real/xl2x2_matched.py @@ -0,0 +1,327 @@ +#!/usr/bin/env python +""" +BASELINE-MATCHED diff-in-diff for the XL 2x2. + +WHY THIS EXISTS (run 18's finding, restated as the defect this script repairs) +----------------------------------------------------------------------------- +The 2x2 asks whether the low-beta interior peak is a HORIZON effect (H1) or an +OUT-OF-SUPPORT extrapolation artefact (H2), by comparing the beta gain on a +checkpoint for which 0.90 is IN its trained support (rise, --beta-lo 0.90) +against one for which it is OUT (nt, --beta-lo 0.95). + +Run 18 ran the PLACEBO row first: at beta 0.95 BOTH checkpoints are in support, +so the diff-in-diff there MUST be 0. It is not. Raw rank pct -0.0787 p=4.3e-7; +on the variance-stabilizing scale it got WORSE (-0.8917); and the ceiling-free +twin `margin_z` fails with the OPPOSITE SIGN (+7.57). A quantity whose sign is +set by the choice of summary statistic is not an estimate of anything. + +The mechanism was already measured on R_M in runs 16-17 and it is not a scale +artefact: LOWERING BETA RESCUES ANCHORS THAT SCORE BADLY AND DOES ~NOTHING FOR +ANCHORS ALREADY AT THE TOP (+0.0150 on the 40 worst anchors, ~0 on the 70 at +exactly 1.000). So the per-anchor gain g is a DECREASING FUNCTION OF THE +ANCHOR'S OWN BASELINE SCORE x. nt is the weak scorer (rank pct 0.836 at the +0.99 reference) and rise the strong one (0.947), so nt has systematically more +to rescue. The naive diff-in-diff averages g over two arms whose x +distributions differ, which is exactly a violation of parallel trends -- and no +monotone re-scaling of the statistic can remove it, because the problem is in +the COVARIATE, not the scale. + +THE FIX +------- +Compare the two arms AT THE SAME BASELINE. Stratify every (arm, anchor) unit on +its own baseline value x at the reference beta, and average the within-stratum +contrast + + d_s = mean(g_rise | x in s) - mean(g_nt | x in s) + +over strata, restricted to the region of COMMON SUPPORT in x (strata holding at +least `--min-cell` units of BOTH arms). Two poolings are reported: + + * ATE -- weights proportional to the total units in the stratum; + * ATT -- weights proportional to the rise (in-support) units, i.e. the effect + re-weighted onto the population the H1 claim is actually about. + +THE CAP IS ITS OWN STRATUM. rank pct is (candidates < logged).mean() over +n_cand=128 draws: a HARD discreteness cap at exactly 1.0 that 17-35% of anchors +already sit on. Those units have zero headroom BY CONSTRUCTION and must never +be averaged with units that have room to move, so `x == cap` is split off as a +separate stratum and is excluded from the pooled estimate (its contribution is +printed separately). + +VALIDATION ORDER, PRE-REGISTERED +-------------------------------- +This estimator is read on the TEST row (beta 0.90) ONLY IF it passes the PLACEBO +row (beta 0.95, where the answer must be 0). The script prints the placebo +verdict above the test verdict every time and refuses to call a test row +readable when its own placebo fails. Matching is not a licence to believe a +number; it is a hypothesis about the confound, and the placebo is its test. + +Pairing is preserved in the bootstrap: anchors are resampled as units (both arms +together), never independently. + +CPU only; reads the cell JSONs already on disk. No GPU work, no new rollouts. +""" +import json, os, argparse +import numpy as np +from scipy.stats import wilcoxon + +ROOT = "/proj/dmfexp/zwhong/rsm_rise/status/real/ACT_COND" +ARMS = [("nt", f"{ROOT}/snr_xlnt"), ("rise", f"{ROOT}/snr_xlrise")] +BETAS = ["99", "95", "90"] +REF_BETA = "99" + +# args that MUST be identical across every cell; ckpt and beta are the two that may differ. +FIXED_ARGS = ("mode", "chain_cap", "gamma", "particles", "temperature", "n_cand", "n_state", + "n_interp", "stride", "anchor_routes", "max_anchors", "seed", "repeats") + +# stem, label, sign (+1 higher-better, -1 lower-better, 0 unscored), capped-at +STATS = [("rank_pct", "rank pct (logged chunk)", +1, 1.0), + ("top1_agree", "top1 agree", +1, 1.0), + ("spearman", "monotone probe rho", -1, None), + ("margin_z", "margin z (cloud-std)", +1, None), + ("rep_spearman", "rep spearman (NOISE)", 0, None)] +PROP = {"rank_pct", "top1_agree"} +CORR = {"spearman", "rep_spearman"} + + +def add_margin_z(rows): + """(score of the logged chunk - mean over the 128 candidates) / sd over them. + + The ceiling-free twin of rank pct, from fields already on disk. Unbounded + above, so it cannot hit rank pct's discreteness cap.""" + for r in rows: + for read, s0 in (("logit", "logit0"), ("prob", "q0")): + sd = float(r[f"var_a_{read}"]) ** 0.5 + r[f"margin_z_{read}"] = ((float(r[s0]) - float(r[f"mean_a_{read}"])) / sd + if sd > 0 else np.nan) + + +def to_scale(v, stem, den, scale): + v = np.asarray(v, float) + if scale == "raw": + return v + if stem in PROP: + n = den["n_cand"] if stem == "rank_pct" else den["n_pairs"] + k = np.rint(v * n) + p = (k + 0.5) / (n + 1.0) + return np.log(p / (1.0 - p)) + if stem in CORR: + return np.arctanh(np.clip(v, -1 + 1e-6, 1 - 1e-6)) + return v + + +def akey(r): + return (int(r["ep"]), int(r["t"]), str(r.get("stage"))) + + +def strata_labels(x_pool, cap, bins): + """Stratum id per pooled unit. -1 is the CAP atom; 0..k-1 are quantile bins + of the NON-cap units (quantile edges are uniq'd, so a large atom below the + cap collapses into its own bin rather than smearing across two).""" + x_pool = np.asarray(x_pool, float) + lab = np.full(len(x_pool), -1, int) + free = np.ones(len(x_pool), bool) if cap is None else (x_pool < cap - 1e-12) + if free.sum() == 0: + return lab, np.array([]) + edges = np.unique(np.quantile(x_pool[free], np.linspace(0, 1, bins + 1))) + if len(edges) < 2: + lab[free] = 0 + return lab, edges + lab[free] = np.clip(np.digitize(x_pool[free], edges[1:-1], right=False), 0, len(edges) - 2) + return lab, edges + + +def matched_dind(xn, gn, xr, gr, cap, bins, min_cell): + """Baseline-matched contrast. Returns (ate, att, diag) or (nan, nan, diag).""" + x_pool = np.concatenate([xn, xr]) + lab_pool, edges = strata_labels(x_pool, cap, bins) + ln, lr = lab_pool[:len(xn)], lab_pool[len(xn):] + rows, num_a, den_a, num_t, den_t = [], 0.0, 0.0, 0.0, 0.0 + cap_n = int((ln == -1).sum()) + int((lr == -1).sum()) + for s in sorted(set(lab_pool.tolist())): + mn, mr = (ln == s), (lr == s) + kn, kr = int(mn.sum()), int(mr.sum()) + ok = (s != -1) and kn >= min_cell and kr >= min_cell + d = float(gr[mr].mean() - gn[mn].mean()) if (kn and kr) else np.nan + rows.append({"stratum": ("CAP" if s == -1 else int(s)), "n_nt": kn, "n_rise": kr, + "gain_nt": float(gn[mn].mean()) if kn else None, + "gain_rise": float(gr[mr].mean()) if kr else None, + "d": None if not np.isfinite(d) else d, "used": bool(ok)}) + if ok: + num_a += (kn + kr) * d; den_a += (kn + kr) + num_t += kr * d; den_t += kr + used_r = sum(r["n_rise"] for r in rows if r["used"]) + used_n = sum(r["n_nt"] for r in rows if r["used"]) + diag = {"strata": rows, "n_strata_used": sum(1 for r in rows if r["used"]), + "n_strata_total": len(rows), "cap_units": cap_n, + "overlap_rise": used_r / max(len(xr), 1), "overlap_nt": used_n / max(len(xn), 1), + "edges": [float(e) for e in edges]} + return (num_a / den_a if den_a else np.nan), (num_t / den_t if den_t else np.nan), diag + + +def boot_matched(xn, gn, xr, gr, cap, bins, min_cell, nboot, seed): + """Bootstrap over ANCHORS (both arms resampled together: pairing preserved).""" + rng = np.random.default_rng(seed) + n = len(xn) + a, t = [], [] + for _ in range(nboot): + i = rng.integers(0, n, n) + va, vt, _ = matched_dind(xn[i], gn[i], xr[i], gr[i], cap, bins, min_cell) + if np.isfinite(va): + a.append(va) + if np.isfinite(vt): + t.append(vt) + q = lambda v: (float(np.percentile(v, 2.5)), float(np.percentile(v, 97.5))) if len(v) > 20 \ + else (float("nan"), float("nan")) + return q(a), q(t) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--out", default=f"{ROOT}/XL2X2_MATCHED.json") + ap.add_argument("--scale", default="raw", choices=("raw", "stab")) + ap.add_argument("--bins", type=int, default=8, help="quantile strata below the cap") + ap.add_argument("--min-cell", type=int, default=5, help="min units of EACH arm for a stratum " + "to enter the pooled estimate") + ap.add_argument("--nboot", type=int, default=4000) + ap.add_argument("--seed", type=int, default=0) + # ACT_COND run 21: the 2x2 design is not specific to the XL pair -- any two checkpoints that + # differ ONLY in the trained beta range form the same matched arms. These flags let the + # deployed-WIDTH pair (R_M_ft_v0_nt / R_M_ft_v0_rise, width 1024) be analysed by the same code + # that produced the run-20 XL numbers, so the two widths are compared under one implementation + # rather than a fork. Defaults are the XL dirs, so every earlier invocation is unchanged. + ap.add_argument("--nt-dir", default=f"{ROOT}/snr_xlnt", + help="arm whose trained beta range EXCLUDES the test beta (narrow band)") + ap.add_argument("--rise-dir", default=f"{ROOT}/snr_xlrise", + help="arm whose trained beta range INCLUDES the test beta (wide band)") + a = ap.parse_args() + global ARMS + ARMS = [("nt", a.nt_dir), ("rise", a.rise_dir)] + print(f"ARMS: nt={a.nt_dir} rise={a.rise_dir}") + + + cells = {} + for arm, d in ARMS: + for b in BETAS: + p = f"{d}/snr_beta{b}.json" + if not os.path.exists(p): + print(f" [skip] {arm}@0.{b}: not written yet ({p})") + continue + cells[(arm, b)] = json.load(open(p)) + add_margin_z(cells[(arm, b)]["rows"]) + if not cells: + raise SystemExit("no XL cells on disk yet") + + # ---- GATES: identical args beyond (ckpt,beta), identical anchor draw ---- + ref = cells[sorted(cells)[0]] + for k in sorted(cells): + bad = [f for f in FIXED_ARGS if cells[k]["args"].get(f) != ref["args"].get(f)] + if bad: + raise SystemExit(f"FAIL {k}: args differ beyond (ckpt,beta): " + + "; ".join(f"{f}={cells[k]['args'].get(f)!r} vs " + f"{ref['args'].get(f)!r}" for f in bad)) + if abs(float(cells[k]["args"]["beta"]) - float("0." + k[1])) > 1e-9: + raise SystemExit(f"FAIL {k}: filename beta 0.{k[1]} != args {cells[k]['args']['beta']}") + refkeys = [akey(r) for r in ref["rows"]] + for k in sorted(cells): + rows = cells[k]["rows"] + if len(rows) != len(refkeys) or any(akey(r) != y for r, y in zip(rows, refkeys)): + raise SystemExit(f"FAIL {k}: anchor draw differs from the reference cell; NOT pairable.") + n = len(refkeys) + print(f"ARG IDENTITY: {len(cells)} cells agree on {list(FIXED_ARGS)}; only ckpt and beta differ.") + print(f"ANCHOR IDENTITY: {len(cells)} cells x {n} anchors EXACT on (ep,t,stage); " + f"repeats={ref['args'].get('repeats')}.") + DEN = {"n_cand": int(ref["args"]["n_cand"]), + "n_pairs": int(ref["args"].get("repeats", 3)) * (int(ref["args"].get("repeats", 3)) - 1) // 2} + print(f"SCALE: {a.scale}. STRATA: {a.bins} quantile bins of the baseline (beta 0.{REF_BETA}) " + f"value below the cap, plus the CAP atom as its own stratum (EXCLUDED from the pooled\n" + f" estimate: those units have zero headroom by construction). min-cell={a.min_cell} " + f"units of EACH arm. Bootstrap {a.nboot} over ANCHORS (pairing preserved).") + + out = {"scale": a.scale, "bins": a.bins, "min_cell": a.min_cell, "n": n, + "cells": {f"{k[0]}@0.{k[1]}": cells[k]["args"]["ckpt"] for k in cells}, "rows": []} + + hdr = (f"{'row':<20} {'statistic':<26} {'naive':>9} {'matched_ATE':>12} " + f"{'bootCI95':>20} {'matched_ATT':>12} {'ovl_r':>6} {'str':>4} verdict") + + placebo_ok = {} + for b in ("95", "90"): + if any((arm, bb) not in cells for arm in ("nt", "rise") for bb in (b, REF_BETA)): + print(f"\n [skip] beta 0.{b}: not all four cells on disk yet") + continue + placebo = (b == "95") + if placebo: + print(f"\nPLACEBO ROW beta 0.95 -- 0.95 is IN support for BOTH checkpoints (nt " + f"--beta-lo 0.95, rise --beta-lo 0.90),\n so H1 and H2 make the SAME prediction " + f"and THE ANSWER MUST BE 0. This row decides whether the matched\n estimator may " + f"be read at all.\n" + hdr + "\n" + "-" * len(hdr)) + else: + print(f"\nTEST ROW beta 0.90 -- IN support for rise, OUT for nt.\n" + f" H1 HORIZON -> gain survives in support -> dind >= 0. " + f"H2 EXTRAPOLATION -> gain only out of support -> dind < 0.\n" + + hdr + "\n" + "-" * len(hdr)) + for read in ("logit", "prob"): + for stem, lab, sign, cap_raw in STATS: + xn_r = np.array([r[f"{stem}_{read}"] for r in cells[("nt", REF_BETA)]["rows"]], float) + yn_r = np.array([r[f"{stem}_{read}"] for r in cells[("nt", b)]["rows"]], float) + xr_r = np.array([r[f"{stem}_{read}"] for r in cells[("rise", REF_BETA)]["rows"]], float) + yr_r = np.array([r[f"{stem}_{read}"] for r in cells[("rise", b)]["rows"]], float) + if not (np.isfinite(xn_r).all() and np.isfinite(yn_r).all() + and np.isfinite(xr_r).all() and np.isfinite(yr_r).all()): + print(f"{('dind 0.'+b+' ['+read+']'):<20} {lab:<26} " + f"{'non-finite input -- skipped':>9}") + continue + xn, yn = to_scale(xn_r, stem, DEN, a.scale), to_scale(yn_r, stem, DEN, a.scale) + xr, yr = to_scale(xr_r, stem, DEN, a.scale), to_scale(yr_r, stem, DEN, a.scale) + gn, gr = yn - xn, yr - xr + # the cap lives on the RAW scale; map it through the same transform + cap = None if cap_raw is None else float(to_scale([cap_raw], stem, DEN, a.scale)[0]) + naive = float(gr.mean() - gn.mean()) + ate, att, diag = matched_dind(xn, gn, xr, gr, cap, a.bins, a.min_cell) + (lo, hi), (tlo, thi) = boot_matched(xn, gn, xr, gr, cap, a.bins, a.min_cell, + a.nboot, a.seed) + if not np.isfinite(ate): + v = "NO COMMON SUPPORT" + elif sign == 0: + v = ("PLACEBO ok" if (lo <= 0 <= hi) else "PLACEBO FAILS") if placebo \ + else ("noise tie" if (lo <= 0 <= hi) else "NOISE MOVED") + elif placebo: + v = "PLACEBO OK (0 as required)" if (lo <= 0 <= hi) else \ + "PLACEBO FAILS -- matching did not fix it" + else: + v = "no difference" if (lo <= 0 <= hi) else \ + ("gain LARGER in support (H1)" if sign * ate > 0 + else "gain SMALLER in support (H2)") + if placebo and sign != 0: + placebo_ok[(read, stem)] = bool(np.isfinite(ate) and lo <= 0 <= hi) + if (not placebo) and sign != 0 and not placebo_ok.get((read, stem), False): + v += " [NOT READABLE: its own placebo failed]" + print(f"{('dind 0.'+b+' ['+read+']'):<20} {lab:<26} {naive:>9.4f} {ate:>12.4f} " + f"[{lo:>8.4f},{hi:>8.4f}] {att:>12.4f} " + f"{diag['overlap_rise']:>6.2f} {diag['n_strata_used']:>4d} {v}") + out["rows"].append({"beta": f"0.{b}", "read": read, "stat": stem, "scale": a.scale, + "placebo": bool(placebo), "naive_dind": naive, + "matched_ate": None if not np.isfinite(ate) else ate, + "boot_lo": lo, "boot_hi": hi, + "matched_att": None if not np.isfinite(att) else att, + "att_lo": tlo, "att_hi": thi, + "verdict": v, "diag": diag, + "placebo_passed": placebo_ok.get((read, stem))}) + + if placebo_ok: + good = [f"{r}/{s}" for (r, s), ok in sorted(placebo_ok.items()) if ok] + print(f"\nPLACEBO SUMMARY: {len(good)}/{len(placebo_ok)} scored (read, statistic) pairs pass " + f"the beta-0.95 placebo under matching.\n READABLE: {good if good else 'NONE'}") + print(" Any beta-0.90 row whose own placebo failed is printed above but is NOT evidence " + "about H1 vs H2.") + print("\nCAVEAT carried into every reading: matching removes the confound it MODELS -- the " + "dependence of the\nbeta gain on the anchor's own baseline score (runs 16-17: lowering " + "beta rescues bad anchors, ~0 for\ngood ones). It cannot remove a confound that acts " + "through anything else, and the overlap column says\nhow much of the rise arm the " + "estimate actually covers.") + json.dump(out, open(a.out, "w"), indent=1) + print(f"\nwrote {a.out}") + + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/real/xl2x2_test.py b/rsm_rise/scripts/real/xl2x2_test.py new file mode 100644 index 0000000000000000000000000000000000000000..071e16e0884b02885421a801141bd985a89f0d87 --- /dev/null +++ b/rsm_rise/scripts/real/xl2x2_test.py @@ -0,0 +1,371 @@ +#!/usr/bin/env python +"""THE IN-SUPPORT CONTROL for the low-beta correctness gain (ACT_COND run 16, gen_q#278). + +WHAT IS OPEN. On R_M (trained beta in [0.95,0.99]) the correctness of the read-out RISES as beta +falls below the trained support -- 0.92 half, 0.90 full, 0.87 saturated -- on rank pct of the logged +goal-route chunk and on the monotone probe, noise-matched against logit@0.99. Two readings survive: + (H1) HORIZON. A longer successor chain genuinely sees more of the route, and the net evaluates it + competently even at a beta it never trained on. Actionable: retrain with a wider beta range. + (H2) EXTRAPOLATION. Out of support the field is untrained and merely happens to correlate with + the logged route. Actionable: none -- and certainly not a deployment change. +Run 13 (0.999, equally untrained, WORSE) killed the crude form of H2, and run 15 (0.87 saturating) +killed the crude form of H1. Neither is settled because on R_M beta=0.90 is ALWAYS out of support. + +THE DESIGN. Two checkpoints differing ONLY in their trained beta range: + R_XL_ft_nt --beta-lo 0.95 --beta-hi 0.99 -> 0.90 is OUT of support + R_XL_ft_rise --beta-lo 0.90 --beta-hi 0.995 -> 0.90 is IN support +same parent (R_XL), width 2048, seed 0, 110k steps, same reward npy. Evaluated at their COMMON +in-support point 0.99 and at 0.95 / 0.90. The DIFF-IN-DIFF (gain at 0.90 on rise MINUS gain at 0.90 +on nt, per anchor) is the estimate that does not need the two checkpoints to be equally good: + * H1 predicts the gain SURVIVES (and is >= as large) where 0.90 is in support -> dind >= 0; + * H2 predicts the gain is an out-of-support artefact, so it appears on nt and NOT on rise -> dind < 0. +The BASELINE arm (nt@0.99 vs rise@0.99) is printed first because the diff-in-diff is only readable +if the two checkpoints are comparable at the point where both are in support. + +CONFOUND, stated once: --beta-trunc-eps is coupled to --beta-hi in the trainer, so rise also has +beta-hi 0.995 vs nt's 0.99. That is the change beta-hi forces; it is not separable here. + +DISCIPLINE (same as readout_cross_test.py): every cell is checked anchor-by-anchor on (ep,t,stage) +against the reference and the run exits non-zero on any mismatch -- pairing misaligned rows +manufactures significance. Every cell is also checked to differ from the reference ONLY in `ckpt` +and `beta`; any other differing argument is a hard failure, because then the contrast is not beta. +Missing cells are SKIPPED with a printed line (the 0.90/0.95 cells land hours after 0.99), so this +runs usefully on a partial grid and again unchanged when the grid completes. +""" +import json, os, argparse +import numpy as np +from scipy.stats import wilcoxon + +ROOT = "/proj/dmfexp/zwhong/rsm_rise/status/real/ACT_COND" +ARMS = [("nt", f"{ROOT}/snr_xlnt"), ("rise", f"{ROOT}/snr_xlrise")] +BETAS = ["99", "95", "90"] +REF_BETA = "99" +# args that MUST be identical across every cell; ckpt and beta are the two that may differ. +FIXED_ARGS = ("mode", "gamma", "particles", "temperature", "chain_cap", "n_cand", + "max_anchors", "seed", "repeats") +STATS = [("rank_pct", "rank pct of LOGGED chunk", +1), + ("margin_z", "margin z of LOGGED chunk", +1), + ("spearman", "monotone probe rho", -1), + ("top1_agree", "top1 agree (self-consist)", +1), + ("rep_spearman", "rep spearman (noise)", +1), + ("cv", "score CV", 0), + ("tie_frac", "tie frac at max", 0)] + + +# --------------------------------------------------------------------------------------------- +# SCALE. Run 18's PLACEBO row (dind at beta 0.95, where 0.95 is IN support for BOTH checkpoints, so +# H1 and H2 make the SAME prediction and the answer must be 0) came out at -0.0787 CI[-0.1195, +# -0.0396] p=4.3e-7 on the raw rank-pct scale. The estimator is therefore NOT calibrated on that +# scale, and the reason is a CEILING: rank pct is a bounded proportion, rise@0.99 starts at 0.947 +# (headroom 0.053) and nt@0.99 at 0.836 (headroom 0.164), and the two raw gains 0.0379 / 0.1166 sit +# in almost exactly the ratio of the two headrooms (0.715 vs 0.707 of headroom closed). A linear +# difference of a bounded statistic measured off two different baselines is confounded by the +# baseline, and no amount of pairing removes it. +# FIX: difference on the variance-stabilizing scale, where a multiplicative (headroom-closing) +# effect is additive and the bound is at infinity -- +# * proportions (rank pct, top1 agree, tie frac) -> log-odds with a continuity correction on the +# statistic's OWN discrete denominator (rank pct is k/n_cand; top1 agree is k/n_pairs); +# * correlations (monotone rho, rep spearman) -> Fisher z = atanh; +# * cv is unbounded and report-only -> raw. +# The LEVELS table always prints RAW numbers (they are what a reader interprets); only the paired +# contrasts are transformed. --scale raw reproduces run 18 exactly. +PROP_DEN = {"rank_pct": "n_cand", "top1_agree": "n_pairs", "tie_frac": "n_cand"} +CORR = ("spearman", "rep_spearman") +HEAVY = ("margin_z",) # unbounded, heavy-tailed -> asinh (~log for large |z|, linear near 0) + + +def add_margin_z(rows): + """CEILING-FREE twin of rank_pct, computed from fields already on disk. + + rank_pct = (candidates < logged).mean() over n_cand=128 draws, so it has a HARD discreteness cap + at exactly 1.0 that 17-35% of anchors already sit on. No monotone transform of a statistic can + undo a cap the statistic hit before the transform, which is why log-odds did not rescue the + placebo row. margin_z standardizes the same quantity against the candidate cloud instead of + ranking inside it -- (score of logged chunk - mean over the 128 candidates) / sd over them -- and + is unbounded above, so a better checkpoint can keep separating. Same sign convention (higher is + better) and the same anchors.""" + for r in rows: + for read, s0 in (("logit", "logit0"), ("prob", "q0")): + sd = float(r[f"var_a_{read}"]) ** 0.5 + r[f"margin_z_{read}"] = (float(r[s0]) - float(r[f"mean_a_{read}"])) / max(sd, 1e-300) + + +def denoms(args): + r = int(args.get("repeats") or 1) + return {"n_cand": int(args["n_cand"]), "n_pairs": max(r * (r - 1) // 2, 1)} + + +def to_scale(v, stem, den, scale): + """Map a raw per-anchor statistic onto the analysis scale.""" + v = np.asarray(v, float) + if scale == "raw": + return v + if stem in PROP_DEN: + n = den[PROP_DEN[stem]] + k = np.rint(v * n) # recover the integer count + p = (k + 0.5) / (n + 1.0) # continuity-corrected proportion + return np.log(p / (1.0 - p)) + if stem in CORR: + return np.arctanh(np.clip(v, -1 + 1e-6, 1 - 1e-6)) + if stem in HEAVY: + return np.arcsinh(v) + return v + + +def akey(r): + return (int(r["ep"]), int(r["t"]), str(r.get("stage"))) + + +def boot_ci(d, n=20000, seed=0): + rng = np.random.default_rng(seed) + idx = rng.integers(0, len(d), size=(n, len(d))) + m = np.asarray(d)[idx].mean(1) + return float(np.percentile(m, 2.5)), float(np.percentile(m, 97.5)) + + +def verdict(d, lo, hi, p, sign): + if sign == 0: + return "-" + if p >= 0.05 or (lo <= 0 <= hi): + return "tie" + return "BETTER" if sign * float(np.mean(d)) > 0 else "worse" + + +def paired(y, x, sign): + d = np.asarray(y, float) - np.asarray(x, float) + lo, hi = boot_ci(d) + try: + p = float(wilcoxon(y, x, zero_method="wilcox").pvalue) + except ValueError: + p = 1.0 + return float(d.mean()), lo, hi, p, verdict(d, lo, hi, p, sign), d + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--out", default=f"{ROOT}/XL2X2.json") + ap.add_argument("--scale", default="raw", choices=("raw", "stab"), + help="scale for the PAIRED contrasts: raw, or variance-stabilizing " + "(log-odds for proportions, Fisher z for correlations). Levels stay raw.") + # ACT_COND run 21: the 2x2 design is not specific to the XL pair -- any two checkpoints that + # differ ONLY in the trained beta range form the same matched arms. These flags let the + # deployed-WIDTH pair (R_M_ft_v0_nt / R_M_ft_v0_rise, width 1024) be analysed by the same code + # that produced the run-20 XL numbers, so the two widths are compared under one implementation + # rather than a fork. Defaults are the XL dirs, so every earlier invocation is unchanged. + ap.add_argument("--nt-dir", default=f"{ROOT}/snr_xlnt", + help="arm whose trained beta range EXCLUDES the test beta (narrow band)") + ap.add_argument("--rise-dir", default=f"{ROOT}/snr_xlrise", + help="arm whose trained beta range INCLUDES the test beta (wide band)") + a = ap.parse_args() + global ARMS + ARMS = [("nt", a.nt_dir), ("rise", a.rise_dir)] + print(f"ARMS: nt={a.nt_dir} rise={a.rise_dir}") + + + cells = {} + for arm, d in ARMS: + for b in BETAS: + p = f"{d}/snr_beta{b}.json" + if not os.path.exists(p): + print(f" [skip] {arm}@0.{b}: not written yet ({p})") + continue + cells[(arm, b)] = json.load(open(p)) + add_margin_z(cells[(arm, b)]["rows"]) + if not cells: + raise SystemExit("no XL cells on disk yet") + + # ---- ARG IDENTITY: only ckpt and beta may differ ---- + ref = cells[sorted(cells)[0]] + for k in sorted(cells): + bad = [f for f in FIXED_ARGS if cells[k]["args"].get(f) != ref["args"].get(f)] + if bad: + raise SystemExit(f"FAIL {k}: args differ beyond (ckpt,beta): " + + "; ".join(f"{f}={cells[k]['args'].get(f)!r} vs {ref['args'].get(f)!r}" + for f in bad)) + if abs(float(cells[k]["args"]["beta"]) - float("0." + k[1])) > 1e-9: + raise SystemExit(f"FAIL {k}: file name says beta 0.{k[1]}, args say {cells[k]['args']['beta']}") + DEN = denoms(ref["args"]) + if a.scale != "raw": + print(f"SCALE: paired contrasts on the variance-stabilizing scale -- log-odds for " + f"proportions (rank pct k/{DEN['n_cand']}, top1 agree k/{DEN['n_pairs']}, tie frac " + f"k/{DEN['n_cand']}; continuity correction (k+0.5)/(n+1)) and Fisher z for " + f"correlations. LEVELS below stay RAW.") + print(f"ARG IDENTITY: {len(cells)} cells agree on {list(FIXED_ARGS)}; only ckpt and beta differ.") + + # ---- ANCHOR IDENTITY across every loaded cell ---- + refrows = ref["rows"] + refkeys = [akey(r) for r in refrows] + for k in sorted(cells): + rows = cells[k]["rows"] + if len(rows) != len(refrows): + raise SystemExit(f"FAIL {k}: n={len(rows)} != {len(refrows)}; NOT pairable.") + bad = [(i, refkeys[i], akey(rows[i])) for i in range(len(rows)) if akey(rows[i]) != refkeys[i]] + if bad: + raise SystemExit(f"FAIL {k}: {len(bad)} anchor positions differ, first={bad[0]}") + print(f"ANCHOR IDENTITY: {len(cells)} cells x {len(refrows)} anchors match on (ep,t,stage) " + f"EXACTLY. repeats={ref['args'].get('repeats')}.") + + # ---- is the R_M ladder on the SAME anchor draw? (reported, not enforced) ---- + rm = f"{ROOT}/snr/snr_beta99.json" + if os.path.exists(rm): + j = json.load(open(rm)) + same = len(j["rows"]) == len(refrows) and all( + akey(x) == y for x, y in zip(j["rows"], refkeys)) + print(f"R_M ladder anchor draw: {'IDENTICAL' if same else 'DIFFERENT'} to the XL cells " + f"(n={len(j['rows'])}) -- reported only; the 2x2 never pairs across model families.") + + out = {"cells": {f"{k[0]}@0.{k[1]}": cells[k]["args"]["ckpt"] for k in cells}, + "scale": a.scale, "denoms": DEN, "n": len(refrows), "levels": [], "baseline": [], "within": [], "dind": []} + + # ---- LEVELS ---- + hdr = (f"{'cell':<14} {'read':<6} {'E[hops]':>9} {'top1':>7} {'rankpct':>8} {'mgnz_med':>9} " + f"{'rho':>8} {'reprho':>8} {'CV':>9} {'tie':>7}") + print("\nLEVELS (same 200 paired anchors)\n" + hdr + "\n" + "-" * len(hdr)) + for k in sorted(cells, key=lambda z: (z[0], -int(z[1]))): + rows = cells[k]["rows"] + hops = float(np.mean([r.get("chain_hops_mean", np.nan) for r in rows])) + for read in ("logit", "prob"): + m = {s: float(np.mean([r[f"{s}_{read}"] for r in rows])) for s, _, _ in STATS} + mz = float(np.median([r[f"margin_z_{read}"] for r in rows])) + print(f"{k[0]+'@0.'+k[1]:<14} {read:<6} {hops:>9.1f} {m['top1_agree']:>7.3f} " + f"{m['rank_pct']:>8.3f} {mz:>9.3f} {m['spearman']:>8.3f} {m['rep_spearman']:>8.3f} " + f"{m['cv']:>9.4f} {m['tie_frac']:>7.3f}") + m["margin_z_median"] = mz + out["levels"].append({"cell": f"{k[0]}@0.{k[1]}", "read": read, "hops": hops, **m}) + + hdr2 = (f"{'comparison':<30} {'statistic':<26} {'A':>8} {'B':>8} {'B-A':>9} " + f"{'bootCI95':>20} {'wilcox_p':>10} verdict") + + # ---- BASELINE ARM: the two checkpoints at their COMMON in-support point ---- + if ("nt", REF_BETA) in cells and ("rise", REF_BETA) in cells: + print(f"\nBASELINE ARM A=nt@0.{REF_BETA} B=rise@0.{REF_BETA} (both IN support; the " + f"diff-in-diff is only readable if these are comparable)\n" + hdr2 + "\n" + "-" * len(hdr2)) + for read in ("logit", "prob"): + for stem, lab, sign in STATS: + xr = [r[f"{stem}_{read}"] for r in cells[("nt", REF_BETA)]["rows"]] + yr = [r[f"{stem}_{read}"] for r in cells[("rise", REF_BETA)]["rows"]] + x = to_scale(xr, stem, DEN, a.scale) + y = to_scale(yr, stem, DEN, a.scale) + dm, lo, hi, p, v, _ = paired(y, x, sign) + print(f"{'rise vs nt @0.'+REF_BETA+' ['+read+']':<30} {lab:<26} {np.mean(x):>8.3f} " + f"{np.mean(y):>8.3f} {dm:>9.4f} [{lo:>8.4f},{hi:>8.4f}] {p:>10.2e} {v}") + out["baseline"].append({"read": read, "stat": stem, "scale": a.scale, + "a_mean": float(np.mean(x)), "b_mean": float(np.mean(y)), + "a_mean_raw": float(np.mean(xr)), "b_mean_raw": float(np.mean(yr)), + "dmean": dm, "boot_lo": lo, + "boot_hi": hi, "wilcoxon_p": p, "verdict": v}) + + # ---- WITHIN-CHECKPOINT beta effect, and the DIFF-IN-DIFF ---- + dind_d = {} # (beta, read, stem) -> per-anchor diff-in-diff array + for b in BETAS: + if b == REF_BETA: + continue + per_arm = {} + for arm, _ in ARMS: + if (arm, b) not in cells or (arm, REF_BETA) not in cells: + continue + print(f"\nWITHIN {arm}: A={arm}@0.{REF_BETA} (ref) B={arm}@0.{b}" + f" [{'IN' if (arm=='rise' and b=='90') or b=='95' else 'OUT of'} support for this ckpt]" + f"\n" + hdr2 + "\n" + "-" * len(hdr2)) + for read in ("logit", "prob"): + for stem, lab, sign in STATS: + xr = [r[f"{stem}_{read}"] for r in cells[(arm, REF_BETA)]["rows"]] + yr = [r[f"{stem}_{read}"] for r in cells[(arm, b)]["rows"]] + x = to_scale(xr, stem, DEN, a.scale) + y = to_scale(yr, stem, DEN, a.scale) + dm, lo, hi, p, v, d = paired(y, x, sign) + per_arm.setdefault((read, stem), {})[arm] = (d, sign, lab) + print(f"{arm+'@0.'+b+' ['+read+']':<30} {lab:<26} {np.mean(x):>8.3f} " + f"{np.mean(y):>8.3f} {dm:>9.4f} [{lo:>8.4f},{hi:>8.4f}] {p:>10.2e} {v}") + out["within"].append({"arm": arm, "beta": f"0.{b}", "read": read, "stat": stem, + "scale": a.scale, + "ref_mean_raw": float(np.mean(xr)), "mean_raw": float(np.mean(yr)), + "ref_mean": float(np.mean(x)), "mean": float(np.mean(y)), + "dmean": dm, "boot_lo": lo, "boot_hi": hi, + "wilcoxon_p": p, "verdict": v}) + ready = {k: v for k, v in per_arm.items() if len(v) == 2} + if ready: + placebo = b == "95" # 0.95 is IN support for BOTH ckpts (nt beta-lo 0.95, rise 0.90) + if placebo: + print(f"\nDIFF-IN-DIFF at beta 0.{b}: ***PLACEBO ROW -- THE ANSWER MUST BE 0.***\n" + f" 0.95 is IN support for BOTH checkpoints (nt beta-lo 0.95, rise beta-lo " + f"0.90), so H1 and H2 make the SAME prediction here. A non-zero dind on this\n" + f" row is a defect of the ESTIMATOR, not evidence about support, and it makes " + f"the 0.90 row unreadable on the same scale.\n" + hdr2 + "\n" + "-" * len(hdr2)) + else: + print(f"\nDIFF-IN-DIFF at beta 0.{b}: (gain on rise) MINUS (gain on nt), per anchor.\n" + f" H1 HORIZON -> the gain survives in support -> >= 0. " + f"H2 EXTRAPOLATION -> gain only out of support -> < 0.\n" + hdr2 + "\n" + + "-" * len(hdr2)) + for (read, stem), v in ready.items(): + dn, sign, lab = v["nt"] + dr, _, _ = v["rise"] + dd = np.asarray(dr) - np.asarray(dn) + lo, hi = boot_ci(dd) + try: + p = float(wilcoxon(dr, dn, zero_method="wilcox").pvalue) + except ValueError: + p = 1.0 + vv = verdict(dd, lo, hi, p, sign) + dind_d[(b, read, stem)] = (dd, sign, lab) + if placebo: + tag = {"tie": "PLACEBO OK (0 as required)", + "BETTER": "PLACEBO FAILS -- estimator biased", + "worse": "PLACEBO FAILS -- estimator biased", "-": "-"}[vv] + else: + tag = {"BETTER": "gain LARGER in support (H1)", + "worse": "gain SMALLER in support (H2)", + "tie": "no difference", "-": "-"}[vv] + print(f"{'dind 0.'+b+' ['+read+']':<30} {lab:<26} {np.mean(dn):>8.4f} " + f"{np.mean(dr):>8.4f} {dd.mean():>9.4f} [{lo:>8.4f},{hi:>8.4f}] {p:>10.2e} {tag}") + out["dind"].append({"beta": f"0.{b}", "read": read, "stat": stem, "scale": a.scale, + "gain_nt": float(np.mean(dn)), "gain_rise": float(np.mean(dr)), + "dind": float(dd.mean()), "boot_lo": lo, "boot_hi": hi, + "wilcoxon_p": p, "verdict": vv, "reading": tag, + "placebo": bool(placebo)}) + + # ---- TRIPLE DIFFERENCE: subtract the placebo row from the test row ---- + # The 0.95 placebo measures how differently the two checkpoints respond to a beta step for + # reasons that have NOTHING to do with support (both are in support there). It is the + # pre-trend of a diff-in-diff, and it is not 0, so dind(0.90) on its own is not identified. + # dind(0.90) - dind(0.95) removes an arm-specific beta slope that is CONSTANT across the two + # steps 0.99->0.95 and 0.99->0.90. That constancy is an assumption and three beta points cannot + # test it; it is stated here and carried into every reading of this block. + trip = [(read, stem) for (b, read, stem) in dind_d if b == "90" + and ("95", read, stem) in dind_d] + if trip: + print("\nTRIPLE DIFFERENCE dind(0.90) - dind(0.95): the placebo row subtracted off.\n" + " ASSUMPTION (untestable with 3 beta points): each checkpoint's non-support response " + "to a beta step is the same size for\n 0.99->0.95 and 0.99->0.90. H1 HORIZON -> " + ">= 0. H2 EXTRAPOLATION -> < 0.\n" + hdr2 + "\n" + "-" * len(hdr2)) + out["triple"] = [] + for read, stem in trip: + d90, sign, lab = dind_d[("90", read, stem)] + d95, _, _ = dind_d[("95", read, stem)] + t = np.asarray(d90) - np.asarray(d95) + lo, hi = boot_ci(t) + try: + pv = float(wilcoxon(d90, d95, zero_method="wilcox").pvalue) + except ValueError: + pv = 1.0 + vv = verdict(t, lo, hi, pv, sign) + tag = {"BETTER": "gain LARGER in support (H1)", + "worse": "gain SMALLER in support (H2)", + "tie": "no difference", "-": "-"}[vv] + print(f"{'triple ['+read+']':<30} {lab:<26} {np.mean(d95):>8.4f} {np.mean(d90):>8.4f} " + f"{t.mean():>9.4f} [{lo:>8.4f},{hi:>8.4f}] {pv:>10.2e} {tag}") + out["triple"].append({"read": read, "stat": stem, "scale": a.scale, + "dind_95": float(np.mean(d95)), "dind_90": float(np.mean(d90)), + "triple": float(t.mean()), "boot_lo": lo, "boot_hi": hi, + "wilcoxon_p": pv, "verdict": vv, "reading": tag}) + + print("\nverdict/reading applies ONLY to the signed correctness statistics (rank pct and top1 " + "higher-better,\nmonotone rho lower-better). rep spearman is the NOISE control -- a cell " + "that wins while its rep\nspearman is lower won on de-noising, not on the field. CV and " + "tie frac are reported, not scored.") + json.dump(out, open(a.out, "w"), indent=1) + print(f"\nwrote {a.out}") + + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/rebuttal_beta_coverage.py b/rsm_rise/scripts/rebuttal_beta_coverage.py new file mode 100644 index 0000000000000000000000000000000000000000..4e2f3bcd1cc558f7d62e39b13f9e29ec04c23b85 --- /dev/null +++ b/rsm_rise/scripts/rebuttal_beta_coverage.py @@ -0,0 +1,263 @@ +#!/usr/bin/env python3 +"""REBUTTAL_BETA (owner 2026-11-08): beta sweep with the rise_repro (union RISE / IDQL) proposers + mug BC-expert fallback. + +Extends scripts/beta_fair_coverage.py (imported as BF; its SPEC, recipe classifier, template finder, eval_cell rewrite +and payload block are reused unchanged). Differences from BETA_FAIR: + * arm "main": proposer = rise_repro proposer per task. Identical to the paper/BETA_FAIR proposer on 6 tasks; on mug + it is the union-trained IDQL policy (S0Aidql @5000) instead of BC-expert (S3H1). Everything else = Table 6. + * arm "mugfb": mug only, proposer = BC-expert (S3H1) = BETA_FAIR's mug row. + * coverage keyed by NOMINAL proposer seed (from eval_ckpt .../_seed/...) x eval_seed, so the S0Aidql replicas + (train.seed 1 on nominal seeds 1 and 2) are not pooled into one key. + * primary value = hop-QC OFF (paper rule, matches Table 1); QC-ON value kept alongside. + * optional: fresh eval seeds 3,4,5 for every beta (+control) of the main arm (separate payload set, costed separately). +Out: status/rebuttal_beta_coverage.json, status/packs/rebuttal_beta/{plan.json, plan_fresh.json, payloads/, payloads_fresh/} +""" +import json, math, os, re, sys, glob, shlex +from collections import defaultdict +from pathlib import Path + +ROOT = Path("/proj/dmfexp/zwhong/rsm_rise") +sys.path.insert(0, str(ROOT / "scripts")) +os.environ["RSM_EXTRA_EPOCHS"] = "500" +import beta_fair_coverage as BF +VT, BP, PB = BF.VT, BF.BP, BF.PB + +GAMMA, BETAS, NEED = BF.GAMMA, BF.BETAS, BF.NEED_EPS +OUT = ROOT / "status/packs/rebuttal_beta" +MUG = "mug_expert_suboptimal" +PSEEDS, ESEEDS, FRESH_ESEEDS = ["0", "1", "2"], ["0", "1", "2"], ["3", "4", "5"] + +SPEC_MAIN = {t: dict(sp) for t, sp in BF.SPEC.items()} +SPEC_MAIN[MUG].update(prop="IDQL policy", plab="S0Aidql", tag="ONS0AidqlP16lo") +ARMS = {"main": SPEC_MAIN, "mugfb": {MUG: dict(BF.SPEC[MUG])}} +FAM_RE = re.compile(r"/policy/([A-Za-z0-9]+)_seed(\d+)/") + + +def arm_groups(task, sp, cs, files): + """recipe -> dict(beta, kind, len, files=[(nominal pseed, eseed, n, s, qc_ok, why, wall_s_per50)])""" + groups = {} + for key, _ in cs.items(): + (head, recipe), pol, _ps, _es = key + if pol != sp["prop"] or head != "rsm:membership": + continue + m = BF.REC.match(recipe) + if not m: + continue + r = m.groupdict(); beta = float(r["beta"]) + kind, diffs = BF.classify(sp, r) + if kind == "other": + continue + g = groups.setdefault(recipe, dict(beta=beta, kind=kind, len=r["len"], recipe=recipe, files=[])) + is_chain = r["len"].startswith("CH") + for f in files.get(key, []): + ok, why, n, s = PB.file_check(f, beta, is_chain) + if not ok and not (why.startswith("chain:") and "beta>=gamma" not in why): + continue # gamma-scope / unreadable: never counted (as BETA_FAIR) + try: + j = json.load(open(f)) + except Exception: + continue + mm = FAM_RE.search(j.get("eval_ckpt", "")) + g["files"].append(dict(file=str(f), pseed=mm.group(2) if mm else "?", eseed=str(j.get("eval_seed")), + n=n, s=sum(s), qc_ok=ok, why=why, ckpt=j.get("eval_ckpt"), + w50=float(j.get("wall_time_s") or 0) / max(1, n) * 50 if n else None)) + return groups + + +def summarize(g, eseeds=ESEEDS): + want = [(p, e) for p in PSEEDS for e in eseeds] + by = defaultdict(list) + for f in g["files"]: + if f["eseed"] in eseeds: + by[(f["pseed"], f["eseed"])].append(f) + n_off = sum(f["n"] for L in by.values() for f in L); s_off = sum(f["s"] for L in by.values() for f in L) + n_on = sum(f["n"] for L in by.values() for f in L if f["qc_ok"]); s_on = sum(f["s"] for L in by.values() for f in L if f["qc_ok"]) + have = {k for k, L in by.items() if sum(f["n"] for f in L) >= NEED} + missing = [f"{p}|{e}" for p, e in want if (p, e) not in have] + qcdrop = sorted({f"{f['pseed']}|{f['eseed']}" for L in by.values() for f in L if not f["qc_ok"]}) + status = "FULL" if not missing else ("MISSING" if not have else "PARTIAL") + return dict(recipe=g["recipe"], beta=g["beta"], kind=g["kind"], status=status, n=n_off, + succ=(s_off / n_off if n_off else None), n_qc=n_on, succ_qc=(s_on / n_on if n_on else None), + missing=missing, qc_dropped=qcdrop, extra=sorted(f"{p}|{e}" for p, e in by if (p, e) not in want)) + + +def wall_fit(groups): + pts = [] + for g in groups.values(): + E = BP.expected_hops(g["beta"], GAMMA) if g["kind"] == "matched_chain" else 0.0 + pts += [(max(E, 0.0), f["w50"]) for f in g["files"] if f["w50"]] + if len({round(e, 3) for e, _ in pts}) < 2: + if not pts: + return None, 0 + # one beta only (tipping): BETA_FAIR's scaling w50 * (0.55 + 0.45 * max(E,1)/max(E0,1)) as a line in E + E0 = pts[0][0]; w = sorted(x for _, x in pts)[len(pts) // 2] + return (0.55 * w, 0.45 * w / max(E0, 1.0)), len(pts) + n = len(pts); mx = sum(e for e, _ in pts) / n; my = sum(w for _, w in pts) / n + vb = sum((e - mx) ** 2 for e, _ in pts) + b = sum((e - mx) * (w - my) for e, w in pts) / vb if vb > 0 else 0.0 + return (my - b * mx, max(b, 0.0)), n + + +def mug_idql_ckpts(): + ck = {} + for f in sorted(glob.glob(str(ROOT / f"runs/{MUG}/eval_onactor/S3H4-N128-ONS0Aidql-es*-sS0Aidqls*.json"))): + j = json.load(open(f)); m = FAM_RE.search(j["eval_ckpt"]) + if m and m.group(1) == "S0Aidql" and j["eval_ckpt"].endswith("model_epoch_5000.pth"): + ck[m.group(2)] = j["eval_ckpt"] + return ck + + +def pack(jobs, prefix, paydir, target_s=3 * 3600.0): + """BETA_FAIR's packer: LPT per task, total payload count a multiple of 8 (full 8-GPU nodes).""" + paydir.mkdir(parents=True, exist_ok=True) + for old in paydir.glob("*.sh"): + old.unlink() + if not jobs: + return [], [] + tot = sum(j["est_s"] for j in jobs) + npay = max(8, int(math.ceil(tot / target_s / 8.0)) * 8) + by_task = defaultdict(list) + for j in jobs: + by_task[j["task"]].append(j) + alloc = {t: max(1, round(npay * sum(x["est_s"] for x in L) / tot)) for t, L in by_task.items()} + while sum(alloc.values()) != npay: + if sum(alloc.values()) < npay: + t = max(alloc, key=lambda t: sum(x["est_s"] for x in by_task[t]) / alloc[t]); alloc[t] += 1 + else: + t = min((t for t in alloc if alloc[t] > 1), key=lambda t: sum(x["est_s"] for x in by_task[t]) / alloc[t]) + alloc[t] -= 1 + payloads = [] + for t in sorted(by_task): + bins = [dict(task=t, cells=[], s=0.0) for _ in range(min(alloc[t], len(by_task[t])))] + for j in sorted(by_task[t], key=lambda x: -x["est_s"]): + b = min(bins, key=lambda b: b["s"]); b["cells"].append(j); b["s"] += j["est_s"] + payloads += bins + while len(payloads) % 8: # a task had fewer cells than its allocation: split the longest payload + b = max(payloads, key=lambda b: b["s"]) + if len(b["cells"]) < 2: + break + half = b["cells"][1::2]; b["cells"] = b["cells"][0::2] + b["s"] = sum(c["est_s"] for c in b["cells"]) + payloads.append(dict(task=b["task"], cells=half, s=sum(c["est_s"] for c in half))) + for i, b in enumerate(payloads): + lines = ["#!/usr/bin/env bash", "set -uo pipefail", f"cd {ROOT}", "rc_all=0", + f"echo \"[{prefix}] host=$(hostname) job=${{SLURM_JOB_ID:-none}} gpu=${{CUDA_VISIBLE_DEVICES:-?}}\""] + for j in b["cells"]: + lines.append(f"mkdir -p {shlex.quote(j['out_dir'] + '/logs')}") + lines.append(BF.cell_block(j["name"], Path(j["json"]), j["cmd"], Path(j["out_dir"])).replace("[beta_fair]", f"[{prefix}]")) + lines.append("exit $rc_all") + p = paydir / f"{prefix}_{i:03d}_{b['task']}.sh" + p.write_text("\n".join(lines) + "\n"); p.chmod(0o755); b["path"] = str(p) + nodes = [[b["path"] for b in payloads[k:k + 8]] for k in range(0, len(payloads), 8)] + return payloads, nodes + + +def main(): + res = defaultdict(dict); plan, fresh = [], [] + idql_ck = mug_idql_ckpts() + print("mug S0Aidql@5000 proposer ckpts:", idql_ck, flush=True) + for task in BF.SPEC: + cs = VT.cells(task); files = dict(VT.CELL_FILES) + tmpl_sh, tmpl = BF.find_template(task, BF.SPEC[task]) # paper payload line (S3H1 on mug: only proposer changes) + for arm, specs in ARMS.items(): + if task not in specs: + continue + sp = specs[task] + groups = arm_groups(task, sp, cs, files) + fit, nfit = wall_fit(groups) + if fit is None and arm == "main" and task == MUG: # no IDQL cells yet: same RSM/P/readout as S3H1 arm + fit, nfit = wall_fit(arm_groups(task, BF.SPEC[MUG], cs, files)); fit_src = "mug S3H1 arm (same RSM, P16 logit)" + else: + fit_src = "this arm" + # proposer ckpts by nominal seed + pck = {} + for g in groups.values(): + for f in g["files"]: + if f["ckpt"]: + pck.setdefault(f["pseed"], f["ckpt"]) + if arm == "main" and task == MUG: + pck = dict(idql_ck) + cov, fcov = {}, {} + pts = {} + for b in BETAS: + kind = "matched_d1" if abs(b - GAMMA) < 1e-9 else "matched_chain" + cand = [g for g in groups.values() if g["kind"] == kind and abs(g["beta"] - b) < 1e-9] + s = summarize(cand[0]) if cand else dict(status="MISSING", beta=b, kind=kind, n=0, succ=None, + missing=[f"{p}|{e}" for p in PSEEDS for e in ESEEDS]) + sf = summarize(cand[0], FRESH_ESEEDS) if cand else dict(status="MISSING", missing=[ + f"{p}|{e}" for p in PSEEDS for e in FRESH_ESEEDS]) + cov[f"{b:.2f}"] = s; fcov[f"{b:.2f}"] = sf; pts[b] = s + mode = "d1" if kind == "matched_d1" else "chain" + for k in s["missing"]: + plan.append(dict(arm=arm, task=task, beta=b, mode=mode, key=k)) + for k in sf["missing"]: + fresh.append(dict(arm=arm, task=task, beta=b, mode=mode, key=k)) + # no-recursion control at the best small beta (<=0.95) with data; BETA_FAIR's choice for mug-IDQL (no data) + small = [(s["succ"], b) for b, s in pts.items() if b <= 0.95 + 1e-9 and s["succ"] is not None] + cb = max(small)[1] if small else (0.90 if task == MUG else sp["beta"]) + cg = [g for g in groups.values() if g["kind"] == "matched_d1" and abs(g["beta"] - cb) < 1e-9] + cs_ = summarize(cg[0]) if cg else dict(status="MISSING", beta=cb, n=0, succ=None, + missing=[f"{p}|{e}" for p in PSEEDS for e in ESEEDS]) + csf = summarize(cg[0], FRESH_ESEEDS) if cg else dict(status="MISSING", missing=[ + f"{p}|{e}" for p in PSEEDS for e in FRESH_ESEEDS]) + for k in cs_["missing"]: + plan.append(dict(arm=arm, task=task, beta=cb, mode="d1", key=k, control=True)) + if arm == "main": + for k in csf["missing"]: + fresh.append(dict(arm=arm, task=task, beta=cb, mode="d1", key=k, control=True)) + res[arm][task] = dict(spec=sp, coverage=cov, fresh_coverage=fcov, control=dict(cs_, beta=cb), + fresh_control=csf, wall_fit=fit, wall_fit_npts=nfit, wall_fit_src=fit_src, + proposer_ckpts=pck, template=tmpl_sh, + other_recipes=sorted(g["recipe"] for g in groups.values())) + print(f"=== {arm} {task} prop={sp['prop']} fit={fit} ({nfit} pts, {fit_src}) pck={sorted(pck)}", flush=True) + for b, s in cov.items(): + print(f" b{b} {s['status']} n={s['n']} succ={s['succ']} qc n={s.get('n_qc')} {s.get('succ_qc')} " + f"miss={s['missing']} qcdrop={s.get('qc_dropped')}", flush=True) + print(f" ctrl d1@{cb}: {cs_['status']} n={cs_['n']} succ={cs_['succ']} miss={cs_['missing']}", flush=True) + res[arm][task]["_tmpl_line"] = tmpl + + def make_jobs(cells): + jobs = [] + for pc in cells: + r = res[pc["arm"]][pc["task"]]; sp = r["spec"] + p, e = pc["key"].split("|") + ck = r["proposer_ckpts"].get(p) + if not r["_tmpl_line"] or not ck: + pc["error"] = "no template" if not r["_tmpl_line"] else f"no proposer ckpt seed {p}"; continue + out_dir = ROOT / f"runs/{pc['task']}/eval_onactor" + name, js, cmd = BF.build_cmd(pc["task"], sp, r["_tmpl_line"], pc["beta"], pc["mode"], + f"{sp['plab']}s{p}", ck, e, out_dir) + if js.exists(): + pc["note"] = "json exists (loader/QC excluded it)"; continue + E = BP.expected_hops(pc["beta"], GAMMA) if pc["mode"] == "chain" else 0.0 + a, b = r["wall_fit"] or (900.0, 0.0) + pc.update(name=name, json=str(js), est_s=1.15 * (a + b * E), cmd=cmd, out_dir=str(out_dir)) + jobs.append(pc) + return jobs + + out = {} + for tag, cells, prefix, paydir in (("plan", plan, "rb", OUT / "payloads"), ("plan_fresh", fresh, "rbf", OUT / "payloads_fresh")): + jobs = make_jobs(cells) + pays, nodes = pack(jobs, prefix, paydir) + per = defaultdict(lambda: dict(cells=0, gpu_h=0.0)) + for j in jobs: + k = f"{j['arm']}:{j['task']}"; per[k]["cells"] += 1; per[k]["gpu_h"] += j["est_s"] / 3600 + pl = dict(n_cells=len(jobs), n_eps=50 * len(jobs), gpu_hours=sum(j["est_s"] for j in jobs) / 3600, + n_payloads=len(pays), n_nodes=len(nodes), payload_hours=[b["s"] / 3600 for b in pays], + wall_h=max([b["s"] / 3600 for b in pays] or [0]), nodes=nodes, per_arm_task=dict(per), + cells=[{k: v for k, v in j.items() if k != "cmd"} for j in jobs], + skipped=[c for c in cells if "error" in c or "note" in c]) + json.dump(pl, open(OUT / f"{tag}.json", "w"), indent=1, default=str) + out[tag] = {k: pl[k] for k in ("n_cells", "n_eps", "gpu_hours", "n_payloads", "n_nodes", "wall_h", "per_arm_task")} + out[tag]["n_skipped"] = len(pl["skipped"]) + print(f"{tag.upper()}: {json.dumps(out[tag], default=str)}", flush=True) + for arm in res: + for t in res[arm]: + res[arm][t].pop("_tmpl_line", None) + json.dump(dict(stamp=VT.build_stamp(("verdict_table",)), betas=BETAS, arms=res, plans=out, + mug_idql_ckpts=idql_ck), open(ROOT / "status/rebuttal_beta_coverage.json", "w"), indent=1, default=str) + print("wrote status/rebuttal_beta_coverage.json", flush=True) + + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/rebuttal_beta_export_final.py b/rsm_rise/scripts/rebuttal_beta_export_final.py new file mode 100644 index 0000000000000000000000000000000000000000..3760d2716b3c8f7d5cc4165f7cb2cf0cce18d137 --- /dev/null +++ b/rsm_rise/scripts/rebuttal_beta_export_final.py @@ -0,0 +1,17 @@ +#!/usr/bin/env python3 +"""Write ckpt_s.pt from a finished run's resume blob ckpt.pt (train_rsm.py:1195-1221: ckpt_s = ckpt.pt minus +opt/invdyn/best_win/hist). Used when the final step is not a multiple of --save-every (tipping ftb80: 10k->30k, save 20k). +Refuses to overwrite and checks blob['step'] == requested step.""" +import sys, torch +from pathlib import Path +d, want = Path(sys.argv[1]), int(sys.argv[2]) +dst = d / f"ckpt_s{want}.pt" +assert not dst.exists(), f"{dst} exists" +b = torch.load(d / "ckpt.pt", map_location="cpu", weights_only=False) +assert int(b["step"]) == want, f"ckpt.pt step {b['step']} != {want}" +for k in ("opt", "invdyn", "best_win", "hist"): + b.pop(k, None) +ref = torch.load(sorted(d.glob("ckpt_s*.pt"))[0], map_location="cpu", weights_only=False) +assert set(b) == set(ref), f"key mismatch {set(b) ^ set(ref)}" +torch.save(b, str(dst) + ".tmp"); Path(str(dst) + ".tmp").rename(dst) +print("wrote", dst, "step", b["step"], "keys", sorted(b)) diff --git a/rsm_rise/scripts/rebuttal_beta_launch.py b/rsm_rise/scripts/rebuttal_beta_launch.py new file mode 100644 index 0000000000000000000000000000000000000000..5b2e16c84f3bc13c9821845fdf41bedc6d6d8f35 --- /dev/null +++ b/rsm_rise/scripts/rebuttal_beta_launch.py @@ -0,0 +1,134 @@ +#!/usr/bin/env python3 +"""REBUTTAL_BETA launch planner (owner decisions 2026-11-08). + +Settings = OpenReview submission exactly (BETA_FAIR's SPEC: paper proposers incl. BC-expert S3H1 on mug, Thread N128, +chain cap(beta,gamma) 1e-3, gamma 0.99). NO hop-QC filter. Same eval seeds as the submission (CRN). + RB_PHASE=n50 : priority 1 = slice proposer seed 0 x eval seed 0 for every missing beta + no-recursion control. + RB_PHASE=p2 : priority 2 = top-up to the full 3 proposer seeds x 3 eval seeds. +Arms: "main" (paper proposers, 7 tasks) and "mugidql" (LOW PRIORITY: mug union IDQL policy S0Aidql@5000). +The control beta is fixed from the FULL 3x3 data (same as BETA_FAIR) so p2 tops up the same cells. +Reuses rebuttal_beta_coverage (arm_groups / wall_fit / pack / mug_idql_ckpts) and beta_fair_coverage (build_cmd ...). +Out: status/packs/rebuttal_beta/plan__.json, payloads__/, status/rebuttal_beta_.json +""" +import json, os, sys +from collections import defaultdict +from pathlib import Path + +ROOT = Path("/proj/dmfexp/zwhong/rsm_rise") +sys.path.insert(0, str(ROOT / "scripts")) +os.environ["RSM_EXTRA_EPOCHS"] = "500" +import rebuttal_beta_coverage as RB +BF, VT, BP = RB.BF, RB.VT, RB.BP + +PHASE = os.environ.get("RB_PHASE", "n50") +ALL = [(p, e) for p in ("0", "1", "2") for e in ("0", "1", "2")] +WANT = [("0", "0")] if PHASE == "n50" else ALL +MUG = RB.MUG +SPEC_IDQL = dict(BF.SPEC[MUG]); SPEC_IDQL.update(prop="IDQL policy", plab="S0Aidql", tag="ONS0AidqlP16lo") +ARMS = {"main": dict(BF.SPEC), "mugidql": {MUG: SPEC_IDQL}} +PREFIX = {"main": f"rb{PHASE}", "mugidql": f"rb{PHASE}i"} + + +def summ(g, want): + by = defaultdict(list) + for f in (g["files"] if g else []): + if (f["pseed"], f["eseed"]) in want: + by[(f["pseed"], f["eseed"])].append(f) + n = sum(f["n"] for L in by.values() for f in L); s = sum(f["s"] for L in by.values() for f in L) + have = {k for k, L in by.items() if sum(f["n"] for f in L) >= BF.NEED_EPS} + miss = [k for k in want if k not in have] + return dict(n=n, succ=(s / n if n else None), missing=[f"{p}|{e}" for p, e in miss], + status="FULL" if not miss else ("MISSING" if not have else "PARTIAL"), + qc_flag=sorted({f"{f['pseed']}|{f['eseed']}" for L in by.values() for f in L if not f["qc_ok"]})) + + +def main(): + res = defaultdict(dict); cells = defaultdict(list) + idql_ck = RB.mug_idql_ckpts() + for task in BF.SPEC: + cs = VT.cells(task); files = dict(VT.CELL_FILES) + tmpl_sh, tmpl = BF.find_template(task, BF.SPEC[task]) + for arm, specs in ARMS.items(): + if task not in specs: + continue + sp = specs[task] + groups = RB.arm_groups(task, sp, cs, files) + fit, nfit = RB.wall_fit(groups) + if fit is None: + fit, nfit = RB.wall_fit(RB.arm_groups(task, BF.SPEC[MUG], cs, files)) + pck = {} + for g in groups.values(): + for f in g["files"]: + if f["ckpt"]: + pck.setdefault(f["pseed"], f["ckpt"]) + if arm == "mugidql": + pck = dict(idql_ck) + + def grp(b, kind): + c = [g for g in groups.values() if g["kind"] == kind and abs(g["beta"] - b) < 1e-9] + return c[0] if c else None + cov = {} + for b in BF.BETAS: + kind = "matched_d1" if abs(b - BF.GAMMA) < 1e-9 else "matched_chain" + g = grp(b, kind) + cov[f"{b:.2f}"] = dict(slice=summ(g, WANT), full=summ(g, ALL), kind=kind) + for k in cov[f"{b:.2f}"]["slice"]["missing"]: + cells[arm].append(dict(arm=arm, task=task, beta=b, mode="d1" if kind == "matched_d1" else "chain", key=k)) + small = [(v["full"]["succ"], float(b)) for b, v in cov.items() + if float(b) <= 0.95 + 1e-9 and v["full"]["succ"] is not None and v["kind"] == "matched_chain"] + cb = max(small)[1] if small else (0.90 if task == MUG else sp["beta"]) + g = grp(cb, "matched_d1") + ctrl = dict(beta=cb, slice=summ(g, WANT), full=summ(g, ALL)) + for k in ctrl["slice"]["missing"]: + cells[arm].append(dict(arm=arm, task=task, beta=cb, mode="d1", key=k, control=True)) + res[arm][task] = dict(spec=sp, coverage=cov, control=ctrl, wall_fit=fit, wall_fit_npts=nfit, + proposer_ckpts=pck, template=tmpl_sh, _tmpl=tmpl) + print(f"=== {arm} {task} prop={sp['prop']} ctrl@{cb} fit={fit} pck={sorted(pck)}", flush=True) + for b, v in cov.items(): + print(f" b{b} slice {v['slice']['status']} n={v['slice']['n']} succ={v['slice']['succ']} " + f"full {v['full']['status']} n={v['full']['n']} succ={v['full']['succ']}", flush=True) + print(f" ctrl d1@{cb}: slice {ctrl['slice']['status']} full {ctrl['full']['status']} {ctrl['full']['succ']}") + + plans = {} + READ_ONLY = os.environ.get("RB_READONLY") == "1" # re-read coverage only; never rewrite live payloads + for arm in ([] if READ_ONLY else ARMS): + jobs, skipped = [], [] + for pc in cells[arm]: + r = res[arm][pc["task"]]; sp = r["spec"]; p, e = pc["key"].split("|") + ck = r["proposer_ckpts"].get(p) + if not r["_tmpl"] or not ck: + pc["error"] = "no template" if not r["_tmpl"] else f"no proposer ckpt seed {p}"; skipped.append(pc); continue + out_dir = ROOT / f"runs/{pc['task']}/eval_onactor" + name, js, cmd = BF.build_cmd(pc["task"], sp, r["_tmpl"], pc["beta"], pc["mode"], f"{sp['plab']}s{p}", ck, e, out_dir) + if js.exists(): + pc["note"] = f"json exists ({js.name}) but loader did not count it"; skipped.append(pc); continue + E = BP.expected_hops(pc["beta"], BF.GAMMA) if pc["mode"] == "chain" else 0.0 + a, b = r["wall_fit"] or (900.0, 0.0) + pc.update(name=name, json=str(js), est_s=1.15 * (a + b * E), cmd=cmd, out_dir=str(out_dir)) + jobs.append(pc) + tag = f"plan_{PHASE}_{arm}" + # n50 is small: one payload per task (8 per node); p2: BETA_FAIR's ~3 h target. + target = 1e9 if PHASE == "n50" else 3 * 3600.0 + pays, nodes = RB.pack(jobs, PREFIX[arm], RB.OUT / f"payloads_{PHASE}_{arm}", target_s=target) + pl = dict(phase=PHASE, arm=arm, n_cells=len(jobs), n_eps=50 * len(jobs), gpu_hours=sum(j["est_s"] for j in jobs) / 3600, + n_payloads=len(pays), n_nodes=len(nodes), + payloads=[dict(path=b["path"], task=b["task"], h=b["s"] / 3600, n=len(b["cells"])) for b in pays], + wall_h=max([b["s"] / 3600 for b in pays] or [0]), nodes=nodes, + cells=[{k: v for k, v in j.items() if k != "cmd"} for j in jobs], skipped=skipped) + json.dump(pl, open(RB.OUT / f"{tag}.json", "w"), indent=1, default=str) + plans[tag] = {k: pl[k] for k in ("n_cells", "gpu_hours", "n_payloads", "n_nodes", "wall_h")} | dict(n_skipped=len(skipped)) + print(f"{tag}: {json.dumps(plans[tag])}", flush=True) + for b in pl["payloads"]: + print(f" {Path(b['path']).name} n={b['n']} {b['h']:.2f}h", flush=True) + for s in skipped: + print(" SKIP", s, flush=True) + for arm in res: + for t in res[arm]: + res[arm][t].pop("_tmpl", None) + json.dump(dict(phase=PHASE, want=WANT, arms=res, plans=plans, mug_idql_ckpts=idql_ck), + open(ROOT / f"status/rebuttal_beta_plan_{PHASE}{'_cov' if READ_ONLY else ''}.json", "w"), indent=1, default=str) + print(f"wrote status/rebuttal_beta_plan_{PHASE}{'_cov' if READ_ONLY else ''}.json", flush=True) + + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/rebuttal_beta_make_ft.py b/rsm_rise/scripts/rebuttal_beta_make_ft.py new file mode 100644 index 0000000000000000000000000000000000000000..25c52ed5b69b106d0eb224c4f2e22443c3b84f9a --- /dev/null +++ b/rsm_rise/scripts/rebuttal_beta_make_ft.py @@ -0,0 +1,135 @@ +#!/usr/bin/env python3 +"""REBUTTAL_BETA P3: copy of scripts/q275_make_finetune.py (the *_ftb80 recipe, same knobs; only the +code dir, payload dir and W&B name differ) -- build the beta_lo-extension FINE-TUNE payloads (sub-0.90 beta points). + +WHY A FINE-TUNE AND NOT AN EVAL. Every flagship successor on disk was trained with +`--beta-lo 0.90` (status/q275_beta_range.json, read from each checkpoint's own `config`), so +beta = 0.85 and 0.80 are OUTSIDE the sampled training range. #275's instruction is explicit that +an out-of-range beta is a defect, not a data point, so the low-beta arm has to come from a +successor whose truncated-geometric offset law was actually fitted down there. + +WHAT THIS BUILDS. One payload per task: copy the pinned flagship checkpoint into a NEW run dir as +`ckpt.pt` (which is the file `train_rsm.py --resume` reads, train_rsm.py:679) and continue training +with the SAME hyper-parameters, changing only `--beta-lo` 0.90 -> 0.80. Short schedule, as the +reward heads were done. + +THE CONTROL THAT MAKES THE LOW-BETA POINTS COMPARABLE. The fine-tuned model is evaluated at the +FULL grid {0.80, 0.85, 0.90, 0.95, 0.98}, not only at the two new betas. The 0.90/0.95/0.98 +overlap is then measured on BOTH the native and the fine-tuned successor, so the figure can show +whether the fine-tune itself moved the curve. Without that bridge a low argmax beta could just be +"the fine-tuned model is different", which is not a beta effect. Every point is labelled +native / fine-tuned, as #275 requires. + +The argparse names are recovered from the checkpoint's stored `config` dict, so a payload cannot +silently differ from the run it continues; the keys actually carried over are written to +status/q275/ft/ARGS_.json beside the payload. + +usage: q275_make_finetune.py [--tasks a,b,c] [--steps 20000] [--beta-lo 0.80] +""" +import json, shutil, sys +from pathlib import Path +import torch + +ROOT = Path("/proj/dmfexp/zwhong/rsm_rise") +RSM = Path("/proj/dmfexp/zwhong/rsm_rise/code/rsm_libero_freeze_20261002") # rebuttal: submission freeze (gen_q_rsm is gone) +sys.path.insert(0, str(ROOT / "scripts")) +from launch_rsm_on_actor import FLAG + +# config key -> train_rsm.py flag. Only knobs that change the FIT are carried; logging / resume / +# wandb knobs are set fresh below so the fine-tune cannot resume the parent's W&B run. +CARRY = { + "d_z": "--d-z", "enc_width": "--enc-width", "flow_width": "--flow-width", + "flow_depth": "--flow-depth", "chunk": "--chunk", "k_success": "--k-success", + "stratify_success": "--stratify-success", "beta_hi": "--beta-hi", + "beta_trunc_eps": "--beta-trunc-eps", "batch": "--batch", "lr": "--lr", "ema": "--ema", + "var_floor": "--var-floor", "w_reward": "--w-reward", "flow_steps": "--flow-steps", + "w_actcon": "--w-actcon", "w_invdyn": "--w-invdyn", "success_gamma": "--success-gamma", + "reward_loss": "--reward-loss", "reward_mode": "--reward-mode", "reward_npy": "--reward-npy", + "weight_npy": "--weight-npy", "success_mask": "--success-mask", "subgoal_dir": "--subgoal-dir", + "seed": "--seed", "enc": "--enc", "pca_dim": "--pca-dim", "flow_dropout": "--flow-dropout", + "flow_norm": "--flow-norm", "wd": "--wd", "sample_clip": "--sample-clip", + "x_noise": "--x-noise", "flow_expectile": "--flow-expectile", "append_proprio": "--append-proprio", + "w_rrank": "--w-rrank", "rrank_tau": "--rrank-tau", +} +# A config key whose flag does not exist in train_rsm.py would make the payload die on an +# unrecognised argument only once it reached a GPU. Checked here instead ("--val-frac" was in an +# earlier draft of CARRY and is NOT a train_rsm.py flag). +_SRC = (RSM / "train_rsm.py").read_text() +CARRY = {k: f for k, f in CARRY.items() if f'"{f}"' in _SRC} + + +def arg(flag, default=None, cast=str): + return cast(sys.argv[sys.argv.index(flag) + 1]) if flag in sys.argv else default + + +def main(): + tasks = arg("--tasks", ",".join(FLAG)).split(",") + extra = arg("--steps", 20000, int) + beta_lo = arg("--beta-lo", 0.80, float) + tag = f"ftb{int(round(beta_lo*100))}" + dst = ROOT / "status/packs/rebuttal_beta/ft" + dst.mkdir(parents=True, exist_ok=True) + manifest = [] + + for task in tasks: + model, ck_name, flag_beta, _ = FLAG[task] + src = ROOT / f"runs/{task}/rsm/{model}/ckpt_{ck_name}.pt" + if not src.exists(): + print(f"[ft] SKIP {task}: no {src}", flush=True); continue + blob = torch.load(src, map_location="cpu", weights_only=False) + cfg, step = blob["config"], int(blob.get("step", 0)) + out = ROOT / f"runs/{task}/rsm/{model}_{tag}" + if (out / "ckpt.pt").exists() or out.exists(): + print(f"[ft] SKIP {task}: {out} already exists (never overwrite)", flush=True); continue + cache = cfg.get("cache", str(ROOT / f"cache/{task}")) + + carried, missing = {}, [] + argv = [] + for k, fl in CARRY.items(): + if k in cfg and cfg[k] not in (None, ""): + v = cfg[k] + v = int(v) if isinstance(v, bool) else v + argv += [fl, str(v)] + carried[k] = v + else: + missing.append(k) + # beta_lo is the ONE knob this run changes. + argv += ["--beta-lo", str(beta_lo)] + argv += ["--cache", cache, "--out", str(out)] + argv += ["--steps", str(step + extra), "--resume", "1", "--save-every", str(extra)] + argv += ["--eval-every", str(max(2000, extra // 4))] + argv += ["--wandb-id-salt", f"rebuttal-{tag}", "--wandb-name", f"rebuttal_{task}_{tag}"] + + sh = dst / f"ft_{task}_{tag}.sh" + sh.write_text( + "#!/usr/bin/env bash\n" + "# gen_q#275 sub-0.90 beta arm: extend the successor's sampled beta range DOWN from\n" + f"# 0.90 to {beta_lo} by continuing the pinned flagship checkpoint. Only --beta-lo differs\n" + f"# from the parent run ({src.name}, step {step}); every other knob is read back out of\n" + "# the parent's stored config, so this is a range extension and not a new model.\n" + "set -euo pipefail\n" + "cd /proj/dmfexp/zwhong/rsm_rise\n" + "export RSM_LIBERO_DIR=/proj/dmfexp/zwhong/rsm_rise/code/rsm_libero_freeze_20261002\n" + "source wandb_env.sh 2>/dev/null || true\n" + f"mkdir -p {out}\n" + f"# --resume reads out/ckpt.pt (train_rsm.py:679); seed it from the parent ONCE.\n" + f"if [ ! -f {out}/ckpt.pt ]; then cp {src} {out}/ckpt.pt; fi\n" + f"exec /proj/dmfexp/zwhong/rsm_rise/venv_rsm/bin/python " + f"{RSM}/train_rsm.py \\\n " + " \\\n ".join( + " ".join(argv[i:i+2]) for i in range(0, len(argv), 2)) + "\n") + sh.chmod(0o755) + (dst / f"ARGS_{task}_{tag}.json").write_text(json.dumps( + dict(task=task, src=str(src), parent_step=step, out=str(out), beta_lo=beta_lo, + extra_steps=extra, carried=carried, not_in_parent_config=missing, + parent_beta_lo=cfg.get("beta_lo"), parent_beta_hi=cfg.get("beta_hi")), indent=1)) + manifest.append(dict(task=task, payload=str(sh), out=str(out), parent_step=step, + parent_beta_lo=cfg.get("beta_lo"))) + print(f"[ft] {task}: {src.name} step={step} beta_lo {cfg.get('beta_lo')} -> {beta_lo}; " + f"{len(carried)} knobs carried, {len(missing)} absent from parent config", flush=True) + + (dst / f"MANIFEST_{tag}.json").write_text(json.dumps(manifest, indent=1)) + print(f"[ft] wrote {len(manifest)} payloads to {dst}", flush=True) + + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/rebuttal_beta_n50_plot.py b/rsm_rise/scripts/rebuttal_beta_n50_plot.py new file mode 100644 index 0000000000000000000000000000000000000000..00a798050c6be8e082dc16095d9a1d85bb4e7684 --- /dev/null +++ b/rsm_rise/scripts/rebuttal_beta_n50_plot.py @@ -0,0 +1,71 @@ +#!/usr/bin/env python3 +"""Plot the n=50 beta slice (proposer seed 0 x eval seed 0) per task, from status/rebuttal_beta_plan_n50_cov.json +(written by RB_PHASE=n50 RB_READONLY=1 scripts/rebuttal_beta_launch.py). Every beta, including the existing ones, is +read on the SAME slice (apples to apples). Marks the paper Table-1 point (full 450 eps), the d1 no-recursion control, +and labels n. No hop QC. Out: status/rebuttal_beta_n50.{pdf,json} +""" +import json, math, sys +from pathlib import Path +import matplotlib +matplotlib.use("Agg") +import matplotlib.pyplot as plt + +ROOT = Path("/proj/dmfexp/zwhong/rsm_rise") +src = sys.argv[1] if len(sys.argv) > 1 else str(ROOT / "status/rebuttal_beta_plan_n50_cov.json") +cov = json.load(open(src)) + + +def ci(p, n): # Wilson 95% + if not n: + return (None, None) + z = 1.96; d = 1 + z * z / n; c = (p + z * z / (2 * n)) / d; h = z * math.sqrt(p * (1 - p) / n + z * z / (4 * n * n)) / d + return (c - h, c + h) + + +out = dict(source=src, slice="proposer seed 0 x eval seed 0 (n=50 per point)", hop_qc="off", arms={}) +arms = [a for a in ("main", "mugidql") if a in cov["arms"]] +panels = [(a, t) for a in arms for t in cov["arms"][a] + if a == "main" or any(v["slice"]["n"] for v in cov["arms"][a][t]["coverage"].values())] +nc = 4; nr = math.ceil(len(panels) / nc) +fig, axes = plt.subplots(nr, nc, figsize=(4.2 * nc, 3.3 * nr), squeeze=False) +for ax, (arm, task) in zip(axes.flat, panels): + r = cov["arms"][arm][task]; sp = r["spec"] + rows = [] + xs, ys, lo, hi = [], [], [], [] + for b, v in sorted(r["coverage"].items(), key=lambda kv: float(kv[0])): + s = v["slice"]; f = v["full"] + rows.append(dict(beta=float(b), kind=v["kind"], n=s["n"], succ=s["succ"], full_n=f["n"], full_succ=f["succ"], + qc_flag=s["qc_flag"])) + if s["n"]: + xs.append(float(b)); ys.append(100 * s["succ"]); l, h = ci(s["succ"], s["n"]) + lo.append(100 * (s["succ"] - l)); hi.append(100 * (h - s["succ"])) + ax.errorbar(xs, ys, yerr=[lo, hi], fmt="-o", color="C0", capsize=3, label="chain (0.99 = 1 hop), n=50") + for x, y, row in zip(xs, ys, [q for q in rows if q["n"]]): + ax.annotate(f"n={row['n']}", (x, y), textcoords="offset points", xytext=(0, 7), ha="center", fontsize=6) + c = r["control"]; cs = c["slice"] + ctrl = dict(beta=c["beta"], n=cs["n"], succ=cs["succ"], full_n=c["full"]["n"], full_succ=c["full"]["succ"]) + if cs["n"]: + ax.plot([c["beta"]], [100 * cs["succ"]], "s", color="C3", label=f"d1 control @{c['beta']:.2f}, n={cs['n']}") + if arm == "main" and sp.get("paper") is not None: + ax.plot([sp["beta"]], [sp["paper"]], "*", ms=13, color="gold", mec="k", zorder=5, + label=f"Table 1: {sp['paper']} @{sp['beta']} (n=450)") + missing = [q["beta"] for q in rows if not q["n"]] + ([c["beta"]] if not cs["n"] else []) + ttl = f"{sp['label']}" + (" [IDQL proposer]" if arm == "mugidql" else "") + ax.set_title(ttl + (f"\nmissing: {missing}" if missing else ""), fontsize=9, color="red" if missing else "k") + ax.set_xlabel(r"$\beta$"); ax.set_ylabel("success % (p0 x e0)"); ax.set_xticks([0.90, 0.93, 0.95, 0.97, 0.98, 0.99]) + ax.tick_params(labelsize=7); ax.grid(alpha=0.3); ax.legend(fontsize=6, loc="best") + out["arms"].setdefault(arm, {})[task] = dict(label=sp["label"], proposer=sp["prop"], paper=sp.get("paper"), + paper_beta=sp["beta"], points=rows, control=ctrl, missing=missing) +for ax in list(axes.flat)[len(panels):]: + ax.axis("off") +fig.suptitle(r"RSM success vs $\beta$ on the n=50 slice (proposer seed 0 $\times$ eval seed 0; submission settings, " + r"N=128, cap$(\beta,\gamma)$=1e-3, no hop QC). Wilson 95% CI.", fontsize=10) +fig.tight_layout(rect=(0, 0, 1, 0.95)) +fig.savefig(ROOT / "status/rebuttal_beta_n50.pdf"); fig.savefig(ROOT / "status/rebuttal_beta_n50.png", dpi=110) +json.dump(out, open(ROOT / "status/rebuttal_beta_n50.json", "w"), indent=1) +print("wrote status/rebuttal_beta_n50.{pdf,png,json}") +for arm in out["arms"]: + for t, d in out["arms"][arm].items(): + pts = " ".join(f"{p['beta']:.2f}:{'-' if p['succ'] is None else round(100 * p['succ'])}" for p in d["points"]) + cc = d["control"] + print(f"{arm:8s} {t:32s} {pts} ctrl@{cc['beta']}:{'-' if cc['succ'] is None else round(100 * cc['succ'])}") diff --git a/rsm_rise/scripts/rebuttal_beta_p3.py b/rsm_rise/scripts/rebuttal_beta_p3.py new file mode 100644 index 0000000000000000000000000000000000000000..80f2d44ba07acface68c6d18a7cca12c73be7034 --- /dev/null +++ b/rsm_rise/scripts/rebuttal_beta_p3.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +"""REBUTTAL_BETA P3 -- low-beta end (beta < 0.90) on the *_ftb80 successors (beta_lo 0.80 fine-tunes). + +The paper successors were trained on beta in [0.90, 0.995], so beta 0.80/0.85 needs the *_ftb80 fine-tune +(scripts/rebuttal_beta_make_ft.py = the q275 recipe). Everything else is the submission setting (BF.SPEC: +proposer, N128, P, readout, flow, gamma 0.99, chain cap 1e-3 tail), same eval seeds, 3 proposer x 3 eval seeds. +The ONLY change from a paper cell is training.rsm_ckpt -> the fine-tuned model's FINAL-step ckpt_s.pt +(never its ckpt_best.pt: selected under a different diagnostic, status q275 run 27). + +env: RB3_BETAS chain betas to plan (default "0.80,0.85") + RB3_D1 d1 (one-hop) betas, e.g. "0.99" (default none) + RB3_TAG plan tag (default "p3low") + RB3_TASKS comma list of tasks to plan (default all) + RB3_READONLY=1 coverage only, never touches payloads +Out: status/packs/rebuttal_beta/plan_.json, payloads_/, status/rebuttal_beta_.json +""" +import glob, json, os, re, sys +from collections import defaultdict +from pathlib import Path + +ROOT = Path("/proj/dmfexp/zwhong/rsm_rise") +sys.path.insert(0, str(ROOT / "scripts")) +os.environ["RSM_EXTRA_EPOCHS"] = "500" +import rebuttal_beta_coverage as RB +BF, VT, BP = RB.BF, RB.VT, RB.BP + +TAG = os.environ.get("RB3_TAG", "p3low") +BETAS = [float(b) for b in os.environ.get("RB3_BETAS", "0.80,0.85").split(",") if b] +D1 = [float(b) for b in os.environ.get("RB3_D1", "").split(",") if b] +READ_ONLY = os.environ.get("RB3_READONLY") == "1" +TASKS = [t for t in os.environ.get("RB3_TASKS", "").split(",") if t] # optional task filter (default all) +ALL = [(p, e) for p in ("0", "1", "2") for e in ("0", "1", "2")] +FT_MODEL = {t: BF.SPEC[t]["model"] + "_ftb80" for t in BF.SPEC} +COST_BETAS = [0.80, 0.85, 0.70, 0.50] + + +def ft_ckpt(task): + """final-step ckpt_s.pt of the fine-tune, or (None, expected step) while it is not trained yet.""" + d = ROOT / f"runs/{task}/rsm/{FT_MODEL[task]}" + steps = sorted(int(m.group(1)) for f in glob.glob(str(d / "ckpt_s*.pt")) + if (m := re.search(r"ckpt_s(\d+)\.pt$", f))) + man = ROOT / f"status/packs/rebuttal_beta/ft/ARGS_{task}_ftb80.json" + want = None + if man.exists(): + a = json.load(open(man)); want = a["parent_step"] + a["extra_steps"] + if want is not None: + return (d / f"ckpt_s{want}.pt" if want in steps else None), want + return (d / f"ckpt_s{steps[-1]}.pt" if steps else None), (steps[-1] if steps else None) + + +def main(): + res, jobs, skipped, cost = {}, [], [], {} + for task, sp0 in BF.SPEC.items(): + if TASKS and task not in TASKS: + continue + cs = VT.cells(task); files = dict(VT.CELL_FILES) + native = RB.arm_groups(task, sp0, cs, files) + fit, nfit = RB.wall_fit(native) + pck = {} + for g in native.values(): + for f in g["files"]: + if f["ckpt"]: + pck.setdefault(f["pseed"], f["ckpt"]) + ck, step = ft_ckpt(task) + sp = dict(sp0); sp["model"] = FT_MODEL[task] + sp["ck"] = f"s{step}" if step else "PENDING" + sp["lab"] = re.sub(r"(b|s\d+k?)$", "", sp0["lab"]) + f"FT80s{(step or 0)//1000}k" + groups = RB.arm_groups(task, sp, cs, files) if step else {} + _sh, tmpl = BF.find_template(task, sp0) + a, b = fit or (900.0, 0.0) + cost[task] = {f"{bb:.2f}": dict(cap=BF.cap_for(bb), E=BP.expected_hops(bb, BF.GAMMA), + gpu_h_450=9 * 1.15 * (a + b * BP.expected_hops(bb, BF.GAMMA)) / 3600) + for bb in COST_BETAS} + cov = {} + for beta, mode in [(x, "chain") for x in BETAS] + [(x, "d1") for x in D1]: + kind = "matched_chain" if mode == "chain" else "matched_d1" + g = [g for g in groups.values() if g["kind"] == kind and abs(g["beta"] - beta) < 1e-9] + have = defaultdict(int); s = defaultdict(int) + for f in (g[0]["files"] if g else []): + have[(f["pseed"], f["eseed"])] += f["n"]; s[(f["pseed"], f["eseed"])] += f["s"] + done = [k for k in ALL if have[k] >= BF.NEED_EPS] + n = sum(have[k] for k in done); succ = sum(s[k] for k in done) / n if n else None + cov[f"{beta:.2f}{'d1' if mode == 'd1' else ''}"] = dict(done=len(done), n=n, succ=succ) + for p, e in ALL: + if (p, e) in done: + continue + pc = dict(task=task, beta=beta, mode=mode, key=f"{p}|{e}") + if ck is None or not ck.exists(): + pc["error"] = f"ft model not trained ({FT_MODEL[task]} step {step})"; skipped.append(pc); continue + if not tmpl or not pck.get(p): + pc["error"] = "no template" if not tmpl else f"no proposer ckpt seed {p}"; skipped.append(pc); continue + old = re.findall(r"training\.rsm_ckpt=(\S+)", tmpl) + assert len(old) == 1, (task, old) + t2 = tmpl.replace(f"training.rsm_ckpt={old[0]}", f"training.rsm_ckpt={ck}") + out_dir = ROOT / f"runs/{task}/eval_onactor" + name, js, cmd = BF.build_cmd(task, sp, t2, beta, mode, f"{sp['plab']}s{p}", pck[p], e, out_dir) + if js.exists(): + pc["note"] = f"json exists ({js.name}) but loader did not count it"; skipped.append(pc); continue + E = BP.expected_hops(beta, BF.GAMMA) if mode == "chain" else 0.0 + pc.update(name=name, json=str(js), est_s=1.15 * (a + b * E), cmd=cmd, out_dir=str(out_dir)) + jobs.append(pc) + res[task] = dict(ft_model=FT_MODEL[task], ft_ckpt=str(ck) if ck else None, ft_step=step, lab=sp["lab"], + coverage=cov, wall_fit=fit, cost=cost[task]) + print(f"=== {task} ft={FT_MODEL[task]}@{sp['ck']} ckpt={'OK' if ck and ck.exists() else 'MISSING'} " + f"fit={fit} cov={json.dumps(cov)}", flush=True) + + tot = {f"{bb:.2f}": sum(c[f"{bb:.2f}"]["gpu_h_450"] for c in cost.values()) for bb in COST_BETAS} + print("COST (7 tasks x 450 eps, GPU-h): " + json.dumps({k: round(v, 1) for k, v in tot.items()}), flush=True) + out = dict(tag=TAG, betas=BETAS, d1=D1, tasks=res, cost_total_gpu_h=tot, + n_jobs=len(jobs), gpu_hours=sum(j["est_s"] for j in jobs) / 3600, + skipped=[{k: v for k, v in s.items() if k != "cmd"} for s in skipped]) + if not READ_ONLY: + pays, nodes = RB.pack(jobs, f"rb{TAG}", RB.OUT / f"payloads_{TAG}", target_s=3 * 3600.0) + out.update(n_payloads=len(pays), n_nodes=len(nodes), nodes=nodes, + payloads=[dict(path=p["path"], task=p["task"], h=p["s"] / 3600, n=len(p["cells"])) for p in pays], + wall_h=max([p["s"] / 3600 for p in pays] or [0]), + cells=[{k: v for k, v in j.items() if k != "cmd"} for j in jobs]) + json.dump(out, open(RB.OUT / f"plan_{TAG}.json", "w"), indent=1, default=str) + for p in out["payloads"]: + print(f" {Path(p['path']).name} n={p['n']} {p['h']:.2f}h", flush=True) + json.dump(out, open(ROOT / f"status/rebuttal_beta_{TAG}{'_cov' if READ_ONLY else ''}.json", "w"), indent=1, default=str) + print(f"{TAG}: jobs={len(jobs)} gpu_h={out['gpu_hours']:.1f} skipped={len(skipped)} " + f"payloads={out.get('n_payloads')} nodes={out.get('n_nodes')} wall_h={out.get('wall_h')}", flush=True) + + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/rebuttal_beta_p3table150.py b/rsm_rise/scripts/rebuttal_beta_p3table150.py new file mode 100644 index 0000000000000000000000000000000000000000..307e96921075470c82b46f5c63ce9c7ab795870d --- /dev/null +++ b/rsm_rise/scripts/rebuttal_beta_p3table150.py @@ -0,0 +1,187 @@ +#!/usr/bin/env python3 +"""P3 low-beta series table (owner 2026-11-08 07:00Z + orchestrator 09:10Z): within ONE beta_lo=0.80 fine-tuned successor +model per task (the *_ftb80 recipe), chain read-out at beta 0.80/0.85/0.90/0.95/0.98 and the 0.99 single hop (d1), +150 episodes per cell = proposer seed 0 x eval seeds 0,1,2 x 50 (same CRN eval seeds as the reviewer table150). +Never spliced onto the submission curve; the submission-model values (table150) are listed alongside for reference only. +No hop QC (cap is the guard); hop accounting is reported for information. Paired bootstrap over the 150 shared episodes. +Out: status/rebuttal_beta_p3table150.{md,json,pdf} +""" +import json +from pathlib import Path +import numpy as np + +ROOT = Path("/proj/dmfexp/zwhong/rsm_rise") +BETAS = [0.80, 0.85, 0.90, 0.95, 0.98, 0.99] +CAP = {0.80: "168-ch", 0.85: "118-ch", 0.90: "73-ch", 0.95: "33-ch", 0.98: "11-ch", 0.99: "1"} +LO_END, HI_END = 0.80, 0.99 +B = 10000 +rng = np.random.default_rng(0) +# task -> (FT label, FT ckpt, name middle "ON", proposer-seed-0 suffix) +SER = { + "square_sub_20100": ("MFT80s120k", "M_ftb80/ckpt_s120000", "ONACTORP16lo", "sS0As0"), + "square_expert_play": ("L40FT80s80k", "L40_ftb80/ckpt_s80000", "ONACTOR", "sS0As0"), + "two_piece_expert_suboptimal": ("MFT80s120k", "M_ftb80/ckpt_s120000", "ONACTORP8pr", "sS0As0"), + "two_piece_expert_play": ("L40FT80s50k", "L40_ftb80/ckpt_s50000", "ONACTOR", "sS0As0"), + "mug_expert_suboptimal": ("Ms1FT80s95k", "M_s1_ftb80/ckpt_s95000", "ONS3H1P16lo", "sS3H1s0"), + "threading_expert_play": ("MFT80s240k", "M_ftb80/ckpt_s240000", "ONS0AidqlE500P8pr", "sS0AidqlE500s0"), + "two_piece_expert_play_tipping": ("MFT80s30k", "M_ftb80/ckpt_s30000", "ONACTORF4", "sS0As0"), +} + + +def main(): + t150 = json.load(open(ROOT / "status/rebuttal_beta_table150.json"))["tasks"] + out = dict(rule="within-FT-model series; proposer seed 0 x eval seeds 0-2 x first 50 eps = 150/cell; no hop QC; " + "paired bootstrap (CRN), B=10000, 95% percentile CI", tasks={}) + order = [t for t in t150 if t in SER] + [t for t in SER if t not in t150] + for task in order: + lab, ck, on, ps = SER[task] + T = dict(label=t150.get(task, {}).get("label", task), ft_model=ck, points={}, missing=[], + native150={k: v.get("mean") for k, v in t150.get(task, {}).get("points", {}).items()}, + native_paper_beta=t150.get(task, {}).get("paper_beta"), native_paper=t150.get(task, {}).get("paper")) + arr = {} + for b in BETAS: + eps, files, hops = [], [], [] + for e in range(3): + f = ROOT / f"runs/{task}/eval_onactor/E1-{lab}-R{b:.2f}-{CAP[b]}-N128-argmax-{on}-es{e}-{ps}.json" + if not f.exists(): + continue + j = json.load(open(f)) + s = [int(bool(x.get("success"))) for x in (j.get("episodes") or [])][:50] + if len(s) < 50: + continue + eps += s; files.append(f.name) + ch = ((j.get("planner") or {}).get("scorer") or {}).get("chain_hops") or {} + hops.append(dict(hops_mean=ch.get("hops_mean"), capped_frac=ch.get("capped_frac"))) + p = dict(n=len(eps), files=files, hop_acct=hops) + if len(eps) == 150: + arr[b] = np.array(eps) + else: + T["missing"].append(f"{b:.2f}") + T["points"][f"{b:.2f}"] = p + idx = rng.integers(0, 150, size=(B, 150)) + boot = {b: v[idx].mean(1) for b, v in arr.items()} + for b, v in arr.items(): + T["points"][f"{b:.2f}"].update(mean=float(v.mean()), ci=[float(np.percentile(boot[b], 2.5)), + float(np.percentile(boot[b], 97.5))]) + curve = [b for b in BETAS if b in arr] + verdict = None + if curve: + means = np.array([arr[b].mean() for b in curve]) + best = curve[int(np.argmax(means))] + ties = [b for b, m in zip(curve, means) if abs(m - means.max()) < 1e-12] + am = np.array(curve)[np.argmax(np.stack([boot[b] for b in curve], 1), 1)] + interior = [b for b in curve if LO_END + 1e-9 < b < HI_END - 1e-9] + d = {} + for e in (LO_END, HI_END): + if e in arr and e != best: + db = boot[best] - boot[e] + d[f"{e:.2f}"] = dict(diff=float(arr[best].mean() - arr[e].mean()), + ci=[float(np.percentile(db, 2.5)), float(np.percentile(db, 97.5))]) + T.update(best=best, ties=ties, p_argmax_interior=float(np.isin(am, interior).mean()), + p_argmax={f"{b:.2f}": float((am == b).mean()) for b in curve}, best_minus_endpoint=d) + fmt = lambda k: f"vs {k} {100*d[k]['diff']:+.1f} [{100*d[k]['ci'][0]:+.1f},{100*d[k]['ci'][1]:+.1f}]" + if best in (LO_END, HI_END): + verdict = f"endpoint optimum at {best:.2f}" + (" (single hop)" if best == HI_END else " (most hops)") + if len(ties) > 1: + verdict += f" (tie with {', '.join(f'{t:.2f}' for t in ties if t != best)})" + else: + sig = [k for k, v in d.items() if v["ci"][0] > 0] + verdict = (f"interior optimum at {best:.2f}; " + "; ".join(fmt(k) for k in d) + + f"; P(argmax interior)={T['p_argmax_interior']:.2f}" + + (f"; separated from {', '.join(sig)} at 95%" if sig else "; not separated from either end at 95%")) + if T["missing"]: + verdict = "INCOMPLETE (missing " + ", ".join(T["missing"]) + "); " + verdict + T["verdict"] = verdict + out["tasks"][task] = T + print(task, {k: (round(100 * v["mean"], 1) if "mean" in v else None) for k, v in T["points"].items()}, verdict, + flush=True) + write_md(out); json.dump(out, open(ROOT / "status/rebuttal_beta_p3table150.json", "w"), indent=1, default=float) + render_pdf(out) + print("wrote status/rebuttal_beta_p3table150.{md,json,pdf}") + + +def write_md(out): + md = ["# Low-beta series (within one beta_lo=0.80 fine-tuned successor model per task), 150 episodes per cell", "", + "Each task: ONE fine-tuned successor model (the *_ftb80 recipe, trained band reaches 0.80), evaluated with the chain " + "read-out at beta 0.80/0.85/0.90/0.95/0.98 and the single-hop read-out at 0.99 (= gamma, no recursion). Proposer " + "seed 0 x eval seeds 0,1,2 x 50 episodes = 150 per cell, the same CRN episodes as the reviewer table " + "(rebuttal_beta_table150). Everything else uses the submission settings (N=128, gamma 0.99, 1e-3 chain tail cap, " + "submission proposer). No hop QC. The CI is a 95% paired bootstrap. **Bold** = best. The 'submission model' row " + "is the reviewer-table curve from the submission successor checkpoint. It is listed for reference only and is " + "never spliced onto the FT curve.", ""] + hdr = "| task | model | " + " | ".join(f"{b:.2f}" + (" (1 hop)" if b == HI_END else "") for b in BETAS) + " | verdict |" + md += [hdr, "|" + "---|" * (len(BETAS) + 3)] + for t, T in out["tasks"].items(): + cells = [] + for b in BETAS: + p = T["points"][f"{b:.2f}"] + if "mean" not in p: + cells.append(f"missing (n={p['n']})"); continue + s = f"{100*p['mean']:.1f} [{100*p['ci'][0]:.1f},{100*p['ci'][1]:.1f}]" + cells.append(f"**{s}**" if b in (T.get("ties") or []) else s) + md.append(f"| {T['label']} | FT {T['ft_model']} | " + " | ".join(cells) + f" | {T['verdict']} |") + nat = [(f"{100*T['native150'][f'{b:.2f}']:.1f}" if T["native150"].get(f"{b:.2f}") is not None else "-") + + ("*" if T["native_paper_beta"] is not None and abs(b - T["native_paper_beta"]) < 1e-9 else "") + for b in BETAS] + md.append(f"| | submission model (ref) | " + " | ".join(nat) + + f" | Table 1: {T['native_paper']} @{T['native_paper_beta']} (* = paper beta) |") + (ROOT / "status/rebuttal_beta_p3table150.md").write_text("\n".join(md) + "\n") + + +def render_pdf(out): + import matplotlib + matplotlib.use("Agg") + import matplotlib.pyplot as plt + from matplotlib.backends.backend_pdf import PdfPages + tasks = list(out["tasks"].items()) + with PdfPages(ROOT / "status/rebuttal_beta_p3table150.pdf") as pdf: + fig, ax = plt.subplots(figsize=(15, 1.2 + 0.8 * len(tasks))); ax.axis("off") + rows, colors, labels = [], [], [] + for t, T in tasks: + r, c = [], [] + for b in BETAS: + p = T["points"][f"{b:.2f}"] + if "mean" in p: + r.append(f"{100*p['mean']:.1f}\n[{100*p['ci'][0]:.0f},{100*p['ci'][1]:.0f}]") + c.append("#c8e6c9" if b in (T.get("ties") or []) else "w") + else: + r.append("missing"); c.append("#ffcdd2") + rows.append(r); colors.append(c); labels.append(f"{T['label']} (FT)") + tb = ax.table(cellText=rows, cellColours=colors, rowLabels=labels, + colLabels=[f"{b:.2f}" + ("\n(1 hop)" if b == HI_END else "") for b in BETAS], loc="center", + cellLoc="center") + tb.auto_set_font_size(False); tb.set_fontsize(8); tb.scale(1, 2.6) + for (i, j), cell in tb.get_celld().items(): + if i > 0 and 0 <= j < len(BETAS) and colors[i - 1][j] == "#c8e6c9": + cell.get_text().set_fontweight("bold") + ax.set_title("Low-beta series within one beta_lo=0.80 fine-tuned successor model per task: success % vs beta,\n" + "150 episodes per cell (proposer seed 0 x eval seeds 0-2 x 50), paired bootstrap 95% CI. Green/bold = best.", + fontsize=10) + pdf.savefig(fig, bbox_inches="tight"); plt.close(fig) + fig = plt.figure(figsize=(17, 1 + 0.45 * len(tasks))) + fig.text(0.01, 0.98, "Verdicts (FT series)", va="top", fontsize=11, weight="bold") + for i, (t, T) in enumerate(tasks): + fig.text(0.01, 0.92 - i * 0.8 / len(tasks), f"{T['label']}: {T['verdict']}", va="top", fontsize=8) + pdf.savefig(fig); plt.close(fig) + nc = 4; nr = -(-len(tasks) // nc) + fig, axes = plt.subplots(nr, nc, figsize=(4.2 * nc, 3.3 * nr), squeeze=False) + for ax, (t, T) in zip(axes.flat, tasks): + pts = [(b, T["points"][f"{b:.2f}"]) for b in BETAS if "mean" in T["points"][f"{b:.2f}"]] + if pts: + x = [b for b, _ in pts]; y = [100 * p["mean"] for _, p in pts] + ax.errorbar(x, y, yerr=[[100 * (p["mean"] - p["ci"][0]) for _, p in pts], + [100 * (p["ci"][1] - p["mean"]) for _, p in pts]], + fmt="-o", capsize=3, label="FT model (0.99 = 1 hop), n=150") + nb = [(float(k), 100 * v) for k, v in sorted(T["native150"].items()) if v is not None] + if nb: + ax.plot(*zip(*nb), "--", color="0.6", marker=".", label="submission model (ref), n=150") + ax.set_title(T["label"] + (f"\nmissing {T['missing']}" if T["missing"] else ""), fontsize=9) + ax.set_xticks(BETAS); ax.tick_params(labelsize=7); ax.grid(alpha=0.3); ax.legend(fontsize=6) + ax.set_xlabel(r"$\beta$"); ax.set_ylabel("success %") + for ax in list(axes.flat)[len(tasks):]: + ax.axis("off") + fig.tight_layout(); pdf.savefig(fig); plt.close(fig) + + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/rebuttal_beta_pdf.py b/rsm_rise/scripts/rebuttal_beta_pdf.py new file mode 100644 index 0000000000000000000000000000000000000000..a0e07a7ae19518a355385ae368f5441e7219c960 --- /dev/null +++ b/rsm_rise/scripts/rebuttal_beta_pdf.py @@ -0,0 +1,152 @@ +#!/usr/bin/env python3 +"""Render docs/rebuttal/beta_sweep_plan.tex from status/rebuttal_beta_coverage.json + capacity.json (REBUTTAL_BETA).""" +import json +from pathlib import Path + +ROOT = Path("/proj/dmfexp/zwhong/rsm_rise") +C = json.load(open(ROOT / "status/rebuttal_beta_coverage.json")) +CAP = json.load(open(ROOT / "status/packs/rebuttal_beta/capacity.json")) +OUTD = ROOT / "docs/rebuttal"; OUTD.mkdir(parents=True, exist_ok=True) +BETAS = ["0.90", "0.93", "0.95", "0.97", "0.98", "0.99"] +ORDER = ["square_sub_20100", "square_expert_play", "two_piece_expert_suboptimal", "two_piece_expert_play", + "mug_expert_suboptimal", "threading_expert_play", "two_piece_expert_play_tipping"] +RED = lambda s: r"\textcolor{red}{" + s + "}" +esc = lambda s: str(s).replace("_", r"\_").replace("%", r"\%").replace("&", r"\&").replace("#", r"\#") + + +def cell(s, is_paper=False): + st = s.get("status") + if st == "MISSING" or not s.get("n"): + return RED(r"\textbf{MISSING}") + v = 100 * s["succ"]; txt = f"{v:.1f} ({s['n']})" + if is_paper: + txt = r"\underline{" + txt + "}" + q = s.get("succ_qc") + if s.get("n_qc") is not None and s.get("n_qc") != s["n"] and q is not None: + txt += r"$^{\dagger}$\,{\scriptsize " + f"{100 * q:.1f}/{s['n_qc']}" + "}" + if st == "PARTIAL": + return RED(txt + r" {\scriptsize miss " + str(len(s["missing"])) + "}") + return txt + + +def table(arm, tasks, caption): + A = C["arms"][arm] + rows = [] + for t in tasks: + r = A[t]; sp = r["spec"] + cs = [cell(r["coverage"][b], abs(float(b) - sp["beta"]) < 1e-9) for b in BETAS] + ct = r["control"] + ctl = (cell(ct) + r" {\scriptsize @" + f"{ct['beta']:.2f}" + "}") + rows.append(esc(sp["label"]) + f" & {sp['paper']:.1f} ({sp['beta']:.2f}) & " + " & ".join(cs) + " & " + ctl + r" \\") + return (r"\begin{table}[H]\centering\scriptsize\setlength{\tabcolsep}{3pt}" "\n" + r"\begin{tabular}{l c " + "c" * len(BETAS) + r" c}\toprule" "\n" + r"Task & Paper T1 ($\beta$) & " + " & ".join( + (r"$\beta$=" + b + (" (1 hop)" if b == "0.99" else "")) for b in BETAS) + + r" & No recursion (d1) \\\midrule" "\n" + "\n".join(rows) + "\n" r"\bottomrule\end{tabular}" "\n" + r"\caption{" + caption + r"}\end{table}" "\n") + + +def proposer_table(): + rows = [ + ("Square (Sub.)", "S0A ``RISE policy''", "union", "5000", "same", ""), + ("Square (Cov.)", "S0A ``RISE policy''", "union", "5000", "same", ""), + ("Piece (Sub.)", "S0A ``RISE policy''", "union", "5000", "same", ""), + ("Piece (Cov.)", "S0A ``RISE policy''", "union", "5000", "same", ""), + ("Piece-tip (Cov.)", "S0A ``RISE policy''", "union", "5000", "same", ""), + ("Thread (Cov.)", "S0Aidql ``IDQL policy''", "union", "500", "same", ""), + ("Mug (Sub.)", "S0Aidql ``IDQL policy''", "union", "5000", + r"\textbf{differs}: S3H1 BC-expert, 20 expert eps, @5000", r"fallback arm"), + ] + body = "\n".join(" & ".join(r) + r" \\" for r in rows) + return (r"\begin{table}[H]\centering\scriptsize" "\n" r"\begin{tabular}{l l l c p{5.2cm} l}\toprule" "\n" + r"Task & rise\_repro proposer & data & epoch & paper (Table 1/6) proposer & \\\midrule" "\n" + body + + "\n" r"\bottomrule\end{tabular}" "\n" + r"\caption{Proposers. Seeds: nominal proposer seeds 0,1,2 (on disk for every row, incl.\ mug S0Aidql@5000: " + r"\texttt{runs/mug\_expert\_suboptimal/policy/S0Aidql\_seed\{0,1,2\}/.../model\_epoch\_5000.pth}; no training " + r"needed). Note: pre-2026-09-21 trainings ran with \texttt{train.seed=1}, so the published proposer seeds " + r"are CUDA-nondeterminism replicas of one init (mug S0Aidql: s1 and s2 replicas, s0 a true seed).}\end{table}" "\n") + + +def budget(): + P = C["plans"]; pm = P["plan"]; pf = P["plan_fresh"] + rows = [] + for k, v in sorted(pm["per_arm_task"].items()): + arm, t = k.split(":") + lab = C["arms"][arm][t]["spec"]["label"] + (" [BC-expert fallback]" if arm == "mugfb" else + (" [IDQL proposer]" if t == "mug_expert_suboptimal" else "")) + rows.append(f"{esc(lab)} & {v['cells']} & {50 * v['cells']} & {v['gpu_h']:.1f}" + r" \\") + tot = (f"\\midrule Total (top-up) & {pm['n_cells']} & {pm['n_eps']} & {pm['gpu_hours']:.1f}" + r" \\") + fr = (f"Optional: fresh eval seeds 3--5, all $\\beta$ (+ control), main arm + mug BC-expert arm & {pf['n_cells']} & {pf['n_eps']} & " + f"{pf['gpu_hours']:.1f}" + r" \\") + return (r"\begin{table}[H]\centering\scriptsize" "\n" r"\begin{tabular}{l r r r}\toprule" "\n" + r"Arm / task & cells & episodes & GPU-h \\\midrule" "\n" + "\n".join(rows) + "\n" + tot + "\n" + fr + + "\n" r"\bottomrule\end{tabular}" "\n" r"\caption{Run list. One cell = 1 proposer seed $\times$ 1 eval seed " + r"$\times$ 50 episodes (horizon 400). GPU-h per cell = per-task fit $a + b\,E[\mathrm{hops}](\beta)$ to the " + r"measured \texttt{wall\_time\_s} of the existing matched cells (+15\% margin); the mug IDQL arm uses the " + r"mug S3H1 fit (same RSM, P16, logit).}\end{table}" "\n"), pm, pf + + +def main(): + bt, pm, pf = budget() + cov_main = table("main", ORDER, r"\textbf{Main arm (rise\_repro proposers).} Success \% (episodes). Black = FULL " + r"(3 proposer $\times$ 3 eval seeds $\times$ 50 = 450 eps); \textcolor{red}{red} = MISSING or " + r"PARTIAL (number of missing seed cells). Underlined = the paper's $\beta$. Value = hop-QC OFF " + r"(paper rule, reproduces Table 1); $^{\dagger}$ = with the chain hop-QC ON (value/episodes) where it " + r"drops cells. $\beta$=0.99=$\gamma$ is the single-hop estimator (chain continuation $p=0$). " + r"d1 = one hop at $\beta$, no recursion.") + cov_fb = table("mugfb", ["mug_expert_suboptimal"], r"\textbf{Mug fallback arm (BC-expert S3H1 proposer = paper " + r"flagship).} Same conventions.") + cap = CAP + nn = pm["n_nodes"] + tex = (r"""\documentclass[10pt]{article} +\usepackage[margin=0.7in,landscape]{geometry} +\usepackage{booktabs,xcolor,hyperref,amsmath,float} +\usepackage[T1]{fontenc} +\title{RSM $\beta$ ablation for the ICLR rebuttal: plan, coverage and GPU budget} +\author{rsm\_rise / REBUTTAL\_BETA worker} +\date{""" + esc(cap["stamp"]) + r"""} +\begin{document}\maketitle +\section*{(a) Goal} +A fair $\beta$ ablation for the rebuttal. Every task uses the shared, \emph{union-data} proposer of the RISE +reproduction (RISE policy S0A, or its special case the IDQL policy S0Aidql), so no row gets a hand-picked proposer; +all other RSM settings are the paper's Table~6 (successor model + checkpoint, $M$ particles, read-out, membership head, +$\gamma=0.99$, $N=128$ candidates, Thread kept at $N=128$). Only $\beta$ (and the chain cap it implies) varies over +$\{0.90,0.93,0.95,0.97,0.98,0.99\}$, where $0.99=\gamma$ is the single-hop estimator; a no-recursion control (one hop, +d1) at the task's best small $\beta$ tests recursion vs.\ single-hop. Claim to test: the best $\beta$ is +task-dependent and recursion to $\gamma$ beats a single hop. Mug is the only row where the rise\_repro proposer +(IDQL@5000, union) differs from the paper (BC-expert, expert-only); if it collapses we additionally report the mug +sweep with the BC-expert proposer (fallback arm). +\section*{(b) Proposers} +""" + proposer_table() + r""" +\section*{(c) Results we already have (canonical loader \texttt{verdict\_table.cells}, CPU job)} +""" + cov_main + cov_fb + r""" +\clearpage +\section*{(d) Run list, GPU budget, nodes} +""" + bt + r""" +\noindent\textbf{Packing.} """ + f"{pm['n_cells']} cells $\\to$ {pm['n_payloads']} payloads (LPT per task, one task per " + f"payload) $\\to$ \\textbf{{{nn} full 8-GPU node(s)}}, one payload per GPU, never a 1-GPU job; longest payload " + f"{pm['wall_h']:.1f}\\,h, so \\textbf{{wall-clock $\\approx$ {pm['wall_h']:.1f}\\,h}} once the nodes start " + f"({pm['gpu_hours']:.0f} GPU-h). The optional fresh-seed set adds {pf['n_payloads']} payloads = {pf['n_nodes']} " + f"nodes, {pf['gpu_hours']:.0f} GPU-h, $\\approx${pf['wall_h']:.1f}\\,h wall in parallel." + r""" +No proposer training is needed: the mug S0Aidql@5000 policies exist for all three seeds (for reference, a 5000-epoch +RISE-recipe training costs $\approx$22 GPU-h per seed on one H100, measured on S0A). Payloads: +\texttt{status/packs/rebuttal\_beta/payloads/rb\_*.sh} (fresh: \texttt{payloads\_fresh/rbf\_*.sh}); each is the paper +cell's own \texttt{eval\_cell.sh} line with only $\beta$/cap (or mode d1), proposer checkpoint, seed and cell name +changed, writes to \texttt{runs//eval\_onactor/}, and skips any cell whose JSON exists. Submit (NOT run): +\texttt{GO=1 bash status/packs/rebuttal\_beta/submit\_nodes.sh} (\texttt{PLAN\_NAME=plan\_fresh} for the fresh set). + +\section*{(e) Cluster capacity snapshot (""" + esc(cap["stamp"]) + r""")} +""" + cap["tex"] + r""" + +\section*{(f) Risks and owner decisions} +\begin{enumerate}\setlength\itemsep{1pt} +""" + "\n".join(r"\item " + x for x in cap["risks"]) + r""" +\end{enumerate} +\end{document} +""") + (OUTD / "beta_sweep_plan.tex").write_text(tex) + print("wrote", OUTD / "beta_sweep_plan.tex") + + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/rebuttal_beta_pdf2.py b/rsm_rise/scripts/rebuttal_beta_pdf2.py new file mode 100644 index 0000000000000000000000000000000000000000..6d981694285b90a2b6530295f4ffc12786c70481 --- /dev/null +++ b/rsm_rise/scripts/rebuttal_beta_pdf2.py @@ -0,0 +1,388 @@ +#!/usr/bin/env python3 +"""REBUTTAL_PDF2: build docs/rebuttal/beta_sweep_plan_v2.tex from existing coverage/plan JSONs (read-only). + +Owner decisions 2026-11-08: OpenReview settings exactly (freeze/rsm-rise-flagship-20261002), Mug = BC-expert S3H1, +Thread N128, 1e-3 chain cap, NO hop-count QC, same eval seeds. n=50 slice (proposer seed 0 x eval seed 0) first. +Nothing here recomputes success rates of the main grid: they come from status/rebuttal_beta_coverage.json and +status/rebuttal_beta_n50.json. Only the low-beta (ftb80) and rise_repro cells are read directly from their JSONs. +""" +import json, glob, os, re, math, subprocess, datetime, collections + +R = "/proj/dmfexp/zwhong/rsm_rise" +OUT = f"{R}/docs/rebuttal/beta_sweep_plan_v2.tex" +J = lambda p: json.load(open(p if p.startswith("/") else f"{R}/{p}")) +cov = J("status/rebuttal_beta_coverage.json") +n50 = J("status/rebuttal_beta_n50.json") +plan = J("status/packs/rebuttal_beta/plan.json") +plan50 = J("status/packs/rebuttal_beta/plan_n50_main.json") +plan50i = J("status/packs/rebuttal_beta/plan_n50_mugidql.json") +planf = J("status/packs/rebuttal_beta/plan_fresh.json") +cap = J("status/packs/rebuttal_beta/capacity.json") + +TASKS = ["square_sub_20100", "square_expert_play", "two_piece_expert_suboptimal", "two_piece_expert_play", + "mug_expert_suboptimal", "threading_expert_play", "two_piece_expert_play_tipping"] +SHORT = {"square_sub_20100": "Square (Sub.)", "square_expert_play": "Square (Cov.)", + "two_piece_expert_suboptimal": "Piece (Sub.)", "two_piece_expert_play": "Piece (Cov.)", + "mug_expert_suboptimal": "Mug (Sub.)", "threading_expert_play": "Thread (Cov.)", + "two_piece_expert_play_tipping": "Piece-tip (Cov.)"} +PAPER = {"square_sub_20100": (54.0, .98), "square_expert_play": (20.9, .90), "two_piece_expert_suboptimal": (47.1, .95), + "two_piece_expert_play": (48.7, .98), "mug_expert_suboptimal": (23.1, .98), + "threading_expert_play": (25.8, .98), "two_piece_expert_play_tipping": (7.3, .95)} +BETAS = ["0.90", "0.93", "0.95", "0.97", "0.98", "0.99"] +GAMMA = 0.99 +hops = lambda b: (GAMMA - b) / (b * (1 - GAMMA)) + + +def arm_of(t): # owner decision: mug = BC-expert S3H1 (= the "mugfb" arm of the coverage json) + return cov["arms"]["mugfb" if t.startswith("mug") else "main"][t] + + +def esc(s): + return s.replace("_", r"\_").replace("%", r"\%").replace("&", r"\&").replace("#", r"\#") + + +RED = lambda s: r"\textcolor{red}{" + s + "}" +GREY = lambda s: r"\textcolor{gray}{" + s + "}" +pct = lambda x: f"{100 * x:.1f}" + + +def cell_sec(t, b, d1=False): + a, k = arm_of(t)["wall_fit"] + return (a + k * (1.0 if d1 else hops(b))) * 1.15 + + +def lpt(secs, max_wall_h=4.0, max_nodes=12): + secs = sorted(secs, reverse=True) + for n in range(1, max_nodes + 1): + bins = [0.0] * (8 * n) + for s in secs: + i = min(range(len(bins)), key=bins.__getitem__); bins[i] += s + if max(bins) / 3600 <= max_wall_h or n == max_nodes: + return n, max(bins) / 3600 + return None + + +# ---------------- Table A + B (existing values) ---------------- +n50pts = {t: {f"{p['beta']:.2f}": p for p in v["points"]} for t, v in n50["arms"]["main"].items()} +n50ctl = {t: v["control"] for t, v in n50["arms"]["main"].items()} +rowsA, rowsB = [], [] +mism = [] +for t in TASKS: + a = arm_of(t); sp = a["spec"]; pv, pb = PAPER[t] + c = a["coverage"][f"{pb:.2f}"] + ours = round(100 * c["succ"], 1) + ok = abs(ours - pv) < 0.05 + if not ok: mism.append((t, pv, ours)) + qc = "" if c.get("n_qc", c["n"]) == c["n"] else rf" (QC-on {pct(c['succ_qc'])}/{c['n_qc']})" + prop = "BC-expert S3H1@5000" if t.startswith("mug") else ( + "IDQL S0Aidql@500" if t.startswith("thread") else "RISE S0A@5000") + rowsA.append(f"{SHORT[t]} & {pv:.1f} & {pb:.2f} & {ours:.1f} ({c['n']}){qc} & " + f"{'yes' if ok else RED('NO')} & \\texttt{{{esc(c['recipe'])}}} & {prop} \\\\") + cells = [] + for b in BETAS: + cc = a["coverage"][b]; p50 = n50pts[t].get(b, {}) + s50 = f"{{\\tiny[50: {pct(p50['succ'])}]}}" if p50.get("n") else "" + mark = r"$^{\star}$" if abs(float(b) - pb) < 1e-9 else "" + if cc["status"] == "FULL": + txt = f"{pct(cc['succ'])} ({cc['n']}){mark}" + if abs(float(b) - pb) < 1e-9: txt = r"\textbf{" + txt + "}" + cells.append(txt + " " + s50) + else: + cells.append(RED(r"\textbf{run} 50$\to$450") + (" " + s50 if s50 else "")) + ct = a["control"]; c50 = n50ctl[t] + if ct.get("status") == "FULL": + s50 = f"{{\\tiny[{c50['n']}: {pct(c50['succ'])}]}}" if c50.get("n") else "" + cells.append(f"{pct(ct['succ'])} ({ct['n']}) {{\\tiny @{ct['beta']:.2f}}} {s50}") + else: + cells.append(RED(r"\textbf{run} 50$\to$450") + f" {{\\tiny @{ct['beta']:.2f}}}") + rowsB.append(f"{SHORT[t]} & {pv:.1f} ({pb:.2f}) & " + " & ".join(cells) + r" \\") + +# ---------------- main-grid budget (plan.json minus main:mug IDQL, plus mugfb) ---------------- +main_cells = [c for c in plan["cells"] if not (c["arm"] == "main" and c["task"].startswith("mug"))] +n50keys = {(c["task"], c["beta"], c["mode"]) for c in plan50["cells"]} +assert len(plan50["cells"]) == 28 +top = [c for c in main_cells if c["key"] != "0|0"] +slice_in_main = [c for c in main_cells if c["key"] == "0|0"] +topN, topW = lpt([c["est_s"] for c in top]) +B = collections.OrderedDict() +B["B1 main grid, n=50 slice (p-seed 0 x e-seed 0)"] = dict(cells=len(plan50["cells"]), gpuh=plan50["gpu_hours"], + nodes=plan50["n_nodes"], wall=plan50["wall_h"]) +B["B2 main grid, top-up 50$\\to$450"] = dict(cells=len(top), gpuh=sum(c["est_s"] for c in top) / 3600, + nodes=topN, wall=topW) +per_task_main = collections.Counter(c["task"] for c in main_cells) + +# ---------------- Table C(a): beta 0.80/0.85 ---------------- +FT = { # task -> (parent arm on paper ckpt, ftb80 dir, eval label, eval ckpt step) ; from runs/*/rsm/*ftb80 + "square_sub_20100": ("M@100k", "M_ftb80", None, 120000), + "two_piece_expert_suboptimal": ("M@s100000", "M_ftb80", "MFT80s120k", 120000), + "two_piece_expert_play": ("L40@30k", "L40_ftb80", "L40FT80s50k", 50000), + "mug_expert_suboptimal": ("M_s1@75k", "M_s1_ftb80", None, 95000), +} +FT_TRAIN_H = {"M": 2003 / 3600, "L40": 2414 / 3600} # measured W&B _runtime of the 2026-09-24 ftb80 runs, 1 H100 +NEED_FT = {"square_expert_play": ("L40@best 60k", "L40"), "threading_expert_play": ("M@best 220k", "M"), + "two_piece_expert_play_tipping": ("M@best 10k", "M")} + + +def ft_cells(t, lab): + agg = collections.defaultdict(lambda: [0, 0, set()]) + for f in glob.glob(f"{R}/runs/{t}/eval_onactor/E1-{lab}-R*-ch-N128-*.json"): + d = json.load(open(f)); b = re.search(r"-R(0\.\d+)-", f).group(1) + n = d["num_episodes"]; agg[b][0] += d["success_rate"] * n; agg[b][1] += n + po = d.get("planner_overrides", {}); agg[b][2].add((po.get("plan_particles"), po.get("plan_score"))) + return {b: (100 * v[0] / v[1], v[1], v[2]) for b, v in agg.items()} + + +rowsC, Ca_cells, Ca_train = [], [], 0.0 +for t in TASKS: + sp = arm_of(t)["spec"]; P, sc = sp["P"], sp["score"]; pb = PAPER[t][1] + ex = ft_cells(t, FT[t][2]) if t in FT and FT[t][2] else {} + if t in FT: + model = esc(f"{FT[t][1]} (from {FT[t][0]}), eval ckpt s{FT[t][3]}") + train = "exists" + else: + model = RED(esc(f"needs FT from {NEED_FT[t][0]}")) + h = FT_TRAIN_H[NEED_FT[t][1]] * 1.15; Ca_train += h + train = RED(f"{h:.2f} GPU-h") + cols = [] + for b, key in ((0.80, "0.80"), (0.85, "0.85"), (pb, f"{pb:.2f}")): + e = ex.get(key) + matched = e and all(p == P and s == sc for p, s in e[2]) + if e and matched: + cols.append(f"{e[0]:.1f} ({e[1]})") + else: + gpuh = 9 * cell_sec(t, b) / 3600 + Ca_cells.append((t, b, cell_sec(t, b))) + note = "" + if e: + pp = ",".join(f"P{p} {s}" for p, s in sorted(e[2])) + note = " " + GREY(f"{{\\tiny [{e[0]:.1f}/{e[1]} at {pp}]}}") + cols.append(RED(f"run 50$\\to$450, {gpuh:.1f}\\,GPU-h") + note) + rowsC.append(f"{SHORT[t]} & P{P} {sc} & {model} & {train} & " + " & ".join(cols) + r" \\") +CaN = len(Ca_cells) * 9 +Ca_gpuh = sum(9 * s for _, _, s in Ca_cells) / 3600 +CaN50 = len(Ca_cells) +Ca_gpuh50 = sum(s for _, _, s in Ca_cells) / 3600 +nodesCa, wallCa = lpt([s for _, _, s in Ca_cells for _ in range(9)] + [FT_TRAIN_H[NEED_FT[t][1]] * 1.15 * 3600 for t in NEED_FT]) +B["C-a $\\beta$ 0.80/0.85 (+FT model at paper $\\beta$), 3 fine-tunes"] = dict( + cells=CaN, gpuh=Ca_gpuh + Ca_train, nodes=nodesCa, wall=wallCa, note=f"incl. {Ca_train:.1f} GPU-h training") + +# ---------------- Table C(b): Mug union IDQL ---------------- +idql = cov["arms"]["main"]["mug_expert_suboptimal"] +idql_cells = [c for c in plan["cells"] if c["arm"] == "main" and c["task"].startswith("mug")] +idql_top = [c for c in idql_cells if c["key"] != "0|0"] +iN, iW = lpt([c["est_s"] for c in idql_top]) +B["C-b Mug union-IDQL (S0Aidql@5000), n=50 slice"] = dict(cells=plan50i["n_cells"], gpuh=plan50i["gpu_hours"], + nodes=plan50i["n_nodes"], wall=plan50i["wall_h"]) +B["C-b Mug union-IDQL, top-up 50$\\to$450"] = dict(cells=len(idql_top), gpuh=sum(c["est_s"] for c in idql_top) / 3600, + nodes=iN, wall=iW) + +# ---------------- Table D: rise_repro ---------------- +def g(k, s): + m = re.search(r"'%s': '?([^,'}]+)" % k, str(s)); return m.group(1) if m else None + + +rowsD, D_cells = [], [] +for t in TASKS: + rs = [J(f"runs_repro/{t}/eval/rsm_es{e}.json") for e in range(3)] + n = sum(d["num_episodes"] for d in rs); s = sum(d["num_episodes"] * d["success_rate"] for d in rs) + sc = str(rs[0]["scorer"]); pr = str(rs[0]["proposer"]); pl = str(rs[0]["planner"]) + rb = float(g("beta", sc)); P = g("n_particles", sc); kind = g("score_kind", sc); fl = g("flow_steps", sc) + N = g("n", pl); ck = g("ckpt", sc).split("/rsm/")[-1]; step = g("step", sc) + walls = [d["wall_time_s"] for d in rs if not d.get("resumed_from_episode")] or [rs[0]["wall_time_s"]] + w = sorted(walls)[len(walls) // 2] + a, k = arm_of(t)["wall_fit"] + scale = lambda h: (a + k * h) / (a + k * hops(rb)) + setting = f"{g('family', pr)}@{g('epoch', pr)} s{g('train_seed', pr)}; {ck}@{step}; P{P} {kind} F{fl}; N{N}" + cols = [] + for b in BETAS: + if abs(float(b) - rb) < 1e-9: + cols.append(r"\textbf{" + f"{100 * s / n:.1f} ({n})" + "}") + else: + d1 = b == "0.99"; sec = w * scale(1.0 if d1 else hops(float(b))) * 1.15 + D_cells += [(t, b, sec)] * 3 + cols.append(RED(f"run 150")) + cb = arm_of(t)["control"]["beta"]; sec = w * scale(1.0) * 1.15; D_cells += [(t, "ctl", sec)] * 3 + cols.append(RED("run 150") + f" {{\\tiny @{cb:.2f}}}") + extra = "" + if t.startswith("mug"): + tun = {} + for bb, tag in (("0.90", "b0p9_ch73"), ("0.95", "b0p95_ch33"), ("0.98", "b0p98_ch11")): + fs = glob.glob(f"{R}/runs_repro/{t}/eval_tuning/S0Aidql_e5000/rsm_{tag}_p8_logit_f8_es*.json") + if fs: + ds = [json.load(open(f)) for f in fs] + tun[bb] = (100 * sum(d["num_episodes"] * d["success_rate"] for d in ds) / sum(d["num_episodes"] for d in ds), + sum(d["num_episodes"] for d in ds)) + if tun: + extra = GREY(r"{\tiny tuning seeds 100--102: " + ", ".join(f"{k} {v[0]:.1f}/{v[1]}" for k, v in tun.items()) + "}") + rowsD.append(f"{SHORT[t]} & {{\\scriptsize {esc(setting)}}} & " + " & ".join(cols) + r" \\" + + (f"\n & \\multicolumn{{8}}{{l}}{{{extra}}} \\\\" if extra else "")) +dN, dW = lpt([s for _, _, s in D_cells]) +B["D rise\\_repro-settings sweep (1 p-seed x 3 e-seeds x 50)"] = dict(cells=len(D_cells), + gpuh=sum(s for _, _, s in D_cells) / 3600, nodes=dN, wall=dW) +fresh = [c for c in planf["cells"] if not (c["arm"] == "main" and c["task"].startswith("mug"))] +fN, fW = lpt([c["est_s"] for c in fresh]) +B["Opt. fresh eval seeds 3--5, main grid (winner's curse)"] = dict(cells=len(fresh), gpuh=sum(c["est_s"] for c in fresh) / 3600, + nodes=fN, wall=fW) + +# ---------------- launch state ---------------- +def sh(cmd): + try: return subprocess.run(cmd, shell=True, capture_output=True, text=True, timeout=60).stdout + except Exception as e: return f"({e})" + + +now = datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%d %H:%MZ") +sq = sh("squeue -u zwhong -h -o '%i|%j|%T|%M|%D|%b|%P|%R'") +mine = [l.split("|") for l in sq.splitlines() if re.search(r"rebut|rbn50|rb_|pack8", l) and "pdf2" not in l] +rb_txt = open(f"{R}/status/REBUTTAL_BETA.md").read() +m = re.search(r"^## LAUNCH.*?(?=^## |\Z)", rb_txt, re.S | re.M) +launch_sec = m.group(0) if m else None +jobids = sorted(set(re.findall(r"\b(9\d{5})\b", launch_sec))) if launch_sec else [] +idle = sh("sinfo -p gpu-mid,gpu-high -h -t idle -o '%P %D' 2>/dev/null").strip().replace("\n", "; ") + +# ---------------- write tex ---------------- +L = [] +A = L.append +A(r"""\documentclass[10pt]{article} +\usepackage[margin=0.6in,landscape]{geometry} +\usepackage{booktabs,xcolor,hyperref,amsmath,float,array} +\usepackage[T1]{fontenc} +\title{RSM $\beta$ sweep for the ICLR rebuttal (v2): OpenReview settings, coverage and budget} +\author{rsm\_rise / REBUTTAL\_PDF2 worker} +\date{built """ + now + r"""} +\begin{document}\maketitle +\section*{1. Goal and settings} +Answer the reviewers' $\beta$ question with a $\beta$ sweep of the \emph{submitted} RSM flagship, run under the OpenReview settings +\emph{exactly}, so every new point is comparable to Table~1. Show how success depends on $\beta$, including the paper's $\beta$, and +whether recursion to $\gamma$ beats a single hop. +\textbf{Code}: \texttt{freeze/rsm-rise-flagship-20261002} (tip \texttt{95842af1a}), byte-identical to the deployed eval code +(packs export \texttt{RSM\_LIBERO\_DIR=code/rsm\_libero\_freeze\_20261002}, a \texttt{git archive} of that tag; the old \texttt{code/gen\_q} link is dangling). +\textbf{``Same settings''} means: same successor-model checkpoints (Table~6: model, checkpoint step, particles $M$, read-out, flow steps), same +proposers and seeds (RISE policy S0A@5000; Thread = IDQL S0Aidql@500; \textbf{Mug = BC-expert S3H1@5000}), $N=128$ candidates on every row +(Thread too), membership head, $\gamma=0.99$, chain cap = the submission's $10^{-3}$ tail cap ($\beta$: 0.90$\to$73, 0.93$\to$48, +0.95$\to$33, 0.97$\to$19, 0.98$\to$11), \textbf{no hop-count QC filter}, and the same eval seeds 0--2 $\times$ proposer seeds 0--2 +$\times$ 50 = 450 episodes. Only $\beta$ (and the cap it implies) changes. $\beta=0.99=\gamma$ gives continuation $p=0$, which is the +single-hop (d1) estimator. Order: the n=50 slice (proposer seed 0 $\times$ eval seed 0) first, then the top-up to 450. +""") +A(r"""\section*{2. Table A: the anchor we must reproduce} +\begin{table}[H]\centering\scriptsize +\begin{tabular}{l c c c c l l}\toprule +Task & Paper T1 RSM & Paper $\beta$ (T6) & Our re-read (eps) & match & matched recipe (canonical loader) & proposer \\\midrule +""" + "\n".join(rowsA) + r""" +\bottomrule\end{tabular} +\caption{Paper Table~1 RSM column vs.\ our re-read of the same cell (\texttt{verdict\_table.cells}, hop QC off, +\texttt{status/rebuttal\_beta\_coverage.json}). """ + (r"All 7 match to 0.1 pt." if not mism else RED("MISMATCH on " + ", ".join(SHORT[t] for t, _, _ in mism))) + r""" +Mug matches only without the hop QC: one paper cell (S3H1 seed 2 $\times$ eval seed 0) has hops\_rel\_err 0.092 and the QC would drop it. +The submission did not apply that QC, and the owner's ruling is no QC.}\end{table} +""") +A(r"""\section*{3. Table B (MAIN): OpenReview-settings $\beta$ sweep} +\begin{table}[H]\centering\scriptsize\setlength{\tabcolsep}{3pt} +\begin{tabular}{l c ccccccc}\toprule +Task & Paper ($\beta$) & $\beta$=0.90 & $\beta$=0.93 & $\beta$=0.95 & $\beta$=0.97 & $\beta$=0.98 & $\beta$=0.99 (1 hop) & No recursion (d1) \\\midrule +""" + "\n".join(rowsB) + r""" +\bottomrule\end{tabular} +\caption{Success \% (episodes). \textbf{Legend:} black = exists at the full 450 episodes; {\tiny[50: x]} = the same point restricted to the n=50 slice +(proposer seed 0 $\times$ eval seed 0, \texttt{status/rebuttal\_beta\_n50.json}); \textcolor{red}{red} = to run, n=50 slice now, then top-up to 450; +bold$^{\star}$ = the paper's $\beta$ (Table~6). d1 = one hop at the $\beta$ shown, no recursion. Its $\beta$ is the best existing small $\beta\le0.95$. +The Piece (Cov.) control has 1000 episodes because extra seeds exist. +Mug row = BC-expert S3H1 proposer (paper flagship). +""" + f"Main grid to run: {len(main_cells)} cells = {len(main_cells) * 50} episodes " + f"({', '.join(SHORT[t] + ' ' + str(per_task_main[t]) for t in TASKS)}); none needs training." + r"""}\end{table} +""") +A(r"""\clearpage\section*{4. Lower priority (after the main grid)} +\subsection*{Table C(a): $\beta$ 0.80 and 0.85 (low-$\beta$ successor models)} +The submission models are trained on $\beta\sim U[0.90,0.995]$, so $\beta<0.90$ is out of their training range. The precedent +is the \texttt{*\_ftb80} fine-tunes (\texttt{scripts/q275\_make\_finetune.py}). The recipe copies the pinned paper checkpoint and continues +\texttt{train\_rsm.py --resume} for +20k steps with every fit knob read from the parent's config, changing only \texttt{--beta-lo} 0.90$\to$0.80. +Each fine-tune measured 0.56\,h (M) and 0.67\,h (L40) of wall time on one H100 (W\&B runtime, 2026-09-24). They are evaluated at \texttt{ckpt.pt}/\texttt{ckpt\_s}. +\emph{Never use their \texttt{ckpt\_best.pt}}, because it is selected inside the eval block at \texttt{beta\_q}. +\textbf{Have a model:} Square (Sub.), Piece (Sub.), Piece (Cov.), Mug. \textbf{Need one:} Square (Cov.), Thread, Piece-tip (3 fine-tunes). +Caveat (q275 run 30/31): the fine-tune itself shifts success. On Piece (Cov.) the FT model scores 38.0 at $\beta$=0.98 vs.\ 48.7 native, with a +$\beta$-dependent tilt. So the 0.80/0.85 points must be read \emph{within} the FT model's series. The plan therefore also evaluates +the FT model at the paper $\beta$ (last column), which is the bridge to Table~B. +\begin{table}[H]\centering\scriptsize\setlength{\tabcolsep}{3pt} +\begin{tabular}{l c l c p{3.7cm} p{3.7cm} p{3.7cm}}\toprule +Task & read-out & low-$\beta$ model & FT training & $\beta$=0.80 (cap 168) & $\beta$=0.85 (cap 118) & FT model at paper $\beta$ \\\midrule +""" + "\n".join(rowsC) + r""" +\bottomrule\end{tabular} +\caption{Black = exists at OpenReview settings on the FT model (450 eps). \textcolor{red}{Red} = to run (9 cells = 450 eps; GPU-h from the task's +wall fit $a+b\,E[\mathrm{hops}]$, +15\%). """ + GREY("Grey") + r""" = an existing FT cell at a \emph{different} read-out ($P$/score). It is shown for reference and does +not count. """ + f"Block total: {CaN} cells ({CaN50} at n=50 first), {Ca_gpuh:.1f} GPU-h eval + {Ca_train:.1f} GPU-h training." + r"""}\end{table} +\subsection*{Table C(b): Mug with the union IDQL proposer (S0Aidql@5000)} +\begin{table}[H]\centering\scriptsize\setlength{\tabcolsep}{3pt} +\begin{tabular}{l ccccccc}\toprule +Proposer & 0.90 & 0.93 & 0.95 & 0.97 & 0.98 & 0.99 (1 hop) & d1 @0.90 \\\midrule +Mug S0Aidql@5000 union (seeds 0,1,2 on disk) & """ + " & ".join([RED("run 50$\\to$450")] * 7) + r""" \\ +\bottomrule\end{tabular} +\caption{Same RSM (M\_s1@best 75k, P16 logit) as the paper mug row, with only the proposer swapped. """ + + f"{plan50i['n_cells']} cells at n=50 ({plan50i['gpu_hours']:.1f} GPU-h), then {len(idql_top)} more for 450 ({sum(c['est_s'] for c in idql_top) / 3600:.1f} GPU-h). " + + r"""No matched cells exist. Context on the same proposers: RISE critic (S3H4) 5.6\% (25/450), bare BC 6.7\% (20/300), rise\_repro's RSM 5.3\% (8/150). +Expect the row to sit near 5\%. Seeds 1 and 2 are train.seed=1 replicas.}\end{table} +""") +A(r"""\subsection*{Table D: the same sweep under the rise\_repro settings (existing rise\_repro checkpoints, nothing to train)} +\begin{table}[H]\centering\scriptsize\setlength{\tabcolsep}{3pt} +\begin{tabular}{l p{6.2cm} ccccccc}\toprule +Task & rise\_repro setting (proposer; RSM ckpt; read-out; N) & 0.90 & 0.93 & 0.95 & 0.97 & 0.98 & 0.99 (1 hop) & d1 \\\midrule +""" + "\n".join(rowsD) + r""" +\bottomrule\end{tabular} +\caption{rise\_repro protocol: \texttt{runs\_repro//\{rsm,hop,policy\}}, configs \texttt{configs//rsm.yaml} on branch \texttt{rise\_repro}, +1 proposer train seed (0) $\times$ eval seeds 0--2 $\times$ 50 = 150 eps per point. Black bold = the existing reported cell at the config's $\beta$ +(\texttt{runs\_repro//eval/rsm\_es\{0,1,2\}.json}). The ckpt column is read from those JSONs (\texttt{ckpt\_best} steps differ from the paper's). +Thread uses the config's $N=16$ (the repro N128 arm scored 9.3). \textcolor{red}{Red} = to run (3 cells each). +GPU-h = the measured rise\_repro wall per 50 eps at the config $\beta$, scaled by the task's $a+b\,E[\mathrm{hops}]$ fit, +15\%. +""" + f"Block: {len(D_cells)} cells, {sum(s for _, _, s in D_cells) / 3600:.1f} GPU-h." + r""" +Needs a small config generator for $\beta$/cap/d1 variants of each \texttt{rsm.yaml}. Check that \texttt{rsmrise} supports the d1 (one-hop) mode before launch.}\end{table} +""") +rows = [] +tot = [0, 0, 0.0] +for k, v in B.items(): + eps = v["cells"] * 50; tot[0] += v["cells"]; tot[1] += eps; tot[2] += v["gpuh"] + rows.append(f"{k} & {v['cells']} & {eps} & {v['gpuh']:.1f} & {v['nodes']} & {v['wall']:.1f} & {v.get('note', '')} \\\\") +A(r"""\clearpage\section*{5. Budget} +\begin{table}[H]\centering\scriptsize +\begin{tabular}{l r r r r r l}\toprule +Block & cells & episodes & GPU-h & 8-GPU nodes & wall (h, once started) & note \\\midrule +""" + "\n".join(rows) + r"""\midrule +""" + f"Total (all blocks incl. optional) & {tot[0]} & {tot[1]} & {tot[2]:.1f} & & & \\\\" + "\n" + + f"Main grid only (B1+B2) & {B[list(B)[0]]['cells'] + B[list(B)[1]]['cells']} & {(B[list(B)[0]]['cells'] + B[list(B)[1]]['cells']) * 50} & " + f"{B[list(B)[0]]['gpuh'] + B[list(B)[1]]['gpuh']:.1f} & & & \\\\" + r""" +\bottomrule\end{tabular} +\caption{One cell = 1 proposer seed $\times$ 1 eval seed $\times$ 50 episodes, horizon 400. B1/C-b n=50 rows come from the launch worker's plans +(\texttt{plan\_n50\_*.json}). The other rows are LPT-packed estimates over whole 8-GPU nodes, using the fewest nodes with makespan $\le$4\,h. +Everything is packed 8 payloads per node (no 1-GPU jobs). The fine-tunes ride inside the C-a nodes.}\end{table} +""") +A(r"\subsection*{Capacity snapshot (" + esc(cap["stamp"]) + r")}" + "\n" + cap["tex"] + "\n") +ls_rows = "\n".join(f"{esc(x[0])} & {esc(x[1])} & {x[2]} & {x[3]} & {x[4]} & {esc(x[6])} & {esc(x[7])} \\\\" for x in mine) or \ + r"\multicolumn{7}{l}{(no rebuttal/pack job in squeue at build time)} \\" +A(r"""\subsection*{Current launch state (built """ + now + r""")} +""" + (r"REBUTTAL\_BETA.md \texttt{\#\# LAUNCH} section: job ids " + ", ".join(jobids) + "." if launch_sec else + r"REBUTTAL\_BETA.md has \textbf{no} \texttt{\#\# LAUNCH} section yet. The launch worker (REBUTTAL\_BETA\_LAUNCH) is still preparing the n=50 slice.") + r""" +\begin{table}[H]\centering\scriptsize +\begin{tabular}{l l l l l l l}\toprule +job & name & state & time & nodes & partition & reason/node \\\midrule +""" + ls_rows + r""" +\bottomrule\end{tabular}\caption{\texttt{squeue -u zwhong}, rows matching rebuttal/pack names. Idle GPU nodes now (sinfo): """ + esc(idle or "n/a") + r""".}\end{table} +""") +A(r"""\section*{6. Notes} +\begin{enumerate}\setlength\itemsep{1pt} +\item \textbf{What n=50 can resolve.} The SE of one 50-episode point is $\sqrt{p(1-p)/50}$, i.e.\ 7.1\,pt at $p$=0.5, 5.7\,pt at 0.2 and 3.7\,pt at 0.07 +(95\% CI about $\pm$14\,pt). The slice only catches gross effects ($\geq$15--20\,pt, e.g.\ a collapse of the 1-hop point) and checks that the runs execute. Existing points show +the noise directly. Square (Sub.) at $\beta$=0.98 is 64 on the slice vs.\ 54.0 at 450, and Mug at 0.98 is 12 vs.\ 23.1. +At 450 episodes the SE is 2.4\,pt at $p$=0.5. Rank betas only on the full 450. +\item \textbf{Eval-seed CRN.} Every $\beta$ uses the same eval seeds and proposer checkpoints. Within a (proposer seed, eval seed) cell the initial states are identical +across $\beta$, so $\beta$ contrasts are paired: compare per-cell differences, not two independent CIs. The candidate noise is identical only until the rollouts diverge. +\item \textbf{Winner's curse.} Each paper $\beta$ was the max over 20--30 arms on the same 450 reported episodes. On those episodes it is biased upward +relative to the new points. Fresh eval seeds 3--5 remove this (optional row in the budget). \textbf{Owner decision still open.} +\item \textbf{Low $\beta$ needs a different model.} The 0.80/0.85 points come from the fine-tuned models. Report them within the FT series (FT at paper $\beta$ as the bridge), +not spliced onto Table~B. Piece (Sub.) FT cells exist only at P16 (paper P8), so the matched cells must be re-run. +\item \textbf{rise\_repro block.} Each point uses 1 proposer seed (150 eps), with checkpoints selected by its own rule. It shows robustness of the $\beta$ trend, not a Table~1 comparison. +\item \textbf{Decided (2026-11-08):} OpenReview settings, freeze code, Mug = BC-expert S3H1, Thread $N$=128, no hop QC, same eval seeds, n=50 slice first. +\end{enumerate} +\end{document} +""") +os.makedirs(os.path.dirname(OUT), exist_ok=True) +open(OUT, "w").write("\n".join(L)) +summary = dict(built=now, tableA_mismatch=mism, budget={k: v for k, v in B.items()}, + main_cells=len(main_cells), main_per_task=dict(per_task_main), Ca_cells=CaN, Ca_train_gpuh=Ca_train, + D_cells=len(D_cells), launch_section=bool(launch_sec), launch_jobids=jobids, squeue_rows=mine) +json.dump(summary, open(f"{R}/docs/rebuttal/beta_sweep_plan_v2.summary.json", "w"), indent=1, default=str) +print(json.dumps(summary, indent=1, default=str)) diff --git a/rsm_rise/scripts/rebuttal_beta_table150.py b/rsm_rise/scripts/rebuttal_beta_table150.py new file mode 100644 index 0000000000000000000000000000000000000000..fa6fab30277fbf27a15f6461c8d751a22fcfb106 --- /dev/null +++ b/rsm_rise/scripts/rebuttal_beta_table150.py @@ -0,0 +1,206 @@ +#!/usr/bin/env python3 +"""Primary reviewer table (owner 2026-11-08 07:25Z): ONE proposer checkpoint (existing seed-0 policy) x eval seeds 0,1,2 +x 50 episodes = 150 episodes per beta, every beta (paper beta + existing cells included) re-read on exactly those episodes. +Submission settings (BF.SPEC: paper RSM ckpt, paper proposer, N=128, chain cap 1e-3 tail, gamma 0.99). No hop QC. + +Per (task, beta) and per eval seed: ONE file (n>=50, first 50 episodes, files sorted by name, so repeats of the same +CRN seed are never double counted). Paired bootstrap over the 150 (eval seed, episode) indices, shared across betas +(CRN), B=10000: mean +- 95% percentile CI per beta, P(argmax is interior), paired differences best vs endpoints. +Endpoints: beta 0.90 (smallest in the trained band, most hops) and 0.99 (= gamma: single hop, no recursion). +Out: status/rebuttal_beta_table150.{md,pdf,json} +""" +import json, os, sys +from pathlib import Path +import numpy as np + +ROOT = Path("/proj/dmfexp/zwhong/rsm_rise") +sys.path.insert(0, str(ROOT / "scripts")) +os.environ["RSM_EXTRA_EPOCHS"] = "500" +import rebuttal_beta_coverage as RB +BF, VT, PB = RB.BF, RB.VT, RB.PB + +ESEEDS = ["0", "1", "2"] +PSEED = "0" +B = 10000 +LO_END, HI_END = 0.90, 0.99 +rng = np.random.default_rng(0) + + +def pick(g, beta, is_chain): + """-> (episodes[150] or None, files used, per-seed n, duplicates ignored)""" + eps, used, nseed, dups = [], [], {}, 0 + for e in ESEEDS: + fs = sorted([f for f in (g["files"] if g else []) if f["pseed"] == PSEED and f["eseed"] == e and f["n"] >= 50], + key=lambda f: f["file"]) + nseed[e] = 0 + if not fs: + continue + dups += len(fs) - 1 + ok, why, n, s = PB.file_check(fs[0]["file"], beta, is_chain) + s = [int(bool(x)) for x in s][:50] + nseed[e] = len(s); eps += s; used.append(fs[0]["file"]) + return (np.array(eps) if len(eps) == 150 else None), used, nseed, dups + + +def main(): + out = dict(rule="proposer seed 0 x eval seeds 0,1,2 x 50 eps = 150 per beta; one file per eval seed; no hop QC; " + "paired bootstrap over episodes (CRN), B=10000, 95% percentile CI", tasks={}) + md = ["# Reviewer beta table (150 episodes per cell)", "", + "One proposer checkpoint (seed 0) x eval seeds 0,1,2 x 50 episodes = 150 episodes per beta. Every beta is read on " + "the same 150 episodes (eval seed = initial conditions + candidate noise, shared across betas). Submission " + "settings: paper RSM and proposer checkpoints, N=128, gamma 0.99, chain read-out with the 1e-3 tail cap, no hop QC. " + "beta 0.99 = gamma, so the read-out is a single hop with no recursion. The d1 control is a single-hop read-out " + "at a small beta (no recursion). The CI is a 95% paired bootstrap over episodes. " + "**Bold** = best beta. The paper Table 1 value (450 episodes = 3 proposer x 3 eval seeds) is a superset average, " + "shown for reference.", ""] + betas = list(BF.BETAS) + hdr = "| task | " + " | ".join(f"{b:.2f}" + (" (1 hop)" if abs(b - HI_END) < 1e-9 else "") for b in betas) + \ + " | d1 control | Table 1 (450 ep) | verdict |" + md += [hdr, "|" + "---|" * (len(betas) + 4)] + for task, sp in BF.SPEC.items(): + cs = VT.cells(task); files = dict(VT.CELL_FILES) + groups = RB.arm_groups(task, sp, cs, files) + T = dict(label=sp["label"], proposer=sp["prop"], paper=sp.get("paper"), paper_beta=sp["beta"], points={}, + controls={}, missing=[]) + arr = {} + for b in betas: + kind = "matched_d1" if abs(b - BF.GAMMA) < 1e-9 else "matched_chain" + g = [x for x in groups.values() if x["kind"] == kind and abs(x["beta"] - b) < 1e-9] + x, used, nseed, dups = pick(g[0] if g else None, b, kind == "matched_chain") + T["points"][f"{b:.2f}"] = dict(kind=kind, n=int(sum(nseed.values())), n_per_eseed=nseed, files=used, + duplicates_ignored=dups) + if x is None: + T["missing"].append(f"{b:.2f}") + else: + arr[b] = x + for g in groups.values(): + if g["kind"] == "matched_d1" and g["beta"] < BF.GAMMA - 1e-9: + x, used, nseed, dups = pick(g, g["beta"], False) + c = dict(n=int(sum(nseed.values())), n_per_eseed=nseed, files=used) + if x is not None: + c["mean"] = float(x.mean()) + idx = rng.integers(0, 150, size=(B, 150)) + bs = x[idx].mean(1); c["ci"] = [float(np.percentile(bs, 2.5)), float(np.percentile(bs, 97.5))] + arr[f"d1@{g['beta']:.2f}"] = x + T["controls"][f"{g['beta']:.2f}"] = c + # paired bootstrap over the shared 150 episode indices + idx = rng.integers(0, 150, size=(B, 150)) + boot = {k: v[idx].mean(1) for k, v in arr.items()} + for b in betas: + p = T["points"][f"{b:.2f}"] + if b in arr: + p["mean"] = float(arr[b].mean()) + p["ci"] = [float(np.percentile(boot[b], 2.5)), float(np.percentile(boot[b], 97.5))] + curve = [b for b in betas if b in arr] + verdict = "INCOMPLETE (missing " + ", ".join(T["missing"]) + ")" if T["missing"] else None + if curve: + means = np.array([arr[b].mean() for b in curve]) + best = curve[int(np.argmax(means))] + ties = [b for b, m in zip(curve, means) if abs(m - means.max()) < 1e-12] + M = np.stack([boot[b] for b in curve], 1) + am = np.array(curve)[np.argmax(M, 1)] + interior = [b for b in curve if LO_END + 1e-9 < b < HI_END - 1e-9] + T.update(best=best, ties=ties, p_argmax_interior=float(np.isin(am, interior).mean()), + p_argmax={f"{b:.2f}": float((am == b).mean()) for b in curve}) + d = {} + for e in (LO_END, HI_END): + if e in arr and e != best: + db = boot[best] - boot[e] + d[f"{e:.2f}"] = dict(diff=float(arr[best].mean() - arr[e].mean()), + ci=[float(np.percentile(db, 2.5)), float(np.percentile(db, 97.5))]) + T["best_minus_endpoint"] = d + if verdict is None: + if best in (LO_END, HI_END): + verdict = f"endpoint optimum at {best:.2f}" + (" (single hop)" if best == HI_END else " (most hops)") + else: + sig = [k for k, v in d.items() if v["ci"][0] > 0] + verdict = (f"interior optimum at {best:.2f}; vs 0.90 {100*d['0.90']['diff']:+.1f} " + f"[{100*d['0.90']['ci'][0]:+.1f},{100*d['0.90']['ci'][1]:+.1f}], vs 0.99 " + f"{100*d['0.99']['diff']:+.1f} [{100*d['0.99']['ci'][0]:+.1f},{100*d['0.99']['ci'][1]:+.1f}]; " + f"P(argmax interior)={T['p_argmax_interior']:.2f}" + + ("" if sig else "; not separated from either endpoint at 95%")) + T["verdict"] = verdict + out["tasks"][task] = T + cells = [] + for b in betas: + p = T["points"][f"{b:.2f}"] + if "mean" not in p: + cells.append(f"missing (n={p['n']})") + continue + s = f"{100*p['mean']:.1f} [{100*p['ci'][0]:.1f},{100*p['ci'][1]:.1f}]" + if T.get("ties") and b in T["ties"]: + s = f"**{s}**" + if abs(b - sp["beta"]) < 1e-9: + s += " (paper beta)" + cells.append(s) + ctl = "; ".join(f"@{k}: " + (f"{100*c['mean']:.1f} [{100*c['ci'][0]:.1f},{100*c['ci'][1]:.1f}]" if "mean" in c + else f"missing (n={c['n']})") for k, c in sorted(T["controls"].items())) or "none" + md.append(f"| {sp['label']} | " + " | ".join(cells) + f" | {ctl} | {sp.get('paper')} @{sp['beta']} | {verdict} |") + print(task, {k: (round(100 * v["mean"], 1) if "mean" in v else None) for k, v in T["points"].items()}, verdict, flush=True) + (ROOT / "status/rebuttal_beta_table150.md").write_text("\n".join(md) + "\n") + json.dump(out, open(ROOT / "status/rebuttal_beta_table150.json", "w"), indent=1, default=float) + render_pdf(out, betas) + print("wrote status/rebuttal_beta_table150.{md,json,pdf}") + + +def render_pdf(out, betas): + import matplotlib + matplotlib.use("Agg") + import matplotlib.pyplot as plt + from matplotlib.backends.backend_pdf import PdfPages + with PdfPages(ROOT / "status/rebuttal_beta_table150.pdf") as pdf: + tasks = list(out["tasks"].items()) + fig, ax = plt.subplots(figsize=(17, 1.2 + 0.75 * len(tasks))); ax.axis("off") + cols = [f"{b:.2f}" + ("\n(1 hop)" if abs(b - HI_END) < 1e-9 else "") for b in betas] + ["d1 ctrl", "Tab.1 (450)"] + rows, colors, labels = [], [], [] + for t, T in tasks: + r, c = [], [] + for b in betas: + p = T["points"][f"{b:.2f}"] + if "mean" in p: + r.append(f"{100*p['mean']:.1f}\n[{100*p['ci'][0]:.0f},{100*p['ci'][1]:.0f}]" + + ("*" if abs(b - T["paper_beta"]) < 1e-9 else "")) + c.append("#c8e6c9" if b in (T.get("ties") or []) else "w") + else: + r.append("missing"); c.append("#ffcdd2") + cc = [f"@{k}: {100*v['mean']:.1f}" for k, v in sorted(T["controls"].items()) if "mean" in v] + r += ["\n".join(cc) or "-", f"{T['paper']} @{T['paper_beta']}"]; c += ["w", "w"] + rows.append(r); colors.append(c); labels.append(T["label"]) + tb = ax.table(cellText=rows, cellColours=colors, rowLabels=labels, colLabels=cols, loc="center", cellLoc="center") + tb.auto_set_font_size(False); tb.set_fontsize(8); tb.scale(1, 2.6) + for (i, j), cell in tb.get_celld().items(): + if i > 0 and 0 <= j < len(betas) and colors[i - 1][j] == "#c8e6c9": + cell.get_text().set_fontweight("bold") + ax.set_title("RSM success % vs beta, 150 episodes per cell (proposer seed 0 x eval seeds 0-2 x 50), paired bootstrap " + "95% CI.\nGreen/bold = best; * = paper beta; Table 1 = 450-episode superset average; red = missing.", + fontsize=10) + pdf.savefig(fig, bbox_inches="tight"); plt.close(fig) + fig = plt.figure(figsize=(17, 1 + 0.45 * len(tasks))); fig.text(0.01, 0.98, "Verdicts", va="top", fontsize=11, + weight="bold") + for i, (t, T) in enumerate(tasks): + fig.text(0.01, 0.92 - i * 0.8 / len(tasks), f"{T['label']}: {T['verdict']}", va="top", fontsize=9) + pdf.savefig(fig); plt.close(fig) + nc = 4; nr = -(-len(tasks) // nc) + fig, axes = plt.subplots(nr, nc, figsize=(4.2 * nc, 3.3 * nr), squeeze=False) + for ax, (t, T) in zip(axes.flat, tasks): + pts = [(b, T["points"][f"{b:.2f}"]) for b in betas if "mean" in T["points"][f"{b:.2f}"]] + if pts: + x = [b for b, _ in pts]; y = [100 * p["mean"] for _, p in pts] + lo = [100 * (p["mean"] - p["ci"][0]) for _, p in pts]; hi = [100 * (p["ci"][1] - p["mean"]) for _, p in pts] + ax.errorbar(x, y, yerr=[lo, hi], fmt="-o", capsize=3, label="chain (0.99 = 1 hop), n=150") + for k, c in T["controls"].items(): + if "mean" in c: + ax.plot([float(k)], [100 * c["mean"]], "s", color="C3", label=f"d1 control @{k}") + if T["paper"] is not None: + ax.plot([T["paper_beta"]], [T["paper"]], "*", ms=13, color="gold", mec="k", label="Table 1 (n=450)") + ax.set_title(T["label"] + (f"\nmissing {T['missing']}" if T["missing"] else ""), fontsize=9, + color="red" if T["missing"] else "k") + ax.set_xticks(betas); ax.tick_params(labelsize=7); ax.grid(alpha=0.3); ax.legend(fontsize=6) + ax.set_xlabel(r"$\beta$"); ax.set_ylabel("success %") + for ax in list(axes.flat)[len(tasks):]: + ax.axis("off") + fig.tight_layout(); pdf.savefig(fig); plt.close(fig) + + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/rebuttal_beta_table450.py b/rsm_rise/scripts/rebuttal_beta_table450.py new file mode 100644 index 0000000000000000000000000000000000000000..73dcba3f8d0c4c8870619daecb62e5e796d9c351 --- /dev/null +++ b/rsm_rise/scripts/rebuttal_beta_table450.py @@ -0,0 +1,208 @@ +#!/usr/bin/env python3 +"""Appendix reviewer table (orchestrator 2026-11-08 12:40Z): 3 proposer checkpoints (seeds 0,1,2) x eval seeds 0,1,2 +x 50 episodes = 450 episodes per beta (the Table 1 protocol). Generalised copy of rebuttal_beta_table150.py. +Submission settings (BF.SPEC: paper RSM ckpt, paper proposer, N=128, chain cap 1e-3 tail, gamma 0.99). No hop QC. + +Per (task, beta) and per (proposer seed, eval seed): ONE file (n>=50, first 50 episodes, files sorted by name, so repeats of the same +CRN seed are never double counted). Paired bootstrap over the 450 (proposer seed, eval seed, episode) indices, shared across betas +(CRN), B=10000: mean +- 95% percentile CI per beta, P(argmax is interior), paired differences best vs endpoints. +Endpoints: beta 0.90 (smallest in the trained band, most hops) and 0.99 (= gamma: single hop, no recursion). +Out: status/rebuttal_beta_table450.{md,pdf,json} +""" +import json, os, sys +from pathlib import Path +import numpy as np + +ROOT = Path("/proj/dmfexp/zwhong/rsm_rise") +sys.path.insert(0, str(ROOT / "scripts")) +os.environ["RSM_EXTRA_EPOCHS"] = "500" +import rebuttal_beta_coverage as RB +BF, VT, PB = RB.BF, RB.VT, RB.PB + +ESEEDS = ["0", "1", "2"] +PSEEDS = ["0", "1", "2"] +NEP = 50 * len(ESEEDS) * len(PSEEDS) # 450 +B = 10000 +LO_END, HI_END = 0.90, 0.99 +rng = np.random.default_rng(0) + + +def pick(g, beta, is_chain): + """-> (episodes[NEP] or None, files used, per-seed n, duplicates ignored)""" + eps, used, nseed, dups = [], [], {}, 0 + for ps, e in [(ps, e) for ps in PSEEDS for e in ESEEDS]: + fs = sorted([f for f in (g["files"] if g else []) if f["pseed"] == ps and f["eseed"] == e and f["n"] >= 50], + key=lambda f: f["file"]) + e = f"p{ps}e{e}" + nseed[e] = 0 + if not fs: + continue + dups += len(fs) - 1 + ok, why, n, s = PB.file_check(fs[0]["file"], beta, is_chain) + s = [int(bool(x)) for x in s][:50] + nseed[e] = len(s); eps += s; used.append(fs[0]["file"]) + return (np.array(eps) if len(eps) == NEP else None), used, nseed, dups + + +def main(): + out = dict(rule="proposer seeds 0,1,2 x eval seeds 0,1,2 x 50 eps = 450 per beta; one file per (proposer, eval) seed; no hop QC; " + "paired bootstrap over episodes (CRN), B=10000, 95% percentile CI", tasks={}) + md = ["# Reviewer beta table, appendix (450 episodes per cell)", "", + "Three proposer checkpoints (seeds 0,1,2) x eval seeds 0,1,2 x 50 episodes = 450 episodes per beta (the Table 1 protocol). Every beta is read on " + "the same 450 episodes (eval seed = initial conditions + candidate noise, shared across betas). Submission " + "settings: paper RSM and proposer checkpoints, N=128, gamma 0.99, chain read-out with the 1e-3 tail cap, no hop QC. " + "beta 0.99 = gamma, so the read-out is a single hop with no recursion. The d1 control is a single-hop read-out " + "at a small beta (no recursion). The CI is a 95% paired bootstrap over episodes. " + "**Bold** = best beta. The paper Table 1 value (450 episodes) is shown for reference; at the paper beta it should " + "reproduce up to cell/file selection.", ""] + betas = list(BF.BETAS) + hdr = "| task | " + " | ".join(f"{b:.2f}" + (" (1 hop)" if abs(b - HI_END) < 1e-9 else "") for b in betas) + \ + " | d1 control | Table 1 (450 ep) | verdict |" + md += [hdr, "|" + "---|" * (len(betas) + 4)] + for task, sp in BF.SPEC.items(): + cs = VT.cells(task); files = dict(VT.CELL_FILES) + groups = RB.arm_groups(task, sp, cs, files) + T = dict(label=sp["label"], proposer=sp["prop"], paper=sp.get("paper"), paper_beta=sp["beta"], points={}, + controls={}, missing=[]) + arr = {} + for b in betas: + kind = "matched_d1" if abs(b - BF.GAMMA) < 1e-9 else "matched_chain" + g = [x for x in groups.values() if x["kind"] == kind and abs(x["beta"] - b) < 1e-9] + x, used, nseed, dups = pick(g[0] if g else None, b, kind == "matched_chain") + T["points"][f"{b:.2f}"] = dict(kind=kind, n=int(sum(nseed.values())), n_per_eseed=nseed, files=used, + duplicates_ignored=dups) + if x is None: + T["missing"].append(f"{b:.2f}") + else: + arr[b] = x + for g in groups.values(): + if g["kind"] == "matched_d1" and g["beta"] < BF.GAMMA - 1e-9: + x, used, nseed, dups = pick(g, g["beta"], False) + c = dict(n=int(sum(nseed.values())), n_per_eseed=nseed, files=used) + if x is not None: + c["mean"] = float(x.mean()) + idx = rng.integers(0, NEP, size=(B, NEP)) + bs = x[idx].mean(1); c["ci"] = [float(np.percentile(bs, 2.5)), float(np.percentile(bs, 97.5))] + arr[f"d1@{g['beta']:.2f}"] = x + T["controls"][f"{g['beta']:.2f}"] = c + # paired bootstrap over the shared NEP episode indices + idx = rng.integers(0, NEP, size=(B, NEP)) + boot = {k: v[idx].mean(1) for k, v in arr.items()} + for b in betas: + p = T["points"][f"{b:.2f}"] + if b in arr: + p["mean"] = float(arr[b].mean()) + p["ci"] = [float(np.percentile(boot[b], 2.5)), float(np.percentile(boot[b], 97.5))] + curve = [b for b in betas if b in arr] + verdict = "INCOMPLETE (missing " + ", ".join(T["missing"]) + ")" if T["missing"] else None + if curve: + means = np.array([arr[b].mean() for b in curve]) + best = curve[int(np.argmax(means))] + ties = [b for b, m in zip(curve, means) if abs(m - means.max()) < 1e-12] + M = np.stack([boot[b] for b in curve], 1) + am = np.array(curve)[np.argmax(M, 1)] + interior = [b for b in curve if LO_END + 1e-9 < b < HI_END - 1e-9] + T.update(best=best, ties=ties, p_argmax_interior=float(np.isin(am, interior).mean()), + p_argmax={f"{b:.2f}": float((am == b).mean()) for b in curve}) + d = {} + for e in (LO_END, HI_END): + if e in arr and e != best: + db = boot[best] - boot[e] + d[f"{e:.2f}"] = dict(diff=float(arr[best].mean() - arr[e].mean()), + ci=[float(np.percentile(db, 2.5)), float(np.percentile(db, 97.5))]) + T["best_minus_endpoint"] = d + if verdict is None: + if best in (LO_END, HI_END): + verdict = f"endpoint optimum at {best:.2f}" + (" (single hop)" if best == HI_END else " (most hops)") + else: + sig = [k for k, v in d.items() if v["ci"][0] > 0] + verdict = (f"interior optimum at {best:.2f}; vs 0.90 {100*d['0.90']['diff']:+.1f} " + f"[{100*d['0.90']['ci'][0]:+.1f},{100*d['0.90']['ci'][1]:+.1f}], vs 0.99 " + f"{100*d['0.99']['diff']:+.1f} [{100*d['0.99']['ci'][0]:+.1f},{100*d['0.99']['ci'][1]:+.1f}]; " + f"P(argmax interior)={T['p_argmax_interior']:.2f}" + + ("" if sig else "; not separated from either endpoint at 95%")) + T["verdict"] = verdict + out["tasks"][task] = T + cells = [] + for b in betas: + p = T["points"][f"{b:.2f}"] + if "mean" not in p: + cells.append(f"missing (n={p['n']})") + continue + s = f"{100*p['mean']:.1f} [{100*p['ci'][0]:.1f},{100*p['ci'][1]:.1f}]" + if T.get("ties") and b in T["ties"]: + s = f"**{s}**" + if abs(b - sp["beta"]) < 1e-9: + s += " (paper beta)" + cells.append(s) + ctl = "; ".join(f"@{k}: " + (f"{100*c['mean']:.1f} [{100*c['ci'][0]:.1f},{100*c['ci'][1]:.1f}]" if "mean" in c + else f"missing (n={c['n']})") for k, c in sorted(T["controls"].items())) or "none" + md.append(f"| {sp['label']} | " + " | ".join(cells) + f" | {ctl} | {sp.get('paper')} @{sp['beta']} | {verdict} |") + print(task, {k: (round(100 * v["mean"], 1) if "mean" in v else None) for k, v in T["points"].items()}, verdict, flush=True) + (ROOT / "status/rebuttal_beta_table450.md").write_text("\n".join(md) + "\n") + json.dump(out, open(ROOT / "status/rebuttal_beta_table450.json", "w"), indent=1, default=float) + render_pdf(out, betas) + print("wrote status/rebuttal_beta_table450.{md,json,pdf}") + + +def render_pdf(out, betas): + import matplotlib + matplotlib.use("Agg") + import matplotlib.pyplot as plt + from matplotlib.backends.backend_pdf import PdfPages + with PdfPages(ROOT / "status/rebuttal_beta_table450.pdf") as pdf: + tasks = list(out["tasks"].items()) + fig, ax = plt.subplots(figsize=(17, 1.2 + 0.75 * len(tasks))); ax.axis("off") + cols = [f"{b:.2f}" + ("\n(1 hop)" if abs(b - HI_END) < 1e-9 else "") for b in betas] + ["d1 ctrl", "Tab.1 (450)"] + rows, colors, labels = [], [], [] + for t, T in tasks: + r, c = [], [] + for b in betas: + p = T["points"][f"{b:.2f}"] + if "mean" in p: + r.append(f"{100*p['mean']:.1f}\n[{100*p['ci'][0]:.0f},{100*p['ci'][1]:.0f}]" + + ("*" if abs(b - T["paper_beta"]) < 1e-9 else "")) + c.append("#c8e6c9" if b in (T.get("ties") or []) else "w") + else: + r.append("missing"); c.append("#ffcdd2") + cc = [f"@{k}: {100*v['mean']:.1f}" for k, v in sorted(T["controls"].items()) if "mean" in v] + r += ["\n".join(cc) or "-", f"{T['paper']} @{T['paper_beta']}"]; c += ["w", "w"] + rows.append(r); colors.append(c); labels.append(T["label"]) + tb = ax.table(cellText=rows, cellColours=colors, rowLabels=labels, colLabels=cols, loc="center", cellLoc="center") + tb.auto_set_font_size(False); tb.set_fontsize(8); tb.scale(1, 2.6) + for (i, j), cell in tb.get_celld().items(): + if i > 0 and 0 <= j < len(betas) and colors[i - 1][j] == "#c8e6c9": + cell.get_text().set_fontweight("bold") + ax.set_title("RSM success % vs beta, 450 episodes per cell (proposer seeds 0-2 x eval seeds 0-2 x 50), paired bootstrap " + "95% CI.\nGreen/bold = best; * = paper beta; Table 1 = paper value (450 ep); red = missing.", + fontsize=10) + pdf.savefig(fig, bbox_inches="tight"); plt.close(fig) + fig = plt.figure(figsize=(17, 1 + 0.45 * len(tasks))); fig.text(0.01, 0.98, "Verdicts", va="top", fontsize=11, + weight="bold") + for i, (t, T) in enumerate(tasks): + fig.text(0.01, 0.92 - i * 0.8 / len(tasks), f"{T['label']}: {T['verdict']}", va="top", fontsize=9) + pdf.savefig(fig); plt.close(fig) + nc = 4; nr = -(-len(tasks) // nc) + fig, axes = plt.subplots(nr, nc, figsize=(4.2 * nc, 3.3 * nr), squeeze=False) + for ax, (t, T) in zip(axes.flat, tasks): + pts = [(b, T["points"][f"{b:.2f}"]) for b in betas if "mean" in T["points"][f"{b:.2f}"]] + if pts: + x = [b for b, _ in pts]; y = [100 * p["mean"] for _, p in pts] + lo = [100 * (p["mean"] - p["ci"][0]) for _, p in pts]; hi = [100 * (p["ci"][1] - p["mean"]) for _, p in pts] + ax.errorbar(x, y, yerr=[lo, hi], fmt="-o", capsize=3, label="chain (0.99 = 1 hop), n=450") + for k, c in T["controls"].items(): + if "mean" in c: + ax.plot([float(k)], [100 * c["mean"]], "s", color="C3", label=f"d1 control @{k}") + if T["paper"] is not None: + ax.plot([T["paper_beta"]], [T["paper"]], "*", ms=13, color="gold", mec="k", label="Table 1 (n=450)") + ax.set_title(T["label"] + (f"\nmissing {T['missing']}" if T["missing"] else ""), fontsize=9, + color="red" if T["missing"] else "k") + ax.set_xticks(betas); ax.tick_params(labelsize=7); ax.grid(alpha=0.3); ax.legend(fontsize=6) + ax.set_xlabel(r"$\beta$"); ax.set_ylabel("success %") + for ax in list(axes.flat)[len(tasks):]: + ax.axis("off") + fig.tight_layout(); pdf.savefig(fig); plt.close(fig) + + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/rebuttal_default_beta.py b/rsm_rise/scripts/rebuttal_default_beta.py new file mode 100644 index 0000000000000000000000000000000000000000..9e464d3c2926f962624eef42a705a28ea11367e2 --- /dev/null +++ b/rsm_rise/scripts/rebuttal_default_beta.py @@ -0,0 +1,152 @@ +#!/usr/bin/env python3 +"""REBUTTAL_DEFAULT_BETA (owner 2026-11-09): can ONE beta, fixed across all 7 tasks, beat every baseline when the +baselines are also restricted to ONE setting across tasks? + +Inputs: status/rebuttal_default_beta_cells.json (scripts/rebuttal_default_beta_dump.py: canonical verdict_table loader, +Table 1 proposer per task) and status/rebuttal_beta_table450.json (RSM beta grid, 450 eps, paper per-task non-beta knobs). +Protocol for every cell: proposer seeds 0,1,2 x eval seeds 0,1,2; per (pseed, eseed) ONE file (n>=50, first by name), +first 50 episodes -> 450 episodes. A setting is COVERED on a task only with all 9 seed-files present. +Per baseline: setting key = the knob(s) it searched in Table 6 (everything else in the arm key held at the published value); +best single setting = highest mean over the 7 tasks among settings covered on all 7. +CI: bootstrap over episodes within each task (independent across tasks), B=10000, 95% percentile, of the 7-task mean. +Out: status/rebuttal_default_beta_table.{md,json}, status/rebuttal_default_beta.pdf +""" +import json, re, sys +from collections import defaultdict +from pathlib import Path +import numpy as np + +ROOT = Path("/proj/dmfexp/zwhong/rsm_rise") +TASKS = ["square_sub_20100", "square_expert_play", "two_piece_expert_suboptimal", "two_piece_expert_play", + "mug_expert_suboptimal", "threading_expert_play", "two_piece_expert_play_tipping"] +LAB = ["Square (Sub.)", "Square (Cov.)", "Piece (Sub.)", "Piece (Cov.)", "Mug (Sub.)", "Thread (Cov.)", "Piece-tip (Cov.)"] +SEEDS = [f"p{p}e{e}" for p in range(3) for e in range(3)] +B = 10000 +# Paper Table 1 (docs/tex/wide/tab_rise_flagship_final.tex), per task in TASKS order. +T1 = {"BC": [14.4, 11.0, 13.8, 18.9, 14.9, 26.3, 2.0], "BC-u": [48.0, 3.1, 33.0, 25.3, 4.9, 1.3, 1.0], + "IDQL": [43.6, 3.7, 22.9, 6.0, 16.2, 12.2, 2.9], "IFQL": [52.0, 2.0, 23.6, 21.1, 18.4, 8.4, 3.3], + "TD-Flow": [50.0, 7.1, 30.2, 16.0, 19.8, 7.1, 1.1], "LeWM": [48.7, 3.1, 29.8, 24.0, 17.3, 10.2, 3.8], + "DINO-WM": [50.0, 13.3, 41.1, 37.6, 18.4, 31.6, 5.1], "DF": [50.7, 6.0, 28.0, 20.7, 19.6, 18.2, 1.3], + "RSM": [54.0, 20.9, 47.1, 48.7, 23.1, 25.8, 7.3]} +SEARCHED = ["IFQL", "TD-Flow", "LeWM", "DINO-WM", "DF"] +BETAS = ["0.90", "0.93", "0.95", "0.97", "0.98", "0.99"] + + +def _df_family(rec): + m = re.search(r"^(.*?)\s*\[([A-Za-z0-9_]+)@s([A-Za-z0-9_]+)\]$", rec) + if not m: + return rec + mdl = m.group(2) + fam = re.sub(r"s\d+$", "", mdl) if re.match(r"^[A-Za-z]+\d+s\d+$", mdl) else mdl + return f"{m.group(1)} [{fam}*@s{m.group(3)}]" + + +def method_setting(fam, rec): + """-> (method, setting key) or None. The setting key keeps every arm-key field; DF pools training-seed replicates + of one world model (as flagship_latex's DF pin does).""" + if fam == "wm:dinowm": + return ("DINO-WM", rec) if rec.endswith(" M1") and " mpc" in rec else None + if fam == "wm:lewm": + return ("LeWM", rec) if rec.endswith(" M16") and " mpc" in rec else None + if fam == "wm:df": + return ("DF", _df_family(rec)) if " mpc" in rec else None + if fam.startswith("critic:ifql"): + return ("IFQL", f"{fam} {rec}") + if fam == "rsm:tdflow": + return ("TD-Flow", rec) if re.search(r"\bCH\d+\b", rec) else None + if fam == "rsm:membership": + return ("RSM*", rec) + return None + + +def vec_of(seedmap): + """seedmap: seed -> list of file dicts (pooled over member arms). -> (np.array or None, n)""" + eps = [] + n = 0 + for s in SEEDS: + fl = sorted([f for f in seedmap.get(s, []) if f["n"] >= 50], key=lambda f: f["file"]) + if fl: + eps += [int(c) for c in fl[0]["s50"]] + n += 50 + return (np.array(eps) if n == 450 else None), n + + +def main(): + D = json.load(open(ROOT / "status/rebuttal_default_beta_cells.json")) + T450 = json.load(open(ROOT / "status/rebuttal_beta_table450.json")) + rng = np.random.default_rng(0) + # ---- baseline matrices + mats = defaultdict(lambda: defaultdict(dict)) # method -> setting -> task -> dict(v, n, pooled) + for t in TASKS: + seedmaps = defaultdict(lambda: defaultdict(list)) + pooled = defaultdict(lambda: [0, 0]) + for k, a in D["tasks"][t]["arms"].items(): + ms = method_setting(a["family"], a["recipe"]) + if not ms: + continue + for s, sd in a["seeds"].items(): + seedmaps[ms][s] += sd["files"] + pooled[ms][0] += sd["succ_pooled"]; pooled[ms][1] += sd["n_pooled"] + for ms, sm in seedmaps.items(): + v, n = vec_of(sm) + ps, pn = pooled[ms] + mats[ms[0]][ms[1]][t] = dict(v=v, n=n, pooled=100.0 * ps / pn if pn else float("nan"), n_pooled=pn) + # ---- RSM fixed beta rows (table450 files, paper per-task non-beta knobs) + rsm = {} + for b in BETAS: + rsm[b] = {} + for t in TASKS: + pt = T450["tasks"][t]["points"][b] + eps = [] + for f in pt["files"]: + j = json.load(open(f)) + eps += [int(bool(e.get("success"))) for e in j["episodes"]][:50] + rsm[b][t] = np.array(eps) if len(eps) == 450 else None + + def boot_mean(vs): + """vs: list of 7 arrays -> mean%, ci lo, ci hi""" + m = np.mean([v.mean() for v in vs]) + bs = np.zeros(B) + for v in vs: + idx = rng.integers(0, len(v), size=(B, len(v))) + bs += v[idx].mean(1) + bs /= len(vs) + return 100 * m, 100 * np.percentile(bs, 2.5), 100 * np.percentile(bs, 97.5) + + out = dict(rule=__doc__, baselines={}, rsm_fixed={}, table1=T1) + # coverage + best single per method + for meth in SEARCHED + ["RSM*"]: + sets = mats.get(meth, {}) + rows = [] + for st, per in sets.items(): + cov = [t for t in TASKS if per.get(t, {}).get("v") is not None] + r = dict(setting=st, covered=len(cov), n={t: per.get(t, {}).get("n", 0) for t in TASKS}, + rate450={t: (100 * per[t]["v"].mean() if per.get(t, {}).get("v") is not None else None) for t in TASKS}, + pooled={t: per.get(t, {}).get("pooled") for t in TASKS}, + n_pooled={t: per.get(t, {}).get("n_pooled", 0) for t in TASKS}) + if len(cov) == 7: + r["mean"], r["lo"], r["hi"] = boot_mean([per[t]["v"] for t in TASKS]) + rows.append(r) + rows.sort(key=lambda r: (-r["covered"], -(r.get("mean") or 0))) + full = [r for r in rows if r["covered"] == 7] + out["baselines"][meth] = dict(settings=rows, best_single=(max(full, key=lambda r: r["mean"]) if full else None), + n_settings=len(rows), n_full=len(full)) + for b in BETAS: + vs = [rsm[b][t] for t in TASKS] + if all(v is not None for v in vs): + m, lo, hi = boot_mean(vs) + out["rsm_fixed"][b] = dict(mean=m, lo=lo, hi=hi, rate={t: 100 * rsm[b][t].mean() for t in TASKS}) + json.dump(out, open(ROOT / "status/rebuttal_default_beta_table.json", "w"), indent=1, default=float) + # coverage print + for meth in SEARCHED: + o = out["baselines"][meth] + print(f"== {meth}: {o['n_settings']} settings, {o['n_full']} covered on 7/7 at 450") + for r in o["settings"][:40]: + print(f" {r['setting'][:60]:60s} cov={r['covered']} mean={r.get('mean')}", + " ".join(f"{(r['rate450'][t] if r['rate450'][t] is not None else float('nan')):5.1f}/{r['n'][t]}" for t in TASKS)) + for b, r in out["rsm_fixed"].items(): + print(f"RSM b{b}: {r['mean']:.1f} [{r['lo']:.1f},{r['hi']:.1f}]") + + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/rebuttal_default_beta_dump.py b/rsm_rise/scripts/rebuttal_default_beta_dump.py new file mode 100644 index 0000000000000000000000000000000000000000..7fe69e905480fa75d29a04aae0da96335c3c15ad --- /dev/null +++ b/rsm_rise/scripts/rebuttal_default_beta_dump.py @@ -0,0 +1,41 @@ +#!/usr/bin/env python3 +"""REBUTTAL_DEFAULT_BETA step 1: dump every arm (all scorer families) on the Table 1 proposer of each task, per +(proposer seed, eval seed), with the per-file first-50-episode success strings, so the single-setting analysis can be +done offline (450-episode protocol = 3 proposer seeds x eval seeds 0-2 x first 50 eps of one file, files sorted by name). +Loader = verdict_table.cells (canonical); proposer = flagship_latex.proposer_for(task) (= Table 1). +Out: status/rebuttal_default_beta_cells.json +""" +import json, os, sys +from pathlib import Path +os.environ.setdefault("RSM_EXTRA_EPOCHS", "500") +ROOT = Path("/proj/dmfexp/zwhong/rsm_rise") +sys.path.insert(0, str(ROOT / "scripts")) +import verdict_table as VT +import flagship_latex as FL + +TASKS = ["square_sub_20100", "square_expert_play", "two_piece_expert_suboptimal", "two_piece_expert_play", + "mug_expert_suboptimal", "threading_expert_play", "two_piece_expert_play_tipping"] + +out = dict(note=__doc__, tasks={}) +for t in TASKS: + cs = VT.cells(t); files = dict(VT.CELL_FILES) + prop = FL.proposer_for(t) + T = dict(proposer=prop, arms={}) + for key, v in cs.items(): + arm, pol, ps, es = key + if not FL.proposer_ok(t, pol): + continue + a = T["arms"].setdefault(f"{arm[0]} || {arm[1]}", dict(family=arm[0], recipe=arm[1], seeds={})) + fl = [] + for f in sorted(files.get(key, [])): + try: + j = json.load(open(f)) + s = "".join("1" if e.get("success") else "0" for e in (j.get("episodes") or [])) + except Exception: + continue + fl.append(dict(file=f, n=len(s), s50=s[:50])) + a["seeds"][f"p{ps}e{es}"] = dict(n_pooled=len(v), succ_pooled=int(sum(v)), files=fl) + out["tasks"][t] = T + print(t, prop, len(T["arms"]), "arms", flush=True) +json.dump(out, open(ROOT / "status/rebuttal_default_beta_cells.json", "w")) +print("wrote status/rebuttal_default_beta_cells.json") diff --git a/rsm_rise/scripts/rebuttal_default_beta_gen.py b/rsm_rise/scripts/rebuttal_default_beta_gen.py new file mode 100644 index 0000000000000000000000000000000000000000..fbacee2ff138982bd8b1fe7b971ab5071780c628 --- /dev/null +++ b/rsm_rise/scripts/rebuttal_default_beta_gen.py @@ -0,0 +1,101 @@ +#!/usr/bin/env python3 +"""REBUTTAL_DEFAULT_BETA: generate the missing cells for "RSM, one config for all tasks". +The only RSM knob that still differs across tasks among the existing 450-ep cells (P/score/flow fixed) is the model +size: L40 on Square(Cov) and Piece(Cov), M elsewhere. This clones the existing Table-1 L40b ONACTOR command for +those two tasks and changes ONLY rsm_ckpt (rsm/L40 -> rsm/M, tag L40b -> Mb) and, for config B, adds +particles=8 score=prob (tag suffix P8pr). Clone rule validated: regenerating every existing L40b-default block in +status/packs/rebuttal_beta/payloads*/ from one template must match byte-for-byte. +Configs: A = M, P16, prob, F8 (default suffix); B = M, P8, prob, F8 (suffix P8pr). betas 0.95 (cap 33), 0.98 (cap 11). +""" +import glob, json, os, re, sys +ROOT = '/proj/dmfexp/zwhong/rsm_rise' +PK = f'{ROOT}/status/packs/rebuttal_beta' +OUT = f'{ROOT}/status/packs/rebuttal_default_beta' +TASKS = ['square_expert_play', 'two_piece_expert_play'] +CAP = {'0.90': 73, '0.93': 48, '0.95': 33, '0.97': 18, '0.98': 11} +cmd_re = re.compile(r'(/proj/dmfexp/zwhong/rsm_rise/scripts/eval_cell\.sh (\S+) .*?) 2>&1') +cmds = {} +for f in sorted(glob.glob(f'{PK}/payloads*/*.sh')): + for m in cmd_re.finditer(open(f).read()): + c = m.group(1); cell = re.search(r'exp\.eval_cell=(\S+)', c).group(1); cmds[(m.group(2), cell)] = c +pat = re.compile(r'^E1-L40b-R(0\.\d+)-(\d+)-ch-N128-argmax-ONACTOR-es(\d+)-sS0As(\d)$') + +def clone(c, beta, es, ps, size='L40', extra=''): + task = re.search(r'eval_cell\.sh (\S+) ', c).group(1) + ob, ocap, oes, ops = pat.match(re.search(r'exp\.eval_cell=(\S+)', c).group(1)).groups() + pol = sorted(glob.glob(f'{ROOT}/runs/{task}/policy/S0A_seed{ps}/{task}_S0A_s{ps}/*/models/model_epoch_5000.pth')) + assert len(pol) == 1, pol + oldpol = re.search(r'eval_cell\.sh \S+ (\S+) ', c).group(1) + tag = {'L40': 'L40b', 'M': 'Mb'}[size] + newcell = f'E1-{tag}-R{beta}-{CAP[beta]}-ch-N128-argmax-ONACTOR{extra}-es{es}-sS0As{ps}' + oldcell = f'E1-L40b-R{ob}-{ocap}-ch-N128-argmax-ONACTOR-es{oes}-sS0As{ops}' + n = c.replace(oldcell, newcell).replace(oldpol, pol[0]) + n = n.replace(f'exp.eval_seed={oes} ', f'exp.eval_seed={es} ') + n = n.replace(f'training.plan_beta={float(ob)} ', f'training.plan_beta={float(beta)} ') + n = n.replace(f'training.plan_chain_cap={ocap} ', f'training.plan_chain_cap={CAP[beta]} ') + n = n.replace(f'/runs/{task}/rsm/L40/ckpt_best.pt', f'/runs/{task}/rsm/{size}/ckpt_best.pt') + if extra == 'P8pr': + n = n.replace(' training.rsm_backend=', ' training.plan_particles=8 training.plan_score=prob training.rsm_backend=') + return n, newcell + +# ---- validation +nval = 0 +for task in TASKS: + ex = {k[1]: v for k, v in cmds.items() if k[0] == task and pat.match(k[1])} + tk = sorted(ex)[0] + for k, v in ex.items(): + b, cap, es, ps = pat.match(k).groups() + if b not in CAP: continue + g, _ = clone(ex[tk], b, int(es), int(ps)) + assert g == v, (k, g, v); nval += 1 +print(f'[validate] {nval} existing L40b blocks reproduced byte-for-byte from one template per task') +# P8pr add-on: compare against an existing L40b P8pr JSON's planner_overrides +for task in TASKS: + ex = {k[1]: v for k, v in cmds.items() if k[0] == task and pat.match(k[1])} + g, cell = clone(ex[sorted(ex)[0]], '0.98', 0, 0, 'L40', 'P8pr') + j = json.load(open(f'{ROOT}/runs/{task}/eval_onactor/{cell}.json')) + po = j['planner_overrides'] + for kv in re.findall(r'training\.(\S+)=(\S+)', g): + k, v = kv; jv = po.get(k) + assert str(jv) == v or (isinstance(jv, float) and float(v) == jv) or (isinstance(jv, int) and str(jv) == v), (task, k, v, jv) + assert j['eval_ckpt'] in g, j['eval_ckpt'] + print(f'[validate] {task} P8pr clone matches existing JSON overrides of {cell}') + +# ---- generate +blocks = [] +for extra in ['', 'P8pr']: + for beta in ['0.98', '0.95']: + for task in TASKS: + ex = {k[1]: v for k, v in cmds.items() if k[0] == task and pat.match(k[1])} + tmpl = ex[sorted(ex)[0]] + for ps in range(3): + for es in range(3): + c, cell = clone(tmpl, beta, es, ps, 'M', extra) + js = f'{ROOT}/runs/{task}/eval_onactor/{cell}.json' + if os.path.exists(js): continue + blocks.append((task, cell, c, js)) +print(f'[gen] {len(blocks)} missing cells') +os.makedirs(f'{OUT}/payloads', exist_ok=True) +for f in glob.glob(f'{OUT}/payloads/rdb_*.sh'): os.remove(f) +NS = 16 +pays = [] +for i in range(NS): + mine = blocks[i::NS] + p = f'{OUT}/payloads/rdb_{i:03d}.sh' + with open(p, 'w') as fh: + fh.write('#!/usr/bin/env bash\nset -uo pipefail\ncd /proj/dmfexp/zwhong/rsm_rise\nrc_all=0\n') + fh.write('echo "[rdb] host=$(hostname) job=${SLURM_JOB_ID:-none} gpu=${CUDA_VISIBLE_DEVICES:-?}"\n') + for task, cell, c, js in mine: + d = os.path.dirname(js) + fh.write(f'mkdir -p {d}/logs\n') + fh.write(f'if [ -f {js} ]; then echo "[rdb] {cell} exists, skip"; else\n') + fh.write(f' {c} 2>&1 | tee {d}/logs/{cell}.log; rc=${{PIPESTATUS[0]}}\n') + fh.write(f' if [ -f {js} ]; then python /proj/dmfexp/zwhong/rsm_rise/scripts/wandb_log_eval.py {js} || true\n') + fh.write(f' else rm -f {js}.tmp; rc_all=${{rc:-1}}; echo "[rdb] {cell} FAILED rc=$rc"; fi\nfi\n\n') + fh.write('exit $rc_all\n') + os.chmod(p, 0o755); pays.append(p) +json.dump({'note': 'REBUTTAL_DEFAULT_BETA: size-M cells on Sq-C/Pc-C, configs A (P16 prob F8) and B (P8 prob F8), beta 0.95/0.98, ' + 'proposer seeds 0-2 x eval seeds 0-2; clone of the L40b Table-1 command with only rsm_ckpt (+P8pr knobs) changed', + 'cells': [b[1] + '@' + b[0] for b in blocks], 'nodes': [pays[:8], pays[8:]]}, + open(f'{PK}/plan_rdb.json', 'w'), indent=1) +print('[gen] wrote', f'{PK}/plan_rdb.json', len(pays), 'payloads') diff --git a/rsm_rise/scripts/rebuttal_default_beta_gen_cd.py b/rsm_rise/scripts/rebuttal_default_beta_gen_cd.py new file mode 100644 index 0000000000000000000000000000000000000000..0129c3eee0a26a19688e34268719d81856366e9b --- /dev/null +++ b/rsm_rise/scripts/rebuttal_default_beta_gen_cd.py @@ -0,0 +1,134 @@ +#!/usr/bin/env python3 +"""REBUTTAL_DEFAULT_BETA configs C/D (orchestrator 2026-11-09 16:35Z): size L40 on EVERY task. + C = L40, P16, prob, F8 (cell suffix '') D = L40, P8, prob, F8 (cell suffix 'P8pr') beta 0.95 (cap 33), 0.98 (cap 11) +Sq-C / Pc-C: their paper cells already are L40b (C = existing '' cells, D = existing P8pr cells) -> nothing to run. +Other 5 tasks: clone each task's Table-1 paper cell command (status/packs/beta_fair + rebuttal_beta payloads), change ONLY + beta/cap/eval seed/proposer seed (validated byte-for-byte on every existing paper-cell block of the task), strip the per-task + P/score/flow overrides (-> default P16 prob F8; validated against the existing size-M '' JSON planner_overrides), swap + rsm_ckpt to rsm/L40 (checkpoint RULE = the paper's: ckpt_best.pt unless the task's paper cell pins a step -> Pc-S uses + L40/ckpt_s100000.pt; Mug's paper M_s1 is a training-seed choice, L40 has a single seed -> L40/ckpt_best.pt), and for D add + plan_particles=8 plan_score=prob. +""" +import glob, json, os, re +ROOT = '/proj/dmfexp/zwhong/rsm_rise' +OUT = f'{ROOT}/status/packs/rebuttal_default_beta' +CAP = {'0.90': 73, '0.93': 48, '0.95': 33, '0.97': 18, '0.98': 11} +# task -> (paper model tag, ON tag, seed-prefix, paper knob suffix, paper knob override string, M ckpt rel, L40 tag, L40 ckpt rel) +T = { + 'square_sub_20100': ('Mb', 'ACTOR', 'S0A', 'P16lo', ' training.plan_particles=16 training.plan_score=logit', 'M/ckpt_best.pt', 'L40b', 'L40/ckpt_best.pt'), + 'two_piece_expert_suboptimal': ('Ms100k', 'ACTOR', 'S0A', 'P8pr', ' training.plan_particles=8 training.plan_score=prob', 'M/ckpt_s100000.pt', 'L40s100k', 'L40/ckpt_s100000.pt'), + 'mug_expert_suboptimal': ('Ms1b', 'S3H1', 'S3H1', 'P16lo', ' training.plan_particles=16 training.plan_score=logit', 'M_s1/ckpt_best.pt', 'L40b', 'L40/ckpt_best.pt'), + 'threading_expert_play': ('Mb', 'S0AidqlE500', 'S0AidqlE500', 'P8pr', ' training.plan_particles=8 training.plan_score=prob', 'M/ckpt_best.pt', 'L40b', 'L40/ckpt_best.pt'), + 'two_piece_expert_play_tipping': ('Mb', 'ACTOR', 'S0A', 'F4', ' training.plan_flow_steps=4', 'M/ckpt_best.pt', 'L40b', 'L40/ckpt_best.pt'), +} +cmd_re = re.compile(r'(/proj/dmfexp/zwhong/rsm_rise/scripts/eval_cell\.sh (\S+) .*?) 2>&1') +cmds = {} +for f in sorted(glob.glob(f'{ROOT}/status/packs/beta_fair/payloads*/*.sh') + glob.glob(f'{ROOT}/status/packs/rebuttal_beta/payloads*/*.sh')): + for m in cmd_re.finditer(open(f).read()): + c = m.group(1); cmds[(m.group(2), re.search(r'exp\.eval_cell=(\S+)', c).group(1))] = c + + +def pat(task): + tag, on, sp, suf, *_ = T[task] + return re.compile(rf'^E1-{tag}-R(0\.\d+)-(\d+)-ch-N128-argmax-ON{on}{suf}-es(\d)-s{sp}s(\d)$') + + +# policy path per (task, proposer seed), taken from the existing commands +POL = {} +for (task, cell), c in cmds.items(): + if task in T and pat(task).match(cell): + ps = int(pat(task).match(cell).group(4)) + POL.setdefault((task, ps), set()).add(re.search(r'eval_cell\.sh \S+ (\S+) ', c).group(1)) +for k, v in POL.items(): + assert len(v) == 1, (k, v) +POL = {k: v.pop() for k, v in POL.items()} + + +def clone(c, task, beta, es, ps, size='M', extra=None): + """extra=None: keep the paper knobs; '' or 'P8pr': fixed config.""" + tag, on, sp, suf, ko, mck, ltag, lck = T[task] + ob, ocap, oes, ops = pat(task).match(re.search(r'exp\.eval_cell=(\S+)', c).group(1)).groups() + oldcell = f'E1-{tag}-R{ob}-{ocap}-ch-N128-argmax-ON{on}{suf}-es{oes}-s{sp}s{ops}' + ntag = tag if size == 'M' else ltag + nsuf = suf if extra is None else extra + newcell = f'E1-{ntag}-R{beta}-{CAP[beta]}-ch-N128-argmax-ON{on}{nsuf}-es{es}-s{sp}s{ps}' + n = c.replace(oldcell, newcell).replace(POL[(task, int(ops))], POL[(task, ps)]) + n = n.replace(f'exp.eval_seed={oes} ', f'exp.eval_seed={es} ') + n = n.replace(f'training.plan_beta={float(ob)} ', f'training.plan_beta={float(beta)} ') + n = n.replace(f'training.plan_chain_cap={ocap} ', f'training.plan_chain_cap={CAP[beta]} ') + if size == 'L40': + assert f'/rsm/{mck} ' in n + n = n.replace(f'/runs/{task}/rsm/{mck} ', f'/runs/{task}/rsm/{lck} ') + if extra is not None: + assert n.endswith(ko), n[-80:] + n = n[:-len(ko)] + if extra == 'P8pr': + n += ' training.plan_particles=8 training.plan_score=prob' + return n, newcell + + +def check_json(cmd, js): + j = json.load(open(js)); po = j['planner_overrides'] + for k, v in re.findall(r'training\.(\S+)=(\S+)', cmd): + jv = po.get(k) + assert str(jv) == v or (isinstance(jv, float) and float(v) == jv), (js, k, v, jv) + for k, d in [('plan_particles', 16), ('plan_score', 'prob'), ('plan_flow_steps', 8)]: + if f'training.{k}=' not in cmd: + assert po[k] == d, (js, k, po[k]) + assert j['eval_ckpt'] in cmd + + +nval = 0; tmpl = {} +for task in T: + ex = {k[1]: v for k, v in cmds.items() if k[0] == task and pat(task).match(k[1])} + tk = sorted(ex)[0]; tmpl[task] = ex[tk] + for k, v in ex.items(): + b, cap, es, ps = pat(task).match(k).groups() + if b not in CAP: continue + g, _ = clone(ex[tk], task, b, int(es), int(ps)) + assert g == v, (k, g, v); nval += 1 + # fixed-config (size M) clones vs existing JSONs (config A '' and B 'P8pr') + for extra in ['', 'P8pr']: + for b in ['0.95', '0.98']: + g, cell = clone(tmpl[task], task, b, 0, 0, 'M', extra) + js = f'{ROOT}/runs/{task}/eval_onactor/{cell}.json' + check_json(g, js); print(f'[validate] {task}: size-M {extra or "P16pr"} clone matches {cell}.json') +print(f'[validate] {nval} existing paper-cell blocks reproduced byte-for-byte from one template per task') +for task in T: + assert os.path.exists(f'{ROOT}/runs/{task}/rsm/{T[task][7]}'), task + +blocks = [] +for extra in ['', 'P8pr']: + for beta in ['0.98', '0.95']: + for task in T: + for ps in range(3): + for es in range(3): + c, cell = clone(tmpl[task], task, beta, es, ps, 'L40', extra) + js = f'{ROOT}/runs/{task}/eval_onactor/{cell}.json' + if os.path.exists(js): continue + blocks.append((task, cell, c, js)) +print(f'[gen] {len(blocks)} missing cells') +os.makedirs(f'{OUT}/payloads_cd', exist_ok=True) +for f in glob.glob(f'{OUT}/payloads_cd/rdbcd_*.sh'): os.remove(f) +NS = 24 +pays = [] +for i in range(NS): + mine = blocks[i::NS] + p = f'{OUT}/payloads_cd/rdbcd_{i:03d}.sh' + with open(p, 'w') as fh: + fh.write('#!/usr/bin/env bash\nset -uo pipefail\ncd /proj/dmfexp/zwhong/rsm_rise\nrc_all=0\n') + fh.write('echo "[rdbcd] host=$(hostname) job=${SLURM_JOB_ID:-none} gpu=${CUDA_VISIBLE_DEVICES:-?}"\n') + for task, cell, c, js in mine: + d = os.path.dirname(js) + fh.write(f'mkdir -p {d}/logs\n') + fh.write(f'if [ -f {js} ]; then echo "[rdbcd] {cell} exists, skip"; else\n') + fh.write(f' {c} 2>&1 | tee {d}/logs/{cell}.log; rc=${{PIPESTATUS[0]}}\n') + fh.write(f' if [ -f {js} ]; then python /proj/dmfexp/zwhong/rsm_rise/scripts/wandb_log_eval.py {js} || true\n') + fh.write(f' else rm -f {js}.tmp; rc_all=${{rc:-1}}; echo "[rdbcd] {cell} FAILED rc=$rc"; fi\nfi\n\n') + fh.write('exit $rc_all\n') + os.chmod(p, 0o755); pays.append(p) +json.dump({'note': 'REBUTTAL_DEFAULT_BETA configs C (L40 P16 prob F8) / D (L40 P8 prob F8) at beta 0.95/0.98 on the 5 tasks ' + 'without L40 cells; proposer seeds 0-2 x eval seeds 0-2', 'cells': [b[1] + '@' + b[0] for b in blocks], + 'nodes': [pays[0:8], pays[8:16], pays[16:24]]}, + open(f'{ROOT}/status/packs/rebuttal_beta/plan_rdbcd.json', 'w'), indent=1) +print('[gen] wrote plan_rdbcd.json', len(pays), 'payloads') diff --git a/rsm_rise/scripts/rebuttal_default_beta_raw.py b/rsm_rise/scripts/rebuttal_default_beta_raw.py new file mode 100644 index 0000000000000000000000000000000000000000..2f9b6196658c0b9cc4baf2be34067cac4f62c3b6 --- /dev/null +++ b/rsm_rise/scripts/rebuttal_default_beta_raw.py @@ -0,0 +1,273 @@ +#!/usr/bin/env python3 +"""REBUTTAL_DEFAULT_BETA headline (owner 2026-11-09 08:45Z): "RSM, one config for all tasks" vs +"DINO-WM, one config for all tasks". Plain raw-JSON reader (no loader dependency), every cell = +proposer seeds 0,1,2 x eval seeds 0,1,2 x first 50 episodes = 450 episodes, Table 1 proposer per task +(S0A; Mug S3H1; Thread S0AidqlE500). A setting counts on a task only with all 9 files present. + +RSM rows + fixed beta, paper per-task knobs -- the table450 grid (status/rebuttal_beta_table450.json files) + one config, per-task size -- P/score/flow fixed (P16 prob F8 = cfg A, or P8 prob F8 = cfg B), model size + still L40 on Sq-C / Pc-C, M elsewhere (existing cells) + one config, ALL knobs fixed -- size M everywhere + cfg A / cfg B (Sq-C/Pc-C M cells from jobs 986414/986415) + Checkpoint RULE kept per task (Table 6 selection: ckpt_best; Pc-S s100000; Mug M_s1) -- a rule, not a knob. +DINO-WM rows: published arm M=1, readout in {mpc, mpcd}, H in {10,20,50,100,200}; single setting = best 7-task mean; + per-task tuned = per-task max over the same grid (Table 1 rule). +Out: status/rebuttal_default_beta_table.{md,json}, status/rebuttal_default_beta.pdf +""" +import json, os +import numpy as np + +ROOT = '/proj/dmfexp/zwhong/rsm_rise' +R = f'{ROOT}/runs' +TASKS = [('square_sub_20100', 'Mb', 'ACTOR', 'S0A'), ('square_expert_play', 'L40b', 'ACTOR', 'S0A'), + ('two_piece_expert_suboptimal', 'Ms100k', 'ACTOR', 'S0A'), ('two_piece_expert_play', 'L40b', 'ACTOR', 'S0A'), + ('mug_expert_suboptimal', 'Ms1b', 'S3H1', 'S3H1'), ('threading_expert_play', 'Mb', 'S0AidqlE500', 'S0AidqlE500'), + ('two_piece_expert_play_tipping', 'Mb', 'ACTOR', 'S0A')] +LAB = ['Square (Sub.)', 'Square (Cov.)', 'Piece (Sub.)', 'Piece (Cov.)', 'Mug (Sub.)', 'Thread (Cov.)', 'Piece-tip (Cov.)'] +CAP = {'0.90': 73, '0.93': 48, '0.95': 33, '0.97': 18, '0.98': 11} +BETAS = ['0.90', '0.93', '0.95', '0.97', '0.98', '0.99'] +T1 = {"BC": [14.4, 11.0, 13.8, 18.9, 14.9, 26.3, 2.0], "BC-u": [48.0, 3.1, 33.0, 25.3, 4.9, 1.3, 1.0], + "IDQL": [43.6, 3.7, 22.9, 6.0, 16.2, 12.2, 2.9], "IFQL": [52.0, 2.0, 23.6, 21.1, 18.4, 8.4, 3.3], + "TD-Flow": [50.0, 7.1, 30.2, 16.0, 19.8, 7.1, 1.1], "LeWM": [48.7, 3.1, 29.8, 24.0, 17.3, 10.2, 3.8], + "DINO-WM": [50.0, 13.3, 41.1, 37.6, 18.4, 31.6, 5.1], "DF": [50.7, 6.0, 28.0, 20.7, 19.6, 18.2, 1.3], + "RSM": [54.0, 20.9, 47.1, 48.7, 23.1, 25.8, 7.3]} +B = 10000 +rng = np.random.default_rng(0) + + +def load(files): + """-> 0/1 array of 450 episodes or None if any of the 9 files is missing.""" + out = [] + for f in files: + if not os.path.exists(f): + return None + eps = json.load(open(f))['episodes'][:50] + if len(eps) < 50: + return None + out += [1.0 if (e.get('success') if isinstance(e, dict) else e) else 0.0 for e in eps] + return np.array(out) + + +def files(task, cell_fn, sp): + return [f'{R}/{task}/eval_onactor/{cell_fn(p, e)}-s{sp}s{p}.json' for p in range(3) for e in range(3)] + + +def rsm_cell(ti, beta, model=None, suf=''): + t, m, on, sp = TASKS[ti] + m = model or m + if beta == '0.99': + fn = lambda p, e: f'E1-{m}-R0.99-1-N128-argmax-ON{on}{suf}-es{e}' + else: + fn = lambda p, e: f'E1-{m}-R{beta}-{CAP[beta]}-ch-N128-argmax-ON{on}{suf}-es{e}' + return load(files(t, fn, sp)) + + +def dwm_cell(ti, mode, H): + t, _, on, sp = TASKS[ti] + prop = 'S0A' if on == 'ACTOR' else on + tag = f'DWMMPC{prop}' + ('D' if mode == 'mpcd' else '') + return load(files(t, lambda p, e: f'E1-DINOWM-R0.95-{H}-{mode}-N128-argmax-{tag}-es{e}', sp)) + + +def summarize(name, arrs, group): + """arrs: list of 7 arrays (or None).""" + ok = all(a is not None for a in arrs) + per = [100 * a.mean() if a is not None else None for a in arrs] + r = {'name': name, 'group': group, 'per_task': per, 'n': [len(a) if a is not None else 0 for a in arrs], + 'complete': ok, + 'per_task_ci': [[float(np.percentile(100 * a[rng.integers(0, len(a), (2000, len(a)))].mean(1), q)) for q in (2.5, 97.5)] + if a is not None else None for a in arrs]} + if ok: + r['mean'] = float(np.mean(per)) + boots = np.mean([100 * a[rng.integers(0, len(a), (B, len(a)))].mean(1) for a in arrs], axis=0) + r['ci'] = [float(np.percentile(boots, 2.5)), float(np.percentile(boots, 97.5))] + return r + + +rows = [] +# ---- table450 per-task paper knobs +t450 = json.load(open(f'{ROOT}/status/rebuttal_beta_table450.json'))['tasks'] +for b in BETAS: + arrs = [] + for t, *_ in TASKS: + pt = t450[t]['points'].get(b) or t450[t]['points'].get(b.rstrip('0')) + arrs.append(load(pt['files']) if pt and pt.get('files') and len(pt['files']) == 9 else None) + rows.append(summarize(f'RSM beta={b} (per-task size/P/score/flow, Table 6)', arrs, 'rsm_beta_pertaskknobs')) +arrs = [] +for t, *_ in TASKS: + pb = t450[t]['paper_beta']; pb = f'{pb:.2f}' + arrs.append(load(t450[t]['points'][pb]['files'])) +rows.append(summarize('RSM per-task tuned (Table 1 cells)', arrs, 'rsm_t1')) +# ---- one config +CFG = {'A': ('', 'P16 prob F8', 'M'), 'B': ('P8pr', 'P8 prob F8', 'M'), + 'C': ('', 'P16 prob F8', 'L40'), 'D': ('P8pr', 'P8 prob F8', 'L40')} +# size L40 everywhere: ckpt RULE as in the paper -- ckpt_best unless the task's paper cell pins a step (Pc-S: s100000) +L40TAG = {i: ('L40s100k' if TASKS[i][1] == 'Ms100k' else 'L40b') for i in range(7)} +for c, (suf, desc, size) in CFG.items(): + for b in ['0.95', '0.98']: + if size == 'M': + rows.append(summarize(f'RSM one config {c} ({desc}), beta={b}, size per task (L40 on Sq-C/Pc-C)', + [rsm_cell(i, b, None, suf) for i in range(7)], f'rsm_cfg{c}_size_pertask')) + mods = ['Mb' if TASKS[i][1] == 'L40b' else None for i in range(7)] + else: + mods = [L40TAG[i] for i in range(7)] + rows.append(summarize(f'RSM one config {c} (size {size}, {desc}), beta={b} -- ALL knobs fixed', + [rsm_cell(i, b, mods[i], suf) for i in range(7)], f'rsm_cfg{c}_allfixed')) +# ---- DINO-WM +dwm = {} +for mode in ['mpc', 'mpcd']: + for H in [10, 20, 50, 100, 200]: + r = summarize(f'DINO-WM {mode} H={H} M=1', [dwm_cell(i, mode, H) for i in range(7)], 'dwm_single') + rows.append(r); dwm[(mode, H)] = r +cov = [k for k, r in dwm.items() if r['complete']] +best = max(cov, key=lambda k: dwm[k]['mean']) +dbest = dwm[best] +# per-task tuned DINO-WM from the same raw grid (Table 1 rule) +pt_arrs = [] +for i in range(7): + cand = [dwm_cell(i, m, H) for (m, H) in cov] + pt_arrs.append(max(cand, key=lambda a: a.mean())) +rows.append(summarize('DINO-WM per-task tuned (max over mode x H, raw grid)', pt_arrs, 'dwm_t1')) +covd = [k for k in cov if k[0] == 'mpcd'] +rows.append(summarize('DINO-WM per-task tuned, Table 1 rule (mpcd only, H per task)', + [max([dwm_cell(i, m, H) for (m, H) in covd], key=lambda a: a.mean()) for i in range(7)], 'dwm_t1rule')) + +# ---- per-row comparisons +bl_means = {k: float(np.mean(v)) for k, v in T1.items() if k != 'RSM'} +for r in rows: + if not r['complete']: + continue + p = r['per_task'] + r['wins_vs_dwm_single'] = int(sum(a > b for a, b in zip(p, dbest['per_task']))) + r['ties_vs_dwm_single'] = int(sum(abs(a - b) < 1e-9 for a, b in zip(p, dbest['per_task']))) + r['wins_vs_T1'] = {k: int(sum(a > b for a, b in zip(p, v))) for k, v in T1.items() if k != 'RSM'} + ranks = [] + for i in range(7): + others = [v[i] for k, v in T1.items() if k != 'RSM'] + ranks.append(1 + sum(o > p[i] for o in others)) + r['mean_rank_vs_T1_baselines'] = float(np.mean(ranks)) + r['beats_every_T1_baseline_mean'] = bool(r['mean'] > max(bl_means.values())) + r['margin_vs_best_T1_baseline'] = r['mean'] - max(bl_means.values()) + r['margin_vs_dwm_single'] = r['mean'] - dbest['mean'] + +out = {'protocol': __doc__, 'dwm_best_single': {'mode': best[0], 'H': best[1], 'M': 1, 'mean': dbest['mean'], + 'ci': dbest['ci'], 'per_task': dbest['per_task'], 'covered_settings': len(cov)}, + 'T1_means': {k: float(np.mean(v)) for k, v in T1.items()}, 'rows': rows} +json.dump(out, open(f'{ROOT}/status/rebuttal_default_beta_table.json', 'w'), indent=1) + +# ---- markdown +def fmt(r): + if not r['complete']: + return f"| {r['name']} | pending (n per task {r['n']}) |" + ' |' * 5 + return (f"| {r['name']} | {r['mean']:.1f} [{r['ci'][0]:.1f},{r['ci'][1]:.1f}] | " + f"{r['wins_vs_dwm_single']}/7 | {r['mean_rank_vs_T1_baselines']:.2f} | " + f"{'yes' if r['beats_every_T1_baseline_mean'] else 'no'} ({r['margin_vs_best_T1_baseline']:+.1f}) | " + + ' / '.join(f'{x:.1f}' for x in r['per_task']) + ' |') + +L = ['# One configuration for all 7 tasks: RSM vs DINO-WM (450 episodes per task-cell)', '', + 'Every cell: proposer seeds 0,1,2 x eval seeds 0,1,2 x 50 episodes = 450, Table 1 proposer per task. ' + 'CI: 95% bootstrap over episodes (independent per task) of the 7-task mean. ' + f"Best single DINO-WM setting = **{best[0]} H={best[1]} (M=1)**, mean {dbest['mean']:.1f} " + f"[{dbest['ci'][0]:.1f},{dbest['ci'][1]:.1f}] ({len(cov)}/10 M=1 settings cover all 7 tasks); " + 'Table 1 DINO-WM (per-task tuned) = 28.2. ' + "Rank = 1 + number of Table 1 baselines (BC..DF, per-task tuned) above the row on that task, averaged over tasks. " + "Checkpoint selection stays per task as a RULE (Table 6 selection), not a tuned hyperparameter.", '', + '## Headline', '', + '| row | 7-task mean [95% CI] | tasks won vs DINO-WM single | mean rank vs T1 baselines | beats every baseline\'s per-task-tuned mean (margin vs DINO-WM 28.2) | per task (Sq-S/Sq-C/Pc-S/Pc-C/Mug/Thr/Tip) |', + '|---|---|---|---|---|---|'] +head = [r for r in rows if r['group'] in ('rsm_cfgA_allfixed', 'rsm_cfgB_allfixed', 'rsm_cfgC_allfixed', 'rsm_cfgD_allfixed')] +L += [fmt(r) for r in head] + [fmt(dbest), fmt([r for r in rows if r['group'] == 'dwm_t1rule'][0]), + fmt([r for r in rows if r['group'] == 'dwm_t1'][0]), + fmt([r for r in rows if r['group'] == 'rsm_t1'][0])] +L += ['', 'Note: Table 1 prints DINO-WM 28.2 = the flagship selection rule (scripts/verdict_table.py rule (1): read-out ' + '`mpcd` only, H in {10,20,50,100,200} chosen per task, M=1). The raw grid per-task max over BOTH read-outs (mpc, mpcd) x H ' + 'is 29.0 (Mug 21.1 = mpc H=100; Pc-C 39.6 = mpc H=10; Pc-S 41.8, Sq-S 50.7 = mpc); both are shown. ' + 'Configs A/B = size M, C/D = size L40 on every task (ckpt rule: ckpt_best, except Pc-S whose paper cell pins step 100k -> ' + 'L40/ckpt_s100000; Mug paper M_s1 is a training-seed pick, L40 has one seed -> L40/ckpt_best). N128, gamma 0.99, ' + 'chain cap = ceil-rule (0.95 -> 33, 0.98 -> 11) are identical on every task in every RSM row.'] +best_fixed = max([r for r in head if r['complete']], key=lambda r: r['mean'], default=None) +if best_fixed: + L += ['', f"**Best all-knobs-fixed RSM row: {best_fixed['name']} = {best_fixed['mean']:.1f} " + f"[{best_fixed['ci'][0]:.1f},{best_fixed['ci'][1]:.1f}] vs DINO-WM one setting {dbest['mean']:.1f} " + f"({best_fixed['mean'] - dbest['mean']:+.1f}); wins {best_fixed['wins_vs_dwm_single']}/7 tasks.**"] + L += ['', 'Wins vs each Table 1 baseline (per-task tuned) for the best all-fixed row: ' + + ', '.join(f'{k} {v}/7' for k, v in best_fixed['wins_vs_T1'].items())] +L += ['', '## RSM one config with model size still per task (existing cells)', '', '| row | mean [CI] | won vs DWM single | mean rank | beats all T1 means | per task |', '|---|---|---|---|---|---|'] +L += [fmt(r) for r in rows if r['group'].endswith('size_pertask')] +L += ['', '## RSM fixed beta, other knobs per task (table450)', '', + '| row | mean [CI] | won vs DWM single | mean rank | beats all T1 means | per task |', '|---|---|---|---|---|---|'] +L += [fmt(r) for r in rows if r['group'] in ('rsm_beta_pertaskknobs', 'rsm_t1')] +L += ['', '## DINO-WM single settings (M=1)', '', + '| row | mean [CI] | won vs DWM single | mean rank | beats all T1 means | per task |', '|---|---|---|---|---|---|'] +L += [fmt(r) for r in rows if r['group'] in ('dwm_single', 'dwm_t1')] +L += ['', 'Paper Table 1 per-task-tuned means: ' + ', '.join(f'{k} {v:.1f}' for k, v in out['T1_means'].items())] +open(f'{ROOT}/status/rebuttal_default_beta_table.md', 'w').write('\n'.join(L) + '\n') + +# ---- figure +import matplotlib +matplotlib.use('Agg') +import matplotlib.pyplot as plt +BLUE, ORANGE, AQUA, VIOLET, INK, MUTED = '#2a78d6', '#eb6834', '#1baf7a', '#6250d6', '#0b0b0b', '#52514e' +bx = [float(b) for b in BETAS] +grid = {b: r for b, r in zip(BETAS, [r for r in rows if r['group'] == 'rsm_beta_pertaskknobs'])} +# best all-knobs-fixed config (A-D) = highest complete 7-task mean; recommended beta = that row's beta +def _beta(r): + return float(r['name'].split('beta=')[1].split()[0].rstrip(',')) +cands = [r for r in head if r['complete']] or [r for r in rows if r['group'] == 'rsm_cfgA_size_pertask' and r['complete']] +rec = max(cands, key=lambda r: r['mean']) +rec_beta = _beta(rec) +fx_group = rec['group'] +fx_rows = sorted([r for r in rows if r['group'] == fx_group and r['complete']], key=_beta) +fx_label = 'RSM, ONE config for all tasks: ' + rec['name'].split(' (')[1].split(')')[0] if 'allfixed' in fx_group else 'RSM one config (size per task)' +fig, axs = plt.subplots(2, 4, figsize=(15, 7.2), sharex=True) +for i in range(8): + ax = axs.flat[i] + for s in ('top', 'right'): + ax.spines[s].set_visible(False) + ax.grid(axis='y', color='#e6e5e0', lw=0.6) + if i < 7: + load_ci = [] + for b in BETAS: + pt = t450[TASKS[i][0]]['points'][b] + load_ci.append((100 * pt['mean'], 100 * pt['ci'][0], 100 * pt['ci'][1])) + y = [v[0] for v in load_ci] + ax.fill_between(bx, [v[1] for v in load_ci], [v[2] for v in load_ci], color=BLUE, alpha=0.10, lw=0) + ax.plot(bx, y, '-o', color=BLUE, lw=1.4, ms=4, alpha=0.6, label='RSM, beta sweep with per-task Table 6 knobs (context)') + if fx_rows: + xs = [_beta(r) for r in fx_rows]; ys = [r['per_task'][i] for r in fx_rows] + lo = [r['per_task'][i] - r['per_task_ci'][i][0] for r in fx_rows]; hi = [r['per_task_ci'][i][1] - r['per_task'][i] for r in fx_rows] + ax.errorbar(xs, ys, yerr=[lo, hi], fmt='-D', color=AQUA, lw=2.4, ms=8, mec='white', mew=1.5, capsize=3, zorder=5, + label=fx_label) + dv, dt = dbest['per_task'][i], T1['DINO-WM'][i] + ttl = LAB[i] + else: + y = [grid[b]['mean'] for b in BETAS] + ax.fill_between(bx, [grid[b]['ci'][0] for b in BETAS], [grid[b]['ci'][1] for b in BETAS], color=BLUE, alpha=0.10, lw=0) + ax.plot(bx, y, '-o', color=BLUE, lw=1.4, ms=4, alpha=0.6) + if fx_rows: + xs = [_beta(r) for r in fx_rows]; ys = [r['mean'] for r in fx_rows] + ax.errorbar(xs, ys, yerr=[[r['mean'] - r['ci'][0] for r in fx_rows], [r['ci'][1] - r['mean'] for r in fx_rows]], + fmt='-D', color=AQUA, lw=2.4, ms=8, mec='white', mew=1.5, capsize=3, zorder=5) + dv, dt = dbest['mean'], float(np.mean(T1['DINO-WM'])) + ttl = 'Mean over 7 tasks' + ax.axhline(dv, color=ORANGE, ls=':', lw=2.2, label=f'DINO-WM, one setting for all tasks ({best[0]}, H={best[1]})') + ax.axhline(dt, color=ORANGE, ls=':', lw=1.4, alpha=0.45, label='DINO-WM, H tuned per task (Table 1, 28.2 mean)') + ax.axvline(rec_beta, color=MUTED, ls='--', lw=1, label=f'recommended default beta = {rec_beta:.2f}') + ax.set_title(ttl, fontsize=11, color=INK, fontweight='bold' if i == 7 else 'normal') + ax.set_xticks(bx); ax.set_xticklabels([b for b in BETAS], fontsize=8) + if i % 4 == 0: + ax.set_ylabel('success rate (%)', color=MUTED) + if i >= 4: + ax.set_xlabel('beta', color=MUTED) +h, l = [], [] +for ax in axs.flat: + for hh, ll in zip(*ax.get_legend_handles_labels()): + if ll not in l: + h.append(hh); l.append(ll) +fig.legend(h, l, loc='lower center', ncol=3, frameon=False, fontsize=9) +fig.suptitle('RSM with one config for all tasks vs DINO-WM with one setting for all tasks (450 episodes per point, 95% CI)', + fontsize=12, color=INK) +fig.tight_layout(rect=(0, 0.08, 1, 0.96)) +fig.savefig(f'{ROOT}/status/rebuttal_default_beta.pdf') +fig.savefig(f'{ROOT}/status/rebuttal_default_beta.png', dpi=110) +print(open(f'{ROOT}/status/rebuttal_default_beta_table.md').read()) diff --git a/rsm_rise/scripts/region_report.py b/rsm_rise/scripts/region_report.py new file mode 100644 index 0000000000000000000000000000000000000000..a21b2ec555c9308dabe65c953e5fb672644100fe --- /dev/null +++ b/rsm_rise/scripts/region_report.py @@ -0,0 +1,45 @@ +"""Every result, grouped by the EVALUATION REGION it was measured in. docs/REGIONS.md + +The same checkpoint scores very differently depending on where the object is allowed to start, so a success rate +without its region is not a number. Each eval JSON records env.init_obj_range; this reads it back and reports, +per task and region, what was run there and how big that region is relative to the task's canonical one. +""" +import sys, glob, json +sys.path.insert(0, "/proj/dmfexp/zwhong/rsm_rise/scripts") +from verdict_table import region_of, region_area, canon_region_key, CANON, TASKS, SKIP +from collections import defaultdict + +ROOT = "/proj/dmfexp/zwhong/rsm_rise" +NICE = {"SquareNut=[-0.16,0.16],[-0.2,0.2]": "coverage (whole table)", + "SquareNut=[-0.115,-0.09],[-0.12,0.11]": "square_image_ood (small, displaced)", + "SquareNut=[-0.115,-0.11],[0.11,0.225]": "p0 (the expert sliver)", + "SquareNut=[0,0.12],[-0.225,0]": "p0 mirrored (diagnostic)", + "Piece1=[-0.22,0.22],[-0.22,0.22]": "coverage (whole table)", + "Piece1=[-0.22,-0],[0,0.22]": "expert quadrant (INVALID for coverage)"} +L = [__doc__.strip().split("\n")[0], "", + "Success rates are only comparable within a region. This lists every region any result was measured in, " + "so a number can never be quoted without its start distribution. The **canonical** region of each task is " + "the one the headline tables use; everything else is a diagnostic and is excluded from them automatically.", ""] +for task, _ in TASKS: + per = defaultdict(lambda: [0.0, 0, set(), None]) + for f in glob.glob(f"{ROOT}/runs/{task}/eval_*/*.json") + glob.glob(f"{ROOT}/runs/{task}/eval/*.json"): + if f.split("/")[-2] in SKIP: continue + try: j = json.load(open(f)) + except Exception: continue + n = j.get("num_episodes") or 0 + if not n or j.get("success_rate") is None: continue + k = region_of(j); e = per[k] + e[0] += j["success_rate"] * n; e[1] += n; e[2].add(f.split("/")[-2]); e[3] = region_area(j) + if not per: continue + ck = canon_region_key(task); nm = CANON.get(task, ("?", None))[0] + L += [f"## {task}", "", f"canonical region: **{nm}**" + (f" `{ck}`" if ck else " (env default, not overridden)"), "", + "| region | area m² | vs canonical | episodes | mean SR % | eval dirs |", "|---|---|---|---|---|---|"] + ca = per[ck][3] if ck in per else None + for k, (s, n, dirs, area) in sorted(per.items(), key=lambda kv: -kv[1][1]): + tag = NICE.get(k, k) + if ck is not None and k == ck: tag = "**" + tag + "** <- canonical" + rel = f"{area/ca:.3f}x" if (area and ca) else ("--" if area is None else "") + L.append(f"| {tag} | {'' if area is None else f'{area:.5f}'} | {rel} | {n} | {100*s/n:.1f} | {', '.join(sorted(dirs))} |") + L.append("") +open(f"{ROOT}/docs/REGIONS.md", "w").write("\n".join(L)) +print("\n".join(L)) diff --git a/rsm_rise/scripts/relabel_dino.py b/rsm_rise/scripts/relabel_dino.py new file mode 100644 index 0000000000000000000000000000000000000000..c8bd84a3609320a992412e2532feda6d3b7b97ce --- /dev/null +++ b/rsm_rise/scripts/relabel_dino.py @@ -0,0 +1,374 @@ +#!/usr/bin/env python +"""Stage-1 data cache for rsm_rise: DINOv2 ViT-S/14 features of a RISE robomimic hdf5. + +Writes, under --out (an rsm_libero `LiberoRSMData` cache dir): + z.f16.npy [N,1536] fp16 [agentview CLS(384) | agentview GeM(384) | wrist CLS | wrist GeM] + proprio.f32.npy [N,9] fp32 [eef_pos(3) | eef_quat(4) | gripper_qpos(2)] (data.py concatenates + it after z -> the 1545-d state, then z-scores with feat_stats.npz) + act.f32.npy [N,7] fp32 executed action at that frame + meta.npz ep_from/ep_to/ep_len/ep_task(all 0)/ep_success/ep_demo(all False)/ + ep_src(demo key)/ep_valid(hdf5 mask/valid)/tasks/dim/adim/stride/n_frames + feat_stats.npz mu/sd over ALL frames of [z|proprio] (dim=1545, sd floored at 1e-3), + the file data.py._fit_norm looks for (so every job uses one transform) + PACK.json encoder="dinov2_vits14_clsgem", cam_res=84, source hdf5 + sha256, layout + tokens/tok.f16.npy [N,514,384] fp16 memmap, same frame order: [agentview CLS, agentview 256 patches, + wrist CLS, wrist 256 patches] + tokens/TOKENS.json shape / dtype / token order + +Feature definition (matches RISE's DinoV2Core, robomimic/models/obs_core.py): image uint8 HWC -> +float [0,1] -> CHW (robomimic ObsUtils.process_frame, i.e. permute(0,3,1,2); NOT the (0,3,2,1) of +RISE's offline relabel_dino_features.py, which transposes H and W -- RISE's live training path +(dataset.py build_state_augmentation_data -> ObsUtils.process_obs -> DinoV2Core) never does that) +-> torchvision Resize(256) (bilinear; 84->256 is an upsample so antialias is irrelevant) -> +CenterCrop(224) -> ImageNet Normalize -> dinov2_vits14.forward_features -> x_norm_clstoken (384) and +x_norm_patchtokens (256x384). GeM on patches: clamp(min=1e-6), pow(4), avg over the 16x16 grid, +pow(1/4). Pooled per camera = [CLS | GeM] (768). All in fp32; stored fp16. +""" +from __future__ import annotations +import argparse, hashlib, json, os, sys, time +from pathlib import Path +import numpy as np +import h5py +import torch +import torch.nn as nn + +CAMS = ("agentview_image", "robot0_eye_in_hand_image") # order: agentview, wrist +PROPRIO = ("robot0_eef_pos", "robot0_eef_quat", "robot0_gripper_qpos") # 3 + 4 + 2 = 9 +D_TOK = 384 +N_PATCH = 256 +ENCODER_TAG = "dinov2_vits14_clsgem" +SD_FLOOR = 1e-2 # STATE DEFINITION (final): x = clip((feat - mu) / max(sd, SD_FLOOR), -Z_CLIP, Z_CLIP) +Z_CLIP = 10.0 + + +def sha256_file(path, bufsize=1 << 24): + h = hashlib.sha256() + with open(path, "rb") as f: + while True: + b = f.read(bufsize) + if not b: + break + h.update(b) + return h.hexdigest() + + +def load_dino(device): + hub_dir = os.environ.get("TORCH_HOME", os.path.expanduser("~/.cache/torch")) + "/hub" + repo = Path(hub_dir) / "facebookresearch_dinov2_main" + if repo.exists(): + m = torch.hub.load(str(repo), "dinov2_vits14", source="local") + else: + m = torch.hub.load("facebookresearch/dinov2", "dinov2_vits14") + return m.to(device).eval() + + +class DinoTransform(nn.Module): + """Exactly DinoV2Core.transform (torchvision Resize(256) -> CenterCrop(224) -> Normalize).""" + def __init__(self): + super().__init__() + from torchvision import transforms + self.t = transforms.Compose([ + transforms.Resize(256), + transforms.CenterCrop(224), + transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]), + ]) + + def forward(self, x): + return self.t(x) + + +def gem_pool(patch_tokens): + """DinoV2Core's GeM: [B,256,384] -> [B,384].""" + B = patch_tokens.shape[0] + pd = int(np.sqrt(patch_tokens.shape[-2])) + p = patch_tokens.reshape(B, pd, pd, -1).clamp(min=1e-6).permute(0, 3, 1, 2) + return nn.functional.avg_pool2d(p.pow(4), (pd, pd)).pow(1 / 4).reshape(B, -1) + + +@torch.no_grad() +def encode_images(model, tf, imgs_u8, device, batch): + """imgs_u8 [M,84,84,3] uint8 -> (pooled [M,768] fp32, tokens [M,257,384] fp32) on CPU.""" + pooled, toks = [], [] + for i in range(0, len(imgs_u8), batch): + x = torch.from_numpy(np.ascontiguousarray(imgs_u8[i:i + batch])).to(device) + x = x.float().div_(255.0).clamp_(0.0, 1.0).permute(0, 3, 1, 2) # ObsUtils.process_frame + x = tf(x) + f = model.forward_features(x) + cls, pt = f["x_norm_clstoken"], f["x_norm_patchtokens"] + assert pt.shape[1] == N_PATCH and pt.shape[2] == D_TOK, pt.shape + pooled.append(torch.cat([cls, gem_pool(pt)], -1).cpu()) + toks.append(torch.cat([cls[:, None], pt], 1).cpu()) + return torch.cat(pooled).numpy(), torch.cat(toks).numpy() + + +def write_stats(out, s1, s2, N, dim): + """feat_stats.npz: mu, sd = max(std, SD_FLOOR), z_clip. data.py applies clip(+-z_clip) after z-scoring.""" + out = Path(out) + mu = (s1 / N).astype(np.float64) + sd_raw = np.sqrt(np.maximum(s2 / N - mu ** 2, 0.0)) + degenerate = np.where(sd_raw < SD_FLOOR)[0] + sd = np.maximum(sd_raw, SD_FLOOR) + np.savez(out / "feat_stats.npz", mu=mu.astype(np.float32), sd=sd.astype(np.float32), dim=dim, n=N, + sd_floor=SD_FLOOR, z_clip=Z_CLIP, sd_raw=sd_raw.astype(np.float32), degenerate_dims=degenerate) + print(f"[relabel] feat_stats: {len(degenerate)} dims with raw sd < {SD_FLOOR}: {degenerate.tolist()} " + f"(raw sd {sd_raw[degenerate].round(5).tolist()}); z_clip={Z_CLIP}", flush=True) + return mu, sd, sd_raw, degenerate + + +def stats_only(out): + """Regenerate feat_stats.npz (+ PACK.json keys) from an existing cache without re-encoding.""" + out = Path(out) + z = np.load(out / "z.f16.npy", mmap_mode="r"); pr = np.load(out / "proprio.f32.npy", mmap_mode="r") + N, D = z.shape + s1 = np.zeros(D + pr.shape[1]); s2 = np.zeros(D + pr.shape[1]) + for i in range(0, N, 16384): + x = np.concatenate([np.asarray(z[i:i + 16384], np.float64), np.asarray(pr[i:i + 16384], np.float64)], -1) + s1 += x.sum(0); s2 += (x * x).sum(0) + mu, sd, sd_raw, degen = write_stats(out, s1, s2, N, D + pr.shape[1]) + # how many frames / dims hit the clip + hit_frames = 0; hit_dims = np.zeros(D + pr.shape[1], np.int64); maxabs = np.zeros(D + pr.shape[1]) + for i in range(0, N, 16384): + x = np.concatenate([np.asarray(z[i:i + 16384], np.float64), np.asarray(pr[i:i + 16384], np.float64)], -1) + x = (x - mu) / sd + hit = np.abs(x) > Z_CLIP + hit_frames += int(hit.any(1).sum()); hit_dims += hit.sum(0); maxabs = np.maximum(maxabs, np.abs(x).max(0)) + rep = {"sd_floor": SD_FLOOR, "z_clip": Z_CLIP, "degenerate_dims": degen.tolist(), + "degenerate_raw_sd": sd_raw[degen].round(6).tolist(), + "frames_hitting_clip": hit_frames, "frames_total": int(N), + "dims_hitting_clip": {int(k): int(v) for k, v in zip(np.where(hit_dims > 0)[0], hit_dims[hit_dims > 0])}, + "max_abs_x_after_floor_before_clip": float(maxabs.max()), "argmax_dim": int(maxabs.argmax())} + pk = json.loads((out / "PACK.json").read_text()) + pk.update({"sd_floor": SD_FLOOR, "z_clip": Z_CLIP, + "state_formula": "x = clip((feat - mu) / max(sd, 0.01), -10, 10) with feat = [z(1536) | proprio(9)], mu/sd from feat_stats.npz", + "feat_stats": "mu/sd over ALL frames of [z|proprio]; STATE = clip((feat - mu) / max(sd, sd_floor), -z_clip, z_clip)", + "state_stats_report": rep}) + (out / "PACK.json").write_text(json.dumps(pk, indent=2)) + print("[relabel] STATS " + json.dumps(rep), flush=True) + return rep + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--stats-only", action="store_true", help="regenerate feat_stats.npz/PACK.json keys from an existing --out") + ap.add_argument("--hdf5", default="") + ap.add_argument("--out", required=True) + ap.add_argument("--task-name", default="", help="stored in meta tasks[0]; default = hdf5 stem") + ap.add_argument("--batch", type=int, default=512, help="images per DINO forward") + ap.add_argument("--max-eps", type=int, default=0, help="0 = all (smoke tests only)") + ap.add_argument("--no-tokens", action="store_true") + ap.add_argument("--no-sha", action="store_true") + ap.add_argument("--validate", type=int, default=1) + ap.add_argument("--seed", type=int, default=0) + args = ap.parse_args() + if args.stats_only: + stats_only(args.out); return + + t0 = time.time() + dev = "cuda" if torch.cuda.is_available() else "cpu" + out = Path(args.out); out.mkdir(parents=True, exist_ok=True) + tokdir = out / "tokens" + if not args.no_tokens: + tokdir.mkdir(exist_ok=True) + task_name = args.task_name or Path(args.hdf5).stem + print(f"[relabel] {args.hdf5} -> {out} device={dev}", flush=True) + + f = h5py.File(args.hdf5, "r") + demos = sorted(f["data"].keys(), key=lambda s: int(s.split("_")[1])) + if args.max_eps: + demos = demos[:args.max_eps] + valid_set = set() + if "mask" in f and "valid" in f["mask"]: + valid_set = {v.decode() if isinstance(v, bytes) else str(v) for v in f["mask/valid"][:]} + lens = np.array([int(f["data"][k]["actions"].shape[0]) for k in demos], np.int64) + succ = np.array([bool(f["data"][k]["rewards"][:].max() > 0) for k in demos]) + for k, L in zip(demos, lens): + g = f["data"][k] + assert g["obs"][CAMS[0]].shape[0] == L and g["obs"][CAMS[1]].shape[0] == L, k + assert g["obs"][CAMS[0]].shape[1:] == (84, 84, 3), g["obs"][CAMS[0]].shape + ep_to = np.cumsum(lens); ep_from = ep_to - lens + N = int(ep_to[-1]); A = int(f["data"][demos[0]]["actions"].shape[1]) + D = 2 * 2 * D_TOK + print(f"[relabel] {len(demos)} episodes, N={N} frames, success {succ.sum()} " + f"({succ.mean():.3f}), A={A}, D={D}", flush=True) + + model = load_dino(dev) + tf = DinoTransform().to(dev) + print(f"[relabel] dinov2_vits14 loaded ({time.time()-t0:.1f}s)", flush=True) + + zmm = np.lib.format.open_memmap(out / "z.f16.npy", mode="w+", dtype=np.float16, shape=(N, D)) + pmm = np.lib.format.open_memmap(out / "proprio.f32.npy", mode="w+", dtype=np.float32, shape=(N, 9)) + amm = np.lib.format.open_memmap(out / "act.f32.npy", mode="w+", dtype=np.float32, shape=(N, A)) + tmm = None + if not args.no_tokens: + tmm = np.lib.format.open_memmap(tokdir / "tok.f16.npy", mode="w+", dtype=np.float16, + shape=(N, 2 * (1 + N_PATCH), D_TOK)) + # running sums for feat_stats over ALL frames (float64) + s1 = np.zeros(D + 9, np.float64); s2 = np.zeros(D + 9, np.float64) + + t_enc = time.time() + for i, k in enumerate(demos): + g = f["data"][k] + s, e = int(ep_from[i]), int(ep_to[i]) + per_cam = [encode_images(model, tf, g["obs"][c][:], dev, args.batch) for c in CAMS] + z = np.concatenate([per_cam[0][0], per_cam[1][0]], -1) # [T,1536] + pr = np.concatenate([np.asarray(g["obs"][p][:], np.float32) for p in PROPRIO], -1) + assert pr.shape == (e - s, 9), pr.shape + zmm[s:e] = z.astype(np.float16) + pmm[s:e] = pr + amm[s:e] = np.asarray(g["actions"][:], np.float32) + if tmm is not None: + tmm[s:e] = np.concatenate([per_cam[0][1], per_cam[1][1]], 1).astype(np.float16) + x = np.concatenate([z, pr], -1).astype(np.float64) + s1 += x.sum(0); s2 += (x * x).sum(0) + if (i + 1) % 20 == 0 or i + 1 == len(demos): + zmm.flush(); pmm.flush(); amm.flush() + if tmm is not None: + tmm.flush() + fps = e / max(time.time() - t_enc, 1e-6) + print(f"[relabel] {i+1}/{len(demos)} eps, {e}/{N} frames, {fps:.0f} frames/s, " + f"eta {(N-e)/max(fps,1e-6)/60:.1f} min", flush=True) + zmm.flush(); pmm.flush(); amm.flush() + if tmm is not None: + tmm.flush() + del zmm, pmm, amm, tmm + + write_stats(out, s1, s2, N, D + 9) + + ep_src = np.array(demos) + np.savez(out / "meta.npz", ep_from=ep_from, ep_to=ep_to, ep_len=lens, + ep_task=np.zeros(len(demos), np.int64), ep_success=succ, + ep_demo=np.zeros(len(demos), bool), + ep_valid=np.array([k in valid_set for k in demos]), + tasks=np.array([task_name]), dim=D, adim=A, stride=1, n_frames=N, ep_src=ep_src) + + sha = None if args.no_sha else sha256_file(args.hdf5) + pack = { + "cam_res": 84, "encoder": ENCODER_TAG, + "src": str(Path(args.hdf5).resolve()), "src_sha256": sha, + "src_size_bytes": os.path.getsize(args.hdf5), + "episodes": len(demos), "frames": N, "dim": D, "adim": A, "stride": 1, + "proprio_dim": 9, "state_dim": D + 9, + "success_rate": float(succ.mean()), "n_success": int(succ.sum()), + "n_demo": 0, "tasks": [task_name], "task_id_source": "single task, id 0", + "episode_success_rule": "rewards.max() > 0 (RISE: 1 on every frame of a successful episode)", + "z_layout": "[agentview CLS(384) | agentview GeM(384) | wrist CLS(384) | wrist GeM(384)]", + "proprio_layout": "[robot0_eef_pos(3) | robot0_eef_quat(4) | robot0_gripper_qpos(2)]", + "state": "data.py concatenates z (1536) and proprio (9) -> 1545, then z-scores with feat_stats.npz", + "feat_stats": "mu/sd over ALL frames of [z|proprio]; STATE = clip((feat - mu) / max(sd, sd_floor), -z_clip, z_clip)", + "sd_floor": SD_FLOOR, "z_clip": Z_CLIP, + "state_formula": "x = clip((feat - mu) / max(sd, 0.01), -10, 10) with feat = [z(1536) | proprio(9)], mu/sd from feat_stats.npz", + "image_pipeline": "uint8 HWC -> float/255 -> CHW (robomimic ObsUtils.process_frame, permute(0,3,1,2); " + "RISE's offline relabel_dino_features.py transpose(0,3,2,1) swaps H/W and is NOT " + "what DinoV2Core sees in RISE's training path, so it is not replicated) -> " + "torchvision Resize(256)+CenterCrop(224)+ImageNet Normalize -> dinov2_vits14 " + "forward_features -> CLS + GeM(patches: clamp 1e-6, pow 4, avg 16x16, pow 1/4)", + "precision": "fp32 compute, fp16 storage", + "tokens": None if args.no_tokens else "tokens/tok.f16.npy [N,514,384], see tokens/TOKENS.json", + "max_eps": args.max_eps, "torch": torch.__version__, + "written_by": "rsm_rise/scripts/relabel_dino.py", + } + (out / "PACK.json").write_text(json.dumps(pack, indent=2)) + if not args.no_tokens: + (tokdir / "TOKENS.json").write_text(json.dumps({ + "file": "tok.f16.npy", "shape": [N, 2 * (1 + N_PATCH), D_TOK], "dtype": "float16", + "format": "numpy .npy (np.load(..., mmap_mode='r'))", + "frame_order": "identical to ../z.f16.npy (episodes contiguous, ../meta.npz ep_from/ep_to)", + "token_order": ["agentview CLS (index 0)", "agentview 256 patches (1..256, row-major 16x16)", + "wrist CLS (257)", "wrist 256 patches (258..513)"], + "pooled_from_tokens": "per camera: [CLS | GeM(patches)] with GeM = clamp(1e-6).pow(4).mean(16x16).pow(1/4); " + "equals ../z.f16.npy to fp16 precision", + "encoder": ENCODER_TAG, "cam_res": 84, "input_res": 224, "src_sha256": sha, + }, indent=2)) + stats_only(out) # adds sd_floor/z_clip/state_formula + the clip-hit report to PACK.json + print(f"[relabel] cache written in {time.time()-t0:.0f}s: N={N}, " + f"z {N*D*2/1e9:.2f} GB, tokens {0 if args.no_tokens else N*514*384*2/1e9:.1f} GB", flush=True) + f.close() + + if args.validate: + validate(out, args.hdf5, N, seed=args.seed, tokens=not args.no_tokens) + print("[relabel] DONE", flush=True) + + +def validate(out, hdf5, N_expected, seed=0, tokens=True, n_check=100, n_nn=20): + out = Path(out) + rng = np.random.default_rng(seed) + m = np.load(out / "meta.npz", allow_pickle=True) + z = np.load(out / "z.f16.npy", mmap_mode="r") + pr = np.load(out / "proprio.f32.npy", mmap_mode="r") + a = np.load(out / "act.f32.npy", mmap_mode="r") + st = np.load(out / "feat_stats.npz") + res = {} + # (2) frame counts + with h5py.File(hdf5, "r") as f: + n_h5 = sum(int(f["data"][k]["actions"].shape[0]) for k in f["data"].keys()) + subset = int(json.loads((out / "PACK.json").read_text()).get("max_eps", 0) or 0) > 0 + ok_n = (z.shape[0] == N_expected == int(m["n_frames"]) == int(m["ep_to"][-1]) + and pr.shape[0] == N_expected and a.shape[0] == N_expected + and (n_h5 == N_expected or subset)) + res["frames"] = {"cache": int(z.shape[0]), "hdf5_total": n_h5, "expected": int(N_expected), + "ok": bool(ok_n), "z_shape": list(z.shape), "proprio_shape": list(pr.shape), + "act_shape": list(a.shape), "feat_stats_dim": int(st["dim"])} + nan_z = int(np.isnan(np.asarray(z[rng.integers(0, N_expected, 2000)], np.float32)).sum()) + res["frames"]["nan_in_2000_random_rows"] = nan_z + # (1) pooled recomputed from tokens + if tokens: + tok = np.load(out / "tokens" / "tok.f16.npy", mmap_mode="r") + idx = np.sort(rng.choice(N_expected, size=min(n_check, N_expected), replace=False)) + t = torch.from_numpy(np.asarray(tok[idx], np.float32)) # [n,514,384] + rec = [] + for c in range(2): + cls = t[:, c * 257] + pt = t[:, c * 257 + 1: (c + 1) * 257] + rec.append(torch.cat([cls, gem_pool(pt)], -1)) + rec = torch.cat(rec, -1).numpy() + zz = np.asarray(z[idx], np.float32) + err = np.abs(rec - zz) + # fp16 has ~11 bits: relative error 2^-11 ~ 4.9e-4; GeM of fp16-rounded patches adds a little + tol = 2e-2 * np.maximum(np.abs(zz), 1e-2) + res["pooled_vs_tokens"] = {"n_frames": int(len(idx)), "max_abs_err": float(err.max()), + "mean_abs_err": float(err.mean()), + "max_rel_err": float((err / np.maximum(np.abs(zz), 1e-3)).max()), + "frac_within_tol": float((err <= tol).mean()), + "ok": bool((err <= tol).all()), + "tok_shape": list(tok.shape)} + # (3) nearest neighbours in z-scored pooled state space are temporally adjacent + X = np.asarray(z, np.float32) + X = np.concatenate([X, np.asarray(pr, np.float32)], -1) + X = (X - st["mu"]) / st["sd"] + ep_from, ep_to = m["ep_from"], m["ep_to"] + ep_of = np.repeat(np.arange(len(ep_from)), ep_to - ep_from) + q = rng.choice(N_expected, size=min(n_nn, N_expected), replace=False) + Xn = (X * X).sum(1) + same_ep, within5, dts = 0, 0, [] + for i in q: + d2 = Xn - 2 * X @ X[i] + Xn[i] + d2[i] = np.inf + j = int(np.argmin(d2)) + same = ep_of[j] == ep_of[i] + same_ep += int(same); dt = abs(int(j) - int(i)) if same else None + within5 += int(same and dt <= 5); dts.append(dt) + res["nn_temporal"] = {"n_queries": int(len(q)), "nn_same_episode": same_ep, + "nn_within_5_frames": within5, "dt": dts} + # success / length correlation (the pack.py leakage note, quantified for this task) + L = m["ep_len"].astype(float); S = m["ep_success"].astype(float) + if S.std() > 0: + r = float(np.corrcoef(L, S)[0, 1]) + order = np.argsort(L); ranks = np.empty(len(L)); ranks[order] = np.arange(1, len(L) + 1) + npos = int(S.sum()); nneg = len(S) - npos + auc_len = float((ranks[S > 0].sum() - npos * (npos + 1) / 2) / (npos * nneg)) + else: + r, auc_len = float("nan"), float("nan") + res["success_vs_length"] = {"n_eps": int(len(L)), "n_success": int(S.sum()), + "len_mean_success": float(L[S > 0].mean()) if (S > 0).any() else None, + "len_mean_failure": float(L[S == 0].mean()) if (S == 0).any() else None, + "pointbiserial_r": r, "auc_length_predicts_success": auc_len} + res["sizes_bytes"] = {p.name: p.stat().st_size for p in list(out.glob("*")) if p.is_file()} + if tokens: + res["sizes_bytes"]["tokens/tok.f16.npy"] = (out / "tokens" / "tok.f16.npy").stat().st_size + (out / "VALIDATION.json").write_text(json.dumps(res, indent=2)) + print("[relabel] VALIDATION " + json.dumps(res), flush=True) + return res + + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/relaunch_mug_relaxed.py b/rsm_rise/scripts/relaunch_mug_relaxed.py new file mode 100644 index 0000000000000000000000000000000000000000..12548b20955bde7495778a9db6cec147e928a2d4 --- /dev/null +++ b/rsm_rise/scripts/relaunch_mug_relaxed.py @@ -0,0 +1,74 @@ +#!/usr/bin/env python3 +"""Re-evaluate mug-cleanup under the paper's RELAXED success criterion ("mug in drawer"; author communication +2026-09-21), with the RISE actor as the single proposer for the method comparison. + +The stock-criterion archive is quarantined in runs/mug_expert_suboptimal/_stock_success/. Everything here +lands in runs/mug_expert_suboptimal/eval_mugrelaxed/ with tag MUGRLX-es; eval_cell.sh exports +RSM_RISE_MUG_SUCCESS=in_drawer and eval.py records it, so verdict_table.cells() admits only these cells. + +Cells (3 policy seeds x 3 eval seeds x 50 episodes, N=128): + * per proposer family S0A (RISE actor), S0B (BC-u), S3H1 (BC-expert): greedy (BC), random- and permuted- + candidate controls at the flagship recipe, and for S0A the IQL-critic cell (S3H4 = RISE / IDQL ranking); + * RSM on the RISE actor: M_s1@best over beta {0.90,0.95,0.98} x hops {1,2,4,8} (the flagship recipe + M_s1@best b0.95 L1 is in the grid) -- one scorer sweep, disclosed; + * the flagship recipe on S3H1 and S0B as well, so Table 3/4 pair up. +""" +import subprocess, sys +from pathlib import Path + + +# IMPORT SAFETY (2026-09-21). A launcher must do NOTHING on import. `launch_rsm_on_actor.py` had its +# submission loop at module level, so `from launch_rsm_on_actor import FLAG` -- which scripts/scorer_rank_check.py +# does, to read the flagship recipe -- submitted the whole grid, reading the IMPORTER's sys.argv as its task +# list, and queued 36 jobs / 144 eval cells before it was caught. Every launcher here is guarded the same way. +def main(): + sys.path.insert(0, str(Path(__file__).resolve().parent)) + from launch_flagship_topup import ckpt + ROOT = Path("/proj/dmfexp/zwhong/rsm_rise") + TASK, ENV = "mug_expert_suboptimal", "robomimic_mug" + OUT = ROOT / f"runs/{TASK}/eval_mugrelaxed" + RSM = ROOT / f"runs/{TASK}/rsm/M_s1/ckpt_best.pt" + HOP = ROOT / f"runs/{TASK}/hop/gauss/policy_r1.pt" + dry = "--print-only" in sys.argv + BETAS, HOPS = (0.90, 0.95, 0.98), (1, 2, 4, 8) + + def run(extra, es): + cmd = [sys.executable, str(ROOT / "scripts/launch_e1_grid.py"), "--task", TASK, "--env", ENV, + "--model", f"Ms1b={RSM}:mlp", "--hop", str(HOP), "--num-rollouts", "50", "--horizon", "400", + "--eval-seed", str(es), "--tag", f"MUGRLX-es{es}", "--out-dir", str(OUT), "--pack", "4", + "--queue", "preemptable", "--primary-beta", "0.95", "--primary-depth", "1", *extra] + if dry: + cmd.append("--print-only") + r = subprocess.run(cmd, capture_output=True, text=True) + tail = [l for l in r.stderr.splitlines() if "jobs submitted" in l or "skipped" in l or "missing" in l] + print(" ", f"es{es}:", tail[-1:] or r.stderr.strip()[-200:]) + + for es in (0, 1, 2): + for fam in ("S0A", "S0B", "S3H1"): + pol = [] + for p in (0, 1, 2): + c = ckpt(TASK, fam, p) + if c: + pol += ["--policy", f"{fam}s{p}={c}"] + s0a = [] + if fam == "S0A": + for p in (0, 1, 2): + c = ckpt(TASK, "S0A", p) + if c: + s0a += ["--s0a", f"S0As{p}={c}"] + subset = "bc,random,permuted,s3h4" if fam == "S0A" else "bc,random,permuted" + print(f"### {fam} controls ({subset})") + run([*pol, *s0a, "--grid", "controls", "--controls-subset", subset], es) + cells = [] + for p in (0, 1, 2): + if not ckpt(TASK, fam, p): + continue + grid = [(b, L) for b in BETAS for L in HOPS] if fam == "S0A" else [(0.95, 1)] + for b, L in grid: + cells += ["--cells", f"Ms1b,{b},{L},{'d1' if L == 1 else 'fold'},128,argmax,{fam}s{p}"] + print(f"### {fam} RSM cells: {len(cells)//2}") + run([*pol, *cells], es) + + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/render_scenes.py b/rsm_rise/scripts/render_scenes.py new file mode 100644 index 0000000000000000000000000000000000000000..f8cbc3abfabca019f7e17a55a15d8c2701a75e77 --- /dev/null +++ b/rsm_rise/scripts/render_scenes.py @@ -0,0 +1,86 @@ +"""Render the actual simulator scenes behind the two findings. Needs a GPU (offscreen EGL). + +panelA: two-piece reset -- the agentview frame plus the object list, showing that only base and piece_1 are on + the table and piece_2 is not in the scene at all. +panelB: square resets under `robomimic_square` (the corner we evaluate in) vs `robomimic_square_coverage` + (the whole table), 12 resets each, tiled. +Writes docs/figs/render_two_piece.png and docs/figs/render_square_envs.png. +""" +from __future__ import annotations +import os, sys, json +from pathlib import Path +import numpy as np +import matplotlib; matplotlib.use("Agg") +import matplotlib.pyplot as plt + +ROOT = Path("/proj/dmfexp/zwhong/rsm_rise"); FIG = ROOT / "docs/figs"; FIG.mkdir(parents=True, exist_ok=True) +sys.path.insert(0, str(ROOT / "code/rise_code")) +os.environ.setdefault("MUJOCO_GL", "egl") + + +def build(cfg_name, seed=0): + from hydra import compose, initialize_config_dir + from sim_pipeline.envs.make_env import make_env + cfgdir = str(ROOT / "code/rise_code/sim_pipeline/configs") + with initialize_config_dir(config_dir=cfgdir, version_base=None): + c = compose(config_name="eval_robomimic_iql_diffusion", overrides=[f"+env={cfg_name}"]) + return make_env(c.env, seed=seed) + + +def frames(cfg_name, n, seed=0): + env = build(cfg_name, seed) + out, poses = [], [] + for i in range(n): + o = env.reset() + o = o[0] if isinstance(o, tuple) else o + img = None + for k in ("agentview_image", "agentview"): + if isinstance(o, dict) and k in o: + img = np.asarray(o[k]); break + if img is None: + base = env + while hasattr(base, "env"): base = base.env + img = base.sim.render(width=256, height=256, camera_name="agentview")[::-1] # direct mujoco render IS flipped + if img.ndim == 3 and img.shape[0] in (3, 4): img = np.transpose(img, (1, 2, 0)) + if img.dtype != np.uint8: img = (255 * np.clip(img, 0, 1)).astype(np.uint8) + out.append(img) + b = env + while hasattr(b, "env"): b = b.env + poses.append({k: np.round(b.sim.data.body_xpos[v], 4).tolist() + for k, v in getattr(b, "obj_body_id", {}).items()}) + return out, poses + + +def main(): + task = sys.argv[1] if len(sys.argv) > 1 else "both" + if task in ("both", "piece"): + imgs, poses = frames("robomimic_three_piece_assembly", 3) + fig, axes = plt.subplots(1, 3, figsize=(10, 3.9)) + for i, (ax, im) in enumerate(zip(axes, imgs)): + ax.imshow(im); ax.set_axis_off() + ax.set_title(f"reset {i}", fontsize=9) + fig.suptitle("Two-piece task as RISE configures it: base + piece_1 on the table, piece_2 absent", y=.99) + fig.text(.5, .03, "body positions at reset 0: " + json.dumps(poses[0]), ha="center", fontsize=6.5) + fig.text(.5, .005, "piece_2 sits at the compiled model origin, 0.74 m below the height the stock " + "success check requires.", ha="center", fontsize=7.5, style="italic") + fig.tight_layout(rect=[0, .07, 1, .97]); fig.savefig(FIG / "render_two_piece.png", dpi=150); plt.close(fig) + print("[done] render_two_piece.png", json.dumps(poses[0]), flush=True) + if task in ("both", "square"): + fig, axes = plt.subplots(2, 6, figsize=(12.6, 4.6)) + for r, (cfg, lab) in enumerate([("robomimic_square", "robomimic_square (what we evaluate in)"), + ("robomimic_square_coverage", "robomimic_square_coverage (the whole table)")]): + imgs, _ = frames(cfg, 6) + for c in range(6): + axes[r, c].imshow(imgs[c]) + axes[r, c].set_axis_off() + axes[r, 0].set_ylabel(lab) + axes[r, 0].text(-0.08, .5, lab, transform=axes[r, 0].transAxes, rotation=90, va="center", + ha="right", fontsize=8) + fig.suptitle("Six resets of each square env config: the nut lands in one corner vs anywhere on the table", + y=.98) + fig.tight_layout(rect=[0, 0, 1, .95]); fig.savefig(FIG / "render_square_envs.png", dpi=150); plt.close(fig) + print("[done] render_square_envs.png", flush=True) + + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/reports_index.py b/rsm_rise/scripts/reports_index.py new file mode 100644 index 0000000000000000000000000000000000000000..5d14e2c1d1dc2b22614103aee6354f28253a6e49 --- /dev/null +++ b/rsm_rise/scripts/reports_index.py @@ -0,0 +1,54 @@ +#!/usr/bin/env python3 +"""Tracked index of every report PDF: what it claims, its source, and whether it is stale. + +A PDF is STALE when its markdown/tex source is newer than it. That happens constantly here because +results land continuously, and a stale PDF looks identical to a fresh one. +""" +import os, time, subprocess +ROOT="/proj/dmfexp/zwhong/rsm_rise" +REPORTS=[ + ("MASTER_TABLE","docs/MASTER_TABLE.md","docs/MASTER_TABLE.pdf","scripts/master_table.py", + "Flagship results, split by reward regime. Section 1 is the only reward-matched comparison."), + ("RUNLIST_0_BASELINES","docs/RUNLIST_0_BASELINES.md","docs/RUNLIST_0_BASELINES.pdf","scripts/runlists.py", + "Every baseline evaluation cell behind the master table."), + ("RUNLIST_1_FLAGSHIP","docs/RUNLIST_1_FLAGSHIP.md","docs/RUNLIST_1_FLAGSHIP.pdf","scripts/runlists.py", + "Every provenance-reward RSM cell (section 1 + 4)."), + ("RUNLIST_2_ALTREWARD","docs/RUNLIST_2_ALTREWARD.md","docs/RUNLIST_2_ALTREWARD.pdf","scripts/runlists.py", + "Every env-success-reward cell. Currently empty: the backup flagship does not exist yet."), + ("RUNLIST_3_ORACLE","docs/RUNLIST_3_ORACLE.md","docs/RUNLIST_3_ORACLE.pdf","scripts/runlists.py", + "Every dense-privileged-reward cell. DISQUALIFIED, retained for traceability."), + ("OGBENCH_REPORT","docs/OGBENCH_REPORT.md","docs/OGBENCH_REPORT.pdf","scripts/ogbench_report.py", + "All OGBench: the 177-cell grid, the pointmaze horizon curve, and the perturbation-scale retraction."), + ("BETA_CURVE","docs/BETA_CURVE.md","docs/BETA_CURVE.pdf","scripts/betacurve_report.py", + "Mixture-series campaign: the scorer sign-flip headline and four figures."), + ("WHY_TASKS_DIFFER","docs/WHY_TASKS_DIFFER.md","docs/WHY_TASKS_DIFFER.pdf","(hand-written)", + "Why hopping helps on square-peg and hurts on piece-assembly: scorer quality."), + ("BIAS_VARIANCE","docs/tex/bias_variance.tex","docs/tex/bias_variance.pdf","(hand-written LaTeX)", + "Theory note: three propositions on horizon splitting, plus measurements."), +] +def ts(p): + q=os.path.join(ROOT,p) + return os.path.getmtime(q) if os.path.exists(q) else None +L=["# Report index","", + "Status is computed, not asserted: a PDF is STALE when its source is newer than it.", + f"Generated {time.strftime('%Y-%m-%d %H:%M')}.","", + "| report | status | source | built from | what it claims |","|---|---|---|---|---|"] +stale=[] +for name, src, pdf, gen, desc in REPORTS: + s, p = ts(src), ts(pdf) + if p is None: status="**MISSING**"; stale.append(name) + elif s is None: status="source missing" + elif p < s: status="**STALE**"; stale.append(name) + else: status="fresh" + age = f"{(time.time()-p)/3600:.1f}h old" if p else "--" + L.append(f"| `{name}` | {status} ({age}) | `{src}` | `{gen}` | {desc} |") +L += ["", f"**{len(stale)} report(s) need rebuilding**: {', '.join(stale) if stale else 'none'}.", "", + "Rebuild a markdown report:", "", + "```", + "RR_MEM=16G scripts/bsub_cpu.sh rr_cpu_pdf_ \\", + " venv_rsm/bin/python scripts/md2pdf.py docs/.md docs/.pdf --fit", + "```", "", + "`--fit` sizes the sheet to the widest table in the file and enables cell wrapping; without it", + "wide tables are clipped off the page rather than compressed.", ""] +open(os.path.join(ROOT,"docs/REPORTS.md"),"w").write("\n".join(L)+"\n") +print("\n".join(L[4:-10])) diff --git a/rsm_rise/scripts/results_table.py b/rsm_rise/scripts/results_table.py new file mode 100644 index 0000000000000000000000000000000000000000..2cea2bd8e8efa0c566af2ca559e2e7b347798000 --- /dev/null +++ b/rsm_rise/scripts/results_table.py @@ -0,0 +1,2547 @@ +#!/usr/bin/env python3 +"""THE deliverable table: scan every eval cell JSON of the project and write docs/RESULTS_TABLE.md + .csv. + +Sources per task (runs//): + eval_v1/*.json wave 1 (S0B pi_beta, N=128, prob read-out) + eval_v1_s0a_bc/*.json wave 1 (S0A pi_beta: BC rate + read-out-free controls) + eval_v1b/*.json wave 1b (priority set on the latest π_β checkpoint, logit read-out) + eval_v2/*.json wave 2 (logit read-out, particle ladder, DWM two-stage, calib/conformal) + eval_final/*.json final (epoch-5000 policies, 3 seeds x 100 rollouts) -> rows marked FINAL + eval_early_dwm/*.json early DWM probe (only with --include-early) + +One row per RSM recipe variation; rows that share a recipe but differ in pi_beta seed are POOLED (successes and +episodes summed, Wilson CI on the pool, seeds listed). RSM rows are sorted by success rate, the best one per task +is bold. Reference rows (paper, RISE-our-run = S3H4, BC, random-of-N, permuted) come first in their own block. + + python scripts/results_table.py # all tasks, writes docs/RESULTS_TABLE.{md,csv} + python scripts/results_table.py --task mug_expert_suboptimal --stdout + python scripts/results_table.py --no-partial # finished cells only (default: partials shown with *) + +Reads only small JSONs -> safe to run on the login node. +""" +from __future__ import annotations + +import argparse +import csv +import glob +import calendar +import json +import math +import os +import re +import sys +import time +from collections import defaultdict +from pathlib import Path + +ROOT = Path("/proj/dmfexp/zwhong/rsm_rise") + +# RISE paper (arXiv 2510.19495) Table I success rates, in %. +PAPER = { + "square_expert_play": dict(label="square play (Coverage)", bc=18.7, idql=19.6, rise=50.7), + "mug_expert_suboptimal": dict(label="mug (Suboptimal)", bc=31.3, idql=36.7, rise=40.7), + "square_expert_suboptimal": dict(label="square (Suboptimal)", bc=8.0, idql=41.3, rise=56.0), + # orchestrator 15:38: the paper-regime variant of square suboptimal -- 20 expert + 80 suboptimal episodes + # subsampled from the released file, trained with NO action augmentation (Table IV, T=0). Same paper row. + "square_sub_paper": dict(label="square (Suboptimal, paper regime 20+80, T=0)", + bc=8.0, idql=41.3, rise=56.0, + regime="Table IV regime: 20 expert + 80 suboptimal, augmentation T=0."), + + # --- orchestrator 17:16 (RISE authors, via Richard): the released HDF5s carry MORE demos than Table IV, + # --- so every released-file task gets a `_paper` sibling subsampled to the Table IV amounts. Both + # --- live in the table side by side; the released-file rows keep the "more data than Table IV" caveat so + # --- a reader never compares an over-fed run against the paper number. + "threading_expert_play": dict(label="threading (Coverage)", bc=17.3, idql=9.8, rise=22.7, + regime="released file (200 play + 250 expert) — MORE data than Table IV " + "(200+200); the paper-regime run is `threading_paper`."), + "threading_paper": dict(label="threading (Coverage, paper regime 200+200, T=0.08)", + bc=17.3, idql=9.8, rise=22.7, + regime="Table IV regime: all 200 play + a random 200 of the 250 expert " + "episodes (seed 0), augmentation T=0.08."), + "mug_paper": dict(label="mug (Suboptimal, paper regime 20+85, T=0.05)", + bc=31.3, idql=36.7, rise=40.7, + regime="Table IV regime: all 20 expert + a random 85 of the 100 " + "suboptimal episodes (seed 0), augmentation T=0.05."), + "two_piece_expert_suboptimal": dict(label="piece-assembly (Suboptimal)", bc=20.0, idql=35.7, rise=36.0, + regime="released file (20 expert + 100 suboptimal) — MORE data than " + "Table IV (10+100); the paper-regime run is `piecesub_paper`. " + "Eval env robomimic_three_piece_assembly_top_right (flat blocks)."), + "piecesub_paper": dict(label="piece-assembly (Suboptimal, paper regime 10+100, T=0)", + bc=20.0, idql=35.7, rise=36.0, + regime="Table IV regime: a random 10 of the 20 expert (seed 0) + all 100 " + "suboptimal, augmentation OFF (T=0). Eval env " + "robomimic_three_piece_assembly_top_right (flat-block caveat)."), + "two_piece_expert_play_tipping": dict(label="piece-assembly (Coverage, tipped env)", + bc=0.0, idql=8.0, rise=51.3, + regime="released file evaluated on robomimic_three_piece_assembly_tipped; " + "the paper-regime run is `piecetip_paper`."), + "piecetip_paper": dict(label="piece-assembly (Coverage, paper regime 200+104+199, T=0.08)", + bc=0.0, idql=8.0, rise=51.3, + regime="Table IV regime: all 200 expert + the 104 TIPPED non-expert " + "episodes (initial Piece1 quaternion not a pure z-rotation) + a " + "random 199 of the remaining flat non-expert episodes (seed 0), " + "augmentation T=0.08. Eval env " + "robomimic_three_piece_assembly_tipped."), + "two_piece_expert_play": dict(label="piece-assembly (Coverage, flat env)", + bc=0.0, idql=8.0, rise=51.3, + regime="already at the Table IV amounts (200 expert + 199 play), so there " + "is no `_paper` sibling. Two caveats. (1) The paper's Coverage " + "row is the TIPPED variant: compare `piecetip_paper` to the paper " + "column, not this row. (2) Cells launched before 2026-09-19 05:10 " + "UTC ran robomimic_three_piece_assembly_top_right — the EXPERT's " + "own quadrant (p0), the one distribution a coverage eval cannot " + "use (`launch_e1_grid.py:63`, fixed 05:10); cells after it run the " + "stock whole-table config. See the env WARNING table below: the " + "two groups do not overlap at all."), +} +TASK_ORDER = [ + # released-file tasks first, then their Table IV siblings, so a reader meets the caveat before the number + "square_expert_play", "mug_expert_suboptimal", "square_expert_suboptimal", + "threading_expert_play", "two_piece_expert_play", "two_piece_expert_suboptimal", + "two_piece_expert_play_tipping", + "square_sub_paper", "threading_paper", "mug_paper", "piecesub_paper", "piecetip_paper", +] + +# ---- orchestrator 18:16 + stream A 18:30/18:40: the ThreePieceAssembly success check did not fire ---- +# Stream A traced it (status/A_env_stage0.md): `_check_success()` required piece_2 stacked on piece_1, but in +# BOTH two_piece datasets piece_2 is inert, so the env returned success=0 for every episode no matter what the +# policy did. A guard was patched in; it takes effect only for jobs that STARTED after the timestamp below. +# Every two-piece eval JSON written before it is a measurement of the broken check, not of the policy: the +# table keeps the rows (they are still the record of what ran) but marks each with a dagger and refuses to +# treat them as results. +PIECE_TASKS = {"two_piece_expert_play", "two_piece_expert_suboptimal", "two_piece_expert_play_tipping", + "piecesub_paper", "piecetip_paper"} +# mtime of code/mimicgen_environments/mimicgen_envs/envs/robosuite/three_piece_assembly.py when the guard +# landed. A cell is judged by when its PROCESS started (Python imports the env module once, at startup), which +# the JSON gives as (last write - wall_time_s). Stream A's own `patchchk_*` verification cells are post-patch +# by construction (that is what they were submitted to test) and are exempt. +PIECE_PATCH_TS = calendar.timegm((2026, 9, 18, 18, 33, 26, 0, 0, 0)) +PIECE_WARN = ( + "\u26a0\ufe0f **Success detection was BROKEN for this task until 2026-09-18 18:40 UTC.** The env's " + "`_check_success()` required piece_2 to be stacked on piece_1, but piece_2 is inert in both two-piece " + "datasets, so **every** episode scored 0 regardless of the policy (stream A, `status/A_env_stage0.md`; " + "stream A's post-patch verification cell `patchchk_S0B_seed2_ep5000` reads **46.7 % (n=30)** on the " + "exact checkpoint that read **0/100 on all three eval seeds** before it). Rows " + "marked \u2021 were written before the patch and are **INVALID \u2014 do not read them as results**; " + "they are being re-run. Unmarked rows use the patched check and are still labelled " + "\u201csuccess detection newly patched, criterion under review\u201d until the " + "`RSM_RISE_PIECE_DZ_TOL` A/B (job 1770920) settles whether xy-only insertion is too lenient.\n\n" + "> **Success criterion for both piece-assembly tasks (orchestrator 20:10):** success = " + "`first_piece_assembled`, **xy-only** \u2014 MimicGen's stock `_check_success()` with only the terms that " + "reference piece_2 dropped, because the released RISE config never places piece_2. `RSM_RISE_PIECE_DZ_TOL` " + "stays unset; the dz-strict variant is reported as a sensitivity footnote (`sr_dz0.05`) on final selected " + "checkpoints only, and is **not** used to rank or re-run anything. No piece row should be read without " + "this sentence. `sr_dz0.05` is blank until a final checkpoint on a piece task is selected." +) + +# directory -> wave label +WAVES = [("eval_v1", "v1"), ("eval_v1_s0a_bc", "v1"), ("eval_v2", "v2"), + # wave 1b (orchestrator 15:09): the priority set re-run on the LATEST π_β checkpoint per task + ("eval_v1b", "v1b"), + # stream A's plain policy evals (runs//eval/S*_seed*_es*.json, policy_mode=bc, 100 rollouts): + # the π_β base rate at a given checkpoint, i.e. the row every RSM cell has to beat. + ("eval", "pol"), + ("eval_val", "VAL"), ("eval_final", "FINAL"), + # orchestrator 20:11: a COMPLETE final table at a matched policy epoch (every arm, incl. the RISE + # flagship, at epoch 3000) while S0A is still short of 5000. Its own directory, its own wave label, + # so no arm is ever compared across policy epochs. + ("eval_final_e3000", "FINAL@3000"), + # orchestrator 23:2x recipe-coverage audit (STATUS.md): the cheap ablation grid on + # square_expert_suboptimal / S0B epoch 5000 / eval seed 0 -- N ladder 8/16/256, rules + # softmax0.05 + topk8, conformal_lcb q=0.10/0.25, particles 16384/32768. Same policy epoch as + # FINAL but ONE eval seed, so it is deliberately NOT in WAVE_STANDING: these rows are shown and + # sortable but can never be bolded as the headline best over a held-out 3-seed FINAL cell. + ("eval_abl", "abl"), + # orchestrator 04:37 (2026-09-19): VERIFY re-runs every arm on RISE's policy for EVERY available S0A + # TRAINING seed (x3 eval seeds x 50 rollouts), so a flagship-beating claim rests on n=3 policy seeds + # and not on one. Its own wave label: 50 rollouts, so it must never outrank a 100-rollout FINAL cell. + ("eval_verify", "VERIFY"), + # orchestrator 04:37: the RISE-policy sweep (4 betas x 2 hops x {M,L40} x {ckpt_best,ckpt_s100k}) on + # the tasks where RSM does not yet beat the plain policy. Selection wave -- one eval seed. + ("eval_risesweep", "sweep"), + # ------------------------------------------------------------------ stream D 2026-09-19 06:25 + # Audit of runs//eval*/ against this list found 133 finished JSONs in directories the + # deliverable never opened: eval_ckptsweep (76), eval_bsweep (33), eval_bigN (13), eval_horizon (11), + # eval_ckptseed1 (3), eval_eefnoise (2). They are real measurements (the RSM-checkpoint sweep, the + # beta sweep, the large-N ladder that is this stream's own assignment), so they are scanned now. + # Each gets its OWN wave label: `wave` is in RECIPE_KEYS, so a selection cell can never pool with a + # FINAL/VERIFY cell of the same recipe, and none of these labels is in WAVE_STANDING, so they are + # shown and sortable but can never be bolded as a task's headline over a held-out wave. + ("eval_ckptsweep", "ckptsweep"), ("eval_ckptsweep_cov", "ckptsweep_cov"), + ("eval_ckptseed1", "ckptseed"), ("eval_ckptseed2", "ckptseed"), + ("eval_bsweep", "bsweep"), ("eval_bigN", "bigN"), + # eval_horizon runs a NON-400 rollout horizon and eval_eefnoise perturbs the eef -- neither shows up + # in the env's init_obj_range, so the wave label is the only thing keeping them out of the normal + # rows. `horizon` is also in RECIPE_KEYS now so two horizons cannot pool inside this wave either. + ("eval_horizon", "horizon"), ("eval_eefnoise", "eefnoise"), + # orchestrator 2026-09-19 05:5x / 07:00 / 07:10 waves (STATUS.md): the bc-path re-measurement, the + # WIN sweeps, and the progress-reward head. Wired up before their JSONs land. + ("eval_bcfix", "bcfix"), ("eval_win", "WIN"), ("eval_prog", "PROG"), + # stream D 06:30: "RISE policy, greedy" on the COVERAGE init distribution (see COV_NOTE) -- the + # existing two_piece_play greedy cells were all measured on the expert's own quadrant. + ("eval_covfix", "covfix"), + # orchestrator 07:05: the scorer-present-vs-absent diagnostic on two_piece_play S0B seed 0. All four + # cells are on the STOCK env and agree (0.23-0.29), which is what retired the "scorer loaded => bad" + # hypothesis; kept in the table as a labelled diagnostic wave, never standing. + ("eval_pathdiag", "pathdiag")] +EARLY = [("eval_early_dwm", "early")] + +EPOCH_RE = re.compile(r"model_epoch_(\d+)\.pth") +RSM_STEP_RE = re.compile(r"ckpt_s(\d+)\.pt") +# Longest-first: "S3H1nosn_seed0" must not match the "S3H1" alternative and then fail on "_seed" (it did, +# so every no-spectral-norm cell parsed as policy "?"), and S0Aidql must not be read as S0A. +POLICY_RE = re.compile(r"/policy/(S0Aidql|S3H1nosn|S0A|S0B|S3H1)_seed(\d+)/") + + +def rsm_step_label(rsm_ckpt): + """Which successor checkpoint a row scored with (orchestrator 13:26: state it in every row).""" + if not rsm_ckpt: + return "-" + m = RSM_STEP_RE.search(rsm_ckpt) + if m: + return f"s{int(m.group(1)) // 1000}k" if int(m.group(1)) % 1000 == 0 else f"s{m.group(1)}" + b = os.path.basename(rsm_ckpt) + if b.startswith("ckpt_best_early"): + return "best(early)" + if b.startswith("ckpt_w2"): + return "best@13:41" + if b.startswith("ckpt_best"): + return "best(live)" + return b.replace("ckpt_", "").replace(".pt", "") + + +def wilson(k, n, z=1.96): + if not n: + return (float("nan"), float("nan")) + p = k / n + den = 1.0 + z * z / n + c = (p + z * z / (2 * n)) / den + h = z * math.sqrt(p * (1 - p) / n + z * z / (4 * n * n)) / den + return (max(0.0, c - h), min(1.0, c + h)) + + +SELECTION_EVAL_SEED = 0 # the seed every recipe was ranked on; seeds 1,2,... are held out + + +def mcnemar(a_succ, b_succ, seeds=None): + """Exact two-sided McNemar on two arms that share init states. + + `a_succ` / `b_succ` map (eval_seed, episode index) -> success. Two eval cells run at the same eval seed + replay the SAME reset states, so the episodes are paired; the paired test only looks at the discordant + pairs and is much more powerful than comparing two independent Wilson intervals at n=150. + Returns (n_pairs, b, c, diff, lo, hi, p) where b = A wins / B loses, c = A loses / B wins. + """ + keys = sorted(set(a_succ) & set(b_succ)) + if seeds is not None: + keys = [k for k in keys if k[0] in seeds] + if not keys: + return None + n = len(keys) + b = sum(1 for k in keys if a_succ[k] and not b_succ[k]) + c = sum(1 for k in keys if b_succ[k] and not a_succ[k]) + diff = (b - c) / n + # Wald CI for the difference of two paired proportions (Agresti, eq. for matched pairs) + var = (b + c - (b - c) ** 2 / n) / (n * n) + h = 1.96 * math.sqrt(max(var, 0.0)) + m = b + c + if m == 0: + pval = 1.0 + else: + tail = sum(math.comb(m, i) for i in range(0, min(b, c) + 1)) / (2.0 ** m) + pval = min(1.0, 2.0 * tail) + return (n, b, c, diff, diff - h, diff + h, pval) + + +# 2026-09-19 07:45 (stream D): `env` added. Without it a paired McNemar could pair an RSM cell run on the +# expert quadrant against a BC/random control run on the coverage box whenever the two shared (wave, policy, +# epoch) -- the episodes pair by (eval seed, episode index), so the test would silently compare two different +# initial-state distributions and attribute the whole gap to the read-out. `eval_risesweep` on +# two_piece_expert_play holds exactly that mix today (5 top-right cells alongside stock ones). +ARM_KEY = ("wave", "policy", "epoch", "env") + + +def arm_key(r): + """The (wave, pi_beta, epoch) an arm was run under. + + Arms may only be compared inside one of these groups: a paired McNemar between an epoch-5000 RSM arm and + an epoch-2500 BC arm would replay the same init states but score two DIFFERENT policies, so the policy + epoch would be confounded with the read-out that the test is supposed to be measuring. + """ + return tuple(r[k] for k in ARM_KEY) + + +def paired_tests(esp, group=None, n_val=None): + """Pairwise McNemar of the best RSM arm against every control arm, on the eval-seed-pooled rows. + + `group` restricts the comparison to one (wave, policy, epoch); with group=None the best RSM arm anywhere + is taken and the controls are restricted to ITS group (never across policy epochs -- see arm_key()). + `n_val` additionally restricts the reference arm to one candidate budget N (the paper's 64 vs the released + code's 128), so the N=64 "paper-faithful" block is tested on its own. + + The resampling controls (random / permuted) are matched on N: "does the read-out beat picking one of the + SAME N candidates at random" is only that question when both arms drew the same number of candidates. + BC (N=1) is a different-budget control on purpose and stays. + """ + if group is not None: + # The RISE flagship lives on the S0A policy by construction (see `_ctrl_ok` below), so a strict + # arm_key match would drop it here -- before `ctrls` is even built -- and no per-wave block could + # ever contain the project's headline comparison. Admit it on matching (wave, epoch). + gw, _gp, ge = group[0], group[1], group[2] + gv = group[ARM_KEY.index("env")] + esp = [r for r in esp + if arm_key(r) == group + or (r["kind"] == "S3H4" and r["wave"] == gw and r["epoch"] == ge + and r.get("env") == gv)] + rsm = [r for r in esp if r["kind"] == "RSM" and r.get("ep_succ") + and (n_val is None or r["N"] == n_val)] + ctrls = [r for r in esp if r["kind"] in ("random", "BC", "permuted", "S3H4") and r.get("ep_succ")] + if not rsm or not ctrls: + return [] + # The reference arm must be a COMPLETE arm whenever one exists. Picking by max SR across arms of + # unequal n systematically favours the SHORT ones: a still-running pooled arm has a wider sampling + # distribution, so it wins the argmax more often than its true SR warrants, and the headline then + # drifts every time a partial cell wobbles. (2026-09-18 22:35: on square (Suboptimal) `FINAL` this + # had selected L40 at 70.7 % n=215* over the finished M arm at 66.3 % n=300, disagreeing with the + # project's own headline.) Fall back to partials only if no finished RSM arm exists in the block, + # and tell the reader -- `ref_partial` drives that sentence. + # + # 2026-09-18 23:45 -- and it must be chosen on the SELECTION eval seed, not on the pooled rate. + # The FINAL wave deliberately carries ONE argmax arm per successor model (M, L40, M_s1, DWM), so an + # argmax over pooled SR re-ranks recipes ON THE HELD-OUT SEEDS -- exactly what this file's preamble + # promises never happens ("recipes are frozen by the seed-0 grids and are never re-ranked on final + # numbers"), and it makes the `held-out only` p-value a max over K arms with no multiplicity + # correction. The reference arm is now picked by its eval-seed-0 rate (the declared selection seed) + # and tested on seeds 1,2 -- selection and test are then disjoint by construction. `arms_considered` + # carries every finished arm so the renderer can show how many the max was taken over. + done_arms = [r for r in rsm if not r.get("partial")] + pool = done_arms or rsm + def _sel_rate(r): + ks = [k for k in r["ep_succ"] if k[0] == SELECTION_EVAL_SEED] + if not ks: + return None + return sum(1 for k in ks if r["ep_succ"][k]) / len(ks), len(ks) + scored = [(r, _sel_rate(r)) for r in pool] + on_sel = [(r, sr) for r, sr in scored if sr is not None] + if on_sel: + a = max(on_sel, key=lambda t: (t[1][0], t[1][1]))[0] + ref_basis = "sel" + else: + a = max(pool, key=lambda r: (r["sr"], r["n"])) + ref_basis = "pooled" + ref_partial = not done_arms + arms_considered = [(r, sr) for r, sr in scored] + def _ctrl_ok(b): + """Which controls may be paired against the reference RSM arm `a`. + + BC / random-of-N / permuted must be on the SAME policy arm: they exist to isolate the read-out, so a + different pi_beta would confound the policy with the scorer. The RISE flagship (S3H4) is the one + control that is cross-policy BY CONSTRUCTION -- the RISE method is "the S0A policy re-ranked by its + own IQL critic", so it can never live on the S0B arm the RSM cells run on. Requiring a full arm_key + match therefore silently dropped it from every block (2026-09-19 02:25): square (Suboptimal)'s + matched-epoch `FINAL@3000` block listed BC, permuted and random-of-128 but NOT the flagship, i.e. the + project's headline comparison was missing from the only block entitled to make it, while + `scripts/paired_final_test.py` computed it all along (+19.0 pts, p<0.0001). For S3H4 the guard that + matters is the EPOCH (and the wave), which is exactly what FINAL@3000 was built to match. + """ + if b["kind"] == "S3H4": + return (b["wave"] == a["wave"] and b["epoch"] == a["epoch"] + and b.get("env") == a.get("env")) + return (arm_key(b) == arm_key(a) + and (b["kind"] not in ("random", "permuted") or b["N"] == a["N"])) + + ctrls = [b for b in ctrls if _ctrl_ok(b)] + if not ctrls: + return [] + out = [] + held = {s for s in (set(k[0] for k in a["ep_succ"]) | set(k[0] for k in a["ep_succ"])) + if s is not None and s != SELECTION_EVAL_SEED} + for b in ctrls: + res = mcnemar(a["ep_succ"], b["ep_succ"]) + if res and res[0] >= 20: + ho = mcnemar(a["ep_succ"], b["ep_succ"], seeds=held) if held else None + out.append((a, b, res, ho if (ho and ho[0] >= 20) else None)) + for o in out: + o[0]["ref_partial"] = ref_partial + o[0]["ref_basis"] = ref_basis + o[0]["arms_considered"] = arms_considered + return out + + +def fmt(x, nd=1, dash="-"): + if x is None or (isinstance(x, float) and math.isnan(x)): + return dash + return f"{x:.{nd}f}" + + +# ---------------------------------------------------------------- loading ----------------------------------------- +def policy_map_from_jobs(d: Path): + """cell name -> policy checkpoint, parsed from the launcher's job scripts (partial JSONs carry no `checkpoint`).""" + out = {} + for sh in glob.glob(str(d / "jobs" / "*.sh")): + try: + txt = Path(sh).read_text() + except OSError: + continue + for line in txt.splitlines(): + if "eval_cell.sh" not in line: + continue + toks = line.split() + try: + i = next(j for j, t in enumerate(toks) if t.endswith("eval_cell.sh")) + except StopIteration: + continue + cell = next((t.split("=", 1)[1] for t in toks if t.startswith("exp.eval_cell=")), None) + if cell and len(toks) > i + 2: + out.setdefault(cell, toks[i + 2]) + return out + + +def dir_progress(d: Path): + """(cells launched, JSONs written, partials in flight) for one eval directory, from its job scripts.""" + if not d.is_dir(): + return (0, 0, 0) + launched = len(policy_map_from_jobs(d)) + done = len([f for f in glob.glob(str(d / "*.json"))]) + part = len(partial_files(d, {Path(f).name for f in glob.glob(str(d / "*.json"))})) + return (launched, done, part) + + +def _n_ep_of(f): + try: + return int(json.load(open(f)).get("num_episodes") or 0) + except Exception: + return 0 + + +PARTIAL_SUFFIXES = (".json.partial", ".json.partial_best") + + +def partial_files(d: Path, done=()): + """cell-json-name -> the LONGEST partial file for that cell, over BOTH partial flavours. + + `scripts/eval_cell.sh` keeps a crashed attempt's furthest progress in `.json.partial_best` and the + next attempt resumes from the furthest COMPATIBLE partial, so a cell's episodes can live in either file. + This loader used to glob `*.json.partial` only, so 58 `.partial_best` files were invisible to the + deliverable: their episodes were dropped, and in the FINAL coverage matrix such a cell rendered as + **DEAD (no job)** even though it had 59 of 100 episodes on disk (mug `E1-M-R0.90-2-N64-random ... es2`, + found 2026-09-18 23:10). `scripts/paired_final_test.py` already read both, so the table and the paired + test were reading different data. Only ONE file per cell may be returned: two rows of the same cell get + POOLED downstream, which would count the same episodes twice. + """ + cand = defaultdict(list) + for suf in PARTIAL_SUFFIXES: + for f in sorted(glob.glob(str(d / ("*" + suf)))): + base = Path(f).name[:-len(suf)] + ".json" + if base in done: + continue + cand[base].append(f) + return {b: max(fs, key=_n_ep_of) for b, fs in cand.items()} + + +def load_dir(task, d: Path, wave, include_partial): + """-> list of per-cell dicts.""" + if not d.is_dir(): + return [] + jobs = policy_map_from_jobs(d) + files = sorted(glob.glob(str(d / "*.json"))) + done = {Path(f).name for f in files} + if include_partial: + files += sorted(partial_files(d, done).values()) + out = [] + for f in files: + if Path(f).name.lower().startswith("smoke"): # runs//eval also holds n=3/5 smoke JSONs + continue + try: + j = json.load(open(f)) + except Exception: + continue + if not j.get("num_episodes"): + continue + cell = j.get("cell") or Path(f).name.split(".json")[0] + ck = j.get("checkpoint") or j.get("checkpoint_file") or jobs.get(cell) or "" + row = parse_cell(task, wave, d.name, cell, j, ck, bool(j.get("partial"))) + # A two-piece cell measured the BROKEN success check unless its PROCESS STARTED after the patch: + # a job that was already running kept the old module in memory, so a post-patch mtime proves nothing. + # start = last write - wall clock spent in the rollout loop (both are recorded in the JSON). + if task in PIECE_TASKS: + try: + started = os.path.getmtime(f) - float(j.get("wall_time_s") or 0.0) + except OSError: + started = 0.0 + row["prepatch"] = (started < PIECE_PATCH_TS + and not Path(f).name.startswith("patchchk")) + else: + row["prepatch"] = False + out.append(row) + return out + + +def parse_cell(task, wave, dirname, cell, j, ckpt, partial): + p = j.get("planner") or {} + sc = p.get("scorer") or {} + n_ep = int(j["num_episodes"]) + k = int(round(float(j["success_rate"]) * n_ep)) + + backend = p.get("rsm_backend") or "" + plan_n = p.get("plan_n") + single = not plan_n or plan_n == 1 # BC / plain policy eval: no planner, so no planner columns + + # 2026-09-19 05:45 (stream D). A cell with NO `training.plan_n` at all is NOT automatically a greedy + # policy eval. `eval.py:364-381`: plan_n=None falls through to the `policy_mode` branch, and with + # `policy_mode=idql` (the eval config's DEFAULT, `configs/exp/_eval/evaluation.py:56`) the rollout policy + # is `RobomimicSamplingRolloutPolicy`, which draws **num_samples = 128** action chunks and ranks them with + # the policy's own IQL critic -- i.e. the RISE released eval, the flagship arm. Only `policy_mode=bc` + # (or an explicit plan_n=1) gives one diffusion sample with no selection. + # `scripts/launch_stage0_evals.sh:83` passes `exp.policy_mode=idql` for EVERY S0A cell and `=bc` for + # S0B/S3H1, so all 97 S0A `eval/`+`eval_val` cells were flagship measurements being rendered as + # "RISE policy, greedy". That mislabel also manufactured a fake "eval-path divergence": on + # two_piece_expert_suboptimal S0A seed 0 @5000, same 3 eval seeds, the `eval/` cells read 16.3 % and the + # plan_n=1 cells 35.3 % -- not two paths for one arm but two DIFFERENT arms, the critic costing ~19 pts. + SAMPLING_N = 128 # robomimic_sampling_rollout_policy.py:63 + critic_sampled = (not plan_n) and str(j.get("policy_mode", "idql")) != "bc" + rule = "-" if single else (p.get("plan_rule") or "argmax") + if rule == "softmax": + rule = f"softmax{p.get('plan_temp')}" + elif rule == "topk_uniform": + rule = f"topk{p.get('plan_topk')}" + + # model label: runs//rsm//ckpt*.pt -> NAME + rsm_ckpt = p.get("rsm_ckpt") or "" + m = re.search(r"/rsm/([^/]+)/", rsm_ckpt) + if m: + model = m.group(1) + elif backend == "iql": + model = "IQL critic" + elif backend == "mc": + model = "MC (S3H5)" + elif not plan_n or plan_n == 1: + model = "-" + elif backend == "dwm": + model = "DWM" + else: + model = backend or "?" + if backend == "dwm" and ("ckpt_best_early" in rsm_ckpt or "frozen" in rsm_ckpt): + model += "(early)" + + # particles / two-stage screening + part = p.get("plan_particles") + rt = p.get("plan_rescore_top") or 0 + pr = p.get("plan_particles_rescore") or 0 + if backend in ("iql", "mc") or not plan_n or plan_n == 1: + parts = "-" + elif rt and pr: + parts = f"{part}->{pr}@top{rt}" + else: + parts = str(part) + + score = p.get("plan_score") or ("-" if backend in ("iql", "mc") or not plan_n or plan_n == 1 else "prob") + + # temperature / calibration / conformal flag + temp_ov = p.get("plan_temperature") + T = sc.get("temperature") + flags = [] + if score == "conformal_lcb": + lq = p.get("plan_lcb_quantile") + flags.append(f"conformal q={lq:g}" if isinstance(lq, (int, float)) else "conformal") + if temp_ov: + flags.append(f"T={temp_ov:g}") + elif T is not None and abs(float(T) - 1.0) > 1e-6: + flags.append(f"calib T={float(T):.3g}") + temp_flag = "+".join(flags) if flags else "-" + + mep = EPOCH_RE.search(ckpt or "") + epoch = int(mep.group(1)) if mep else None + mpol = POLICY_RE.search(ckpt or "") + pol_kind, pol_seed = (mpol.group(1), int(mpol.group(2))) if mpol else ("?", None) + if dirname == "eval_v1_s0a_bc" and pol_kind == "?": + pol_kind = "S0A" + + pt = j.get("planner_time") or {} + steps = pt.get("steps_total") or 0 + t_plan = (pt.get("t_sample_s") or 0.0) + (pt.get("t_score_s") or 0.0) + + # row kind + if critic_sampled: + kind, plan_n = "S3H4", SAMPLING_N # released RISE eval: best-of-128 under the policy's own critic + elif not plan_n or plan_n == 1: + kind = "BC" + elif rule == "random": + kind = "random" + elif rule == "permuted": + kind = "permuted" + elif backend == "iql": + kind = "S3H4" + elif backend == "mc": + kind = "S3H5" + else: + kind = "RSM" + + # Knobs that the cell never used must not enter the recipe key, or ONE arm is split into several rows. + # Verified against `code/rise_robomimic/robomimic/algo/rsm_planner.py`: + # rule == "random" -> the scorer is never constructed (`if rule == "random": scores = zeros`), so the + # model, beta, L, mode, particles and score read-out are all inert; + # backend == "iql" -> `IQLCriticBackend.score` is a single-step critic over (obs, action), so the + # successor knobs (beta, L, mode, particles, plan_score) are inert; + # plan_n <= 1 -> nothing is ranked, so every selection knob is inert. + # Without this, mug's RISE-policy-greedy arm showed up as two rows (`prob` and `logit`) that were the + # same 100 episodes, and a `random-of-128` control launched from the M grid did not pool with the + # identical one launched from the L40 grid. + inert = single or rule == "random" or backend == "iql" + _env_ok, _env_exp = env_valid(task, j) + if inert: + model = "-" if rule == "random" else model + return dict( + task=task, wave=wave, dirname=dirname, cell=cell, kind=kind, partial=partial, + env=env_label(j), env_ok=_env_ok, env_expected=_env_exp, + model=model, beta=None if inert else p.get("plan_beta"), + L=None if inert else p.get("plan_depth"), mode=None if inert else p.get("plan_mode"), + N=plan_n, particles="-" if inert else parts, score="-" if inert else score, + rule="-" if single else rule, temp_flag="-" if inert else temp_flag, + n_particles=part, rescore_top=rt, particles_rescore=pr, lcb_quantile=p.get("plan_lcb_quantile"), + policy=pol_kind, epoch=epoch, seed=pol_seed, checkpoint=ckpt, rsm_ckpt=rsm_ckpt, + rsm_step=rsm_step_label(rsm_ckpt), + k=k, n=n_ep, sr=(k / n_ep if n_ep else float("nan")), + mean_len=j.get("mean_length"), steps=steps, t_plan=t_plan, + gap=pt.get("gap_chosen_minus_mean"), ties=pt.get("ties_at_max_mean"), + wall_ep=j.get("wall_time_per_episode_s"), horizon=j.get("rollout_horizon"), + eval_seed=j.get("eval_seed"), requested=j.get("num_rollouts_requested"), + reset_states=j.get("reset_states_file"), + # per-episode outcomes keyed by (eval_seed, episode index): two cells run at the SAME eval seed see the + # SAME init states, so arms are PAIRED episode-by-episode and McNemar applies (see paired_tests()). + ep_succ={(j.get("eval_seed"), int(e.get("episode", i))): bool(e.get("success")) + for i, e in enumerate(j.get("episodes") or [])}, + ) + + +# ---------------------------------------------------------------- aggregation ------------------------------------- +RECIPE_KEYS = ("wave", "kind", "model", "beta", "L", "mode", "N", "particles", "score", "rule", + "temp_flag", "policy", "epoch", "rsm_step", "eval_seed", + # a cell run to a different rollout horizon is a different experiment (eval_horizon). + "horizon", + # the initial-state distribution the cell actually ran (see EVAL ENV CONFIG above): two cells + # on different init boxes are different experiments, not two seeds of one. + "env", + # never pool a two-piece cell that ran under the BROKEN success check with one that ran under + # the patched one -- that would launder an invalid 0/100 into a valid row (see PIECE_WARN). + "prepatch") + + +def pool(rows): + """Pool a list of per-seed cells of the same recipe into one row.""" + r0 = dict(rows[0]) + k = sum(r["k"] for r in rows) + n = sum(r["n"] for r in rows) + lo, hi = wilson(k, n) + lens = [(r["mean_len"], r["n"]) for r in rows if r["mean_len"] is not None] + steps = sum(r["steps"] for r in rows) + t_plan = sum(r["t_plan"] for r in rows) + gaps = [(r["gap"], r["n"]) for r in rows if r["gap"] is not None] + per_seed = defaultdict(lambda: [0, 0]) + for r in rows: + # pool() is also called on already-pooled rows (eval-seed pooling, grid means). Such a row carries + # the FIRST cell's `seed` field but episodes from several seeds, so merging its `per_seed` map is the + # only correct read -- keying on r["seed"] there would credit every episode to one training seed. + for sd, (a, b) in (r.get("per_seed") or {r["seed"]: (r["k"], r["n"])}).items(): + ps = per_seed[sd] + ps[0] += a; ps[1] += b + r0.update( + k=k, n=n, sr=k / n if n else float("nan"), lo=lo, hi=hi, + # The 05:10 protocol reports the MEAN OVER TRAINING SEEDS with the per-seed values shown, which is not + # the same number as the pooled rate whenever the seeds carry different episode counts. Keeping the + # breakdown on the row is what lets every table print it without re-reading the JSONs. + per_seed={s: (a, b) for s, (a, b) in per_seed.items()}, + seeds=sorted({r["seed"] for r in rows if r["seed"] is not None}), + n_cells=len(rows), partial=any(r["partial"] for r in rows), + mean_len=(sum(a * b for a, b in lens) / sum(b for _, b in lens)) if lens else float("nan"), + s_per_step=(t_plan / steps) if steps else float("nan"), + gap=(sum(a * b for a, b in gaps) / sum(b for _, b in gaps)) if gaps else None, + cells=sorted(r["cell"] for r in rows), + prepatch=any(r.get("prepatch") for r in rows), + ep_succ={k2: v for r in rows for k2, v in (r.get("ep_succ") or {}).items()}, + ) + return r0 + + +# ---------------------------------------------------------------- EVAL ENV CONFIG --------------------------- +# 2026-09-19 05:10 (stream D). A row is only comparable to another row if BOTH ran the same initial-state +# distribution. That is not automatic here: `scripts/launch_e1_grid.py` (planner cells) and +# `scripts/launch_stage0_evals.sh` (stream A's plain-policy `pol`/`VAL` cells) each carry their OWN task -> +# env-config map, and on `two_piece_expert_play` they disagreed -- the grids ran the expert's top-right +# quadrant (p0) while the policy evals ran the stock whole-table coverage config. Same checkpoint, same eval +# seeds, 44 points apart (28.9 % n=350 vs 72.7 % n=300 on S0B_seed0@5000), which is what the 04:50 STATUS +# entry logged as a "SUSPECTED EVAL-PATH BUG" (policy_mode bc vs idql). It is not a code-path bug: of the 15 +# checkpoints measured on both code paths, 13 agree. +# +# So the env config is identified from the JSON itself -- `env.init_obj_range` plus whether a reset-states +# file pins the inits -- rather than trusted from the launcher, and it is part of RECIPE_KEYS so that two +# cells on different init distributions can never pool into one row. +ENV_CFG_DIR = Path("code/rise_code/sim_pipeline/configs/env") +_ENV_SIGS = None + + +def _norm_rng(rng): + """{object -> rounded range tuple}, float-tolerant.""" + return {k: tuple(round(float(x), 4) for lo_hi in v for x in lo_hi) for k, v in (rng or {}).items()} + + +def _env_cfgs(): + """[(config name, declared init_obj_range, pins-reset-states)], parsed from the released env configs. + + A config declares only the objects IT randomises; the runtime env dict a JSON records also carries the + keys inherited from `robomimic_base` (every piece JSON carries `SquareNut`). So the match below is + "declared is a subset of observed", resolved by specificity, not dict equality. + """ + global _ENV_SIGS + if _ENV_SIGS is not None: + return _ENV_SIGS + _ENV_SIGS = [] + ns = {"np": __import__("numpy"), "math": math, "pi": math.pi} + for f in sorted(ENV_CFG_DIR.glob("robomimic_*.py")): + try: + txt = f.read_text() + except OSError: + continue + m = re.search(r"init_obj_range[^=]*=\s*field\(default_factory=lambda:\s*(\{.*?\})\s*\)", txt, re.S) + if not m: + continue + try: # threading/tool configs use expressions (np.pi/2), so eval + rng = eval(re.sub(r"#.*", "", m.group(1)), ns) # noqa: S307 - our own repo's config files + except Exception: + continue + _ENV_SIGS.append((f.stem, _norm_rng(rng), bool(re.search(r"reset_states_file[^=\n]*=\s*'", txt)))) + return _ENV_SIGS + + +def _box_str(rng): + """Compact, never-wrong description of the initial-state box actually recorded in the JSON.""" + parts = [] + for k, v in sorted(_norm_rng(rng).items()): + if all(abs(x) < 1e-9 for x in v): # pinned-at-reference objects carry no information + continue + parts.append(k + "".join(f"[{v[i]:g},{v[i + 1]:g}]" for i in range(0, len(v) - 1, 2))) + return " ".join(parts) or "-" + + +def env_label(j): + """Which initial-state distribution a cell actually ran. + + Returns the released config's name when exactly one most-specific config explains the recorded ranges + (e.g. `3piece_top_right`), otherwise a literal description of the box -- never a name that might be + wrong, because the whole point of this column is to stop incomparable rows being read side by side. + """ + e = j.get("env") or {} + obs = _norm_rng(e.get("init_obj_range")) + pinned = bool(e.get("reset_states_file") or j.get("reset_states_file")) + if not obs: + return "-" + hits = [(len(rng), name) for name, rng, pin in _env_cfgs() + if rng and pin == pinned and all(obs.get(k) == v for k, v in rng.items())] + best = max((n for n, _ in hits), default=0) + names = sorted({nm for n, nm in hits if n == best}) + lab = _box_str(e.get("init_obj_range")) + if len(names) == 1: + lab = (names[0].replace("robomimic_three_piece_assembly", "3piece") + .replace("robomimic_threading", "threading") + .replace("robomimic_square", "square").replace("robomimic_", "")) + if lab == "base": # robomimic_base's SquareNut box, inherited by square/mug + lab = "stock" + return lab + (" +pinned-inits" if pinned else "") + + +# ---------------------------------------------------------------- EVAL ENV VALIDITY ------------------------ +# A task DEFINES the initial-state distribution it is evaluated on; a cell run on any other distribution is +# not a weaker measurement of that task, it is a measurement of a different task. This became concrete on +# 2026-09-19: `launch_e1_grid.py` mapped `two_piece_expert_play` (a COVERAGE task) to the expert's own +# top-right quadrant until the 05:10 fix, so every planner cell on it was a p0 cell -- and they read 58-75 % +# against 0-35 % for the same checkpoints on the coverage box. The orchestrator quarantined 135 of them at +# 07:15 (`runs//_invalid_top_right/`), but 11 survive in directories the move did not cover and ~62 +# more are still QUEUED from pre-fix job scripts, so a table that trusts the directory layout will start +# publishing p0 numbers again the moment they land. The guard below is therefore on the cell's OWN recorded +# env, mirroring `scripts/launch_e1_grid.py:ENV_OF` (kept in sync by hand; a task missing here is unchecked). +TASK_ENV_CFG = { + "square_expert_play": "robomimic_square_coverage", + "square_expert_suboptimal": "robomimic_square", + "square_sub_paper": "robomimic_square", + "mug_expert_suboptimal": "robomimic_mug", + "mug_paper": "robomimic_mug", + "threading_expert_play": "robomimic_threading_coverage", + "threading_paper": "robomimic_threading_coverage", + "two_piece_expert_play": "robomimic_three_piece_assembly", + "two_piece_expert_suboptimal": "robomimic_three_piece_assembly_top_right", + "piecesub_paper": "robomimic_three_piece_assembly_top_right", + "two_piece_expert_play_tipping": "robomimic_three_piece_assembly_tipped", + "piecetip_paper": "robomimic_three_piece_assembly_tipped", +} + + +def env_valid(task, j): + """(is the cell on the task's own init distribution?, the config name it should be on). + + Unchecked -- returns (True, None) -- when the task is not in the map, when the expected config declares + no `init_obj_range` of its own (it inherits `robomimic_base`, so there is nothing to disagree with), or + when the JSON records no env at all. The test is the same "declared is a subset of observed" match + `env_label` uses, plus the pinned-reset-states flag, which is the ONLY thing separating + `three_piece_assembly` from `three_piece_assembly_tipped`. + """ + cfg = TASK_ENV_CFG.get(task) + if not cfg: + return True, None + e = j.get("env") or {} + obs = _norm_rng(e.get("init_obj_range")) + if not obs: + return True, None + pinned = bool(e.get("reset_states_file") or j.get("reset_states_file")) + for name, rng, pin in _env_cfgs(): + if name != cfg: + continue + if not rng: + return True, None + return (pin == pinned and all(obs.get(k) == v for k, v in rng.items())), cfg + return True, None + + +# ---------------------------------------------------------------- LABEL CONVENTION ------------------------- +# Orchestrator 2026-09-19 04:05 UTC (STATUS.md "LABEL CONVENTION"): every table in this deliverable uses +# exactly these names, and EVERY RSM row must name the policy it selects from. The names map onto the +# paper's Sec. V terms: +# BC-expert (S3H1) = the paper's "Behavior cloning" -- trained on D_E only +# BC-unified (S0B) = the paper's "Behavior cloning unified" -- trained on D_E u D_NE +# RISE policy, greedy (S0A) = RISE's pi_B acting with NO selection -- not a paper row +# RISE flagship (S3H4) = the paper's "RISE" -- S0A + its own IQL critic, best-of-N +# RSM (on ) = ours -- successor value over N candidates +# The raw S0A/S0B/S3H1 codes stay in RESULTS_TABLE.csv (machine-readable) and in parentheses in the Markdown, +# so a reader can still trace a row back to a checkpoint path. +POLICY_LABEL = {"S3H1": "BC-expert", "S3H1nosn": "BC-expert, no spectral norm", + "S0B": "BC-unified", "S0A": "RISE policy", + # orchestrator 04:40: the offline-RL baseline the paper compares against -- the S0A trainer + # with the spectral norm, the bottleneck and both augmentations switched OFF. + "S0Aidql": "IDQL policy"} + + +def policy_label(policy, code=True): + """Convention name for a pi_beta arm, e.g. "BC-unified (S0B)".""" + lab = POLICY_LABEL.get(policy) + if lab is None: + return str(policy) + return f"{lab} ({policy})" if code else lab + + +def kind_label(kind, policy=None, N=None, long=False): + """Convention name for one row, given its kind and the policy it ran on. + + `BC` is plan_n=1, i.e. no selection at all -- so it is simply the named policy acting greedily, and its + label is the POLICY's convention name (the orchestrator's point: "greedy 24.2" is BC-unified, not + BC-expert). Every other kind names the policy it selects from. + """ + if kind == "BC": + base = policy_label(policy) + if policy in ("S0A", "S0Aidql"): # a critic-trained pi_B with the critic switched off + code = f" ({policy})" + base = base.replace(code, f", greedy{code}") if code in base else base + ", greedy" + return base + (" — plan_n=1, no selection" if long else "") + if kind == "S3H4": + # best-of-N under the policy's OWN jointly-trained IQL critic. On S0A that is the paper's RISE row; + # on the no-augmentation/no-spectral-norm policy it is the paper's IDQL row (orchestrator 04:40). + if policy == "S0Aidql": + return "IDQL" + (f" (IDQL policy + its own IQL critic, N={N})" if long + else f" (S0Aidql + IQL critic, N={N})") + if policy not in ("S0A", "?"): + # best-of-N under a NON-RISE policy's own critic (e.g. the S0B/S3H1 `eval_eefnoise` cells, which + # ran with the eval config's default policy_mode=idql). It is the same mechanism but it is not + # the paper's RISE row, which is defined by the S0A training recipe. + return f"best-of-{N} under own IQL critic (on {policy_label(policy, code=False)})" + return "RISE flagship" + (f" (RISE policy + its own IQL critic, N={N})" if long + else f" (S0A + IQL critic, N={N})") + if kind == "S3H5": + return f"MC critic control (on {policy_label(policy, code=False)}, N={N})" + if kind == "random": + return f"random-of-{N} (on {policy_label(policy, code=False)})" + if kind == "permuted": + return f"permuted scores (N={N}, on {policy_label(policy, code=False)})" + if kind == "RSM": + return f"RSM (on {policy_label(policy, code=False)})" + return str(kind) + + +# ---------------------------------------------------------------- FINAL coverage matrix ------------------------- +# Orchestrator 20:09 (4): "an arm missing a seed that another arm has is the one failure mode that silently +# biases the comparison". Every FINAL wave is therefore rendered as {arm} x {pi_beta seed} x {eval seed} +# before any number is read off it. +def arm_label(c): + if c["kind"] == "RSM": + return (f"{c['model']} \u03b2={fmt(c['beta'], 2)} L={c['L']} N{c['N']} " + f"P{c['particles']} {c['score']} {c['rule']}") + return kind_label(c["kind"], c.get("policy"), c["N"]) + + +FINAL_CELL_RE = re.compile( + r"^(?P.+?)-(?Ps0a-)?e(?P\d+)-(?P.+)-es(?P\d+)-s(?P\w+)$") +FINAL_DIRS = {"FINAL": "eval_final", "FINAL@3000": "eval_final_e3000"} + + +_LIVE_JOBS = None + + +def live_job_names(): + """Set of LSF job names currently in a live state, or None if bjobs is unavailable. + + The coverage matrix used to call any cell without a JSON "queued", which is indistinguishable from a cell + whose job died (exit 134 / preemption) -- exactly the silent-bias failure the matrix exists to catch. + """ + global _LIVE_JOBS + if _LIVE_JOBS is not None: + return _LIVE_JOBS if _LIVE_JOBS != "unavailable" else None + import subprocess + try: + r = subprocess.run(["bjobs", "-u", "zwhong", "-noheader", "-o", "stat job_name delimiter=','"], + capture_output=True, text=True, timeout=120) + if r.returncode not in (0, 255): + raise RuntimeError(r.stderr[:200]) + names = set() + for line in r.stdout.splitlines(): + p_ = line.strip().split(",") + if len(p_) >= 2 and p_[0] in ("RUN", "PEND", "PSUSP", "SSUSP", "USUSP", "PROV", "WAIT"): + names.add(p_[1]) + _LIVE_JOBS = names + return names + except Exception: + _LIVE_JOBS = "unavailable" + return None + + +# stream D 2026-09-19 06:30. `FINAL_CELL_RE` only parses the `-[s0a-]e--es-s` +# naming that `launch_wave2.py --step final` emits. An audit of runs//eval_final/ found that naming is +# now the MINORITY: of the cells on disk, ~120 carry the orchestrator's 02:50 `FLAG5000` tag +# (`-FLAG5000[-S0A_seed]-es-s0a`), 36 carry `ctl`, 27 carry `f5k`, and `_final_key` returns None for +# every one of them. Two consequences, both bad: the FINAL@5000 flagship wave -- the whole point of the block +# -- was INVISIBLE in the coverage matrix, and its `launch_wave2.py`-named siblings showed as **DEAD (no job)** +# although the measurement exists under the other tag, inviting exactly the duplicate relaunch Round 24 warned +# about (square play alone showed 6 such cells). +# Fix: stop parsing the epoch / policy / seed out of the NAME and read them from the cell's own metadata -- +# the checkpoint path and `exp.eval_seed`, both of which are present in the parsed JSON row AND on the +# `eval_cell.sh` line of the job script, so queued-but-not-yet-written cells are still keyed correctly. +# The name is used only for the arm label, truncated at whichever wave tag it carries. +# The arm is the recipe identity ONLY: everything from the wave tag onwards (and the trailing eval-seed / +# policy-seed suffix, which the metadata already supplies) is stripped, so the same arm measured under two +# tags lands on one row instead of one row per tag per eval seed. +FINAL_TAG_RE = re.compile(r"-(?:FLAG5000|ctl|f5k|COVFIX|VERIFY\w*|onRISEpol|qwin\w*|bcu\w*|s0a|e\d+)(?:-|$)") + + +def _final_arm(cell): + c = re.sub(r"-es\d+-s\w+$", "", cell) + if c == cell: + c = re.sub(r"-es\d+$", "", c) + if c == cell: + c = re.sub(r"-s\w+$", "", c) + m = FINAL_TAG_RE.search(c) + return c[:m.start()] if m else c + + +def _final_key_meta(cell, ckpt, eval_seed): + """(arm label, epoch, pi_beta seed, eval seed) from a cell's checkpoint + eval seed, or None.""" + if eval_seed is None or not ckpt: + return None + mep = EPOCH_RE.search(ckpt) + mpol = POLICY_RE.search(ckpt) + if not mep or not mpol: + return None + arm = _final_arm(cell) + (" [on the S0A policy]" if mpol.group(1).startswith("S0A") else "") + return arm, int(mep.group(1)), mpol.group(2), int(eval_seed) + + +def _final_key(cell): + """Name-only fallback, for cells whose checkpoint could not be recovered.""" + m = FINAL_CELL_RE.match(cell) + if not m: + return None + arm = m.group("arm") + (" [on the S0A policy]" if m.group("s0a") else "") + return arm, int(m.group("epoch")), m.group("sd"), int(m.group("es")) + + +def _final_planned_from_jobs(d: Path): + """[(cell, key, job script stem)] for every cell named by a job script in /jobs/.""" + out = [] + for sh in sorted((d / "jobs").glob("*.sh")) if (d / "jobs").is_dir() else []: + try: + txt = sh.read_text() + except OSError: + continue + for line in txt.splitlines(): + if "eval_cell.sh" not in line: + continue + toks = line.split() + try: + i = next(j for j, t in enumerate(toks) if t.endswith("eval_cell.sh")) + except StopIteration: + continue + cell = next((t.split("=", 1)[1] for t in toks if t.startswith("exp.eval_cell=")), None) + if not cell: + continue + ckpt = toks[i + 2] if len(toks) > i + 2 else None + es = next((t.split("=", 1)[1] for t in toks if t.startswith("exp.eval_seed=")), None) + try: + es = int(es) if es is not None else None + except ValueError: + es = None + key = _final_key_meta(cell, ckpt, es) or _final_key(cell) + if key: + out.append((cell, key, sh.stem)) + return out + + +GRID_DIRS = [("eval_v1", "wave 1"), ("eval_v1b", "wave 1b"), ("eval_v2", "wave 2")] + + +def grid_completeness(tasks): + """md lines: planned vs landed vs live cells for each selection grid. + + The per-task "best RSM recipe" is an argmax over the grid cells that ACTUALLY LANDED. If a grid only + half-ran, that argmax is taken over a biased subset and nothing else in the table says so -- this block + is the check. Planned = every `exp.eval_cell=` in /jobs/*.sh; landed = a final (non-partial) JSON. + """ + live = live_job_names() + rows = [] + for t in tasks: + for dname, label in GRID_DIRS: + d = ROOT / "runs" / t / dname + if not (d / "jobs").is_dir(): + continue + planned, cell_live = set(), {} + for sh in sorted((d / "jobs").glob("*.sh")): + is_live = live is None or sh.stem in live + for cell in re.findall(r"exp\.eval_cell=(\S+)", sh.read_text()): + planned.add(cell) + cell_live[cell] = cell_live.get(cell, False) or is_live + if not planned: + continue + landed = {c for c in planned if (d / f"{c}.json").exists()} + running = {c for c in planned - landed if cell_live.get(c)} + dead = planned - landed - running + rows.append((t, label, len(landed), len(running), len(dead), len(planned))) + if not rows: + return [] + out = ["## Selection-grid completeness — how much of each (β, L) grid actually ran", "", + "The bolded \"best RSM recipe\" per task is an argmax over the grid cells that LANDED. A grid that " + "only partly ran makes that argmax a choice over a biased subset, and no other block in this table " + "would show it. `dead` = the job script names the cell, no JSON exists and no LSF job is live — those " + "are resubmitted each round; a non-zero `dead` count means the recipe ranking for that task is " + "provisional.", "", + "> Every dead **wave 1 / wave 1b** cell is a cell of the *same* \u03c0_\u03b2 seed as the cells that landed " + "(checked 21:55: all `-s1`), so those grids really are half-run, not double-counted. They are NOT " + "resubmitted: **wave 2 is the selection grid of record** — it spans the same 16 (\u03b2, L) cells per " + "model with the better read-out (`plan_score=logit`) and is now fully in flight on all three main " + "tasks. Until wave 2 lands on mug and square play, the bolded recipe there comes from a wave-1 grid " + "that only ran 21/52 and 10/52 cells and must be read as provisional.", "", + "| task | grid | landed | running | dead | planned | complete |", "|---|---|---|---|---|---|---|"] + for t, label, nl, nr, nd, np_ in rows: + out.append(f"| `{t}` | {label} | {nl} | {nr} | {'**' + str(nd) + '**' if nd else '0'} | {np_} | " + f"{'yes' if nl == np_ else 'no'} |") + out.append("") + return out + + +def final_coverage(task, raw, waves=("FINAL@3000", "FINAL")): + """md lines: per FINAL wave, done / running / queued / MISSING for every (arm, pi_beta, eval seed). + + The planned set is read from the LSF job scripts in /jobs/ as well as from the JSONs, so an arm that + has not written a single episode yet still shows up -- an arm entirely absent from the matrix is exactly + the failure the matrix exists to catch. + """ + out = [] + for w in waves: + d = ROOT / "runs" / task / FINAL_DIRS[w] + got = {} + for c in raw: + if c["wave"] != w: + continue + # metadata first (the cell's own checkpoint + eval seed), name only as a fallback. + k = (_final_key_meta(c["cell"], c.get("checkpoint"), c.get("eval_seed")) + or _final_key(c["cell"])) + if k: + prev = got.get(k) + cur = f"{c['n']}" + ("* (running)" if c["partial"] else "") + # two tags for the same (arm, epoch, seed, eval seed) are the SAME measurement duplicated; + # show the finished one rather than letting a partial mask it. + if prev is None or (prev.endswith("(running)") and not c["partial"]): + got[k] = cur + planned = set(got) + live = live_job_names() + key_live = {} # (arm, epoch, sd, eseed) -> True if ANY job script naming it has a live LSF job + for cell, k, stem in _final_planned_from_jobs(d): + is_live = live is None or stem in live + planned.add(k) + key_live[k] = key_live.get(k, False) or is_live + got.setdefault(k, "queued") + # a cell with no JSON and no live job is DEAD, not queued; a partial with no live job is STALLED. + for k, v in list(got.items()): + if live is None or key_live.get(k, True): + continue + if v == "queued": + got[k] = "**DEAD (no job)**" + elif v.endswith("* (running)"): + got[k] = v.split("*")[0] + "* **STALLED**" + if not planned: + continue + eseeds = sorted({k[3] for k in planned}) + rows_ = sorted({k[:3] for k in planned}) + out.append(f"#### {task} — `{w}` coverage") + out.append("") + out.append("| arm | epoch | π_β seed | " + " | ".join(f"eval seed {e}" for e in eseeds) + " | complete |") + out.append("|---|---|---|" + "---|" * (len(eseeds) + 1)) + n_missing = 0 + for arm, ep, sd in rows_: + cells_ = [got.get((arm, ep, sd, e), "**MISSING**") for e in eseeds] + n_missing += sum(1 for v in cells_ if v.startswith("**") or "DEAD" in v or "STALLED" in v) + done = all(v.isdigit() for v in cells_) + out.append(f"| `{arm}` | {ep} | s{sd} | " + " | ".join(cells_) + f" | {'yes' if done else 'no'} |") + out.append("") + ep_arg = w.split("@")[1] if "@" in w else "5000" + out.append(f"_{'No missing or dead cells' if not n_missing else f'**{n_missing} missing/dead cells**'} in `{w}`; " + f"`launch_wave2.py --step final --final-epoch {ep_arg}` is idempotent and resubmits exactly " + f"the gaps._") + out.append("") + return out + + +# Exact re-measurements found by `dedupe_measurements`, as (task, wave, kept, dropped, n, dropped?). +DUP_CELLS = [] + + +def dedupe_measurements(rows): + """Drop exact re-measurements of one arm before pooling. + + Cells of the SAME recipe at the same π_β CHECKPOINT and the same eval seed replay the SAME initial states + -- the eval seed fixes the env's init-state sequence -- so summing their k/n counts the same episodes + twice: the Wilson interval shrinks by ~sqrt(2) on evidence that does not exist, and the paired McNemar + arms stop lining up episode for episode. This fires whenever two waves of jobs measure one arm under two + different cell TAGS, which is not hypothetical: on 2026-09-19 the RISE-policy-greedy arm at epoch 5000 was + launched both as `BC-FLAG5000-es{k}-s0a` (the head-to-head set) and as `BC-s0a-e5000-...-es{k}` (the FINAL + relay's control block) on mug and square play. + + Matching on the full checkpoint PATH, not on (seed, epoch), is deliberate: several cells carry no parsed + π_β seed at all, and keying on a None seed collapsed genuinely different checkpoints + (`S0A_seed1_ep3500` vs `S0A_seed0_ep5000`) into one "duplicate". + + Stream A's `pol` wave is REPORTED but never dropped: its diagnostic re-runs (`patchchk_*`, `dz05_*`) share + a checkpoint with the plain policy eval but are deliberately different measurements (a patched success + check, a different dead zone), and this table cannot see that distinction in the row -- so a human decides. + Keeps the most-evidenced copy: finished over partial, then larger n, then lexicographic cell name. + """ + if len(rows) < 2: + return rows + by, out = defaultdict(list), [] + for r in rows: + if not r.get("checkpoint"): # no checkpoint parsed -> cannot prove it is the same arm, keep it + out.append(r) + else: + by[(r["checkpoint"], r["eval_seed"])].append(r) + for g in by.values(): + g = sorted(g, key=lambda r: (r["partial"], -r["n"], r["cell"])) + drop = g[0]["wave"] != "pol" + out += [g[0]] if drop else g + for d in g[1:]: + DUP_CELLS.append((d["task"], d["wave"], g[0]["cell"], d["cell"], d["n"], drop)) + return out + + +def aggregate(cells): + groups = defaultdict(list) + for c in cells: + # stream A's policy evals stay PER TRAINING SEED: the grids run on one π_β seed, so the base rate + # has to be readable at that same seed (pooling 3 seeds would compare seed 0 against seeds 0/1/2). + key = tuple(c[k] for k in RECIPE_KEYS) + ((c["seed"],) if c["wave"] == "pol" else ()) + groups[key].append(c) + return [pool(dedupe_measurements(v)) for v in groups.values()] + + +# ---------------------------------------------------------------- rendering --------------------------------------- +COLS = ["model", "rsm_step", "beta", "L", "mode", "N", "particles", "score", "rule", "temp_flag", + "policy", "epoch", "seed", "eval_seed", "sr_ci", "n", "mean_len", "s_step"] +HEAD = ["model", "RSM ckpt", "β", "L", "read-out", "N", "particles", "score", "rule", "T / calib / conformal", + "π_β", "epoch", "π_β seed", "eval seed", "SR % [Wilson 95% CI]", "n ep", "mean len", "plan s/step"] + + +def eval_seed_str(r): + """The eval seed(s) a row was measured at. + + Without this the reference block renders several byte-identical rows (same recipe, same pi_beta seed, one + per eval seed) that a reader cannot tell apart -- and the 13:26/20:25 protocol turns on WHICH eval seed a + number came from (0 = selection, 1/2 = held out). + """ + ess = r.get("eval_seeds") or ([r["eval_seed"]] if r.get("eval_seed") is not None else []) + return ",".join(str(x) for x in ess) if ess else "-" + + +def seed_col(r): + """pi_beta seeds of a row, with the per-seed success rate once there is more than one. + + Orchestrator 05:10: "every arm = mean over 3 TRAINING seeds x >=50 rollouts, per-seed values shown". A + bare seed list hides the case this rule exists to catch -- one seed carrying the arm while the others sit + at chance -- so the column prints `0,1,2 (62/58/4)` whenever the row spans seeds. + """ + if not r["seeds"]: + return "-" + seeds = ",".join(str(s) for s in r["seeds"]) + ps = r.get("per_seed") or {} + if len(r["seeds"]) < 2: + return seeds + vals = [] + for s in r["seeds"]: + k, n = ps.get(s, (0, 0)) + vals.append(f"{100.0 * k / n:.0f}" if n else "-") + return f"{seeds} ({'/'.join(vals)})" + + +def cellvals(r, wave_tag=True): + seeds = seed_col(r) + sr = f"{100 * r['sr']:.1f} [{100 * r['lo']:.1f}, {100 * r['hi']:.1f}]" + if r.get("prepatch"): # broken success check -> not a result, see PIECE_WARN + sr += " \u2021" + nep = f"{r['n']}" + ("*" if r["partial"] else "") + return { + "model": r["model"], + "rsm_step": r.get("rsm_step") or "-", + "beta": fmt(r["beta"], 2), + "L": r["L"] if r["L"] is not None else "-", + "mode": r["mode"] or "-", + "N": (f"{r['N']} †" if r["N"] == 64 else (r["N"] or "-")), + "particles": r["particles"], + "score": r["score"], + "rule": r["rule"], + "temp_flag": r["temp_flag"], + # 07:45: an off-distribution row is marked in the row itself, not only in the block's warning -- + # the recipe tables are sorted by success rate, so a p0 row lands at the TOP of a coverage task and + # is the first thing a reader sees. + "policy": (policy_label(r["policy"]) + + (" " + r["wave"] if wave_tag and r["wave"].startswith("FINAL") else "") + + ("" if r.get("env_ok", True) else " ⚠OFF-DIST")), + "epoch": r["epoch"] if r["epoch"] is not None else "-", + "seed": seeds, + "eval_seed": eval_seed_str(r), + "sr_ci": sr, + "n": nep, + "mean_len": fmt(r["mean_len"], 0), + "s_step": fmt(r["s_per_step"], 2), + } + + +def md_row(vals, label=None, bold=False): + cells = [str(vals[c]) for c in COLS] + if label is not None: + cells = [label] + cells + if bold: + cells = [f"**{c}**" for c in cells] + return "| " + " | ".join(cells) + " |" + + +# ---------------------------------------------------------------- anti-selection aggregates ---------------------- +def grid_mean_rows(rsm, min_cells=4): + """Pool every finished argmax (β, L) cell of one model/wave/particle setting into ONE row. + + The bolded "best RSM" row is the MAXIMUM over a 16-cell grid evaluated at n=50, so it is inflated by + selection: with 16 noisy cells the max sits ~1.5 sd above the mean by construction. The pooled grid mean + is the unbiased "what does a typical RSM recipe do" number and has ~16x the episodes, so its CI is the one + that can actually be compared against the random-of-N control. + """ + groups = defaultdict(list) + for r in rsm: + if r["rule"] != "argmax" or r["partial"]: + continue + key = (r["wave"], r["model"], r["particles"], r["score"], r["temp_flag"], + r["policy"], r["epoch"], r["rsm_step"], r["N"]) + groups[key].append(r) + out = [] + for key, g in groups.items(): + if len({(r["beta"], r["L"]) for r in g}) < min_cells: + continue + pr = pool(g) + pr.update(beta=None, L=None, mode="grid", n_cells=len(g)) + out.append(pr) + return sorted(out, key=lambda r: (-r["sr"], -r["n"])) + + +def eval_seed_pooled(rows, min_seeds=2): + """Pool the same recipe across eval seeds (the TEST set is eval seeds 0/1/2, 13:26 protocol).""" + keys = tuple(k for k in RECIPE_KEYS if k != "eval_seed") + groups = defaultdict(list) + for r in rows: + if r["wave"] in ("VAL", "pol"): + continue + groups[tuple(r[k] for k in keys)].append(r) + out = [] + for g in groups.values(): + seeds = sorted({r["eval_seed"] for r in g if r["eval_seed"] is not None}) + if len(seeds) < min_seeds: + continue + pr = pool(g) + pr["eval_seeds"] = seeds + out.append(pr) + return sorted(out, key=lambda r: (r["kind"] != "RSM", -r["sr"])) + + +# ---------------------------------------------------------------- 3-training-seed protocol ----------------- +# Orchestrator 2026-09-19 05:10 + 05:15 clarification: +# "Every arm = mean over 3 TRAINING seeds x >=50 rollouts, per-seed values shown; pool eval seeds WITHIN a +# training seed; if <3 training seeds exist at the epoch, drop to the largest epoch where all 3 do and +# label it. Add a seeds column to every table. runs//eval_verify/ is the source for the verified +# rows." The rule is for FLAGSHIP rows only -- swept RSM recipes stay single-seed selection cells and are +# promoted to this table only once the winner has been re-run on 3 policy seeds. +# +# Why this cannot be read off the per-recipe rows above: those pool EPISODES across training seeds, so an arm +# whose seed 0 ran 300 episodes and whose seeds 1/2 ran 50 each is reported as ~75 % seed 0. The protocol +# number weights each training seed equally and shows the spread, which is the quantity a reader needs to +# decide whether a flagship-beating claim survives re-training the policy. +SEED_ARM_KEYS = tuple(k for k in RECIPE_KEYS if k not in ("wave", "eval_seed", "epoch", "prepatch")) +# Waves that deliberately change the EVALUATION conditions rather than the recipe; they belong in the +# per-task recipe tables (where `wave` separates them) but never in the flagship protocol section. +PERTURBATION_WAVES = ("horizon", "eefnoise") +SEED_MIN_ROLLOUTS = 50 +FLAGSHIP_KINDS = ("BC", "S3H4", "S3H5", "random", "permuted") + + +def _seed_dedupe(cells): + """Keep one cell per (checkpoint, eval seed) inside an arm, without touching the global DUP_CELLS table. + + The same arm can be measured by two waves (a 100-rollout FINAL cell and a 50-rollout VERIFY cell on the + same checkpoint and eval seed replay the SAME init states), and aggregate() only dedupes within a wave. + Keeps the most-evidenced copy. + """ + by, out = {}, [] + for r in cells: + if not r.get("checkpoint"): + out.append(r) + continue + k = (r["checkpoint"], r["eval_seed"]) + cur = by.get(k) + if cur is None or (r["partial"], -r["n"], r["cell"]) < (cur["partial"], -cur["n"], cur["cell"]): + by[k] = r + return out + list(by.values()) + + +def seed_protocol_rows(cells, min_rollouts=SEED_MIN_ROLLOUTS): + """One row per arm under the 3-training-seed protocol. Returns a list of dicts.""" + arms = defaultdict(lambda: defaultdict(list)) # armkey -> epoch -> cells + for c in cells: + if c["wave"] == "VAL" or c.get("prepatch") or c["epoch"] is None or c["seed"] is None: + continue + arms[tuple(c[k] for k in SEED_ARM_KEYS)][c["epoch"]].append(c) + + rows = [] + for key, by_epoch in arms.items(): + per_epoch = {} + for ep, cs in by_epoch.items(): + seeds = defaultdict(lambda: [0, 0, [], set()]) # seed -> k, n, cells, eval seeds + for c in _seed_dedupe(cs): + sd = seeds[c["seed"]] + sd[0] += c["k"]; sd[1] += c["n"]; sd[2].append(c) + if c["eval_seed"] is not None: + sd[3].add(c["eval_seed"]) + ok = {s: v for s, v in seeds.items() if v[1] >= min_rollouts} + per_epoch[ep] = (ok, seeds) + # the protocol epoch: the largest epoch at which >=3 training seeds clear the rollout floor; if none + # does, the best available (most seeds, then latest epoch) -- labelled as short of the protocol. + full = [ep for ep, (ok, _) in per_epoch.items() if len(ok) >= 3] + if full: + ep = max(full) + else: + ep = max(per_epoch, key=lambda e: (len(per_epoch[e][0]), e)) + ok, allseeds = per_epoch[ep] + use = ok or allseeds + if not use: + continue + srs = [k_ / n_ for s, (k_, n_, _, _) in sorted(use.items()) if n_] + if not srs: + continue + k_tot = sum(v[0] for v in use.values()) + n_tot = sum(v[1] for v in use.values()) + mean = sum(srs) / len(srs) + sd = (sum((x - mean) ** 2 for x in srs) / (len(srs) - 1)) ** 0.5 if len(srs) > 1 else float("nan") + lo, hi = wilson(k_tot, n_tot) + c0 = sorted(use.items())[0][1][2][0] + rows.append(dict( + key=key, cell0=c0, kind=c0["kind"], policy=c0["policy"], epoch=ep, + label=(arm_label(c0) if c0["kind"] == "RSM" else kind_label(c0["kind"], c0["policy"], c0["N"])), + n_seeds=len(use), seeds=sorted(use), + per_seed={s: (v[0], v[1], sorted(v[3])) for s, v in use.items()}, + mean=mean, sd=sd, pooled=k_tot / n_tot if n_tot else float("nan"), lo=lo, hi=hi, + k=k_tot, n=n_tot, env=c0.get("env"), + waves=sorted({c["wave"] for v in use.values() for c in v[2]}), + partial=any(c["partial"] for v in use.values() for c in v[2]), + max_epoch=max(per_epoch), epochs_with_3=sorted(full), + )) + return rows + + +def seed_protocol_section(tasks, raw_by_task, min_rollouts=SEED_MIN_ROLLOUTS): + out = ["## Flagship rows under the 3-training-seed protocol (orchestrator 05:10)", "", + "Each row is **one arm on one task**, aggregated the way the protocol asks for: eval seeds pooled " + "*within* a training seed, then the **mean over training seeds** (each seed weighted equally, " + f">= {min_rollouts} rollouts to count), with the per-seed values printed. The pooled-episode rate " + "and its Wilson interval are kept alongside, because the mean-over-seeds has no useful CI at n=3 " + "-- the `sd` column is the spread that matters. A row marked **under-seeded** has fewer than 3 " + "training seeds at its epoch and is NOT a protocol number yet; the `epoch` column says which " + "checkpoint was used (the largest epoch at which the available seeds exist). Swept RSM recipes are " + "deliberately absent unless they have been re-run on >= 2 policy seeds (05:15 clarification: sweep " + "at one seed, promote the winner). The **bolded** row of each task is the best arm that actually " + "meets the protocol (>= 3 training seeds) -- not the best number on the task.", ""] + any_rows = False + for t in tasks: + # stream D 06:45: PERTURBATION waves are not protocol arms. `eval_horizon` runs a non-400 rollout + # horizon and `eval_eefnoise` perturbs the end effector; since `wave` is not a SEED_ARM_KEY they would + # otherwise appear here as a SECOND row with the same arm name and a different number, distinguished + # only by the `waves` column -- e.g. two "BC-expert (S3H1)" rows on square play at 4.0 and 3.0. + cells = [c for c in (raw_by_task.get(t) or []) if c["wave"] not in PERTURBATION_WAVES] + rows = [r for r in seed_protocol_rows(cells, min_rollouts) + if r["n_seeds"] >= 2 or r["kind"] in FLAGSHIP_KINDS] + if not rows: + continue + any_rows = True + rows.sort(key=lambda r: (r["n_seeds"] < 3, -r["mean"])) # protocol rows first, then by mean + # stream D 07:30: `env` IS a SEED_ARM_KEY, so arms on two init distributions never pool -- but the + # arm LABEL does not mention the env, so two_piece_play printed "BC-unified (S0B)" twice, at 72.7 + # (the expert's own quadrant) and 29.7 (coverage), separated only by the `waves` column. When a task + # carries more than one env, every row says which one it is measured on. + multi_env = len({r.get("env") for r in rows}) > 1 + # The bolded row must also be an arm on the env the task is ABOUT: with two distributions present, + # bolding the best mean would crown the p0 rows on a coverage task. Prefer the env that the most + # recent (largest-epoch, most-seeded) rows use, which is the post-fix one. + best_pool = [r for r in rows if r["n_seeds"] >= 3] + if multi_env and best_pool: + by_env = defaultdict(lambda: [0, 0]) + for r in best_pool: + e = by_env[r.get("env")]; e[0] += r["n_seeds"]; e[1] = max(e[1], r["epoch"] or 0) + main_env = max(by_env, key=lambda e: (by_env[e][0], by_env[e][1])) + best_pool = [r for r in best_pool if r.get("env") == main_env] + # 07:45: and when the task DECLARES its env (env_valid), that declaration wins over the "most-seeded + # env" heuristic above -- the heuristic is only a guess about which group is the intended one, and on + # a task whose pre-fix cells outnumber its post-fix ones it guesses wrong. + declared = [r for r in (best_pool or []) if r.get("cell0", {}).get("env_ok", True)] + if declared: + best_pool = declared + best = max(best_pool, key=lambda r: r["mean"], default=None) + info = PAPER.get(t, {}) + out.append(f"### {info.get('label', t)} (`{t}`)") + out.append("") + out.append("| arm | π_β | epoch | seeds | mean over seeds % | sd | per-seed % (n ep) | " + "pooled % [Wilson 95% CI] | n ep | waves | protocol |") + out.append("|---|---|---:|---:|---:|---:|---|---|---:|---|---|") + for r in rows: + ps = "; ".join(f"s{s}: {100.0 * k_ / n_:.1f} ({n_})" if n_ else f"s{s}: -" + for s, (k_, n_, _) in sorted(r["per_seed"].items())) + status = "3 seeds ✓" if r["n_seeds"] >= 3 else f"under-seeded ({r['n_seeds']})" + if r["n_seeds"] < 3 and r["max_epoch"] != r["epoch"]: + status += f", latest epoch {r['max_epoch']} has fewer" + label = r["label"] + (f" [env `{r.get('env')}`]" if multi_env else "") + cells_ = [label, policy_label(r["policy"]), str(r["epoch"]), str(r["n_seeds"]), + f"{100.0 * r['mean']:.1f}", fmt(100.0 * r["sd"], 1), ps, + f"{100.0 * r['pooled']:.1f} [{100.0 * r['lo']:.1f}, {100.0 * r['hi']:.1f}]", + f"{r['n']}" + ("*" if r["partial"] else ""), ",".join(r["waves"]), status] + if best is not None and r is best: + cells_ = [f"**{c}**" for c in cells_] # best arm that actually MEETS the protocol + out.append("| " + " | ".join(cells_) + " |") + out.append("") + return out if any_rows else [] + + +SQUARE_ENV_TASKS = ("square_expert_suboptimal", "square_sub_paper") +COV_ENV_NOTE = ( + "> **Two initial-state distributions on this task, and they do not overlap (stream D, 2026-09-19 07:10).** " + "Every cell here whose `env` reads `3piece_top_right` was launched before the 05:10 fix to " + "`launch_e1_grid.py:63` and measures the EXPERT's own quadrant (p0), not coverage. Grouping all 95 " + "greedy (`plan_n<=1`) cells on this task by the env each JSON records splits them perfectly: top-right " + "**0.58-0.75** (15 cells) vs stock **0.00-0.35** (80 cells), with no cell on either side of the gap. Two " + "successive cluster-wide investigations (the 05:56 \"bc vs plan_n=1 path bug\" and the 07:05 \"scorer " + "loaded => bad\" refinement) were both this confound: their evidence pairs differed in `env." + "init_obj_range.Piece1` and in nothing else that moves a number. The four `pathdiag` cells settle the " + "second one directly — all stock, and all agree at 0.23-0.29 whether or not the scorer is constructed " + "(no-scorer 0.273, N=1 P16+logit 0.226, N=1 P256+prob 0.273, N=2 random 0.286). **Only the stock rows " + "are the Coverage experiment.**" +) +# The one matched-env, matched-checkpoint, matched-eval-seed comparison of the paper's selection rule against +# its own policy on a Coverage task (stream D jobs 1780803/1780804 -> eval_covfix). +COV_FLAGSHIP_NOTE = ( + "> **On the coverage distribution, RISE's own critic costs its own policy ~24 points.** S0A seed 0, " + "epoch 5000, stock env: the flagship (that policy re-ranked by its own IQL critic, N=128) reads " + "**2.7 %** (0.03/0.02/0.03 over eval seeds 0/1/2, n=300); the SAME checkpoint at `plan_n=1` reads " + "**27 %** (eval seed 0, n=100). Every earlier reading of this comparison on this task was a p0 reading " + "and had the opposite sign." +) +COV_PROG_NOTE = ( + "> **The progress-reward head is the only read-out on this task that beats picking at random — but the " + "number below it is a SELECTION number.** All stock env, epoch 5000, eval seed 0, recipe `Mprog β=0.95 " + "L=1 N=128 P256 logit argmax` (`PROG` / `covfix` waves, n=50 per cell): on RISE's own policy (S0A s0) " + "argmax **38 %** vs random-of-128 **24 %** — paired McNemar b=10, c=3, **Δ +14.0 pts, p=0.092** (n=50); " + "on BC-unified (S0B s0) argmax **40 %** vs random-of-128 **27 %** — b=13, c=7, Δ +12.5 pts, p=0.263 " + "(n=48, control still running). Same direction on both policies, so the gain is a selection effect and " + "not candidate resampling; but eval seed 0 is the SELECTION seed and 38 % is the argmax over the landed " + "`PROG` cells, so neither figure is a result yet and neither is bolded. The held-out half is running: the " + "orchestrator's `PROGVER` wave (RSM side, every π_β seed x eval seeds 0/1/2) and stream D's " + "`COVCTL-es1`/`COVCTL-es2` controls (random + permuted, both policies, jobs 1781538-1781541), which is " + "what makes `PROGVER` readable against anything other than greedy. For contrast the MEMBERSHIP head on " + "this task reads 7-11 % against the same 24-27 % random baseline." +) +def progver_note(task): + """LIVE note for the progress-reward (PROGVER) wave: paired argmax-vs-control test, recomputed each run. + + Hand-written notes go stale the moment another PROGVER cell lands, and this one carries the project's + headline number, so it is generated from the JSONs instead. The controls are the FLAG5000 cells, which + share the PROGVER cells' checkpoint, env, eval seed, plan_n=128, plan_particles=256 and plan_score=logit + and differ only in `plan_rule` -- and `random` ignores the score entirely, so argmax-vs-random isolates + the read-out. See scripts/progver_paired.py for the test itself. + """ + try: + sys.path.insert(0, str(ROOT / "scripts")) + import progver_paired + st = progver_paired.stats(task) + except Exception as e: # never let a note break the deliverable + return f"> _(progress-head paired test unavailable: {type(e).__name__}: {e})_" + if not st: + return None + S, P = st["summary"], st["pairs"] + if "random" not in S: + return None + r = S["random"] + seeds = sorted({x["seed"] for x in P}) + ess = sorted({x["es"] for x in P}) + waven = "/".join(str(n) for n in sorted({x["n"] for x in P})) + waves = "/".join(sorted({x.get("tag", "PROGVER") for x in P})) + per = "; ".join(f"{x['seed']}/{x['es']} {100*x['sr']:.0f} vs {100*x['ctl']['random']['sr']:.0f}" + for x in P if "random" in x["ctl"]) + bits = [] + for rule, label in (("random", "random-of-128"), ("permuted", "permuted scores (same score SET, ordering destroyed)"), + ("BC", "BC (greedy, `plan_n=1`)"), + ("S3H4", "the RISE flagship (same policy + its own IQL critic)")): + v = S.get(rule) + if v: + bits.append(f"vs {label}: **{100*v['mean_d']:+.1f} pts** ({v['npos']}/{v['k']} pairs positive, " + f"pooled McNemar b={v['b']} c={v['c']}, exact p={v['p']:.1e})") + return ( + "> **Progress-reward (privileged) RSM beats the paper's selection rule, BC and random-of-128 on this " + f"task — matched, and held out over both training and eval seeds.** Recipe `Mprog β=0.95 L=1 N=128 " + f"P256 logit argmax` (`{waves}` wave) against the `FLAG5000` controls on the SAME checkpoint, env and " + f"eval seed, differing only in `plan_rule`: {'; '.join(bits)}. " + f"{len(P)} matched (π_β seed, eval seed) pairs so far over π_β seeds {', '.join(seeds)} and eval seeds " + f"{', '.join(e[-1] for e in ess)}, {waven} rollouts per RSM cell vs 100 per control (paired over the shared " + f"prefix). Per pair (argmax vs random, %): {per}. " + "The (β, L) was chosen on a different task's eval seed 0, and every pair here is a different " + "(training seed, eval seed) combination from that choice, so this is not a selection number. " + + ("The 3 π_β seeds x 3 eval seeds matrix is COMPLETE at 100 rollouts per cell. " + if len(P) >= 9 and min(x["n"] for x in P) >= 100 else + "The remaining cells of the wave are still running. ") + + "This note is regenerated from the JSONs on every refresh " + "(`scripts/progver_paired.py`; `scripts/paired_final_test.py` computes the same contrasts " + "independently and agrees)." + ) + + +SQUARE_ENV_NOTE = ( + "> **Eval env (resolved, orchestrator 20:55).** The 20:16 \"eval-env mismatch\" caveat is WITHDRAWN: the paper states the suboptimal experiment evaluates at p_0 — robosuite's default init corner, which is the " + "`robomimic_square` config every row of this task uses. The env configs are correct and the numbers below stand as measured; the diagnostic cells opened to test the alternative were cancelled." +) + + +# Protocol standing of each wave, best first. `FINAL` is the pre-registered held-out wave at the paper's +# training length (100 rollouts x 3 eval seeds), `FINAL@3000` its matched-epoch sibling, `v2` the selection +# grid of record (frozen ckpt_w2.pt, logit read-out). `v1`/`v1b` are RETIRED grids (round 18: they scored +# against a live-rewritten ckpt_best.pt and only half-ran), and `early` is the 12:28 diagnostic probe (4 +# particles, dense head) that this file's own preamble calls "a smoke signal, not a result". +WAVE_STANDING = ("FINAL", "FINAL@3000", "v2") +BEST_EXCLUDE_WAVES = ("early",) + + +def pick_best(rsm, best_min_n=20): + """(best, raw_best): the row to bold/quote, and the highest raw SR anywhere for the footnote. + + Taking a plain argmax over every wave had the headline quoting, on square play, a cell from the RETIRED + wave-1 grid scored with the EARLY diagnostic DWM checkpoint (4.0 %, n=50) while the pre-registered FINAL + protocol on the same task reads 1.7 % over n=58 -- i.e. the deliverable's first table advertised a number + the same document disclaims two paragraphs above. The bolded best now comes from the best-standing wave + that has a usable cell, exactly as the paired-test column does, and the footnote names any higher raw + number so nothing is hidden. + """ + def _argmax(pool_): + cands = ([r for r in pool_ if not r["partial"]] + or [r for r in pool_ if r["n"] >= best_min_n] or pool_) + return max(cands, key=lambda r: (r["sr"], r["n"]), default=None) + + # A cell measured on an init distribution the task is not about is not a weaker result, it is a + # different experiment (see env_valid): on two_piece_expert_play the surviving top-right cells read up + # to 79 % against 0-35 % for the coverage box, so without this filter the headline -- and the "higher + # raw rate" footnote, which is why `raw` is filtered too -- would quote a p0 number as the task's best. + rsm = [r for r in rsm if r.get("env_ok", True)] or rsm + usable = [r for r in rsm if r["wave"] not in BEST_EXCLUDE_WAVES] + best = None + for w in WAVE_STANDING: + best = _argmax([r for r in usable if r["wave"] == w]) + if best is not None: + break + if best is None: # only retired grids exist for this task + best = _argmax(usable) or _argmax(rsm) + raw = _argmax(rsm) + return best, raw + + +def render_task(task, rows, out, best_min_n=20): + info = PAPER.get(task, dict(label=task, bc=None, idql=None, rise=None)) + out.append(f"## {info['label']} (`{task}`)") + out.append("") + if info.get("regime"): + out.append(f"**Data regime:** {info['regime']}") + out.append("") + if task in SQUARE_ENV_TASKS: + out.append(SQUARE_ENV_NOTE) + out.append("") + if task == "two_piece_expert_play": + out.append(COV_ENV_NOTE) + out.append("") + out.append(COV_FLAGSHIP_NOTE) + out.append("") + out.append(COV_PROG_NOTE) + out.append("") + _pv = progver_note(task) + if _pv: + out.append(_pv) + out.append("") + if task in PIECE_TASKS: + n_pre = sum(1 for r in rows if r.get("prepatch")) + out.append(PIECE_WARN + f" ({n_pre} of {len(rows)} rows below are pre-patch.)") + out.append("") + + # Which initial-state distribution(s) these rows ran. More than one means the rows below are NOT all + # measuring the same experiment, and the difference is usually far larger than any recipe effect. + envs = defaultdict(lambda: [0, 0, 0, set(), True]) + for r in rows: + e = envs[r.get("env", "-")] + e[0] += r["k"]; e[1] += r["n"]; e[2] += 1; e[3].add(r["wave"]) + e[4] = e[4] and bool(r.get("env_ok", True)) + bad_env = {name for name, v in envs.items() if not v[4]} + exp_cfg = next((r.get("env_expected") for r in rows if r.get("env_expected")), None) + if len(envs) > 1: + out.append(f"> **WARNING — {len(envs)} DIFFERENT eval env configs in this task's rows.** A success rate " + f"is only comparable to another success rate measured from the SAME initial-state " + f"distribution, so rows below may not be comparable across the `env` groups listed here. " + f"Rows are never pooled across configs (`env` is part of the recipe key).") + out.append("") + out.append("| eval env config | this task's env? | rows | n ep | pooled SR % | waves |") + out.append("|---|---|---:|---:|---:|---|") + for name, (k, n, nr, ws, ok) in sorted(envs.items(), key=lambda kv: -kv[1][1]): + out.append(f"| `{name}` | {'yes' if ok else '**NO — off-distribution**'} | {nr} | {n} | " + f"{100.0 * k / n if n else float('nan'):.1f} | {', '.join(sorted(ws))} |") + out.append("") + if bad_env: + n_bad = sum(1 for r in rows if not r.get("env_ok", True)) + out.append(f"> **{n_bad} of {len(rows)} rows below were measured on an init distribution this task " + f"is not about** ({', '.join('`%s`' % e for e in sorted(bad_env))}; the task is defined " + f"on `{exp_cfg}`). They are shown for the record, are never pooled with a valid row " + f"(`env` is part of the recipe key) and can never be bolded, quoted as the task's best " + f"or paired against a control (`env` is part of the arm key). Read them as a different " + f"experiment, not as a noisier version of this one.") + out.append("") + elif envs: + out.append(f"Eval env config: `{next(iter(envs))}` (all rows).") + out.append("") + + # header facts: which pi_beta checkpoints the rows use + ck = defaultdict(set) + for r in rows: + if r["epoch"] is not None: + ck[(r["wave"], r["policy"])].add(r["epoch"]) + if ck: + parts = [f"{w} {p} epoch {'/'.join(str(e) for e in sorted(es))}" for (w, p), es in sorted(ck.items())] + out.append(f"π_β policy checkpoints: {'; '.join(parts)}.") + blobs = sorted({r["rsm_ckpt"] for r in rows if r["rsm_ckpt"]}) + if blobs: + out.append("") + out.append("
RSM blobs scored by these rows (path, current mtime)") + out.append("") + for b in blobs: + try: + mt = time.strftime("%Y-%m-%d %H:%M UTC", time.gmtime(os.path.getmtime(b))) + except OSError: + mt = "missing" + out.append(f"- `{b.replace(str(ROOT) + '/', '')}` — mtime {mt}") + out.append("") + out.append("
") + out.append("") + prog = [] + for dname, wave in WAVES + EARLY: + launched, done, part = dir_progress(ROOT / "runs" / task / dname) + if launched or done: + prog.append(f"`{dname}` {done}/{launched} done" + (f", {part} running" if part else "")) + if prog: + out.append(f"Cells: {'; '.join(prog)}.") + hz = sorted({r["horizon"] for r in rows if r["horizon"]}) + es = sorted({r["eval_seed"] for r in rows if r["eval_seed"] is not None}) + out.append(f"Rollout horizon {'/'.join(str(h) for h in hz) or '-'}, eval seed {'/'.join(str(x) for x in es) or '-'}; " + f"`n ep`* = cell still running (partial JSON).") + out.append("") + + # VALIDATION rows (orchestrator 13:26: eval seed 100, disjoint from the test seeds 0/1/2) are + # reported separately and can never be the bolded best -- they exist to SELECT a checkpoint. + val = [r for r in rows if r["wave"] == "VAL"] + rows = [r for r in rows if r["wave"] != "VAL"] + rsm = [r for r in rows if r["kind"] == "RSM"] + ref = [r for r in rows if r["kind"] != "RSM"] + # "best" must not be a 1-episode partial, must not come from the diagnostic `early` grid, and must be + # taken from the highest-standing wave available (see pick_best). + best, raw_best = pick_best(rsm, best_min_n) + + hdr = "| row | " + " | ".join(HEAD) + " |" + sep = "|" + "---|" * (len(HEAD) + 1) + + out.append("### Reference rows") + out.append("") + out.append(hdr) + out.append(sep) + blank = {c: "-" for c in COLS} + if info["rise"] is not None: + for nm, v in (("BC", info["bc"]), ("IDQL", info["idql"]), ("RISE", info["rise"])): + b = dict(blank, sr_ci=f"{v:.1f}", n="-") + out.append(md_row(b, label=f"RISE paper (Table I) — {nm}")) + order = {"S3H4": 0, "BC": 1, "random": 2, "permuted": 3, "S3H5": 4} + for r in sorted(ref, key=lambda r: (order.get(r["kind"], 9), r["policy"], -r["sr"])): + label = kind_label(r["kind"], r["policy"], r["N"], long=True) + if r["wave"].startswith("FINAL"): + label += f" [{r['wave']}]" + elif r["wave"] == "pol": + label += " [stream-A policy eval]" + out.append(md_row(cellvals(r), label=label)) + out.append("") + + out.append(f"### RSM recipes ({len(rsm)} cells, sorted by success rate)") + out.append("") + if not rsm: + out.append("_no RSM cells finished yet_") + out.append("") + return best + out.append(hdr) + out.append(sep) + for i, r in enumerate(sorted(rsm, key=lambda r: (-r["sr"], -r["n"])), 1): + label = f"{i}" + (f" [{r['wave']}]" if r["wave"].startswith("FINAL") else + "" if r["wave"] == "v1" else f" ({r['wave']})") + out.append(md_row(cellvals(r), label=label, bold=(r is best))) + out.append("") + if best is not None: + out.append(f"The bolded row is the best cell of the highest-standing wave present for this task " + f"(**{best['wave']}**); the `early` diagnostic grid can never be bolded, and the retired " + f"`v1`/`v1b` grids are used only if no FINAL/v2 cell exists. " + + (f"A higher raw success rate does appear elsewhere in this table — " + f"`{raw_best['cells'][0]}` ({raw_best['wave']}) at {100 * raw_best['sr']:.1f} % over " + f"n={raw_best['n']}{'*' if raw_best['partial'] else ''} — and is deliberately not quoted " + f"as the task's result." + if raw_best is not None and raw_best is not best and raw_best["sr"] > best["sr"] else "")) + out.append("") + + gm = grid_mean_rows(rsm) + if gm: + out.append("### Anti-selection view — pooled (β, L) grid mean per model") + out.append("") + out.append("The bolded best RSM row is the max over a 16-cell grid at n=50 and is inflated by selection. " + "These rows pool every finished argmax cell of one model/particle setting, so they are unbiased " + "and have ~16x the episodes — this is the row to compare against `random-of-N`.") + out.append("") + out.append(hdr) + out.append(sep) + for i, r in enumerate(gm, 1): + out.append(md_row(cellvals(r), label=f"G{i} ({r['n_cells']} cells)")) + out.append("") + + # ---- particle ladder: same (model, beta, L, rule, policy), varying training.plan_particles ---- + lad = defaultdict(list) + for r in rows: + if r["kind"] != "RSM" or r["wave"] == "VAL" or r["particles"] in (None, "-"): + continue + if r["eval_seed"] not in (None, SELECTION_EVAL_SEED): + continue # one seed only, else the rungs are not comparable + lad[(r["model"], r["beta"], r["L"], r["rule"], r["policy"], r["epoch"], r["score"])].append(r) + lad = {k: v for k, v in lad.items() if len({r["particles"] for r in v}) >= 3} + if lad: + out.append("### Particle ladder (`training.plan_particles`)") + out.append("") + out.append("`plan_particles` is NOT the number of action candidates (that is `N`) \u2014 it is how many " + "particles the scorer averages to estimate each candidate's successor value. More particles = " + "a lower-variance estimate of the SAME quantity, so success rate should rise and then flatten. " + "If it instead peaks and falls, the RSM's *mean* ranking is worse than its noisy one and the " + "sampling noise was acting as a regulariser \u2014 i.e. the value function, not the search " + "budget, is the bottleneck.") + out.append("") + for key, g in sorted(lad.items(), key=lambda kv: -len(kv[1])): + model, beta, L, rule, pol, ep, sco = key + g = sorted(g, key=lambda r: (int(r["particles"]) if str(r["particles"]).isdigit() else 0)) + out.append(f"**{model}, \u03b2={fmt(beta,2)}, L={L}, {rule}, {sco}, {pol} ep{ep}** " + f"(eval seed {SELECTION_EVAL_SEED})") + out.append("") + out.append("| particles | SR % [Wilson 95% CI] | n ep | plan s/step |") + out.append("|---|---|---|---|") + for r in g: + lo, hi = wilson(r["k"], r["n"]) + sps = (r["t_plan"] / r["steps"]) if r.get("steps") else float("nan") + out.append(f"| {r['particles']} | {fmt(100*r['sr'])} [{fmt(100*lo)}, {fmt(100*hi)}] | " + f"{r['n']}{'*' if r['partial'] else ''} | {fmt(sps, 3)} |") + out.append("") + + esp = eval_seed_pooled(rows) + if esp: + out.append("### TEST-set pooling across eval seeds") + out.append("") + out.append("Same recipe, eval seeds 0/1/2 pooled (the TEST init sets of the 13:26 protocol). These rows " + "are the out-of-sample numbers: only eval seed 0 was used to rank recipes.") + out.append("") + out.append(hdr) + out.append(sep) + for i, r in enumerate(esp, 1): + lab = (f"RSM {r['model']}" if r["kind"] == "RSM" + else kind_label(r["kind"], r.get("policy"), r["N"])) + out.append(md_row(cellvals(r), label=f"T{i} {lab} (seeds {','.join(str(x) for x in r['eval_seeds'])})")) + out.append("") + + # One block per (wave, pi_beta, epoch): never pair an epoch-5000 arm against an epoch-2500 control. + groups, seen = [], set() + for r in esp: + k = arm_key(r) + if k not in seen: + seen.add(k) + groups.append(k) + ns = sorted({r["N"] for r in esp if r["kind"] == "RSM" and r.get("ep_succ") and r["N"]}, reverse=True) + blocks = [((k, nv), paired_tests(esp, k, nv)) for k in groups for nv in (ns or [None])] + blocks = [(k, bt) for k, bt in blocks if bt] + # FINAL (epoch-5000 policies, 3 x 100 rollouts) first, then the largest paired sample. + # matched-epoch FINAL first (every arm at the same policy epoch, flagship included), then the + # epoch-5000 FINAL, then the largest paired sample. + blocks.sort(key=lambda kb: (0 if kb[0][0][0] == "FINAL@3000" else 1 if kb[0][0][0] == "FINAL" else 2, + -kb[1][0][0]["n"])) + for (gk, gn), pt in blocks: + a = pt[0][0] + gwave, gpol, gep, genv = gk + title = "#### Paired significance (exact McNemar) — best pooled RSM arm vs each control" + if len(blocks) > 1: + title += f" — `{gwave}`, π_β {gpol} epoch {gep}, env `{genv}`" + if gn: + title += f", N={gn}" + (" (paper-faithful)" if gn == 64 else " (released code)") + out.append(title) + out.append("") + out.append(f"Arms run at the same eval seed replay the **same init states**, so episodes pair up " + f"one-for-one and only the discordant pairs carry information — far more powerful " + f"than reading two overlapping Wilson intervals. Every arm in this block ran on the SAME " + f"π_β ({gpol} epoch {gep}, wave `{gwave}`) and the SAME init distribution " + f"(`{genv}`), so neither the policy epoch nor the eval env can confound " + f"the read-out. Reference arm: " + f"**{a['model']} β={fmt(a['beta'],2)} L={a['L']}, {a['particles']} particles, " + f"{a['score']}, {a['rule']}** at {fmt(100*a['sr'])} % " + f"(n={a['n']}{'*' if a.get('partial') else ''}) — " + + ("**no RSM arm in this block has finished**, so this reference arm is still running " + "(`n*`); its success rate is provisional and upward-biased by being the argmax over " + "arms of unequal length, so do not quote it." + if a.get("ref_partial") else + ("the best **finished** RSM arm in this block *as ranked on eval seed " + f"{SELECTION_EVAL_SEED}*" if a.get("ref_basis") == "sel" else + "the best **finished** RSM arm in this block") + + ". Arms still running are excluded from " + "this choice: a short arm has a wider sampling distribution and therefore wins a " + "max-SR argmax more often than its true rate warrants.")) + out.append("") + # How the reference arm was chosen, and over how many arms -- the `held-out only` rows below are + # only honestly out-of-sample if the arm was picked on the SELECTION seed. + cons = a.get("arms_considered") or [] + if a.get("ref_basis") == "sel": + why = (" (the FINAL wave runs one argmax recipe per successor model)" + if gwave.startswith("FINAL") else "") + out.append(f"**Arm selection is disjoint from the held-out test.** This block contains " + f"**{len(cons)}** RSM arm{'s' if len(cons) != 1 else ''}{why}. The reference arm " + f"above is the argmax of **eval seed {SELECTION_EVAL_SEED} only** — the declared " + f"selection seed — so the `held-out only` rows (eval seeds ≠ " + f"{SELECTION_EVAL_SEED}) involve no selection on the data they are computed from" + + (f", and their p-values need no multiplicity correction over the {len(cons)} " + f"arms." if len(cons) > 1 else ".")) + if len(cons) > 1: + out.append("") + out.append("| RSM arm | selection seed SR (used to pick) | pooled SR | n |") + out.append("|---|---|---|---|") + for r, sr in sorted(cons, key=lambda t: -(t[1][0] if t[1] else -1)): + mark = " ←" if r is a else "" + srtxt = f"{fmt(100*sr[0])} % (n={sr[1]})" if sr else "_no seed-0 episodes_" + out.append(f"| {r['model']} β={fmt(r['beta'],2)} L={r['L']} N{r['N']} " + f"P{r['particles']} {r['score']} {r['rule']}{mark} | {srtxt} | " + f"{fmt(100*r['sr'])} % | {r['n']}{'*' if r.get('partial') else ''} |") + elif len(cons) > 1: + out.append(f"⚠ No arm in this block has episodes at eval seed {SELECTION_EVAL_SEED}, so the " + f"reference arm is the argmax of the POOLED rate over {len(cons)} arms — the same " + f"episodes the test below uses. Treat the `held-out only` p-value as needing a " + f"multiplicity correction over {len(cons)} arms (Bonferroni: multiply by " + f"{len(cons)}).") + out.append("") + out.append("| vs control | seeds | paired n | RSM win / ctrl lose (b) | RSM lose / ctrl win (c) | " + "paired Δ SR pts [95% CI] | exact p (2-sided) | verdict |") + out.append("|---|---|---|---|---|---|---|---|") + for _a, b, res, ho in pt: + lab = kind_label(b["kind"], b.get("policy"), b["N"]) + for tag, rr in (("all", res), ("**held-out only**", ho)): + if not rr: + continue + n, bb, cc, diff, lo, hi, pv = rr + verdict = ("**significant**" if pv < 0.05 else + "borderline" if pv < 0.10 else "not significant") + out.append(f"| {lab} ({fmt(100*b['sr'])} %) | {tag} | {n} | {bb} | {cc} | " + f"{fmt(100*diff)} [{fmt(100*lo)}, {fmt(100*hi)}] | {pv:.3f} | {verdict} |") + out.append("") + out.append(f"`held-out only` drops eval seed {SELECTION_EVAL_SEED} — the seed the recipe was " + f"selected on — so it is the honest out-of-sample effect; `all` adds it back for the " + f"extra power. If the two disagree, believe the held-out row.") + out.append("") + if gk == ("v2", "S0B", 2500) and gn == 128: + out.append( + "**Pre-registered stopping rule (stream D, 2026-09-18 18:45 UTC, recorded BEFORE the data " + "landed).** The held-out sample for this comparison is fixed at **eval seeds 1-8, 50 " + "rollouts each = n=400 paired episodes**. At the discordance observed at n=200 (b=41, c=27) " + "that n resolves a Δ of +7 pts at p≈" "0.02. **No further eval seed will be added " + "to this comparison afterwards**, whatever the p value comes out at — the number " + "reported at n=400 is the project's answer, so that adding seeds until significance " + "(optional stopping) cannot inflate it.") + out.append("") + + # The recipe-ablation grid (orchestrator 23:2x) changes ONE knob at a time off the reference recipe at + # a fixed eval seed, so its cells pair against the reference episode-for-episode. The per-task recipe + # table above can only show their unpaired Wilson intervals, which overlap on every cell; without this + # block a reader has no way to tell "N=8 beats N=128 by 8 points" from noise. + try: + sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) # the refresh loop runs from runs/ + import paired_abl_test + out += paired_abl_test.render(task) + except Exception as e: # never let an ablation block break the deliverable + out.append(f"_(ablation paired block unavailable: {e})_") + out.append("") + + if val: + out.append(f"### Validation sweep (eval seed 100, 50 rollouts \u2014 checkpoint selection only)") + out.append("") + out.append("Per the orchestrator's 13:26 protocol these init states are disjoint from the test seeds " + "0/1/2; the winning checkpoint is chosen here and only its TEST numbers are reported above.") + out.append("") + out.append(hdr) + out.append(sep) + vbest = max(val, key=lambda r: (r["sr"], r["n"]), default=None) + for i, r in enumerate(sorted(val, key=lambda r: (r["model"], -r["sr"])), 1): + out.append(md_row(cellvals(r), label=f"V{i}", bold=(r is vbest))) + out.append("") + if vbest is not None: + out.append(f"Validation-selected checkpoint: **{vbest['model']} {vbest['rsm_step']}** " + f"({100 * vbest['sr']:.1f}% over n={vbest['n']}).") + out.append("") + if best is not None: + vs = "" + if info["rise"] is not None: + d = 100 * best["sr"] - info["rise"] + vs = f" ({'+' if d >= 0 else ''}{d:.1f} pts vs the RISE paper's {info['rise']})" + out.append(f"Best RSM cell: **{best['cells'][0] if len(best['cells']) == 1 else best['model']}** — " + f"{100 * best['sr']:.1f}% [{100 * best['lo']:.1f}, {100 * best['hi']:.1f}] over n={best['n']}{vs}") + out.append("") + return best + + +def _pool_eval_seeds(cands, pick): + """Pool every candidate that matches `pick` on the whole recipe EXCEPT the eval seed. + + The control rows (BC / random-of-N) are the ones every RSM row is judged against, so they should carry all + the episodes we have: the same control run at eval seeds 0/1/2 is the TEST set of the 13:26 protocol, not + three different recipes. Returns `pick` unchanged when only one eval seed exists. + """ + keys = tuple(k for k in RECIPE_KEYS if k != "eval_seed") + sig = tuple(pick[k] for k in keys) + same = [r for r in cands if tuple(r[k] for k in keys) == sig] + if len({r["eval_seed"] for r in same}) < 2: + return pick + pr = pool(same) + pr["eval_seeds"] = sorted({r["eval_seed"] for r in same if r["eval_seed"] is not None}) + return pr + + +def base_row(rows, prefer_epoch=None, prefer_policy=None, prefer_seeds=()): + """The best-evidenced base-policy row for a task: BC (plan_n=1) or random-of-N, TEST waves only. + + This is the number every RSM row has to beat for the search to be doing anything; it is also the + apples-to-apples analogue of the paper's BC column. Rows at the same π_β checkpoint as the grid win. + """ + cands = [r for r in rows if r["kind"] in ("BC", "random") and r["wave"] != "VAL"] + if not cands: + return None + want = set(prefer_seeds or ()) + pick = sorted(cands, key=lambda r: ((r["epoch"], r["policy"]) != (prefer_epoch, prefer_policy), + bool(want) and not want.issubset(set(r["seeds"] or ())), + r["partial"], -r["n"], r["kind"] != "BC"))[0] + return _pool_eval_seeds(cands, pick) + + +def ctrl_row(rows, kind, prefer_epoch=None, prefer_policy=None, prefer_seeds=()): + """The best-evidenced row of one control kind ("random" / "permuted" / "BC") at the matched π_β checkpoint. + + `random-of-N` is the control that isolates what the RSM SCORE contributes: it draws the same N candidates + from the same π_β and picks one uniformly, so any gap between it and an argmax cell is the read-out's doing. + An RSM row that beats BC but not random-of-N has shown only that resampling helps, not that the RSM ranks. + """ + want = set(prefer_seeds or ()) + cands = [r for r in rows if r["kind"] == kind and r["wave"] != "VAL"] + if not cands: + return None + pick = sorted(cands, key=lambda r: ((r["epoch"], r["policy"]) != (prefer_epoch, prefer_policy), + bool(want) and not want.issubset(set(r["seeds"] or ())), + r["partial"], -r["n"]))[0] + return _pool_eval_seeds(cands, pick) + + +def rise_row(rows, prefer_epoch=None): + """Our own run of the RISE method (S3H4 = IDQL best-of-N with the S0A IQL critic), TEST waves only. + + Orchestrator 15:09: the headline comparison is at MATCHED epochs -- the RSM cells on the S0B policy at + epoch N against the RISE method on the S0A policy at epoch N -- so a row whose epoch matches the best + RSM row's wins, then the one with the most episodes. + + Two properties this function is responsible for, both added 2026-09-19 02:15 after the headline printed + `beats our RISE? **YES** (+23.3 pts, CI above)` on square (Suboptimal) from an RSM row at policy epoch + 5000 against a flagship row at epoch 3000 -- exactly the comparison this table's own preamble says is + "deliberately NOT made" while S0A is still training: + + 1. `epoch_matched` is stamped on the returned row so the caller can refuse to render a verdict when the + two arms are at different policy epochs. The flagship CELL is still printed (it is informative and + its epoch is named), only the YES/no is withheld. + 2. The row is pooled over eval seeds like `base_row`/`ctrl_row`. Without this the flagship column was a + single-eval-seed cell (n=100) while the RSM column was pooled over seeds 0/1/2 (n=300) -- the same + asymmetry the `bq = _pool_eval_seeds(...)` comment in `main()` calls out for "beats our base?", and it + biases the verdict toward YES because a 3x wider flagship CI is easier for `lo > rise` to clear. + """ + cands = [r for r in rows if r["kind"] == "S3H4" and r["wave"] != "VAL"] + if not cands: + return None + pick = sorted(cands, key=lambda r: (r["epoch"] != prefer_epoch, r["partial"], -r["n"]))[0] + row = _pool_eval_seeds(cands, pick) + row["epoch_matched"] = (prefer_epoch is None or pick["epoch"] == prefer_epoch) + row["want_epoch"] = prefer_epoch + return row + + +def _task_of_label(label): + for t, info in PAPER.items(): + if info.get("label") == label: + return t + return label + + +def main(): + ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + ap.add_argument("--task", action="append", default=[], help="restrict to these tasks (default: all with evals)") + ap.add_argument("--no-partial", action="store_true", help="skip cells that are still running") + ap.add_argument("--no-early", action="store_true", + help="skip runs//eval_early_dwm (the 12:28 diagnostic grid: 4 particles, dense head)") + ap.add_argument("--out-md", default=str(ROOT / "docs" / "RESULTS_TABLE.md")) + ap.add_argument("--out-csv", default=str(ROOT / "docs" / "RESULTS_TABLE.csv")) + ap.add_argument("--best-min-n", type=int, default=20, + help="a still-running cell needs this many episodes before it can be the bolded best row") + ap.add_argument("--stdout", action="store_true", help="also print the markdown") + ap.add_argument("--stdout-coverage", action="store_true", + help="print the FINAL coverage matrices to stdout (the per-run check of the 20:09 protocol)") + a = ap.parse_args() + + if a.task: + tasks = list(a.task) + else: + tasks = [t for t in TASK_ORDER if (ROOT / "runs" / t).is_dir()] + tasks += [t for t in sorted(os.listdir(ROOT / "runs")) + if t not in tasks and any((ROOT / "runs" / t / d).is_dir() for d, _ in WAVES)] + + dirs = WAVES + ([] if a.no_early else EARLY) + all_rows, per_task, raw_by_task = [], {}, {} + for t in tasks: + cells = [] + for dname, wave in dirs: + got = load_dir(t, ROOT / "runs" / t / dname, wave, not a.no_partial) + if wave == "pol": # stream A's in-flight policy evals: only settled base rates belong here + got = [c for c in got if not c["partial"]] + cells += got + if not cells: + continue + per_task[t] = aggregate(cells) + raw_by_task[t] = cells + all_rows += per_task[t] + + now = time.strftime("%Y-%m-%d %H:%M UTC", time.gmtime()) + + # The flagship (S3H4 = S0A policy + its own IQL critic) can only reach epoch 5000 once stream A's S0A + # training does, and it lands task by task. This used to be a hand-written "S0A is still training, so + # the flagship row is pending", which went stale the moment the first task's S0A hit 5000. Read it off + # the rows instead, so the preamble can never contradict the per-task `beats our RISE?` column. + _f5, _f3 = set(), set() + for _t, _rows in per_task.items(): + for _r in _rows: + if _r["kind"] == "S3H4" and _r["wave"] != "VAL": + (_f5 if _r["epoch"] == 5000 else _f3).add(_t) + if _f5: + _flag5k_note = ("The epoch-5000 flagship (S0A policy + its own IQL critic) has landed on " + + ", ".join(sorted(_f5)) + ", so those tasks carry an epoch-matched RISE comparison; " + + ("the remaining tasks are still waiting on S0A training and show the epoch-3000 " + "flagship only." if _f3 - _f5 else "no task is still waiting on S0A.")) + else: + _flag5k_note = ("No task has an epoch-5000 flagship yet (S0A is still training), so every RISE " + "comparison below is the epoch-3000 one.") + # Orchestrator 04:05: the naming legend is part of the deliverable -- a reader must be able to map every + # row name onto the paper's Sec. V terms without reading STATUS.md. + label_legend = [ + "**Label convention** (orchestrator, 2026-09-19 04:05 UTC) — every row name below maps onto the " + "paper's Sec. V terms:", "", + "| label here | paper term | trained on | our cell |", + "|---|---|---|---|", + "| **BC-expert** | Behavior cloning | D_E only (expert demos) | S3H1 |", + "| **BC-unified** | Behavior cloning unified | D_E ∪ D_NE (expert + non-expert) | S0B |", + "| **RISE policy, greedy** | (not a paper row) | RISE's π_B (D_E ∪ D_NE, critic trained jointly), " + "no selection | S0A greedy |", + "| **RISE flagship** | RISE | RISE policy + its own IQL critic, best-of-N | S3H4 on S0A |", + "| **RSM (on \u003cpolicy\u003e)** | ours | successor-model value selecting among N candidates from the " + "NAMED policy | E1-* |", "", + "Every RSM row names the π_β it selects from, and a `BC` (plan_n=1) row is just that policy acting " + "greedily — so *\"greedy\"* on an S0B arm is **BC-unified**, not BC-expert. Our BC-unified carries the " + "RISE spectral-norm penalty; the no-penalty ablation is labelled *BC-expert, no spectral norm*. " + "The raw `S0A`/`S0B`/`S3H1` codes are kept in parentheses and in `RESULTS_TABLE.csv`.", "", + ] + out = ["# RSM x RISE — results table", "", + f"Generated {now} by `scripts/results_table.py` from " + f"`runs//{{eval_v1,eval_v1_s0a_bc,eval_v1b,eval_v2,eval_val,eval_abl,eval_final*}}/*.json`.", "", + "One row per recipe; cells of the same recipe that differ only in π_β seed are pooled (Wilson 95% CI on " + "the pooled counts). `plan s/step` = (sampler + scorer) seconds per planning step (one action chunk of 8). " + "Rows marked **FINAL@3000** are the *matched-epoch* final wave: every arm — RSM recipes, BC, " + "random-of-N, permuted scores and the RISE flagship (S0A policy + its own IQL critic) — at policy " + "epoch 3000, 100 rollouts, eval seeds 0/1/2, so no arm is trained longer than any other. This is the " + "interim headline. Rows marked **FINAL** are the epoch-5000 wave on the S0B arms. " + _flag5k_note + + " An RSM@5000 vs flagship@3000 comparison is never made: the `beats RISE flagship?` column withholds " + "its verdict per task whenever the two arms sit at different policy epochs. " + "Eval seed 0 is the SELECTION seed (recipes were ranked there); eval seeds 1 " + "and 2 are HELD-OUT, and the McNemar blocks report `held-out only` as the honest number. Recipes are " + "frozen by the seed-0 grids and are never re-ranked on final numbers.", "", + "> **N (behaviour-policy samples), paper vs released code.** RISE's Table III specifies **64** samples from π_β per planning step; the released `robomimic_sampling_rollout_policy.py` hardcodes " + "**128**, and every grid here was run at N=128 to match the code we evaluate against. Rows whose N is marked † (N=64) are the **paper-faithful** ones; all other rows are code-faithful. " + "A paper-faithful N=64 block (best RSM recipe, random-of-64 and the RISE flagship, epoch 3000, 100 rollouts, eval seeds 0/1/2) is running on square (Suboptimal) — jobs 1773098-1773106, and on mug (Suboptimal) and square play (Coverage) — jobs 1773531-1773548, submitted 21:52 after the coverage matrix showed their scripts had been written but never queued. Those cells were launched with `launch_e1_grid.py --n-primary 64` directly, so `launch_wave2.py --step final` does not regenerate them.", "", + "> **Selection caveat.** The wave-1/wave-2 (\u03b2, L) grids run at eval seed 0, which is one of the " + "TEST seeds (0/1/2), so the recipe ranking above is an in-sample ranking. Per the orchestrator's " + "13:26 protocol the *checkpoint* choice is made on the disjoint VALIDATION set (eval seed 100, " + "`runs//eval_val`, `launch_wave2.py --step val`), shown in its own block per task and never " + "bolded as a result. Re-running the winning grid at seed 100 would make the recipe choice " + "out-of-sample too; it is a GPU-budget call for the orchestrator.", "", + "> **Where the RSM-vs-RISE-method comparison lives (changed 2026-09-19 02:25).** The headline's " + "`beats our RISE?` column is now **withheld whenever the two arms sit at different policy " + "epochs**, and says so. It previously read **YES (+23.3 pts, CI above)** on square (Suboptimal) " + "by comparing the best RSM row at π_β epoch **5000** against the flagship at epoch **3000** — the " + "exact comparison the paragraph above says is deliberately not made — with the flagship side " + "taken from a single eval seed (n=100) against a 3-seed RSM side (n=300), so the flagship's CI " + "was ~3x too wide and `lo > rise` was correspondingly easy to clear. The flagship column is now " + "pooled over eval seeds like every other control. **The comparison itself has moved to where it " + "is sound:** each task's matched-epoch `FINAL@3000` paired block now carries `RISE method (IQL " + "critic, N=128/64)` as a control. The flagship is the one control that is cross-policy *by " + "construction* (the RISE method is the S0A policy re-ranked by its own IQL critic, so it can " + "never run on the S0B arm), and the strict same-π_β guard had been dropping it from every block " + "— the project's headline comparison was absent from the only block entitled to make it. It is " + "admitted on matching (wave, epoch); BC / random-of-N / permuted stay strictly same-policy.", "", + "> **How the headline's first column is decided (changed 2026-09-19 00:20).** `verdict: RSM vs " + "random-of-N` now reports the **paired McNemar** result (held-out eval seeds when the task has " + "them, else pooled) — the same number as the next column — and never a bare Wilson-CI comparison. " + "It used to be the unpaired comparison between the argmax-selected best cell and the pooled " + "control, which is unsafe twice over: the RSM side is a max over every cell on the task, so its " + "95 % interval is not valid for the selected recipe, and it discards the pairing even though both " + "arms replay the same init states. Concretely, mug read **YES (+2.6 pts, CI above)** off a " + "61-episode partial while the McNemar cell immediately to its right read p=0.375 — the deliverable " + "contradicted its own authoritative test in adjacent cells. The unpaired number is still printed " + "when the paired test is not significant, and tasks with no paired test yet are marked " + "`unpaired only`. Note the paired test uses the best *finished* arm at matched eval seeds, which " + "can be a different recipe from the plain-argmax `best RSM` column; the McNemar cell names its arm.", "", + "> **Which cell is bolded as \"best RSM\" (changed 2026-09-18 23:15).** The bolded row and the " + "headline's `best RSM` column are the argmax over the **highest-standing wave** that has a usable " + "cell — `FINAL`, else `FINAL@3000`, else `v2` — never over all waves at once. The 12:28 `early` " + "diagnostic grid (4 particles, dense head) can never be bolded, and the retired `v1`/`v1b` grids " + "are used only when nothing better exists for a task. Before this, square play's headline quoted a " + "wave-1 cell scored with the early DWM checkpoint (4.0 %, n=50) while its `FINAL` protocol read " + "1.1 % over n=188 — the deliverable was advertising a number its own preamble disclaims. The " + "headline's RSM row is also **pooled over eval seeds**, like the control rows, so the two sides of " + "`beats our base?` always carry the same episodes. Each task's block names the wave the bolded row " + "came from and, if a retired/diagnostic grid holds a higher raw rate, prints it explicitly.", "", + "> **Caveat on the wave-1 MLP rows.** `runs//rsm/{M,L40,M_s1}/ckpt_best.pt` is rewritten while " + "stream B's successor trainings run, and the wave-1 job scripts point at that live path, so wave-1 MLP " + "cells that dispatched at different times may have scored with different weights. Wave 2 evaluates a " + "frozen copy (`ckpt_w2.pt`, `scripts/freeze_rsm_w2.sh`); the DWM rows already use the frozen " + "`ckpt_best_early.pt`.", "", + "> **How to read the recipe-ablation grid (`eval_abl`).** Those cells change ONE read-out knob " + "(candidate count N, decision rule, score kind, particle count) off an existing arm at the same " + "\u03c0_\u03b2 checkpoint, so they are reported as a **paired** McNemar test against a reference cell " + "on their own arm in each task's `Recipe ablations` block, not by comparing Wilson intervals in " + "the recipe table (those overlap on every one of them). They are never bolded as `best RSM`: the " + "grid was launched and first read on eval seed 0, so its seed-0 deltas are selection statistics, " + "and only the held-out (eval seed 1/2) block is a test. Cells still running are paired on the " + "prefix both arms have; because this table regenerates every few minutes, a p-value from a " + "running cell is a peeked interim number and is labelled **provisional** rather than reported as " + "a result. A knob measured on more than one successor arm must also move the SAME WAY on both " + "before it is called a result: the block flags any knob (and any knob ladder) whose sign flips " + "between arms, suppresses the significance bolding on it, and attaches no claim to it. The " + "candidate-count ladder N is currently in exactly that state (+8.5 pts on the M arm, -8.5 on " + "L40 \u2014 same task, same \u03c0_\u03b2 checkpoint, same held-out seeds), so **this project " + "reports no candidate-count effect**; the ladder is listed as measured.", "", + "> **What actually capped the N ladder: a retained autograd graph, not the RSM.** At " + "`plan_n=2048` the cells OOM’d an 80 GB card with ~75 GB live (jobs " + "1777014/1777018/1777022/1777026 inside `idql._sample_action_chunks`; then " + "1777587-1777590 inside `rsm_scorer._q_fold_logit`). The cause is that **nothing on the " + "rollout path disables autograd** — `sim_pipeline/eval/rollout.py` → " + "`robomimic_rollout_policy.predict` → `idql.get_action` → `plan_get_action` had no " + "`torch.no_grad()` anywhere — so the released DDPM sampler retained a graph across all " + "100 inference timesteps for all `B*N` rows. At N=128 that is a few GB and nobody noticed; at " + "N=2048 it is ~75 GB, and the OOM surfaced in whichever allocation happened to come next, " + "which is why it looked like a scorer problem. Fixed 03:35 UTC by decorating " + "`plan_get_action` with `@torch.no_grad()`. **This is bit-for-bit result-neutral** — grad " + "mode changes no forward number and consumes no RNG (unit-tested) — so every cell already " + "on disk stands, and the N=2048 argmax cells run the plain released path with no memory knob " + "set. Two opt-in knobs from the earlier, mistaken diagnosis remain available and default to " + "off: `training.plan_sample_batch` (slice the DDPM sampler; NOT result-neutral — it " + "changes the order in which the sampler consumes its RNG) and `training.plan_max_rows` " + "(override `rsm_scorer.MAX_ROWS = 65536`; provably result-neutral, CRN drawn once per " + "particle and indexed by particle, unit-tested identical down to a 1-row slice). The N=2048 " + "**random** control cells were launched at 03:00 with `plan_sample_batch=512` and are left " + "running: their candidate draws are a different realisation from the same i.i.d. sampler, " + "which is what varying N does anyway, and episodes are paired by init state, not by " + "candidate noise.", "", + "> **Timing caveat from the same fix.** `plan s/step` is comparable *within* a wave but not " + "across 03:35 UTC: cells dispatched before that built the sampler’s autograd graph and " + "cells dispatched after do not, so later cells are somewhat cheaper in both time and GPU " + "memory at the same recipe. Success rates are unaffected (the forward numbers and the RNG " + "draws are identical); only the seconds-per-step column moves.", "", + "> Rows labelled **(early)** come from the 12:28 diagnostic grid (`eval_early_dwm`): 4 particles and the " + "dense expert-membership head, 50 rollouts, and mostly still running — they are a smoke signal, not a " + "result. `--no-early` drops them.", ""] + label_legend + if not per_task: + out += ["_No eval JSONs found yet._", ""] + + preamble_end = len(out) + summary = [] + gm_by_label = {} + mcn_by_label = {} + for t in tasks: + if t not in per_task: + continue + best = render_task(t, per_task[t], out, a.best_min_n) + info = PAPER.get(t, {}) + # the unbiased "typical RSM recipe" number: the largest pooled (β, L) grid at the best row's + # checkpoint if one exists, else the largest grid anywhere (the FINAL waves run ONE frozen recipe, so + # restricting to the best row's checkpoint would blank this column out on exactly the tasks that have + # reached FINAL -- and this is the column that de-biases the selection max). + all_gms = grid_mean_rows([r for r in per_task[t] if r["kind"] == "RSM" and r["wave"] != "VAL"]) + gms = [g for g in all_gms + if best is None or (g["policy"], g["epoch"]) == (best["policy"], best["epoch"])] + if gms or all_gms: + gm_by_label[info.get("label", t)] = max(gms or all_gms, key=lambda g: g["n"]) + # paired (McNemar) test of the best eval-seed-pooled RSM arm vs the random-of-N arm: the arms share + # init states seed-for-seed, so this is the powered version of "does the read-out beat resampling". + # The headline must quote the wave with the highest PROTOCOL standing, not the one with the most + # episodes. `FINAL` is the pre-registered held-out protocol at the paper's training length (epoch + # 5000) and is the project's answer; `FINAL@3000` is the matched-epoch version. Taking the best arm + # across ALL waves instead had the headline quoting the epoch-2500 `v2` grid (Δ +4.5, p=0.159) while + # the actual FINAL result on the same task was Δ +12.0, p=0.008 -- opposite verdicts, and nothing in + # the row said which epoch it came from. (Fixed 2026-09-18 22:45.) + esp_t = eval_seed_pooled(per_task[t]) + for wave_pref in ("FINAL", "FINAL@3000", None): + sub = [r for r in esp_t if r["wave"] == wave_pref] if wave_pref else esp_t + hit = [x for x in paired_tests(sub) if x[1]["kind"] == "random"] + if hit: + for _a, _b, _res, _ho in hit: + mcn_by_label[info.get("label", t)] = (_a, _b, _res, _ho, wave_pref or _a["wave"]) + break + if best is not None: + # The control columns are pooled over eval seeds (`_pool_eval_seeds`), so the RSM column must be + # too -- otherwise the headline compares a single-eval-seed argmax cell (n=50/61) against a + # 3-seed control (n=300) and the "beats our base?" verdict is decided by that asymmetry. + bq = _pool_eval_seeds([r for r in per_task[t] if r["kind"] == "RSM" and r["wave"] != "VAL"], best) + summary.append((info.get("label", t), 100 * bq["sr"], 100 * bq["lo"], 100 * bq["hi"], + bq["n"], info.get("rise"), bq["model"], + f"`{best['cells'][0]}{'*' if bq['partial'] else ''}` " + f"({bq['wave']}, eval seed{'s' if len(bq.get('eval_seeds') or []) > 1 else ''} " + f"{eval_seed_str(bq)})", + (f"{policy_label(best['policy'], code=False)} ep{best['epoch']}" + if best["epoch"] else policy_label(best["policy"], code=False)), + base_row(per_task[t], best["epoch"], best["policy"], best["seeds"]), + rise_row(per_task[t], best["epoch"]), + ctrl_row(per_task[t], "random", best["epoch"], best["policy"], best["seeds"]))) + + if summary: + out.insert(preamble_end, "") + # Orchestrator 15:51: random-of-N is THE control of this project (it draws the same N candidates from + # pi_beta and picks one uniformly), so "best RSM vs random-of-N" is the first column of the headline. + head = ["| task | **verdict: RSM vs random-of-N** | **paired test vs random-of-N (McNemar, pooled eval seeds)** | " + "best RSM | SR % [95% CI] | n | " + "**RSM (β,L) grid mean (unbiased)** | random-of-N control | " + "π_β policy | our π_β base (greedy / random-of-N) | beats our base? | RISE flagship (ours) | " + "beats RISE flagship? | RISE paper (BC / RISE) | beats RISE paper? |", + "|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|"] + + def _verdict(sr, lo, rise): + if rise is None: + return "-" + if lo > rise: + return "**YES** (CI above)" + return "point estimate only" if sr > rise else "no" + + def _vs_base(sr, lo, b): + if b is None: + return "-" + bsr = 100 * b["sr"] + if lo > bsr: + return f"**YES** (+{sr - bsr:.1f} pts, CI above)" + if sr > bsr: + return f"point estimate only (+{sr - bsr:.1f})" + return f"no ({sr - bsr:+.1f} pts)" + + def _rnd_verdict(sr, lo, rnd, mc): + """The headline's first column: RSM vs random-of-N, decided by the PAIRED test when one exists. + + It used to be `_vs_base(sr, lo, rnd)` -- an unpaired Wilson comparison between the argmax-selected + best cell and the pooled random-of-N control. Two things make that unsafe as the deliverable's + most prominent verdict: (a) the RSM side is a max over every cell on the task, so its CI is not a + valid 95 % interval for the selected recipe, and (b) the comparison throws away the pairing even + though both arms replay the same init states. On mug it printed "**YES** (+2.6 pts, CI above)" + from a 61-episode partial while this same row's McNemar column read p=0.375 -- the table + contradicted its own authoritative test in adjacent cells. `rflags` already deferred to the + paired test in the other direction (it suppresses the "indistinguishable from random" warning when + McNemar is significant); this makes the deference symmetric. + The unpaired number is still printed, just never on its own as a YES. + """ + unp = _vs_base(sr, lo, rnd) + if mc is None: + return "-" if rnd is None else f"{unp} _(unpaired only; no paired test yet)_" + res = mc[3] or mc[2] # held-out if the task has held-out seeds, else pooled + d, p = 100 * res[3], res[6] + tag = "held-out" if mc[3] else "pooled" + if p < 0.05: + return (f"**YES** (paired Δ {d:+.1f}, p={p:.3f}, {tag})" if d > 0 + else f"no (paired Δ {d:+.1f}, p={p:.3f}, {tag})") + return f"not significant (paired Δ {d:+.1f}, p={p:.3f}, {tag}; unpaired {unp})" + + body = [] + for lab, sr, lo, hi, n, rise, mdl, cell, pib, base, ourrise, rnd in summary: + if base is None: + bcell = "_none finished_" + else: + sd = f" s{','.join(str(x) for x in base['seeds'])}" if base["seeds"] else "" + _bp = policy_label(base["policy"], code=False) + bck = (f"{_bp}{sd} ep{base['epoch']}" if base["epoch"] else _bp) + same = f", {bck}" # always name the checkpoint the base came from + bcell = (f"{100 * base['sr']:.1f} [{100 * base['lo']:.1f}, {100 * base['hi']:.1f}] " + f"(n={base['n']}{'*' if base['partial'] else ''}, " + f"{'greedy' if base['kind'] == 'BC' else base['kind']}{same})") + paper_bc = PAPER.get(_task_of_label(lab), {}).get("bc") + if ourrise is None: + rcell, rverdict = "_none finished_", "-" + else: + rep = (f", {policy_label(ourrise['policy'], code=False)} ep{ourrise['epoch']}" + if ourrise["epoch"] else "") + res = ourrise.get("eval_seeds") + rcell = (f"{100 * ourrise['sr']:.1f} [{100 * ourrise['lo']:.1f}, {100 * ourrise['hi']:.1f}] " + f"(n={ourrise['n']}{'*' if ourrise['partial'] else ''}{rep}" + + (f", eval seeds {','.join(str(x) for x in res)}" if res else "") + ")") + if not ourrise.get("epoch_matched", True): + # Epoch-mismatched arms: the RSM policy has trained longer than the flagship policy, so + # any gap mixes the read-out's effect with extra BC training. Withhold the verdict and + # name the matched-epoch wave that does carry an honest answer. + rverdict = (f"_epoch-mismatched (RSM ep{ourrise['want_epoch']} vs flagship " + f"ep{ourrise['epoch']}) — read the **FINAL@3000** rows / " + f"`scripts/paired_final_test.py eval_final_e3000 `_") + else: + rverdict = _vs_base(sr, lo, ourrise) + mc = mcn_by_label.get(lab) # needed by _rnd_verdict below, printed further down + if rnd is None: + ncell = "_none finished_" + else: + nep = (f", {policy_label(rnd['policy'], code=False)} ep{rnd['epoch']}" + if rnd["epoch"] else "") + nes = rnd.get("eval_seeds") + ncell = (f"{100 * rnd['sr']:.1f} [{100 * rnd['lo']:.1f}, {100 * rnd['hi']:.1f}] " + f"(n={rnd['n']}{'*' if rnd['partial'] else ''}{nep}" + + (f", eval seeds {','.join(str(x) for x in nes)}" if nes else "") + ")") + nverdict = _rnd_verdict(sr, lo, rnd, mc) + g = gm_by_label.get(lab) + gcell = ("_n/a_" if g is None else + f"{100 * g['sr']:.1f} [{100 * g['lo']:.1f}, {100 * g['hi']:.1f}] " + f"(n={g['n']}, {g['n_cells']} cells, {g['model']})") + if mc is None: + mcell = "_needs the same recipe at >=2 eval seeds_" + else: + _a, _b, _res, _ho, _w = mc + # name the arm: the paired test uses the best FINISHED arm while the "best RSM" column is a + # plain argmax, so the two columns can legitimately refer to different recipes -- say which. + mcell = (f"`{_w}` (π_β {policy_label(_a['policy'], code=False)} ep{_a['epoch']}, " + f"arm {arm_label(_a)}): " + f"Δ {100*_res[3]:+.1f} pts, p={_res[6]:.3f} (n={_res[0]} paired)") + if _ho: + mcell += f"; held-out Δ {100*_ho[3]:+.1f}, p={_ho[6]:.3f} (n={_ho[0]})" + if (_ho or _res)[6] < 0.05: + mcell = "**" + mcell + "**" + _lab = lab + (" \u2021" if _task_of_label(lab) in PIECE_TASKS else "") + body.append(f"| {_lab} | {nverdict} | {mcell} | {mdl} {cell} | {sr:.1f} [{lo:.1f}, {hi:.1f}] | {n} | " + f"{gcell} | {ncell} | {pib} | {bcell} | {_vs_base(sr, lo, base)} | {rcell} | {rverdict} | " + f"{fmt(paper_bc, 1)} / {fmt(rise, 1)} | {_verdict(sr, lo, rise)} |") + + # Sanity flag: our own base policy far above the paper's BC number means the comparison is not like-for-like. + flags = [] + for lab, sr, lo, hi, n, rise, mdl, cell, pib, base, ourrise, rnd in summary: + info = PAPER.get(_task_of_label(lab), {}) + if base is None or info.get("bc") is None: + continue + bsr = 100 * base["sr"] + if bsr - info["bc"] > 15.0: + flags.append(f"**{lab}**: our base π_β ({base['kind']}, n={base['n']}) = {bsr:.1f}% vs the " + f"paper's BC {info['bc']:.1f}%" + + (f" and the paper's RISE {info['rise']:.1f}%" if bsr > (info.get("rise") or 1e9) else "")) + # The control that actually tests the RSM: random-of-N draws the same N candidates and picks one at + # random, so an argmax cell that does not beat it has shown nothing about the read-out. + rflags = [] + for lab, sr, lo, hi, n, rise, mdl, cell, pib, base, ourrise, rnd in summary: + if rnd is None or rnd["n"] < 20: + continue + # Do not flag a task whose PAIRED test against random-of-N is significant. The flag compares two + # unpaired 50-episode cells, which is the weakest read of the same question; the McNemar block two + # paragraphs down is the powered one and is authoritative. Listing a task in both places printed + # "not distinguishable from random" and "p=0.008" about the same task in adjacent lines. + _mc = mcn_by_label.get(lab) + if _mc is not None: + # The paired test is the powered read of exactly this question, so when it exists it decides + # membership of this list in BOTH directions: significant -> the task is not flagged (it used + # to print "not distinguishable from random" next to p=0.008), NOT significant -> the task IS + # flagged even if the argmax cell's Wilson interval happens to clear the control, because that + # interval belongs to a selected maximum and is not a 95 % interval for the chosen recipe. + # Mug was the case in point: p=0.453 held-out, yet it was silently absent from this warning. + _r = _mc[3] or _mc[2] + if _r[6] < 0.05: + continue + _pq = (f" — **paired McNemar Δ {100 * _r[3]:+.1f} pts, p={_r[6]:.3f}** " + f"({'held-out' if _mc[3] else 'pooled'}, n={_r[0]} paired), the powered read") + elif lo > 100 * rnd["sr"]: + continue + else: + _pq = "" + g = gm_by_label.get(lab) + gtxt = ("" if g is None else + f", and the unbiased pooled (β,L) grid mean is {100 * g['sr']:.1f}% " + f"[{100 * g['lo']:.1f}, {100 * g['hi']:.1f}] (n={g['n']}, {g['n_cells']} cells)") + rflags.append(f"**{lab}**: best RSM {sr:.1f}% [{lo:.1f}, {hi:.1f}] (n={n}) vs random-of-N " + f"{100 * rnd['sr']:.1f}% [{100 * rnd['lo']:.1f}, {100 * rnd['hi']:.1f}] " + f"(n={rnd['n']}{'*' if rnd['partial'] else ''}){gtxt}{_pq}") + flag_lines = [] + if rflags: + flag_lines += ["> **⚠ The RSM read-out is not yet distinguishable from random selection.** " + + "; ".join(rflags) + ". `random-of-N` samples the same N action chunks from the same " + "π_β and picks one uniformly, so it carries the whole benefit of resampling without " + "using the RSM at all. Until an argmax cell's CI clears that row, a lift over BC is " + "evidence for best-of-N *sampling*, not for the successor read-out. (`permuted scores` " + "is the matching negative control and should land in the same place.) Membership of " + "this list is decided by the **paired** McNemar test whenever a task has one: " + "significant \u2192 omitted (it used to print \u201cnot distinguishable from random\u201d " + "beside p=0.008 for the same task), not significant \u2192 listed **even when the " + "argmax cell's Wilson interval clears the control**, because that interval belongs " + "to a selected maximum over every cell on the task and is not a valid 95 % interval " + "for the chosen recipe. Tasks with no paired test yet fall back to the unpaired CI " + "comparison. See the next paragraph for the powered numbers.", ""] + mcn_lines = [] + for lab, (_a, _b, _res, _ho, _w) in sorted(mcn_by_label.items()): + rr = _ho or _res + tag = "held-out eval seeds" if _ho else "pooled eval seeds" + mcn_lines.append(f"**{lab}**: Δ {100*rr[3]:+.1f} pts, exact p={rr[6]:.3f} " + f"(n={rr[0]} paired, {tag}, `{_w}` π_β ep{_a['epoch']})") + if mcn_lines: + flag_lines += ["> **The powered version of that comparison is the paired McNemar test**, because " + "the RSM arm and the `random-of-N` arm run at the same eval seeds and therefore " + "replay the same init states episode for episode: " + "; ".join(mcn_lines) + + ". Read this rather than the overlapping Wilson intervals above \u2014 it is " + "several times more powerful at the same n. Each task's `Paired significance` " + "block gives b/c and the BC comparison.", ""] + if flags: + flag_lines += ["> **⚠ Sanity flag — our π_β is much stronger than the paper's BC baseline.** " + + "; ".join(flags) + ". A search that starts from a far better base policy is not " + "comparable to the paper's rows: beating the paper's RISE number is then not evidence " + "that the RSM read-out helps. The meaningful comparison on such a task is the " + "*lift over our own base* (the `beats our base?` column), and the discrepancy itself " + "(dataset mix, success criterion, env init range or horizon) is a setup question for " + "the orchestrator / stream A.", ""] + + _foot = [] + if any(_task_of_label(x[0]) in PIECE_TASKS for x in summary): + _foot = ["", "\u2021 **piece-assembly tasks: the env success check was broken until 2026-09-18 " + "18:40 UTC** (`_check_success()` required piece_2 stacked on piece_1, but piece_2 is " + "inert in both two-piece datasets, so every episode scored 0 whatever the policy did). " + "Numbers on these rows are dominated by pre-patch cells and are **not results**; the " + "per-task blocks mark each pre-patch row with \u2021 and the cells are being re-run. " + "See `status/A_env_stage0.md`."] + for i, line in enumerate(["## Headline", ""] + head + body + _foot + [""] + flag_lines): + out.insert(preamble_end + i, line) + + # ---- the 3-training-seed protocol view (orchestrator 05:10), inserted just under the headline + sp = seed_protocol_section(tasks, raw_by_task) + if sp: + for i, line in enumerate(sp): + out.insert(preamble_end + i, line) + + # ---- selection-grid completeness, then the FINAL coverage matrices (orchestrator 20:09 item 4) + out += grid_completeness(tasks) + cov = [] + for t in tasks: + cov += final_coverage(t, raw_by_task.get(t, [])) + if cov: + out += ["## FINAL coverage — {arm} x {π_β seed} x {eval seed}", "", + "Eval seed 0 is the **SELECTION** seed (the wave-1/wave-2 (β, L) grids ranked recipes there); " + "eval seeds 1 and 2 are **HELD-OUT**. Every arm must appear at every eval seed: an arm missing " + "a seed that another arm has biases the comparison silently. `n*` = still running.", ""] + cov + if a.stdout_coverage: + print("\n".join(cov)) + + if DUP_CELLS: + # Say it out loud: a dropped cell is real GPU work that measured an arm a second time at the same + # eval seed, so the reader can see the arm is not under-evidenced, it is double-launched. + out += ["## Duplicate measurements dropped", "", + "These cells re-measure an arm that another cell already measured at the **same π_β seed and " + "the same eval seed**, i.e. over the same initial states. They are excluded from the pooled " + "row (see `dedupe_measurements`); counting them would shrink the interval by ~√2 on episodes " + "that are not independent and would break the paired McNemar alignment. Stream A's `pol` " + "wave is listed but NOT dropped: its `patchchk_*` / `dz05_*` re-runs share a checkpoint with " + "the plain policy eval yet are deliberately different measurements, which this table cannot " + "tell apart from a row alone.", "", + "| task | wave | kept | duplicate (n) | action |", "|---|---|---|---|---|"] + for t, w, keep, drop, n, dropped in sorted(DUP_CELLS): + out.append(f"| {t} | {w} | `{keep}` | `{drop}` ({n}) | " + f"{'dropped from the pooled row' if dropped else '**kept** — `pol` wave, see below'} |") + out.append("") + + md = "\n".join(out) + "\n" + Path(a.out_md).parent.mkdir(parents=True, exist_ok=True) + Path(a.out_md).write_text(md) + + with open(a.out_csv, "w", newline="") as fh: + w = csv.writer(fh) + # `label` / `policy_label` carry the 04:05 orchestrator naming convention; `kind` / `policy` keep the + # raw codes so the CSV stays machine-joinable against the job scripts. + w.writerow(["task", "wave", "kind", "label", "env", "cells", "model", "beta", "L", "mode", "N", "particles", "score", + "rule", "temp_flag", "policy", "policy_label", "epoch", "seeds", "n_seeds", + "per_seed_sr", "eval_seeds", "k", "n", + "success_rate", "ci_lo", "ci_hi", + "mean_len", "plan_s_per_step", "gap_chosen_minus_mean", "partial", "checkpoint"]) + for t in tasks: + for r in sorted(per_task.get(t, []), key=lambda r: (r["kind"] != "RSM", -r["sr"])): + w.writerow([r["task"], r["wave"], r["kind"], + kind_label(r["kind"], r["policy"], r["N"]), r.get("env", ""), + ";".join(r["cells"]), r["model"], + fmt(r["beta"], 2), r["L"], r["mode"], r["N"], r["particles"], r["score"], r["rule"], + r["temp_flag"], r["policy"], policy_label(r["policy"], code=False), + r["epoch"], ",".join(str(s) for s in r["seeds"]), len(r["seeds"]), + ";".join(f"{s}:{(v[0] / v[1]):.4f}" for s, v in sorted( + (r.get("per_seed") or {}).items(), key=lambda kv: (kv[0] is None, kv[0])) + if v[1] and s is not None), + eval_seed_str(r), r["k"], r["n"], f"{r['sr']:.4f}", f"{r['lo']:.4f}", f"{r['hi']:.4f}", + fmt(r["mean_len"], 1), fmt(r["s_per_step"], 3), + fmt(r["gap"], 4) if r["gap"] is not None else "", int(r["partial"]), r["checkpoint"]]) + + n_cells = sum(len(v) for v in per_task.values()) + print(f"[results_table] {n_cells} recipe rows over {len(per_task)} tasks -> {a.out_md}, {a.out_csv}", + file=sys.stderr) + if a.stdout: + print(md) + + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/reward_head_probe.py b/rsm_rise/scripts/reward_head_probe.py new file mode 100644 index 0000000000000000000000000000000000000000..6d54145336793e2c5cc1e02dcd285e83fcd56036 --- /dev/null +++ b/rsm_rise/scripts/reward_head_probe.py @@ -0,0 +1,53 @@ +"""What does the successor model's reward head actually respond to on a coverage task? + +Scores every frame of the cache with the MEMBERSHIP head (from ckpt_best.pt) and with the TASK-COMPLETION head +(ckpt_goalhead.pt), then reports mean logit by frame category. If the membership head fires at the FIRST frame +of expert episodes -- before any task progress -- it is detecting the initial-state region, not the task. +usage: reward_head_probe.py [model] +""" +import sys, json, numpy as np, torch +ROOT = "/proj/dmfexp/zwhong/rsm_rise"; RSM = "/proj/dmfexp/zwhong/projs/issue_resolver_richardrl/gen_q_rsm/rsm_libero" +sys.path.insert(0, RSM); from model import RewardHead # noqa +task = sys.argv[1]; model = sys.argv[2] if len(sys.argv) > 2 else "M" +cache = f"{ROOT}/cache/{task}"; dev = "cuda" if torch.cuda.is_available() else "cpu" +fs = np.load(f"{cache}/feat_stats.npz"); mu = fs["mu"] if "mu" in fs.files else fs["mean"]; sd = fs["sd"] if "sd" in fs.files else fs["std"] +zc = float(fs["z_clip"]) if "z_clip" in fs.files else 10.0; fl = float(fs["sd_floor"]) if "sd_floor" in fs.files else 0.01 +z = np.load(f"{cache}/z.f16.npy", mmap_mode="r"); pr = np.load(f"{cache}/proprio.f32.npy", mmap_mode="r") +meta = np.load(f"{cache}/meta.npz"); g = np.load(f"{cache}/goal.npz") +N = z.shape[0]; ep_from, ep_to, ep_succ = meta["ep_from"], meta["ep_to"], meta["ep_success"].astype(bool) +def state(idx): + f = np.concatenate([np.asarray(z[idx], np.float32), np.asarray(pr[idx], np.float32)], -1) + return np.clip((f - mu) / np.maximum(sd, fl), -zc, zc).astype(np.float32) +def head_from(path): + ck = torch.load(path, map_location="cpu", weights_only=False) + d = int(ck.get("d_in", ck["config"]["d_z"])) + int(ck.get("n_pr", 0) or 0) + h = RewardHead(d, 1).to(dev); h.load_state_dict(ck["rew"]); h.eval(); return h +heads = {"membership head (ckpt_best)": head_from(f"{ROOT}/runs/{task}/rsm/{model}/ckpt_best.pt")} +try: heads["task-completion head (goalhead)"] = head_from(f"{ROOT}/runs/{task}/rsm/{model}/ckpt_goalhead.pt") +except Exception as e: print("no goalhead:", e) +# frame categories +first_exp = np.array([ep_from[e] for e in range(len(ep_from)) if ep_succ[e]]) +first_play = np.array([ep_from[e] for e in range(len(ep_from)) if not ep_succ[e]]) +# expert frames in the first 10 % of their episode (no progress yet) vs last 10 % +early_exp, late_exp, mid_play = [], [], [] +for e in range(len(ep_from)): + a, b = ep_from[e], ep_to[e]; L = b - a + if ep_succ[e]: early_exp += list(range(a, a + max(1, L // 10))); late_exp += list(range(b - max(1, L // 10), b)) + else: mid_play += list(range(a + L // 4, a + 3 * L // 4)) +goal_frames = np.where(g["goal"] > 0)[0] +cats = {"expert episode, FIRST frame (no progress yet)": first_exp, + "expert episode, first 10 % of frames": np.array(early_exp), + "expert episode, last 10 % (piece placed)": np.array(late_exp), + "frames labelled goal=1 (piece placed)": goal_frames, + "play episode, FIRST frame": first_play, + "play episode, middle 50 % of frames": np.array(mid_play)} +rng = np.random.RandomState(0) +print(f"{task} / {model}: mean reward-head LOGIT by frame category (higher = 'more expert / more complete')\n") +print(f"{'category':48s}" + "".join(f"{k[:28]:>30s}" for k in heads)) +for name, idx in cats.items(): + idx = np.asarray(idx); idx = idx if len(idx) <= 4000 else rng.choice(idx, 4000, replace=False); idx = np.sort(idx) + x = torch.from_numpy(state(idx)).to(dev); t = torch.zeros(len(idx), dtype=torch.long, device=dev) + row = f"{name:48s}" + with torch.no_grad(): + for k, h in heads.items(): row += f"{h(x, t).mean().item():>30.2f}" + print(row + f" (n={len(idx)})") diff --git a/rsm_rise/scripts/rollout_gallery.py b/rsm_rise/scripts/rollout_gallery.py new file mode 100644 index 0000000000000000000000000000000000000000..554a0defb36d7e0163b5091ee284210d71543a7e --- /dev/null +++ b/rsm_rise/scripts/rollout_gallery.py @@ -0,0 +1,168 @@ +"""Roll out a policy in the RISE eval env and save labelled SUCCESS / FAILURE trajectories. + +Uses the harness's own `setup_eval()` + `rollout()`, so the trajectories come from exactly the code path our +eval numbers come from. The policy is image-based, so the camera frames are already in the observation dict; +no extra rendering pass is needed. + +NOTE: scripts/eval_cell.sh passes BOTH `exp.eval_seed=0` and `exp.seed=0`; `exp.seed` drives the diffusion +policy's action sampling. An earlier revision set only `exp.eval_seed`, so its episodes are not the same draws +as our reported cells and its per-run success rate must NOT be quoted as a measurement. Frames are already right-side up (docs/figs/orient_check.png), drawn RAW. + +usage: rollout_gallery.py --task mug_expert_suboptimal --env robomimic_mug --ckpt + [--n-success 3] [--n-failure 3] [--max-eps 40] [--horizon 400] + [--policy-mode bc|idql] [--eval-seed 0] [--tag S3H1_s1_ep5000] + +Writes docs/figs/rollout__/{success,failure}_.png filmstrips, the same as .mp4, and a +SUMMARY.json with per-episode length / first-success step / outcome. +""" +from __future__ import annotations +import argparse, json, os, sys, time +from pathlib import Path +import numpy as np + +ROOT = Path("/proj/dmfexp/zwhong/rsm_rise") +sys.path.insert(0, str(ROOT / "code/rise_code")) +os.environ.setdefault("MUJOCO_GL", "egl") + +CAMS = ("agentview_image", "robot0_eye_in_hand_image") + + +def to_uint8(im): + im = np.asarray(im) + if im.ndim == 4: + im = im[0] + if im.ndim == 3 and im.shape[0] in (3, 4): # CHW -> HWC + im = np.transpose(im, (1, 2, 0)) + if im.dtype != np.uint8: + im = (255.0 * np.clip(im, 0.0, 1.0)).astype(np.uint8) + return im[..., :3] + + +def frames_from_obs(obs_list): + """-> {cam: [HWC uint8]} for whichever cameras the obs carries.""" + out = {} + for cam in CAMS: + seq = [] + for o in obs_list: + if isinstance(o, dict) and cam in o: + seq.append(to_uint8(o[cam])) + if seq: + out[cam] = seq + return out + + +def filmstrip(per_cam, n_cols, title, path, subtitle=""): + import matplotlib; matplotlib.use("Agg") + import matplotlib.pyplot as plt + cams = list(per_cam) + T = len(per_cam[cams[0]]) + idx = np.unique(np.linspace(0, T - 1, min(n_cols, T)).astype(int)) + fig, axes = plt.subplots(len(cams), len(idx), figsize=(1.55 * len(idx), 1.75 * len(cams)), squeeze=False) + for r, cam in enumerate(cams): + for c, t in enumerate(idx): + ax = axes[r][c]; ax.imshow(per_cam[cam][t]); ax.set_axis_off() + if r == 0: + ax.set_title(f"t={t}", fontsize=7) + if c == 0: + ax.text(-0.08, .5, cam.replace("_image", "").replace("robot0_eye_in_hand", "wrist"), + transform=ax.transAxes, rotation=90, va="center", ha="right", fontsize=7) + fig.suptitle(title, fontsize=10, y=.99) + if subtitle: + fig.text(.5, .015, subtitle, ha="center", fontsize=7.5, style="italic") + fig.tight_layout(rect=[0, .05, 1, .95]); fig.savefig(path, dpi=140); plt.close(fig) + + +def write_mp4(per_cam, path, fps=20): + try: + import cv2 + except Exception: + return False + cams = list(per_cam); T = len(per_cam[cams[0]]) + h, w = per_cam[cams[0]][0].shape[:2] + vw = cv2.VideoWriter(str(path), cv2.VideoWriter_fourcc(*"mp4v"), fps, (w * len(cams), h)) + if not vw.isOpened(): + return False + for t in range(T): + row = [per_cam[c][t] for c in cams] + vw.write(np.concatenate(row, axis=1)[:, :, ::-1]) + vw.release() + return True + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--task", required=True) + ap.add_argument("--env", required=True) + ap.add_argument("--ckpt", required=True) + ap.add_argument("--n-success", type=int, default=3) + ap.add_argument("--n-failure", type=int, default=3) + ap.add_argument("--max-eps", type=int, default=40) + ap.add_argument("--horizon", type=int, default=400) + ap.add_argument("--policy-mode", default="bc") + ap.add_argument("--eval-seed", type=int, default=0) + ap.add_argument("--cols", type=int, default=8) + ap.add_argument("--tag", default="run") + ap.add_argument("--extra", nargs="*", default=[], help="extra hydra overrides, e.g. planner settings " + "training.plan_n=128 training.rsm_ckpt=... -- lets the gallery render the RSM planner path") + a = ap.parse_args() + + from hydra import compose, initialize_config_dir + from sim_pipeline.eval.eval import setup_eval + from sim_pipeline.eval.rollout import rollout + from sim_pipeline.eval.rollout_stats import RolloutStats + + out = ROOT / "docs/figs" / f"rollout_{a.task}_{a.tag}"; out.mkdir(parents=True, exist_ok=True) + with initialize_config_dir(config_dir=str(ROOT / "code/rise_code/sim_pipeline/configs"), version_base=None): + cfg = compose(config_name="eval_robomimic_iql_diffusion", overrides=[ + f"+env={a.env}", f"exp.model_path={a.ckpt}", "exp.use_model_manager=False", + f"exp.num_rollouts={a.max_eps}", f"exp.rollout_horizon={a.horizon}", + f"exp.eval_seed={a.eval_seed}", f"exp.seed={a.eval_seed}", f"++exp.policy_mode={a.policy_mode}", + "exp.log_video=False", "exp.verbose=False", + ] + list(a.extra)) + cfg.env.horizon = a.horizon + env, policy, render_mode, video_writers = setup_eval(cfg) + print(f"[gallery] env={a.env} ckpt={a.ckpt} mode={a.policy_mode} horizon={a.horizon}", flush=True) + + got = {"success": 0, "failure": 0} + summary = [] + stats = RolloutStats() + for ep in range(a.max_eps): + t0 = time.time() + traj = rollout(policy=policy, eval_envs=env, rollout_stats=stats, reset_state=None, logger=None, + total_steps=a.horizon, render_mode=None, log_video=False, video_writers=None, + return_trajectory=True, end_on_success=True) + # NOTE: rollout() already calls rollout_stats.finalize_episode() (rollout.py:244) -- calling it + # again here raised "need at least one array to stack" on an emptied episode buffer. + ok = bool(stats.all_successes[-1] > 0) + kind = "success" if ok else "failure" + first = stats.all_first_success[-1] + rec = {"episode": ep, "outcome": kind, "steps": stats.all_lengths[-1], + "first_success_step": first, "seconds": round(time.time() - t0, 1)} + summary.append(rec) + print(f"[gallery] ep {ep}: {kind} steps={rec['steps']} first_success={first} " + f"({rec['seconds']}s)", flush=True) + if got[kind] >= (a.n_success if ok else a.n_failure): + continue + per_cam = frames_from_obs(traj.get("obs", [])) + if not per_cam: + print("[gallery] no camera frames in obs -- cannot draw this episode", flush=True); continue + k = got[kind]; got[kind] += 1 + sub = (f"{a.task} {a.tag} policy_mode={a.policy_mode} horizon={a.horizon} " + f"episode {ep} steps {rec['steps']}" + + (f" first success at step {first}" if ok else " never succeeded")) + filmstrip(per_cam, a.cols, f"{kind.upper()} (episode {ep})", out / f"{kind}_{k}.png", sub) + write_mp4(per_cam, out / f"{kind}_{k}.mp4") + if got["success"] >= a.n_success and got["failure"] >= a.n_failure: + print("[gallery] collected the requested episodes", flush=True); break + + stats.compute_statistics() + (out / "SUMMARY.json").write_text(json.dumps( + {"task": a.task, "env": a.env, "ckpt": a.ckpt, "policy_mode": a.policy_mode, "horizon": a.horizon, + "eval_seed": a.eval_seed, "episodes": summary, + "success_rate_over_these_episodes": round(float(stats.avg_success), 4), + "n_episodes": int(stats.num_episodes)}, indent=1)) + print(f"[done] {out} success_rate={stats.avg_success:.3f} over {stats.num_episodes} eps", flush=True) + + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/rr_build_square_sub_paper.sh b/rsm_rise/scripts/rr_build_square_sub_paper.sh new file mode 100644 index 0000000000000000000000000000000000000000..c5a007452d77ce11e4f915e5b5554b0261a60045 --- /dev/null +++ b/rsm_rise/scripts/rr_build_square_sub_paper.sh @@ -0,0 +1,4 @@ +#!/usr/bin/env bash +set -euo pipefail +ROOT=/proj/dmfexp/zwhong/rsm_rise +exec $ROOT/venv_rsm/bin/python $ROOT/scripts/build_square_sub_paper.py diff --git a/rsm_rise/scripts/rr_calib_dwm.sh b/rsm_rise/scripts/rr_calib_dwm.sh new file mode 100644 index 0000000000000000000000000000000000000000..aba5b2765aeba150612e77a2e3a4f202246c935f --- /dev/null +++ b/rsm_rise/scripts/rr_calib_dwm.sh @@ -0,0 +1,8 @@ +#!/usr/bin/env bash +# Temperature calibration of a DWM checkpoint's dense head on held-out frames (exclusive 1-GPU job). +# usage: rr_calib_dwm.sh [ckpt=runs//rsm/DWM/ckpt_best.pt] +# env: RR_QUEUE (preemptable by default; short GPU jobs must not sit on grp_runtime's 256-GPU quota) +set -euo pipefail +ROOT=/proj/dmfexp/zwhong/rsm_rise; TASK=${1:?usage: rr_calib_dwm.sh [ckpt]}; CK=${2:-$ROOT/runs/$TASK/rsm/DWM/ckpt_best.pt} +RR_QUEUE=${RR_QUEUE:-preemptable} bash "$ROOT/scripts/rr_gpu_submit.sh" "rr_dwm_calib_${TASK}" \ + bash -c "cd $ROOT/code/gen_q/rsm_libero && $ROOT/venv_rsm/bin/python calib_dwm.py --cache $ROOT/cache/$TASK --ckpt $CK" diff --git a/rsm_rise/scripts/rr_calib_dwm_best.sh b/rsm_rise/scripts/rr_calib_dwm_best.sh new file mode 100644 index 0000000000000000000000000000000000000000..5dabb0472511114eec45ab68fa0ffaf0554860eb --- /dev/null +++ b/rsm_rise/scripts/rr_calib_dwm_best.sh @@ -0,0 +1,30 @@ +#!/usr/bin/env bash +# Keep runs//rsm/DWM/calib.json in sync with the CURRENT ckpt_best.pt. +# ckpt_best.pt is overwritten whenever a new best q_action_winrate appears, but calib.json records the step it +# was fitted at; when the two disagree the planner (launch_wave2.py reads calib.json) applies a temperature that +# was fitted for different weights. Re-fit only when stale or missing -> idempotent, safe every babysit round. +# usage (inside a GPU job): rr_calib_dwm_best.sh [task...] +set -uo pipefail +ROOT=/proj/dmfexp/zwhong/rsm_rise +PY=$ROOT/venv_rsm/bin/python +cd "$ROOT/code/gen_q/rsm_libero" || exit 1 +rc=0 +for TASK in "$@"; do + D=$ROOT/runs/$TASK/rsm/DWM + if [ ! -s "$D/ckpt_best.pt" ]; then echo "[best] $TASK: no ckpt_best.pt yet, skip"; continue; fi + read -r best cur <<<"$("$PY" - "$D" <<'EOF' +import json, sys, pathlib +d = pathlib.Path(sys.argv[1]) +h = json.loads((d / "history.json").read_text()) if (d / "history.json").exists() else [] +best = max(h, key=lambda r: r.get("q_action_winrate", -1))["step"] if h else -1 +c = d / "calib.json" +cur = json.loads(c.read_text()).get("step", -3) if c.exists() else -2 +print(best, cur) +EOF +)" + if [ "$best" = "$cur" ]; then echo "[best] $TASK calib.json already fitted at best step $best"; continue; fi + echo "[best] === $TASK calib.json stale (has s$cur, best is s$best) -> re-fit from ckpt_best.pt" + "$PY" calib_dwm.py --cache "$ROOT/cache/$TASK" --ckpt "$D/ckpt_best.pt" --out "$D/calib.json" || rc=1 +done +echo "[best] DONE rc=$rc" +exit $rc diff --git a/rsm_rise/scripts/rr_calib_dwm_sweep.sh b/rsm_rise/scripts/rr_calib_dwm_sweep.sh new file mode 100644 index 0000000000000000000000000000000000000000..01bfa8f4a47edc456d6b6ba3dd08e1aefa681cd3 --- /dev/null +++ b/rsm_rise/scripts/rr_calib_dwm_sweep.sh @@ -0,0 +1,22 @@ +#!/usr/bin/env bash +# Fit the DWM reward-head temperature for EVERY existing runs//rsm/DWM/ckpt_s*.pt of the given tasks, +# writing calib_s.json next to each (calib.json for ckpt_best is left alone). +# Rationale: calib.json is fitted for ckpt_best only; the planner's checkpoint sweep scores other ckpt_s*.pt, +# and a probability-space read-out on those needs its own T (ranking by q_logit is temperature-free). +# usage (inside a GPU job): rr_calib_dwm_sweep.sh [task...] +set -uo pipefail +ROOT=/proj/dmfexp/zwhong/rsm_rise +PY=$ROOT/venv_rsm/bin/python +cd "$ROOT/code/gen_q/rsm_libero" || exit 1 +rc=0 +for TASK in "$@"; do + for CK in $(ls -1 $ROOT/runs/$TASK/rsm/DWM/ckpt_s*.pt 2>/dev/null | sort -V); do + step=$(basename "$CK" .pt); step=${step#ckpt_s} + out=$ROOT/runs/$TASK/rsm/DWM/calib_s${step}.json + if [ -s "$out" ]; then echo "[sweep] $TASK s$step already done ($out)"; continue; fi + echo "[sweep] === $TASK ckpt_s$step -> $out" + "$PY" calib_dwm.py --cache "$ROOT/cache/$TASK" --ckpt "$CK" --out "$out" || rc=1 + done +done +echo "[sweep] DONE rc=$rc" +exit $rc diff --git a/rsm_rise/scripts/rr_ckpt_choice_all6.sh b/rsm_rise/scripts/rr_ckpt_choice_all6.sh new file mode 100644 index 0000000000000000000000000000000000000000..125bad62ebeec979e3bf5e1e3b1031f99b64afc9 --- /dev/null +++ b/rsm_rise/scripts/rr_ckpt_choice_all6.sh @@ -0,0 +1,11 @@ +#!/usr/bin/env bash +# Regenerate docs/RSM_CKPT_CHOICE.md over ALL SIX tasks (the existing doc covers only 4; the two +# "floor / no signal" tasks -- mug_expert_suboptimal and square_expert_play -- were never scanned, +# so the orchestrator's "win-rate tracks outcome" table has no row for them). +set -euo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +source scripts/env.sh +mkdir -p runs/_diag +python scripts/pick_rsm_ckpt.py \ + square_expert_suboptimal two_piece_expert_suboptimal two_piece_expert_play \ + threading_expert_play mug_expert_suboptimal square_expert_play diff --git a/rsm_rise/scripts/rr_cpu.sh b/rsm_rise/scripts/rr_cpu.sh new file mode 100644 index 0000000000000000000000000000000000000000..d8b7efb7c4a5bbdd11ad39c9cee55e5d4e18dc0e --- /dev/null +++ b/rsm_rise/scripts/rr_cpu.sh @@ -0,0 +1,9 @@ +#!/usr/bin/env bash +# Generic LSF CPU runner: rr_cpu.sh [args...] (no login-node compute; submit with bsub, no -gpu) +set -euo pipefail +ROOT=/proj/dmfexp/zwhong/rsm_rise +source "$ROOT/wandb_env.sh" || true +export TORCH_HOME=/u/zwhong/.cache/torch XFORMERS_DISABLED=1 CUDA_VISIBLE_DEVICES="" +cd "$ROOT" +echo "[rr_cpu] host=$(hostname) $(date) :: $*" +exec "$ROOT/venv_rsm/bin/python" "$@" diff --git a/rsm_rise/scripts/rr_cpu_basetopup_flag7.sh b/rsm_rise/scripts/rr_cpu_basetopup_flag7.sh new file mode 100644 index 0000000000000000000000000000000000000000..cc8b139319554a95d7c1feaae3c2f2d9c0f3bfb0 --- /dev/null +++ b/rsm_rise/scripts/rr_cpu_basetopup_flag7.sh @@ -0,0 +1,26 @@ +#!/usr/bin/env bash +# BASE_TOPUP run 7: flagship BEFORE/AFTER the critic:dino column + the three arm-key fixes. +set -uo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +source scripts/env.sh >/dev/null 2>&1 +export PYTHONPATH=/proj/dmfexp/zwhong/rsm_rise/scripts:${PYTHONPATH:-} +O=status/basetopup/verdict7 +mkdir -p $O + +# PRE = both builders as they were before this run (sibling import needs them in scripts/ under the +# names the modules import each other by, so the pre pair goes into its own directory). +mkdir -p scripts/_pre7 && cp scripts/*.py scripts/_pre7/ 2>/dev/null +cp scripts/verdict_table.py.bak.20260926_gammaarm scripts/_pre7/verdict_table.py +cp scripts/flagship_latex.py.bak.20260926_criticdino scripts/_pre7/flagship_latex.py + +( export PYTHONPATH=/proj/dmfexp/zwhong/rsm_rise/scripts/_pre7; \ + python3 scripts/_pre7/flagship_latex.py > $O/flag_pre.txt 2> $O/flag_pre.err ); echo "flag pre rc=$?" +python3 scripts/flagship_latex.py > $O/flag_post.txt 2> $O/flag_post.err; echo "flag post rc=$?" +rm -rf scripts/_pre7 + +diff -u $O/flag_pre.txt $O/flag_post.txt > $O/flag.diff; echo "flag diff lines: $(wc -l < $O/flag.diff)" + +echo "=== threading + critic:dino evidence, verdict_table with the pinned proposer epoch admitted ===" +RSM_EXTRA_EPOCHS=500 python3 scripts/verdict_table.py > $O/verdict_e500.txt 2> $O/verdict_e500.err +echo "rc=$? lines=$(wc -l < $O/verdict_e500.txt)" +grep -nE "critic:dino|critic " $O/verdict_e500.txt | head -30 diff --git a/rsm_rise/scripts/rr_cpu_basetopup_run10.sh b/rsm_rise/scripts/rr_cpu_basetopup_run10.sh new file mode 100644 index 0000000000000000000000000000000000000000..9c65b62ad38c23d9e23d8ccf073360ffc9c6c822 --- /dev/null +++ b/rsm_rise/scripts/rr_cpu_basetopup_run10.sh @@ -0,0 +1,53 @@ +#!/usr/bin/env bash +# BASE_TOPUP run 10: rebuild both published tables on the CURRENT disk state and diff against run 8b's +# POST build (the last verified one). Every difference is a cell that landed since 03:2xZ -- so this is +# also the integrity check that the critic-health CONTROL cells (permuted / random) and the epoch-500 +# PREVIEW cells do NOT pool into any published arm (the leak class of bug found in run 8). +set -uo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +source scripts/env.sh >/dev/null 2>&1 +O=status/basetopup/run10 +mkdir -p $O +export PYTHONPATH=/proj/dmfexp/zwhong/rsm_rise/scripts:${PYTHONPATH:-} + +python3 scripts/verdict_table.py > $O/verdict_now.txt 2> $O/verdict_now.err; echo "verdict rc=$?" +python3 scripts/flagship_latex.py > $O/flag_now.txt 2> $O/flag_now.err; echo "flag rc=$?" + +diff -u status/basetopup/run8b/verdict_post.txt $O/verdict_now.txt > $O/verdict.diff +echo "verdict.diff lines: $(wc -l < $O/verdict.diff)" +diff -u status/basetopup/run8b/flag_post.txt $O/flag_now.txt > $O/flag.diff +echo "flag.diff lines: $(wc -l < $O/flag.diff)" + +echo "=== INTEGRITY 1: every critic:dino arm the loader sees (permuted/random must be their OWN arms) ===" +grep -oE "critic:dino[^|]*" $O/verdict_now.txt | sed 's/ *$//' | sort | uniq -c | sort -rn | head -20 + +echo "=== INTEGRITY 2: any arm mentioning permuted / random / CPIX-at-500 ===" +grep -oE "(permuted|random)[^|]*" $O/verdict_now.txt | sort | uniq -c | head -20 + +echo "=== INTEGRITY 3: the IFQL baseline rows (n must stay 450 -- no gamma pooling) ===" +awk -F'|' '/IFQL \(published\)|IFQL critic \/ RISE actor|IFQL policy/{gsub(/^ +| +$/,"",$3);gsub(/^ +| +$/,"",$5);gsub(/^ +| +$/,"",$7); print $3" SR="$5" n="$7}' $O/verdict_now.txt + +echo "=== INTEGRITY 4: gamma arms visible separately ===" +grep -oE "critic:ifql \[[a-z0-9_]+\]" $O/verdict_now.txt | sort | uniq -c + +echo "=== the prelim flagship row block ===" +awk '/^Task & RISE-g/{f=1} f&&/^(Square|Piece|Mug|Thread)/{print} /^\\bottomrule/{if(f)f=0}' $O/flag_now.txt | tail -8 + +echo "=== IFQL gamma census, off the JSONs (252 = complete) ===" +python3 - <<'PY' +import glob, collections +c = collections.Counter() +for f in glob.glob("runs/*/eval_ifql/*.json"): + b = f.split('/')[-1] + for g in ("g0p95","g0p98","g0p995","g0p99"): + if "IFQL"+g.replace("g0p","g0p") in b or g in b: + if g == "g0p99" and "g0p995" in b: continue + c[(f.split('/')[1], g)] += 1 + break +tot = 0 +for task in sorted(set(k[0] for k in c)): + row = {g: c[(task,g)] for g in ("g0p95","g0p98","g0p99","g0p995") if (task,g) in c} + tot += sum(row.values()) + print(f"{task:34s} {row}") +print("total gamma cells:", tot, "/ 252") +PY diff --git a/rsm_rise/scripts/rr_cpu_basetopup_run15.sh b/rsm_rise/scripts/rr_cpu_basetopup_run15.sh new file mode 100644 index 0000000000000000000000000000000000000000..bfd4d6c06dc93459368768f9bbdc8ea23dcd8fbf --- /dev/null +++ b/rsm_rise/scripts/rr_cpu_basetopup_run15.sh @@ -0,0 +1,15 @@ +#!/usr/bin/env bash +# BASE_TOPUP run 15: rebuild verdict + flagship with the first three COMPLETE critic:dino(Dq) rows +# (two_piece_expert_play_tipping, mug_expert_suboptimal, square_expert_play) and diff against run 10's build. +set -uo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +source scripts/env.sh >/dev/null 2>&1 +O=status/basetopup/run15 +mkdir -p $O +export PYTHONPATH=/proj/dmfexp/zwhong/rsm_rise/scripts:${PYTHONPATH:-} +python3 scripts/verdict_table.py > $O/verdict_now.txt 2> $O/verdict_now.err; echo "verdict rc=$?" +python3 scripts/flagship_latex.py > $O/flag_now.txt 2> $O/flag_now.err; echo "flagship rc=$?" +diff -u status/basetopup/run10/verdict_now.txt $O/verdict_now.txt > $O/verdict.diff; echo "verdict diff lines: $(wc -l < $O/verdict.diff)" +diff -u status/basetopup/run10/flag_now.txt $O/flag_now.txt > $O/flag.diff; echo "flag diff lines: $(wc -l < $O/flag.diff)" +echo "=== every critic arm line in the new verdict table ===" +grep -nE "critic" $O/verdict_now.txt | head -80 diff --git a/rsm_rise/scripts/rr_cpu_basetopup_run15b.sh b/rsm_rise/scripts/rr_cpu_basetopup_run15b.sh new file mode 100644 index 0000000000000000000000000000000000000000..d8c2dcfe4c7a70c819fae2d67d23d83e3e35c2ed --- /dev/null +++ b/rsm_rise/scripts/rr_cpu_basetopup_run15b.sh @@ -0,0 +1,16 @@ +#!/usr/bin/env bash +# BASE_TOPUP run 15b: verdict table AFTER the critic:dino top-up rows + the tau arm key. +# PRE is status/basetopup/run15/verdict_now.txt, built by job 1924315 from the code as it was at 08:25Z. +set -uo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +source scripts/env.sh >/dev/null 2>&1 +O=status/basetopup/run15b +mkdir -p $O +export PYTHONPATH=/proj/dmfexp/zwhong/rsm_rise/scripts:${PYTHONPATH:-} +python3 scripts/verdict_table.py > $O/verdict_post.txt 2> $O/verdict_post.err; echo "post rc=$?" +diff -u status/basetopup/run15/verdict_now.txt $O/verdict_post.txt > $O/verdict.diff +echo "diff lines: $(wc -l < $O/verdict.diff)" +echo "=== REMOVED or CHANGED lines (must be ZERO: the change is additive) ===" +grep -E "^-[^-]" $O/verdict.diff | head -20 +echo "=== the new rows ===" +grep -nE "top-up \(not eligible" $O/verdict_post.txt diff --git a/rsm_rise/scripts/rr_cpu_basetopup_run15c.sh b/rsm_rise/scripts/rr_cpu_basetopup_run15c.sh new file mode 100644 index 0000000000000000000000000000000000000000..10d99de9a66bf2a953a14b45d670c4f9724d8e9d --- /dev/null +++ b/rsm_rise/scripts/rr_cpu_basetopup_run15c.sh @@ -0,0 +1,11 @@ +#!/usr/bin/env bash +# BASE_TOPUP run 15c: verify the "critic (planner ctl)" arm split changes NOTHING on disk today. +set -uo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +source scripts/env.sh >/dev/null 2>&1 +O=status/basetopup/run15c; mkdir -p $O +export PYTHONPATH=/proj/dmfexp/zwhong/rsm_rise/scripts:${PYTHONPATH:-} +python3 scripts/verdict_table.py > $O/verdict_post.txt 2> $O/verdict_post.err; echo "post rc=$?" +diff -u status/basetopup/run15b/verdict_post.txt $O/verdict_post.txt > $O/verdict.diff +echo "diff lines (expect only the build stamp): $(wc -l < $O/verdict.diff)" +cat $O/verdict.diff | head -20 diff --git a/rsm_rise/scripts/rr_cpu_basetopup_run16.sh b/rsm_rise/scripts/rr_cpu_basetopup_run16.sh new file mode 100644 index 0000000000000000000000000000000000000000..0b8c0a2585cbc638d0fdd110fa0d2bb543e6b693 --- /dev/null +++ b/rsm_rise/scripts/rr_cpu_basetopup_run16.sh @@ -0,0 +1,18 @@ +#!/usr/bin/env bash +# BASE_TOPUP run 16: rebuild verdict + flagship now that the matched PIXEL control at epoch 5000 +# (CPIX5K, 54 cells) and 5 of 7 complete critic:dino(Dq) rows have landed. Diff against run 15c. +set -uo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +source scripts/env.sh >/dev/null 2>&1 +O=status/basetopup/run16 +mkdir -p $O +export PYTHONPATH=/proj/dmfexp/zwhong/rsm_rise/scripts:${PYTHONPATH:-} +python3 scripts/verdict_table.py > $O/verdict_now.txt 2> $O/verdict_now.err; echo "verdict rc=$?" +python3 scripts/flagship_latex.py > $O/flag_now.txt 2> $O/flag_now.err; echo "flagship rc=$?" +python3 scripts/master_table.py > $O/master_now.txt 2> $O/master_now.err; echo "master rc=$?" +diff -u status/basetopup/run15c/verdict_post.txt $O/verdict_now.txt > $O/verdict.diff; echo "verdict diff lines: $(wc -l < $O/verdict.diff)" +diff -u status/basetopup/run15/flag_now.txt $O/flag_now.txt > $O/flag.diff; echo "flag diff lines: $(wc -l < $O/flag.diff)" +echo "=== every critic arm line in the new verdict table ===" +grep -nE "critic" $O/verdict_now.txt | head -100 +echo "=== verdict diff ===" +head -120 $O/verdict.diff diff --git a/rsm_rise/scripts/rr_cpu_basetopup_run16b.sh b/rsm_rise/scripts/rr_cpu_basetopup_run16b.sh new file mode 100644 index 0000000000000000000000000000000000000000..f16e6f7b09540a8402cd7fdeef183251e6d5bfe6 --- /dev/null +++ b/rsm_rise/scripts/rr_cpu_basetopup_run16b.sh @@ -0,0 +1,24 @@ +#!/usr/bin/env bash +# BASE_TOPUP run 16b: PRE/POST diff for the run-16 fix that stops an IQL critic's own destroyed-score +# controls (plan_rule random/permuted/first/argmin) from pooling into the critic ARM. The PRE build uses +# the pre-patch loader from the backup, so the diff isolates exactly this change. flagship_latex imports +# verdict_table by NAME, so the PRE flagship needs the PRE loader installed under that name. +set -uo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +source scripts/env.sh >/dev/null 2>&1 +O=status/basetopup/run16b; mkdir -p $O +T=$(mktemp -d /tmp/zwhong/vtpre.XXXXXX) +cp scripts/verdict_table.py.bak.20260926_r16_iqlctlorder $T/verdict_table.py +for f in scripts/*.py; do b=$(basename $f); [ "$b" = verdict_table.py ] || cp $f $T/$b; done +PYTHONPATH=$T python3 $T/verdict_table.py > $O/verdict_pre.txt 2> $O/verdict_pre.err; echo "pre verdict rc=$?" +PYTHONPATH=$T python3 $T/flagship_latex.py > $O/flag_pre.txt 2> $O/flag_pre.err; echo "pre flag rc=$?" +export PYTHONPATH=/proj/dmfexp/zwhong/rsm_rise/scripts:${PYTHONPATH:-} +python3 scripts/verdict_table.py > $O/verdict_post.txt > $O/verdict_post.txt 2> $O/verdict_post.err; echo "post verdict rc=$?" +python3 scripts/flagship_latex.py > $O/flag_post.txt 2> $O/flag_post.err; echo "post flag rc=$?" +diff -u $O/verdict_pre.txt $O/verdict_post.txt > $O/verdict.diff; echo "verdict diff lines: $(wc -l < $O/verdict.diff)" +diff -u $O/flag_pre.txt $O/flag_post.txt > $O/flag.diff; echo "flag diff lines: $(wc -l < $O/flag.diff)" +echo "=== which arms moved (verdict) ===" +grep -E "^[-+]\|" $O/verdict.diff | grep -vE "^\+\+\+|^---" | head -60 +echo "=== flagship diff ===" +head -60 $O/flag.diff +rm -rf $T diff --git a/rsm_rise/scripts/rr_cpu_basetopup_run16c.sh b/rsm_rise/scripts/rr_cpu_basetopup_run16c.sh new file mode 100644 index 0000000000000000000000000000000000000000..ddd36478e7d288cbd66bd77810bbf94de40aaf15 --- /dev/null +++ b/rsm_rise/scripts/rr_cpu_basetopup_run16c.sh @@ -0,0 +1,18 @@ +#!/usr/bin/env bash +# BASE_TOPUP run 16c: all 7 critic:dino(Dq) rows and all 7 matched CPIX5K pixel-control rows are now +# 9/9. Rebuild and diff against run 16b's POST (same loader), so the diff is purely the 8 new cells. +set -uo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +source scripts/env.sh >/dev/null 2>&1 +O=status/basetopup/run16c; mkdir -p $O +export PYTHONPATH=/proj/dmfexp/zwhong/rsm_rise/scripts:${PYTHONPATH:-} +python3 scripts/verdict_table.py > $O/verdict_now.txt 2> $O/verdict_now.err; echo "verdict rc=$?" +python3 scripts/flagship_latex.py > $O/flag_now.txt 2> $O/flag_now.err; echo "flagship rc=$?" +diff -u status/basetopup/run16b/verdict_post.txt $O/verdict_now.txt > $O/verdict.diff; echo "verdict diff lines: $(wc -l < $O/verdict.diff)" +diff -u status/basetopup/run16b/flag_post.txt $O/flag_now.txt > $O/flag.diff; echo "flag diff lines: $(wc -l < $O/flag.diff)" +echo "=== critic:dino rows ===" +grep -E "critic:dino" $O/verdict_now.txt | sed 's/|/ | /g' | cut -c1-200 +echo "=== verdict lines that moved ===" +grep -E "^[-+]\|" $O/verdict.diff | cut -c1-230 +echo "=== flagship lines that moved ===" +grep -E "^[-+]" $O/flag.diff | grep -vE "^\+\+\+|^---" | cut -c1-240 | head -20 diff --git a/rsm_rise/scripts/rr_cpu_basetopup_run16d.sh b/rsm_rise/scripts/rr_cpu_basetopup_run16d.sh new file mode 100644 index 0000000000000000000000000000000000000000..cab3f417e735c09a29f50700365b16783ce09696 --- /dev/null +++ b/rsm_rise/scripts/rr_cpu_basetopup_run16d.sh @@ -0,0 +1,22 @@ +#!/usr/bin/env bash +# BASE_TOPUP run 16d: PRE/POST for the throughput.py fix -- the critic's representation/discount/ +# expectile now enters the throughput arm key, plus the critic-epoch and plan-rule guards the loop was +# missing. PRE = the pre-patch throughput module imported under its own name from a temp dir. +set -uo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +source scripts/env.sh >/dev/null 2>&1 +O=status/basetopup/run16d; mkdir -p $O +T=$(mktemp -d /tmp/zwhong/thrpre.XXXXXX) +cp scripts/throughput.py.bak.20260926_r16_criticrep $T/throughput.py +for f in scripts/*.py; do b=$(basename $f); [ "$b" = throughput.py ] || cp $f $T/$b; done +PYTHONPATH=$T python3 $T/flagship_latex.py > $O/flag_pre.txt 2> $O/flag_pre.err; echo "pre rc=$?" +export PYTHONPATH=/proj/dmfexp/zwhong/rsm_rise/scripts:${PYTHONPATH:-} +python3 scripts/flagship_latex.py > $O/flag_post.txt 2> $O/flag_post.err; echo "post rc=$?" +diff -u $O/flag_pre.txt $O/flag_post.txt > $O/flag.diff; echo "flag diff lines: $(wc -l < $O/flag.diff)" +echo "=== throughput rows PRE vs POST ===" +grep -E "^[-+](Square|Piece|Mug|Thread)" $O/flag.diff | cut -c1-230 +echo "=== any other moved line ===" +grep -E "^[-+]" $O/flag.diff | grep -vE "^\+\+\+|^---" | grep -vE "^[-+](Square|Piece|Mug|Thread)" | cut -c1-200 | head -20 +echo "=== throughput.py alone, per task ===" +python3 scripts/throughput.py --flagship 2> $O/thr.err | head -60 +rm -rf $T diff --git a/rsm_rise/scripts/rr_cpu_basetopup_run16e.sh b/rsm_rise/scripts/rr_cpu_basetopup_run16e.sh new file mode 100644 index 0000000000000000000000000000000000000000..8ec0ddfb47aa531a92ef95cbf385b51bdc8f95e4 --- /dev/null +++ b/rsm_rise/scripts/rr_cpu_basetopup_run16e.sh @@ -0,0 +1,25 @@ +#!/usr/bin/env bash +# BASE_TOPUP run 16e: WHY did the throughput fix move nothing? Print, for the row whose RISE throughput +# moved in run 16c (two_piece_expert_suboptimal), which cell files land in ("critic N=128","RISE policy") +# under the PRE and the POST throughput loader, with episode counts. +set -uo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +source scripts/env.sh >/dev/null 2>&1 +O=status/basetopup/run16e; mkdir -p $O +T=$(mktemp -d /tmp/zwhong/thrpre.XXXXXX) +cp scripts/throughput.py.bak.20260926_r16_criticrep $T/throughput.py +for f in scripts/*.py; do b=$(basename $f); [ "$b" = throughput.py ] || cp $f $T/$b; done +cat > $O/probe.py <<'PY' +import sys, collections +task = "two_piece_expert_suboptimal" +import throughput as T +out, horiz = T.collect(task) +print("module:", T.__file__) +for k in sorted(out, key=lambda k: -len(out[k]))[:14]: + print(f" n={len(out[k]):5d} {k}") +key = ("critic N=128", "RISE policy") +print("TARGET", key, "->", len(out.get(key, [])), "episodes") +PY +echo "=== PRE ==="; PYTHONPATH=$T python3 $O/probe.py +echo "=== POST ==="; PYTHONPATH=/proj/dmfexp/zwhong/rsm_rise/scripts python3 $O/probe.py +rm -rf $T diff --git a/rsm_rise/scripts/rr_cpu_basetopup_run16f.sh b/rsm_rise/scripts/rr_cpu_basetopup_run16f.sh new file mode 100644 index 0000000000000000000000000000000000000000..a9d8b791c9186e43e2fe9ee14353bff8acb6e875 --- /dev/null +++ b/rsm_rise/scripts/rr_cpu_basetopup_run16f.sh @@ -0,0 +1,39 @@ +#!/usr/bin/env bash +# BASE_TOPUP run 16f: REDO the PRE/POST for the throughput.py fix with a harness that actually works. +# +# Run 16d's PRE build was INVALID and this is why: `flagship_latex` imports `master_table`, and +# `master_table.py:5` does sys.path.insert(0, "/proj/dmfexp/zwhong/rsm_rise/scripts") -- an ABSOLUTE +# path. So a PRE build that puts a patched copy of the tree in a temp dir loses the race the moment +# master_table is imported, and every LATER `from throughput import ...` silently loads the REAL, +# post-patch module. That is exactly the run-8 lesson (a copy-the-tree harness is not sound; import the +# backup under its OWN private name and monkeypatch the symbol), which run 16d failed to follow. +# +# Here PRE = the real module tree with `throughput.collect` / `throughput.collect_by_seed` replaced by +# the pre-patch backup's functions, loaded from the .bak file under the private name `_thr_pre`. +set -uo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +source scripts/env.sh >/dev/null 2>&1 +O=status/basetopup/run16f; mkdir -p $O +export PYTHONPATH=/proj/dmfexp/zwhong/rsm_rise/scripts:${PYTHONPATH:-} +# spec_from_file_location cannot infer a loader for a path that does not end in .py, so the backup is +# copied to a .py name FIRST (run 16f's first attempt died on exactly this: AttributeError NoneType.loader). +cp scripts/throughput.py.bak.20260926_r16_criticrep $O/_thr_pre.py +cat > $O/pre_build.py <<'PY' +import importlib.util, sys, runpy +spec = importlib.util.spec_from_file_location( + "_thr_pre", "/proj/dmfexp/zwhong/rsm_rise/status/basetopup/run16f/_thr_pre.py") +pre = importlib.util.module_from_spec(spec); sys.modules["_thr_pre"] = pre +spec.loader.exec_module(pre) +import throughput +throughput.collect = pre.collect +throughput.collect_by_seed = pre.collect_by_seed +print("[pre] throughput.collect <- pre-patch", file=sys.stderr) +sys.argv = ["flagship_latex.py"] +runpy.run_path("/proj/dmfexp/zwhong/rsm_rise/scripts/flagship_latex.py", run_name="__main__") +PY +python3 $O/pre_build.py > $O/flag_pre.txt 2> $O/flag_pre.err; echo "pre rc=$?" +python3 scripts/flagship_latex.py > $O/flag_post.txt 2> $O/flag_post.err; echo "post rc=$?" +grep -c "throughput.collect <- pre-patch" $O/flag_pre.err || true +diff -u $O/flag_pre.txt $O/flag_post.txt > $O/flag.diff; echo "flag diff lines: $(wc -l < $O/flag.diff)" +echo "=== every moved line ===" +grep -E "^[-+]" $O/flag.diff | grep -vE "^\+\+\+|^---" | cut -c1-235 diff --git a/rsm_rise/scripts/rr_cpu_basetopup_run17.sh b/rsm_rise/scripts/rr_cpu_basetopup_run17.sh new file mode 100644 index 0000000000000000000000000000000000000000..23731a7d16cbd0f46f9ceab8d5eeec5fdb5f0226 --- /dev/null +++ b/rsm_rise/scripts/rr_cpu_basetopup_run17.sh @@ -0,0 +1,41 @@ +#!/usr/bin/env bash +# BASE_TOPUP run 17: rebuild with the run-16 fixes LANDED (verdict_table iql-control order, +# throughput critic arm key) and with threading's gamma/tau eval cells arriving. Purpose: +# (a) confirm nothing except the new cells moves against run 16c's POST build, +# (b) print every critic arm per task with its n, so the gamma/tau/health arms can be read +# without hand-rolling a loader, +# (c) print threading's critic-health triplet (argmax / permuted / random) as the builder pools it. +set -uo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +source scripts/env.sh >/dev/null 2>&1 +O=status/basetopup/run17; mkdir -p $O +export PYTHONPATH=/proj/dmfexp/zwhong/rsm_rise/scripts:${PYTHONPATH:-} +python3 scripts/verdict_table.py > $O/verdict_now.txt 2> $O/verdict_now.err; echo "verdict rc=$?" +python3 scripts/flagship_latex.py > $O/flag_now.txt 2> $O/flag_now.err; echo "flagship rc=$?" +diff -u status/basetopup/run16c/verdict_now.txt $O/verdict_now.txt > $O/verdict.diff 2>/dev/null; echo "verdict diff lines: $(wc -l < $O/verdict.diff)" +diff -u status/basetopup/run16c/flag_now.txt $O/flag_now.txt > $O/flag.diff 2>/dev/null; echo "flag diff lines: $(wc -l < $O/flag.diff)" +echo "=== every critic arm, per task, with n (from the loader: cells() + the arm key) ===" +python3 - > $O/critic_arms.txt 2>&1 <<'PY' +import collections, verdict_table as vt +# cells(task) -> {(arm, proposer, policy_seed, eval_seed): [per-episode 0/1, ...]} +for task, nice in vt.TASKS: + c = vt.cells(task) + agg = collections.defaultdict(lambda: [0, 0, 0]) # n_eps, n_succ, n_cells + for (arm, p, ps, es), v in c.items(): + k = (arm, p) + agg[k][0] += len(v); agg[k][1] += sum(v); agg[k][2] += 1 + sel = {k: a for k, a in agg.items() if "critic" in str(k).lower()} + if not sel: + continue + print("###", task, "|", nice) + for k in sorted(sel, key=lambda k: str(k)): + n, sc, nc = sel[k] + print(f" {str(k):78s} cells={nc:3d} n={n:5d} rate={100.0*sc/max(n,1):5.1f}") +PY +head -80 $O/critic_arms.txt +echo "=== critic arms in the verdict table ===" +grep -E "critic" $O/verdict_now.txt | sed 's/|/ | /g' | cut -c1-210 +echo "=== verdict lines that moved vs run16c ===" +grep -E "^[-+]" $O/verdict.diff | grep -vE "^\+\+\+|^---" | cut -c1-230 | head -60 +echo "=== flagship lines that moved vs run16c ===" +grep -E "^[-+]" $O/flag.diff | grep -vE "^\+\+\+|^---" | cut -c1-240 | head -40 diff --git a/rsm_rise/scripts/rr_cpu_basetopup_run18.sh b/rsm_rise/scripts/rr_cpu_basetopup_run18.sh new file mode 100644 index 0000000000000000000000000000000000000000..ec7f7116edb5ea4cd7faa4b50abaf41fcbcde68a --- /dev/null +++ b/rsm_rise/scripts/rr_cpu_basetopup_run18.sh @@ -0,0 +1,65 @@ +#!/usr/bin/env bash +# BASE_TOPUP run 18: rebuild as the 216 critic-health control cells land, and print the +# CRITIC-HEALTH TRIPLET (argmax / permuted / random) for every critic family x task from the +# builder's own loader -- the deliverable-1 "critic-health number", which until run 17 existed +# on one row only. Diffed against run 17's POST build so only the new cells may move a line. +set -uo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +source scripts/env.sh >/dev/null 2>&1 +O=status/basetopup/run18; mkdir -p $O +export PYTHONPATH=/proj/dmfexp/zwhong/rsm_rise/scripts:${PYTHONPATH:-} +python3 scripts/verdict_table.py > $O/verdict_now.txt 2> $O/verdict_now.err; echo "verdict rc=$?" +python3 scripts/flagship_latex.py > $O/flag_now.txt 2> $O/flag_now.err; echo "flagship rc=$?" +diff -u status/basetopup/run17/verdict_now.txt $O/verdict_now.txt > $O/verdict.diff 2>/dev/null; echo "verdict diff lines: $(wc -l < $O/verdict.diff)" +diff -u status/basetopup/run17/flag_now.txt $O/flag_now.txt > $O/flag.diff 2>/dev/null; echo "flag diff lines: $(wc -l < $O/flag.diff)" +python3 - > $O/critic_arms.txt 2>&1 <<'PY' +import collections, verdict_table as vt +for task, nice in vt.TASKS: + agg = collections.defaultdict(lambda: [0, 0, 0]) + for (arm, p, ps, es), v in vt.cells(task).items(): + agg[(arm, p)][0] += len(v); agg[(arm, p)][1] += sum(v); agg[(arm, p)][2] += 1 + sel = {k: a for k, a in agg.items() if "critic" in str(k).lower()} + if not sel: continue + print("###", task, "|", nice) + for k in sorted(sel, key=lambda k: str(k)): + n, sc, nc = sel[k] + print(f" {str(k):78s} cells={nc:3d} n={n:5d} rate={100.0*sc/max(n,1):5.1f}") +PY +# CRITIC HEALTH: argmax vs its OWN permuted/random control, same proposer, from the same loader. +python3 - > $O/critic_health.txt 2>&1 <<'PY' +import collections, math, verdict_table as vt +print("critic-health triplet: argmax vs its own controls on the SAME 128 candidates, same proposer") +print(f"{'task':30s} {'critic':26s} {'proposer':26s} {'argmax':>13s} {'permuted':>13s} {'random':>13s} {'argmax-random':>15s}") +def se(n, k): + p = k / n if n else 0.0 + return 100 * math.sqrt(max(p * (1 - p), 0) / n) if n else 0.0 +for task, nice in vt.TASKS: + agg = collections.defaultdict(lambda: [0, 0]) + for (arm, p, ps, es), v in vt.cells(task).items(): + agg[(arm, p)][0] += len(v); agg[(arm, p)][1] += sum(v) + # argmax arms are ('', 'N=128'); their controls are ('random'|'permuted', '') + for (arm, prop), (n, k) in sorted(agg.items(), key=str): + if not (isinstance(arm, tuple) and arm[1] == "N=128" and "critic" in str(arm[0])): continue + row = [f"{100*k/max(n,1):6.1f}+-{se(n,k):4.1f}"] + got = False + for ctl in ("permuted", "random"): + c = agg.get((ctl, arm[0]), None) + # the control is keyed on the critic label, and must be on the SAME proposer + c2 = None + for (a2, p2), v2 in agg.items(): + if a2 == (ctl, arm[0]) and p2 == prop: c2 = v2 + if c2: row.append(f"{100*c2[1]/max(c2[0],1):6.1f}+-{se(*c2):4.1f}"); got = True + else: row.append(f"{'--':>13s}") + d = "" + for (a2, p2), v2 in agg.items(): + if a2 == ("random", arm[0]) and p2 == prop: + dd = 100*k/max(n,1) - 100*v2[1]/max(v2[0],1) + d = f"{dd:+6.1f} +- {math.sqrt(se(n,k)**2 + se(*v2)**2):4.1f}" + if not got: continue + print(f"{task:30s} {str(arm[0]):26s} {str(prop):26s} {row[0]:>13s} {row[1]:>13s} {row[2]:>13s} {d:>15s}") +PY +cat $O/critic_health.txt +echo "=== verdict lines that moved vs run17 ===" +grep -E "^[-+]" $O/verdict.diff | grep -vE "^\+\+\+|^---" | cut -c1-230 | head -60 +echo "=== flagship lines that moved vs run17 ===" +grep -E "^[-+]" $O/flag.diff | grep -vE "^\+\+\+|^---" | cut -c1-240 | head -40 diff --git a/rsm_rise/scripts/rr_cpu_basetopup_run19.sh b/rsm_rise/scripts/rr_cpu_basetopup_run19.sh new file mode 100644 index 0000000000000000000000000000000000000000..494f7369ee6ef71b51cca9b576256f2eb3737f18 --- /dev/null +++ b/rsm_rise/scripts/rr_cpu_basetopup_run19.sh @@ -0,0 +1,65 @@ +#!/usr/bin/env bash +# BASE_TOPUP run 18: rebuild as the 216 critic-health control cells land, and print the +# CRITIC-HEALTH TRIPLET (argmax / permuted / random) for every critic family x task from the +# builder's own loader -- the deliverable-1 "critic-health number", which until run 17 existed +# on one row only. Diffed against run 17's POST build so only the new cells may move a line. +set -uo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +source scripts/env.sh >/dev/null 2>&1 +O=status/basetopup/run19; mkdir -p $O +export PYTHONPATH=/proj/dmfexp/zwhong/rsm_rise/scripts:${PYTHONPATH:-} +python3 scripts/verdict_table.py > $O/verdict_now.txt 2> $O/verdict_now.err; echo "verdict rc=$?" +python3 scripts/flagship_latex.py > $O/flag_now.txt 2> $O/flag_now.err; echo "flagship rc=$?" +diff -u status/basetopup/run18/verdict_now.txt $O/verdict_now.txt > $O/verdict.diff 2>/dev/null; echo "verdict diff lines: $(wc -l < $O/verdict.diff)" +diff -u status/basetopup/run18/flag_now.txt $O/flag_now.txt > $O/flag.diff 2>/dev/null; echo "flag diff lines: $(wc -l < $O/flag.diff)" +python3 - > $O/critic_arms.txt 2>&1 <<'PY' +import collections, verdict_table as vt +for task, nice in vt.TASKS: + agg = collections.defaultdict(lambda: [0, 0, 0]) + for (arm, p, ps, es), v in vt.cells(task).items(): + agg[(arm, p)][0] += len(v); agg[(arm, p)][1] += sum(v); agg[(arm, p)][2] += 1 + sel = {k: a for k, a in agg.items() if "critic" in str(k).lower()} + if not sel: continue + print("###", task, "|", nice) + for k in sorted(sel, key=lambda k: str(k)): + n, sc, nc = sel[k] + print(f" {str(k):78s} cells={nc:3d} n={n:5d} rate={100.0*sc/max(n,1):5.1f}") +PY +# CRITIC HEALTH: argmax vs its OWN permuted/random control, same proposer, from the same loader. +python3 - > $O/critic_health.txt 2>&1 <<'PY' +import collections, math, verdict_table as vt +print("critic-health triplet: argmax vs its own controls on the SAME 128 candidates, same proposer") +print(f"{'task':30s} {'critic':26s} {'proposer':26s} {'argmax':>13s} {'permuted':>13s} {'random':>13s} {'argmax-random':>15s}") +def se(n, k): + p = k / n if n else 0.0 + return 100 * math.sqrt(max(p * (1 - p), 0) / n) if n else 0.0 +for task, nice in vt.TASKS: + agg = collections.defaultdict(lambda: [0, 0]) + for (arm, p, ps, es), v in vt.cells(task).items(): + agg[(arm, p)][0] += len(v); agg[(arm, p)][1] += sum(v) + # argmax arms are ('', 'N=128'); their controls are ('random'|'permuted', '') + for (arm, prop), (n, k) in sorted(agg.items(), key=str): + if not (isinstance(arm, tuple) and arm[1] == "N=128" and "critic" in str(arm[0])): continue + row = [f"{100*k/max(n,1):6.1f}+-{se(n,k):4.1f}"] + got = False + for ctl in ("permuted", "random"): + c = agg.get((ctl, arm[0]), None) + # the control is keyed on the critic label, and must be on the SAME proposer + c2 = None + for (a2, p2), v2 in agg.items(): + if a2 == (ctl, arm[0]) and p2 == prop: c2 = v2 + if c2: row.append(f"{100*c2[1]/max(c2[0],1):6.1f}+-{se(*c2):4.1f}"); got = True + else: row.append(f"{'--':>13s}") + d = "" + for (a2, p2), v2 in agg.items(): + if a2 == ("random", arm[0]) and p2 == prop: + dd = 100*k/max(n,1) - 100*v2[1]/max(v2[0],1) + d = f"{dd:+6.1f} +- {math.sqrt(se(n,k)**2 + se(*v2)**2):4.1f}" + if not got: continue + print(f"{task:30s} {str(arm[0]):26s} {str(prop):26s} {row[0]:>13s} {row[1]:>13s} {row[2]:>13s} {d:>15s}") +PY +cat $O/critic_health.txt +echo "=== verdict lines that moved vs run17 ===" +grep -E "^[-+]" $O/verdict.diff | grep -vE "^\+\+\+|^---" | cut -c1-230 | head -60 +echo "=== flagship lines that moved vs run17 ===" +grep -E "^[-+]" $O/flag.diff | grep -vE "^\+\+\+|^---" | cut -c1-240 | head -40 diff --git a/rsm_rise/scripts/rr_cpu_basetopup_run20.sh b/rsm_rise/scripts/rr_cpu_basetopup_run20.sh new file mode 100644 index 0000000000000000000000000000000000000000..20217a068cb535788e429bb7410433b0ec8ef652 --- /dev/null +++ b/rsm_rise/scripts/rr_cpu_basetopup_run20.sh @@ -0,0 +1,95 @@ +#!/usr/bin/env bash +# BASE_TOPUP run 20: rebuild after the N=4 wave and the 9/9 health arms; print the N-SWEEP curve +# CRITIC-HEALTH TRIPLET (argmax / permuted / random) for every critic family x task from the +# builder's own loader -- the deliverable-1 "critic-health number", which until run 17 existed +# on one row only. Diffed against run 17's POST build so only the new cells may move a line. +set -uo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +source scripts/env.sh >/dev/null 2>&1 +O=status/basetopup/run20; mkdir -p $O +export PYTHONPATH=/proj/dmfexp/zwhong/rsm_rise/scripts:${PYTHONPATH:-} +python3 scripts/verdict_table.py > $O/verdict_now.txt 2> $O/verdict_now.err; echo "verdict rc=$?" +python3 scripts/flagship_latex.py > $O/flag_now.txt 2> $O/flag_now.err; echo "flagship rc=$?" +diff -u status/basetopup/run19/verdict_now.txt $O/verdict_now.txt > $O/verdict.diff 2>/dev/null; echo "verdict diff lines: $(wc -l < $O/verdict.diff)" +diff -u status/basetopup/run19/flag_now.txt $O/flag_now.txt > $O/flag.diff 2>/dev/null; echo "flag diff lines: $(wc -l < $O/flag.diff)" +python3 - > $O/critic_arms.txt 2>&1 <<'PY' +import collections, verdict_table as vt +for task, nice in vt.TASKS: + agg = collections.defaultdict(lambda: [0, 0, 0]) + for (arm, p, ps, es), v in vt.cells(task).items(): + agg[(arm, p)][0] += len(v); agg[(arm, p)][1] += sum(v); agg[(arm, p)][2] += 1 + sel = {k: a for k, a in agg.items() if "critic" in str(k).lower()} + if not sel: continue + print("###", task, "|", nice) + for k in sorted(sel, key=lambda k: str(k)): + n, sc, nc = sel[k] + print(f" {str(k):78s} cells={nc:3d} n={n:5d} rate={100.0*sc/max(n,1):5.1f}") +PY +# CRITIC HEALTH: argmax vs its OWN permuted/random control, same proposer, from the same loader. +python3 - > $O/critic_health.txt 2>&1 <<'PY' +import collections, math, verdict_table as vt +print("critic-health triplet: argmax vs its own controls on the SAME 128 candidates, same proposer") +print(f"{'task':30s} {'critic':26s} {'proposer':26s} {'argmax':>13s} {'permuted':>13s} {'random':>13s} {'argmax-random':>15s}") +def se(n, k): + p = k / n if n else 0.0 + return 100 * math.sqrt(max(p * (1 - p), 0) / n) if n else 0.0 +for task, nice in vt.TASKS: + agg = collections.defaultdict(lambda: [0, 0]) + for (arm, p, ps, es), v in vt.cells(task).items(): + agg[(arm, p)][0] += len(v); agg[(arm, p)][1] += sum(v) + # argmax arms are ('', 'N=128'); their controls are ('random'|'permuted', '') + for (arm, prop), (n, k) in sorted(agg.items(), key=str): + if not (isinstance(arm, tuple) and arm[1] == "N=128" and "critic" in str(arm[0])): continue + row = [f"{100*k/max(n,1):6.1f}+-{se(n,k):4.1f}"] + got = False + for ctl in ("permuted", "random"): + c = agg.get((ctl, arm[0]), None) + # the control is keyed on the critic label, and must be on the SAME proposer + c2 = None + for (a2, p2), v2 in agg.items(): + if a2 == (ctl, arm[0]) and p2 == prop: c2 = v2 + if c2: row.append(f"{100*c2[1]/max(c2[0],1):6.1f}+-{se(*c2):4.1f}"); got = True + else: row.append(f"{'--':>13s}") + d = "" + for (a2, p2), v2 in agg.items(): + if a2 == ("random", arm[0]) and p2 == prop: + dd = 100*k/max(n,1) - 100*v2[1]/max(v2[0],1) + d = f"{dd:+6.1f} +- {math.sqrt(se(n,k)**2 + se(*v2)**2):4.1f}" + if not got: continue + print(f"{task:30s} {str(arm[0]):26s} {str(prop):26s} {row[0]:>13s} {row[1]:>13s} {row[2]:>13s} {d:>15s}") +PY +cat $O/critic_health.txt +echo "=== verdict lines that moved vs run19 ===" +grep -E "^[-+]" $O/verdict.diff | grep -vE "^\+\+\+|^---" | cut -c1-230 | head -60 +echo "=== flagship lines that moved vs run19 ===" +grep -E "^[-+]" $O/flag.diff | grep -vE "^\+\+\+|^---" | cut -c1-240 | head -40 +# N-SWEEP (run 20): the pre-registered mechanism test, read from the builder's loader, not by hand. +# Under TAIL SELECTION success must fall monotonically in N with random@128 as the N=1 reference. +python3 - > $O/nsweep.txt 2>&1 <<'PY' +import collections, math, verdict_table as vt +def se(n,k): + p=k/n if n else 0.0 + return 100*math.sqrt(max(p*(1-p),0)/n) if n else 0.0 +print("N-SWEEP: same proposer, same critic ckpt, only plan_n differs. N=1 reference = random@128.") +print(f"{'task':32s} {'critic':22s} {'N=1(rand)':>12s} {'N=4':>12s} {'N=16':>12s} {'N=128':>12s} monotone?") +for task,nice in vt.TASKS: + agg=collections.defaultdict(lambda:[0,0]) + for (arm,p,ps,es),v in vt.cells(task).items(): + agg[(arm,p)][0]+=len(v); agg[(arm,p)][1]+=sum(v) + crits=sorted({arm[0] for (arm,p) in agg if isinstance(arm,tuple) and "critic" in str(arm[0])},key=str) + for c in crits: + cols={} + for (arm,p),(n,k) in agg.items(): + if not isinstance(arm,tuple) or arm[0]!=c: continue + cols[str(arm[1])]=(n,k) + rnd=None + for (arm,p),(n,k) in agg.items(): + if arm==("random",c): rnd=(n,k) + if not rnd or not any(x in cols for x in ("N=4","N=16")): continue + def f(x): return f"{100*x[1]/max(x[0],1):6.1f}+-{se(*x):4.1f}" if x else f"{'--':>12s}" + seq=[rnd,cols.get("N=4"),cols.get("N=16"),cols.get("N=128")] + vals=[100*x[1]/max(x[0],1) for x in seq if x] + mono="YES" if all(a>=b for a,b in zip(vals,vals[1:])) else "no" + print(f"{task:32s} {str(c):22s} "+" ".join(f(x) for x in seq)+f" {mono}") +PY +cat $O/nsweep.txt diff --git a/rsm_rise/scripts/rr_cpu_basetopup_run20b.sh b/rsm_rise/scripts/rr_cpu_basetopup_run20b.sh new file mode 100644 index 0000000000000000000000000000000000000000..8096cdef454aaf571073aa28b268194486301836 --- /dev/null +++ b/rsm_rise/scripts/rr_cpu_basetopup_run20b.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# BASE_TOPUP run 20b: PRE/POST for the top-up-row N-pooling fix (verdict_table.py dino_base). +# The N-sweep diagnostic cells were pooling into the deliverable-1 `critic:dino(Dq)` top-up row. +# The fix must move ONLY those top-up rows and nothing else -- prove it against run20's own build. +set -uo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +source scripts/env.sh >/dev/null 2>&1 +O=status/basetopup/run20b; mkdir -p $O +export PYTHONPATH=/proj/dmfexp/zwhong/rsm_rise/scripts:${PYTHONPATH:-} +python3 scripts/verdict_table.py > $O/verdict_post.txt 2> $O/verdict_post.err; echo "verdict rc=$?" +python3 scripts/flagship_latex.py > $O/flag_post.txt 2> $O/flag_post.err; echo "flagship rc=$?" +diff -u status/basetopup/run20/verdict_now.txt $O/verdict_post.txt > $O/verdict.diff 2>/dev/null +diff -u status/basetopup/run20/flag_now.txt $O/flag_post.txt > $O/flag.diff 2>/dev/null +echo "=== VERDICT diff (must be top-up rows + build stamp ONLY) ===" +grep -E "^[-+]" $O/verdict.diff | grep -vE "^\+\+\+|^---" | cut -c1-200 +echo "=== FLAGSHIP diff (must be build stamp ONLY) ===" +grep -E "^[-+]" $O/flag.diff | grep -vE "^\+\+\+|^---" | cut -c1-200 +echo "=== non-top-up, non-stamp verdict lines that moved (MUST BE EMPTY) ===" +grep -E "^[-+]" $O/verdict.diff | grep -vE "^\+\+\+|^---" | grep -v "top-up" | grep -v "_built " +echo "=== end ===" diff --git a/rsm_rise/scripts/rr_cpu_basetopup_run21.sh b/rsm_rise/scripts/rr_cpu_basetopup_run21.sh new file mode 100644 index 0000000000000000000000000000000000000000..8f6781d043e01e7f6e836653fecb19b3132ecf1f --- /dev/null +++ b/rsm_rise/scripts/rr_cpu_basetopup_run21.sh @@ -0,0 +1,88 @@ +#!/usr/bin/env bash +# BASE_TOPUP run 21: rebuild after the N=4 wave + the 9/9 N=16 and threading-gamma arms. +# Prints (a) the 4-POINT N curve (N=1/4/16/128) from the builder's loader, (b) an ARM[0]-CONSUMER +# AUDIT -- run 20 found the third pooling defect of one shape (a consumer keyed on arm[0] alone, +# ignoring arm[1]); this enumerates, from the DATA, every distinct arm[1] each such predicate would +# swallow, so the question "does this pool?" is answered by measurement and not by reading code. +set -uo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +source scripts/env.sh >/dev/null 2>&1 +O=status/basetopup/run21; mkdir -p $O +export PYTHONPATH=/proj/dmfexp/zwhong/rsm_rise/scripts:${PYTHONPATH:-} +python3 scripts/verdict_table.py > $O/verdict_now.txt 2> $O/verdict_now.err; echo "verdict rc=$?" +python3 scripts/flagship_latex.py > $O/flag_now.txt 2> $O/flag_now.err; echo "flagship rc=$?" +diff -u status/basetopup/run20b/verdict_post.txt $O/verdict_now.txt > $O/verdict.diff 2>/dev/null; echo "verdict diff lines: $(wc -l < $O/verdict.diff)" +diff -u status/basetopup/run20b/flag_post.txt $O/flag_now.txt > $O/flag.diff 2>/dev/null; echo "flag diff lines: $(wc -l < $O/flag.diff)" + +# ---- (a) the 4-point N curve ------------------------------------------------------------------- +python3 - > $O/nsweep.txt 2>&1 <<'PY' +import collections, math, verdict_table as vt +def se(n,k): + p=k/n if n else 0.0 + return 100*math.sqrt(max(p*(1-p),0)/n) if n else 0.0 +print("N-SWEEP (4 points): same proposer, same critic ckpt, only plan_n differs. N=1 ref = random@128.") +print(f"{'task':32s} {'critic':22s} {'N=1(rand)':>13s} {'N=4':>13s} {'N=16':>13s} {'N=128':>13s} mono? cells(4/16)") +for task,nice in vt.TASKS: + agg=collections.defaultdict(lambda:[0,0,0]) + for (arm,p,ps,es),v in vt.cells(task).items(): + a=agg[(arm,p)]; a[0]+=len(v); a[1]+=sum(v); a[2]+=1 + crits=sorted({arm[0] for (arm,p) in agg if isinstance(arm,tuple) and "critic" in str(arm[0])},key=str) + for c in crits: + cols={} + for (arm,p),(n,k,nc) in agg.items(): + if not isinstance(arm,tuple) or arm[0]!=c: continue + cols[str(arm[1])]=(n,k,nc) + rnd=None + for (arm,p),v in agg.items(): + if arm==("random",c): rnd=v + if not rnd or not any(x in cols for x in ("N=4","N=16")): continue + def f(x): return f"{100*x[1]/max(x[0],1):6.1f}+-{se(x[0],x[1]):4.1f}" if x else f"{'--':>13s}" + seq=[rnd,cols.get("N=4"),cols.get("N=16"),cols.get("N=128")] + vals=[100*x[1]/max(x[0],1) for x in seq if x] + mono="YES" if all(a>=b for a,b in zip(vals,vals[1:])) else "no" + c4=cols.get("N=4",(0,0,0))[2]; c16=cols.get("N=16",(0,0,0))[2] + print(f"{task:32s} {str(c):22s} "+" ".join(f(x) for x in seq)+f" {mono:5s} {c4}/{c16}") +PY +cat $O/nsweep.txt + +# ---- (b) ARM[0]-CONSUMER AUDIT ------------------------------------------------------------------ +# Every predicate in the published builders that tests arm[0] and NOT arm[1]. For each, list the +# distinct arm[1] values actually present for that family, with n and cell count. A family with one +# arm[1] cannot pool; a family with several DOES pool and must be looked at. +python3 - > $O/arm0_audit.txt 2>&1 <<'PY' +import collections, verdict_table as vt +PREDS = [("master_table:826,1110 a[0]=='greedy'", lambda a: a[0]=="greedy"), + ("flagship:1197 matched a[0]=='critic'", lambda a: a[0]=="critic"), + ("flagship:1196 matched a[0]=='greedy'", lambda a: a[0]=="greedy"), + ("master/flagship a[0].startswith('rsm:membership')", lambda a: str(a[0]).startswith("rsm:membership")), + ("verdict_table a[0].startswith('critic:dino')", lambda a: str(a[0]).startswith("critic:dino")), + ("flagship:1012 a[0] in (wm:dinowm, wm:lewm)", lambda a: a[0] in ("wm:dinowm","wm:lewm")), + ("flagship a[0]=='wm:df'", lambda a: a[0]=="wm:df")] +print("ARM[0]-CONSUMER AUDIT -- distinct arm[1] per family, per task, from the loader.") +print("A predicate on arm[0] alone POOLS every arm[1] listed under it.\n") +for label, pred in PREDS: + print("="*100); print(label) + for task,_ in vt.TASKS: + agg=collections.defaultdict(lambda:[0,0,0]) + for (arm,p,ps,es),v in vt.cells(task).items(): + if not isinstance(arm,tuple) or len(arm)<2: continue + try: + if not pred(arm): continue + except Exception: continue + a=agg[(arm[1],p)]; a[0]+=len(v); a[1]+=sum(v); a[2]+=1 + if not agg: continue + byprop=collections.defaultdict(list) + for (a1,p),v in agg.items(): byprop[p].append((a1,v)) + for p,items in sorted(byprop.items(), key=str): + if len(items)==1: continue # cannot pool + tot_n=sum(v[0] for _,v in items) + print(f" {task:30s} proposer={str(p):22s} POOLS {len(items)} arm[1] values, n_total={tot_n}") + for a1,v in sorted(items, key=lambda x: -x[1][0]): + print(f" arm[1]={str(a1):34s} cells={v[2]:3d} n={v[0]:5d} rate={100.0*v[1]/max(v[0],1):5.1f}") +PY +sed -n '1,160p' $O/arm0_audit.txt + +echo "=== verdict lines that moved vs run20b POST ===" +grep -E "^[-+]" $O/verdict.diff | grep -vE "^\+\+\+|^---" | cut -c1-230 | head -70 +echo "=== flagship lines that moved vs run20b POST ===" +grep -E "^[-+]" $O/flag.diff | grep -vE "^\+\+\+|^---" | cut -c1-240 | head -40 diff --git a/rsm_rise/scripts/rr_cpu_basetopup_run21b.sh b/rsm_rise/scripts/rr_cpu_basetopup_run21b.sh new file mode 100644 index 0000000000000000000000000000000000000000..1a51b275e5a70a8ba9872d20bebf1fe23231b33c --- /dev/null +++ b/rsm_rise/scripts/rr_cpu_basetopup_run21b.sh @@ -0,0 +1,17 @@ +#!/usr/bin/env bash +# BASE_TOPUP run 21b: PROVE the family-pool tripwire added to flagship_latex.matched() is a no-op on +# today's data. The guard raises if a family keyed on arm[0] alone ever pools >1 arm[1]; the audit +# measured one arm[1] per (task, proposer) today, so the render must be byte-identical to run 21's PRE +# build apart from the build stamp. If it raises, that IS the finding and the backup restores instantly. +set -uo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +source scripts/env.sh >/dev/null 2>&1 +O=status/basetopup/run21b; mkdir -p $O +export PYTHONPATH=/proj/dmfexp/zwhong/rsm_rise/scripts:${PYTHONPATH:-} +python3 scripts/flagship_latex.py > $O/flag_post.txt 2> $O/flag_post.err; echo "flagship rc=$?" +diff -u status/basetopup/run21/flag_now.txt $O/flag_post.txt > $O/flag.diff 2>/dev/null +echo "flag diff lines: $(wc -l < $O/flag.diff)" +echo "=== NON-STAMP flagship lines that moved (MUST BE EMPTY) ===" +grep -E "^[-+]" $O/flag.diff | grep -vE "^\+\+\+|^---" | grep -v "% built" | cut -c1-200 +echo "=== end (empty above = tripwire is a no-op, as measured) ===" +grep -iE "FAMILY POOL|Traceback|SystemExit" $O/flag_post.err | head -5 diff --git a/rsm_rise/scripts/rr_cpu_basetopup_run22.sh b/rsm_rise/scripts/rr_cpu_basetopup_run22.sh new file mode 100644 index 0000000000000000000000000000000000000000..427c75d643850584635598a5c0ea6abbff505525 --- /dev/null +++ b/rsm_rise/scripts/rr_cpu_basetopup_run22.sh @@ -0,0 +1,95 @@ +#!/usr/bin/env bash +# BASE_TOPUP run 22: rebuild + three read-outs the run needs to DECIDE with, not to narrate: +# (a) the N=4 wave's progress with CELL COUNTS (partial reads on this curve have moved 2-5 points twice, +# so nothing here is quoted without its n); +# (b) the IFQL gamma table per task -> which discount the expectile sweep's second leg must use if the +# owner rules "best over gamma" (#287 open (c)); +# (c) the IDQL-DINO expectile (tau) arms at 1 seed -> the owner's "extend to 3 seeds only where it is +# competitive" test, measured against that row's OWN gamma-0.99 (Dq) arm and its OWN random control. +set -uo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +source scripts/env.sh >/dev/null 2>&1 +O=status/basetopup/run22; mkdir -p $O +export PYTHONPATH=/proj/dmfexp/zwhong/rsm_rise/scripts:${PYTHONPATH:-} +python3 scripts/verdict_table.py > $O/verdict_now.txt 2> $O/verdict_now.err; echo "verdict rc=$?" +python3 scripts/flagship_latex.py > $O/flag_now.txt 2> $O/flag_now.err; echo "flagship rc=$?" +diff -u status/basetopup/run21/verdict_now.txt $O/verdict_now.txt > $O/verdict.diff 2>/dev/null; echo "verdict diff lines: $(wc -l < $O/verdict.diff)" +diff -u status/basetopup/run21b/flag_post.txt $O/flag_now.txt > $O/flag.diff 2>/dev/null; echo "flag diff lines: $(wc -l < $O/flag.diff)" + +python3 - > $O/reads.txt 2>&1 <<'PY' +import collections, math, verdict_table as vt +def se(n,k): + p=k/n if n else 0.0 + return 100*math.sqrt(max(p*(1-p),0)/n) if n else 0.0 +def load(task): + agg=collections.defaultdict(lambda:[0,0,0]) + for (arm,p,ps,es),v in vt.cells(task).items(): + a=agg[(arm,p)]; a[0]+=len(v); a[1]+=sum(v); a[2]+=1 + return agg +def fmt(v): return f"{100*v[1]/max(v[0],1):5.1f}+-{se(v[0],v[1]):4.1f} (n={v[0]:4d},c={v[2]:2d})" if v else f"{'--':>24s}" + +print("="*110) +print("(a) N-SWEEP -- all five rows, with CELL COUNTS. c=9 is complete; anything less is PARTIAL.") +print(f"{'task':30s} {'critic':22s} {'N=1(rand)':>24s} {'N=4':>24s} {'N=16':>24s} {'N=128':>24s}") +for task,nice in vt.TASKS: + agg=load(task) + crits=sorted({arm[0] for (arm,p) in agg if isinstance(arm,tuple) and "critic" in str(arm[0])},key=str) + for c in crits: + cols={str(arm[1]):v for (arm,p),v in agg.items() if isinstance(arm,tuple) and arm[0]==c} + rnd=None + for (arm,p),v in agg.items(): + if arm==("random",c): rnd=v + if not any(x in cols for x in ("N=4","N=16")): continue + print(f"{task:30s} {str(c):22s} "+" ".join(fmt(x) for x in + [rnd, cols.get("N=4"), cols.get("N=16"), cols.get("N=128")])) + +print() +print("="*110) +print("(b) IFQL GAMMA TABLE per task (label `critic:ifql [g...]`; plain `critic:ifql` = published 0.9999).") +print(" BEST = the discount with the highest rate among arms with c>=9; used to pick the expectile sweep's") +print(" second leg IF the owner rules best-over-gamma.") +GS=["","g0p95","g0p98","g0p99","g0p995"] +print(f"{'task':30s} "+" ".join(f"{(g or 'published'):>12s}" for g in GS)+" BEST") +for task,nice in vt.TASKS: + agg=load(task) + row={} + for (arm,p),v in agg.items(): + if not isinstance(arm,tuple) or not str(arm[0]).startswith("critic:ifql"): continue + lab=str(arm[0]) + tag=lab.split("[")[1].rstrip("]") if "[" in lab else "" + if "N=128" not in str(arm[1]): continue + key=(tag,str(p)) + cur=row.get(tag) + if cur is None or v[0]>cur[0]: row[tag]=v + if not row: continue + cells=[] + for g in GS: + v=row.get(g) + cells.append(f"{100*v[1]/max(v[0],1):7.1f}/{v[2]:<2d}" if v else f"{'--':>10s}") + ok={g:v for g,v in row.items() if v[2]>=9} + best=max(ok.items(), key=lambda kv: kv[1][1]/max(kv[1][0],1))[0] if ok else "?" + print(f"{task:30s} "+" ".join(f"{c:>12s}" for c in cells)+f" {best or 'published'}") + +print() +print("="*110) +print("(c) IDQL-DINO EXPECTILE (tau) arms vs that row's gamma-0.99 (Dq) arm and its OWN random control.") +for task,nice in vt.TASKS: + agg=load(task) + rel={} + for (arm,p),v in agg.items(): + if not isinstance(arm,tuple): continue + a0=str(arm[0]) + if a0.startswith("critic:dino") or a0=="random" or a0.startswith("random"): + rel[(a0,str(arm[1]),str(p))]=v + keys=[k for k in rel if "t0p" in k[0] or "dino" in k[0].lower() or k[0].startswith("random")] + if not any("t0p" in k[0] for k in keys): continue + print(f"-- {task}") + for k in sorted(keys, key=str): + print(f" {k[0]:34s} {k[1]:16s} prop={k[2]:16s} {fmt(rel[k])}") +PY +cat $O/reads.txt + +echo "=== verdict lines that moved vs run21 ===" +grep -E "^[-+]" $O/verdict.diff | grep -vE "^\+\+\+|^---" | cut -c1-220 | head -80 +echo "=== flagship lines that moved vs run21b POST ===" +grep -E "^[-+]" $O/flag.diff | grep -vE "^\+\+\+|^---" | cut -c1-230 | head -40 diff --git a/rsm_rise/scripts/rr_cpu_basetopup_run22b.sh b/rsm_rise/scripts/rr_cpu_basetopup_run22b.sh new file mode 100644 index 0000000000000000000000000000000000000000..82afbd7c0ce182bc8a7f62c00e4899e302cfa676 --- /dev/null +++ b/rsm_rise/scripts/rr_cpu_basetopup_run22b.sh @@ -0,0 +1,82 @@ +#!/usr/bin/env bash +# BASE_TOPUP run 22b: repair THREE defects in run 22's own read-out before any of it is reported. +# 1. (b) pooled PROPOSERS. The published `critic:ifql` arm exists for TWO proposers -- "IFQL policy" +# (column (a), IFQL's own flow actor) and "RISE policy" (column (b), the single-actor row) -- while every +# gamma VARIANT has only the RISE-policy cells. Run 22 took whichever had the larger n, so the +# "published" column could be the flow-actor number (Pc-S 0.4) compared against RISE-policy variants +# (23.6). Same shape as the pooling defects this stream keeps finding, this time in my own reporting +# script: print the proposer explicitly, never pick one by n. +# 2. (c) matched the wrong label form: the tau arms print as `critic:dino(Dq) t0.5`, with a DOT, and the +# predicate looked for `t0p`, so section (c) came out empty rather than wrong. +# 3. BOTH skipped `square_sub_20100` (Sq-S), which `verdict_table.TASKS` does not list (§3.1 of #287). +# `cells()` reads it fine -- only the TASKS list is short -- so add it here explicitly. +# No table is rebuilt: run 22's build is current (flagship diff = build stamp only). +set -uo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +source scripts/env.sh >/dev/null 2>&1 +O=status/basetopup/run22b; mkdir -p $O +export PYTHONPATH=/proj/dmfexp/zwhong/rsm_rise/scripts:${PYTHONPATH:-} +python3 - > $O/reads.txt 2>&1 <<'PY' +import collections, math, verdict_table as vt +def se(n,k): + p=k/n if n else 0.0 + return 100*math.sqrt(max(p*(1-p),0)/n) if n else 0.0 +def load(task): + agg=collections.defaultdict(lambda:[0,0,0]) + for (arm,p,ps,es),v in vt.cells(task).items(): + a=agg[(arm,p)]; a[0]+=len(v); a[1]+=sum(v); a[2]+=1 + return agg +def fmt(v): return f"{100*v[1]/max(v[0],1):5.1f}+-{se(v[0],v[1]):4.1f} (n={v[0]:4d},c={v[2]:2d})" if v else f"{'--':>24s}" +ROWS = list(vt.TASKS) + [("square_sub_20100","Sq-S (20/100, absent from verdict_table.TASKS)")] + +print("="*118) +print("(b') IFQL GAMMA TABLE, PROPOSER PINNED. One block per proposer; a variant only ever has RISE-policy") +print(" cells, so only the RISE-policy block is a like-for-like gamma comparison.") +TAGS=["","g0p95","g0p98","g0p99","g0p995","t0p7","t0p9"] +for want in ("RISE policy","IFQL policy"): + print(f"\n-- proposer = {want}") + print(f"{'task':30s} "+" ".join(f"{(g or 'published'):>13s}" for g in TAGS)+" BEST(c>=9)") + for task,_ in ROWS: + agg=load(task); row={} + for (arm,p),v in agg.items(): + if not isinstance(arm,tuple) or not str(arm[0]).startswith("critic:ifql"): continue + if str(p)!=want or "N=128" not in str(arm[1]): continue + lab=str(arm[0]); tag=lab.split("[")[1].rstrip("]") if "[" in lab else "" + row[tag]=v + if not row: continue + cells=[(f"{100*v[1]/max(v[0],1):7.1f}/{v[2]:<2d}" if (v:=row.get(g)) else f"{'--':>10s}") for g in TAGS] + ok={g:v for g,v in row.items() if v[2]>=9} + best=max(ok.items(), key=lambda kv: kv[1][1]/max(kv[1][0],1))[0] if ok else "?" + print(f"{task:30s} "+" ".join(f"{c:>13s}" for c in cells)+f" {best or 'published'}") + +print() +print("="*118) +print("(c') IDQL-DINO EXPECTILE (tau) arms -- label form `critic:dino(Dq) t0.5` -- beside that row's") +print(" gamma-0.99 (Dq) arm (the tau=0.9 released value) and the row's OWN random control.") +for task,_ in ROWS: + agg=load(task) + got={} + for (arm,p),v in agg.items(): + if not isinstance(arm,tuple): continue + a0=str(arm[0]) + if a0.startswith("critic:dino") and "N=128" in str(arm[1]): got[(a0,str(p))]=v + if a0=="random": got[("random ctl","")]=v + if not any(" t0." in k[0] for k in got): continue + print(f"-- {task}") + for k in sorted(got, key=str): + print(f" {k[0]:40s} prop={k[1]:18s} {fmt(got[k])}") + +print() +print("="*118) +print("(a') N=4 SWEEP -- the two rows run 22 dropped (threading's label carries its @500 critic epoch;") +print(" square_sub_20100 is absent from verdict_table.TASKS), every critic:dino/critic arm printed.") +for task in ("threading_expert_play","square_sub_20100"): + agg=load(task) + print(f"-- {task}") + for (arm,p),v in sorted(agg.items(), key=str): + if not isinstance(arm,tuple): continue + if not (str(arm[0]).startswith("critic") or str(arm[0])=="random"): continue + if not any(x in str(arm[1]) for x in ("N=4","N=16","N=128")) and str(arm[0])!="random": continue + print(f" {str(arm[0]):40s} {str(arm[1]):10s} prop={str(p):18s} {fmt(v)}") +PY +cat $O/reads.txt diff --git a/rsm_rise/scripts/rr_cpu_basetopup_run23.sh b/rsm_rise/scripts/rr_cpu_basetopup_run23.sh new file mode 100644 index 0000000000000000000000000000000000000000..d89850da9defbe85018cb8b8bba9fc543bf56e83 --- /dev/null +++ b/rsm_rise/scripts/rr_cpu_basetopup_run23.sh @@ -0,0 +1,141 @@ +#!/usr/bin/env bash +# BASE_TOPUP run 23: +# (0) SETTLE run 22 section 6 -- "verdict_table.cells('threading_expert_play') shows no critic:dino arms" +# -- by DEMONSTRATION rather than assertion. Hypothesis from the code: verdict_table admits policy +# epoch 5000 only, plus whatever RSM_EXTRA_EPOCHS names (verdict_table.py:190). flagship_latex sets +# that variable from PROPOSER_BY_TASK ("threading_expert_play": "IDQL policy@500", flagship_latex.py +# :122-132); a STANDALONE verdict_table -- which every one of my reporting scripts has been -- does +# not, so every threading cell against its pinned @500 proposer is dropped. Printed BOTH ways below. +# If true, the two readers never disagreed: runs 20-21's threading DINO numbers came from the +# criticdino JSON scan (epoch-500 cells, the row's pinned proposer) and are right; my dump was the +# one missing the variable. +# (1) The N=4 wave at its FINAL cell counts, against the three predictions pre-registered at 14:25Z. +# (2) Expectile leg progress. +# (3) Rebuild verdict + flagship and diff against run 22. +set -uo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +source scripts/env.sh >/dev/null 2>&1 +O=status/basetopup/run23; mkdir -p $O +export PYTHONPATH=/proj/dmfexp/zwhong/rsm_rise/scripts:${PYTHONPATH:-} + +python3 scripts/verdict_table.py > $O/verdict_now.txt 2> $O/verdict_now.err; echo "verdict rc=$?" +python3 scripts/flagship_latex.py > $O/flag_now.txt 2> $O/flag_now.err; echo "flagship rc=$?" +diff -u status/basetopup/run22/verdict_now.txt $O/verdict_now.txt > $O/verdict.diff 2>/dev/null; echo "verdict diff lines: $(wc -l < $O/verdict.diff)" +diff -u status/basetopup/run22/flag_now.txt $O/flag_now.txt > $O/flag.diff 2>/dev/null; echo "flag diff lines: $(wc -l < $O/flag.diff)" + +python3 - > $O/reads.txt 2>&1 <<'PY' +import collections, math, os, importlib + +def se(n,k): + p=k/n if n else 0.0 + return 100*math.sqrt(max(p*(1-p),0)/n) if n else 0.0 + +def loader(extra=None): + """A FRESH verdict_table with RSM_EXTRA_EPOCHS set (or not). The variable is read inside + _allowed_epochs() at call time, but re-importing keeps this honest if that ever changes.""" + if extra is None: os.environ.pop("RSM_EXTRA_EPOCHS", None) + else: os.environ["RSM_EXTRA_EPOCHS"] = extra + import verdict_table as vt + importlib.reload(vt) + return vt + +def agg(vt, task): + out=collections.defaultdict(lambda:[0,0,0]) + for (arm,p,ps,es),v in vt.cells(task).items(): + a=out[(arm,p)]; a[0]+=len(v); a[1]+=sum(v); a[2]+=1 + return out + +print("="*118) +print("(0) SECTION-6 RESOLUTION -- threading_expert_play, critic* arms, WITHOUT vs WITH RSM_EXTRA_EPOCHS=500") +for extra in (None, "500"): + vt = loader(extra) + a = agg(vt, "threading_expert_play") + keys=[k for k in a if isinstance(k[0],tuple) and str(k[0][0]).startswith("critic:dino")] + print(f"\n-- RSM_EXTRA_EPOCHS={extra!r}: {len(keys)} critic:dino arm(s)") + for k in sorted(keys, key=str): + v=a[k]; print(f" {str(k[0][0]):30s} {str(k[0][1]):8s} prop={str(k[1]):18s} " + f"{100*v[1]/max(v[0],1):5.1f}+-{se(v[0],v[1]):4.1f} (n={v[0]:4d},c={v[2]:2d})") + +# Everything below uses the flagship's own epoch policy, which is the one the paper tables use. +vt = loader("500") +ROWS = [("square_sub_20100","Sq-S"),("square_expert_play","Sq-C"), + ("two_piece_expert_suboptimal","Pc-S"),("two_piece_expert_play","Pc-C"), + ("mug_expert_suboptimal","Mug"),("threading_expert_play","Thr"), + ("two_piece_expert_play_tipping","Pc-tip")] + +print() +print("="*118) +print("(1) N SWEEP AT FINAL COUNTS. `random` here is the row's own uniform-pick-of-128 control (N=1).") +print(f"{'row':8s} {'critic':22s} {'N=1 (random ctl)':>18s} {'N=4':>18s} {'N=16':>18s} {'N=128':>18s}") +NS = {"N=4":"N=4","N=16":"N=16","N=128":"N=128"} +table={} +for task,short in ROWS: + a = agg(vt, task) + fams = {} + for (arm,p),v in a.items(): + if not isinstance(arm,tuple): continue + a0,a1 = str(arm[0]), str(arm[1]) + if a0 == "random": + fams.setdefault(("ctl", a1, str(p)), v) + if a0 in ("critic (planner ctl)","critic:dino(Dq)") and a1 in NS: + fams[(a0, a1, str(p))] = v + for fam,lab in (("critic (planner ctl)","pixel (planner ctl)"),("critic:dino(Dq)","DINO (Dq)")): + row={} + props={p for (f,n,p) in fams if f==fam} + for p in sorted(props): + for n in ("N=4","N=16","N=128"): + if (fam,n,p) in fams: row[n]=fams[(fam,n,p)] + ctl = fams.get(("ctl", fam, p)) + if not row: continue + def c(n): + v=row.get(n) + return f"{100*v[1]/max(v[0],1):5.1f}+-{se(v[0],v[1]):3.1f}/{v[2]}" if v else f"{'--':>14s}" + cs = f"{100*ctl[1]/max(ctl[0],1):5.1f}+-{se(ctl[0],ctl[1]):3.1f}/{ctl[2]}" if ctl else f"{'--':>14s}" + print(f"{short:8s} {lab:22s} {cs:>18s} {c('N=4'):>18s} {c('N=16'):>18s} {c('N=128'):>18s}") + table[(short,fam)] = (ctl, row) + row={} + +print() +print("-- VERDICT ON THE THREE PREDICTIONS PRE-REGISTERED 2026-09-26 14:25Z (#287), complete arms only (c>=9)") +def rate(v): return 100*v[1]/max(v[0],1) if v else None +p1=[];p2p=[];p2d=[];p3=[] +for (short,fam),(ctl,row) in sorted(table.items()): + n4, n128 = row.get("N=4"), row.get("N=128") + if not (n4 and n128 and ctl): continue + complete = n4[2]>=9 and n128[2]>=9 and ctl[2]>=9 + r4,r128,rc_ = rate(n4), rate(n128), rate(ctl) + tag = "" if complete else " [INCOMPLETE: N=4 c=%d]" % n4[2] + # P1: N=4 > N=128 wherever N=128 is below its own control + if r128 < rc_: + p1.append((short,fam,r4>r128,f"{r4:.1f} vs {r128:.1f} (ctl {rc_:.1f}){tag}")) + # P2: pixel within 2 SEM of / above its control at N=4; DINO below + s = math.sqrt(se(n4[0],n4[1])**2 + se(ctl[0],ctl[1])**2) + if fam=="critic (planner ctl)": p2p.append((short, r4 >= rc_-2*s, f"{r4:.1f} vs {rc_:.1f} (2SEM {2*s:.1f}){tag}")) + else: p2d.append((short, r4 < rc_-2*s, f"{r4:.1f} vs {rc_:.1f} (2SEM {2*s:.1f}){tag}")) + # P3: no reversal -- N=4 must not be BELOW N=128 by more than 2 SEM + s2 = math.sqrt(se(n4[0],n4[1])**2 + se(n128[0],n128[1])**2) + p3.append((short,fam, r4 >= r128-2*s2, f"{r4:.1f} vs {r128:.1f} (2SEM {2*s2:.1f}){tag}")) +for nm, lst in (("P1 N=4>N=128 where N=128= ctl-2SEM at N=4", p2p), + ("P2b DINO < ctl-2SEM at N=4", p2d), ("P3 no reversal (N=4 >= N=128-2SEM)", p3)): + ok=sum(1 for x in lst if x[-2]); print(f"\n {nm}: {ok}/{len(lst)}") + for x in lst: print(f" {'PASS' if x[-2] else 'FAIL'} {x[0]:8s} {str(x[1] if len(x)>3 else ''):22s} {x[-1]}") + +print() +print("="*118) +print("(2) EXPECTILE LEG -- IFQL tau arms and IDQL-DINO tau arms, all rows") +for task,short in ROWS: + a=agg(vt,task); got=[] + for (arm,p),v in a.items(): + if not isinstance(arm,tuple): continue + a0=str(arm[0]) + if ("t0" in a0) and "N=128" in str(arm[1]): got.append((a0,str(p),v)) + if not got: continue + print(f"-- {short} ({task})") + for a0,p,v in sorted(got): + print(f" {a0:34s} prop={p:14s} {100*v[1]/max(v[0],1):5.1f}+-{se(v[0],v[1]):4.1f} (n={v[0]:4d},c={v[2]:2d})") +PY +echo "=== reads ==="; cat $O/reads.txt +echo "=== verdict diff (first 60) ===" +grep -E "^[-+]" $O/verdict.diff | grep -vE "^\+\+\+|^---" | cut -c1-220 | head -60 +echo "=== flagship diff (first 40) ===" +grep -E "^[-+]" $O/flag.diff | grep -vE "^\+\+\+|^---" | cut -c1-230 | head -40 diff --git a/rsm_rise/scripts/rr_cpu_basetopup_run24.sh b/rsm_rise/scripts/rr_cpu_basetopup_run24.sh new file mode 100644 index 0000000000000000000000000000000000000000..65894541de3deff91c01939ebe3a89190ce33cb6 --- /dev/null +++ b/rsm_rise/scripts/rr_cpu_basetopup_run24.sh @@ -0,0 +1,137 @@ +#!/usr/bin/env bash +# BASE_TOPUP run 24: +# (1) The N grid at its now-four-point state on every row (the run-23 N=16 wave, 81 cells, and threading's +# own random/permuted DINO controls, 18 cells, have been landing since 16:00Z). Re-score the three +# predictions pre-registered at 14:25Z at FINAL counts -- in particular P2a, which run 23 could only +# score on 4 complete arms because three pixel N=4 arms were still filling (job 1926208). +# (2) Threading, which had NO control at all until run 23, now enters the prediction scoring. +# (3) Expectile leg progress (IFQL published + best-gamma legs, IDQL-DINO tau). +# (4) Rebuild verdict + flagship and diff against run 23. +# RSM_EXTRA_EPOCHS is set EXPLICITLY and printed (integrity item 10, run 23 section 2). +set -uo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +source scripts/env.sh >/dev/null 2>&1 +O=status/basetopup/run24; mkdir -p $O +export PYTHONPATH=/proj/dmfexp/zwhong/rsm_rise/scripts:${PYTHONPATH:-} + +python3 scripts/verdict_table.py > $O/verdict_now.txt 2> $O/verdict_now.err; echo "verdict rc=$?" +python3 scripts/flagship_latex.py > $O/flag_now.txt 2> $O/flag_now.err; echo "flagship rc=$?" +diff -u status/basetopup/run23/verdict_now.txt $O/verdict_now.txt > $O/verdict.diff 2>/dev/null; echo "verdict diff lines: $(wc -l < $O/verdict.diff)" +diff -u status/basetopup/run23/flag_now.txt $O/flag_now.txt > $O/flag.diff 2>/dev/null; echo "flag diff lines: $(wc -l < $O/flag.diff)" + +python3 - > $O/reads.txt 2>&1 <<'PY' +import collections, math, os, importlib + +def se(n,k): + p=k/n if n else 0.0 + return 100*math.sqrt(max(p*(1-p),0)/n) if n else 0.0 + +def loader(extra=None): + """A FRESH verdict_table with RSM_EXTRA_EPOCHS set (or not). The variable is read inside + _allowed_epochs() at call time, but re-importing keeps this honest if that ever changes.""" + if extra is None: os.environ.pop("RSM_EXTRA_EPOCHS", None) + else: os.environ["RSM_EXTRA_EPOCHS"] = extra + import verdict_table as vt + importlib.reload(vt) + return vt + +def agg(vt, task): + out=collections.defaultdict(lambda:[0,0,0]) + for (arm,p,ps,es),v in vt.cells(task).items(): + a=out[(arm,p)]; a[0]+=len(v); a[1]+=sum(v); a[2]+=1 + return out + +print("="*118) +print("(0) SECTION-6 RESOLUTION -- threading_expert_play, critic* arms, WITHOUT vs WITH RSM_EXTRA_EPOCHS=500") +for extra in (None, "500"): + vt = loader(extra) + a = agg(vt, "threading_expert_play") + keys=[k for k in a if isinstance(k[0],tuple) and str(k[0][0]).startswith("critic:dino")] + print(f"\n-- RSM_EXTRA_EPOCHS={extra!r}: {len(keys)} critic:dino arm(s)") + for k in sorted(keys, key=str): + v=a[k]; print(f" {str(k[0][0]):30s} {str(k[0][1]):8s} prop={str(k[1]):18s} " + f"{100*v[1]/max(v[0],1):5.1f}+-{se(v[0],v[1]):4.1f} (n={v[0]:4d},c={v[2]:2d})") + +# Everything below uses the flagship's own epoch policy, which is the one the paper tables use. +vt = loader("500") +ROWS = [("square_sub_20100","Sq-S"),("square_expert_play","Sq-C"), + ("two_piece_expert_suboptimal","Pc-S"),("two_piece_expert_play","Pc-C"), + ("mug_expert_suboptimal","Mug"),("threading_expert_play","Thr"), + ("two_piece_expert_play_tipping","Pc-tip")] + +print() +print("="*118) +print("(1) N SWEEP AT FINAL COUNTS. `random` here is the row's own uniform-pick-of-128 control (N=1).") +print(f"{'row':8s} {'critic':22s} {'N=1 (random ctl)':>18s} {'N=4':>18s} {'N=16':>18s} {'N=128':>18s}") +NS = {"N=4":"N=4","N=16":"N=16","N=128":"N=128"} +table={} +for task,short in ROWS: + a = agg(vt, task) + fams = {} + for (arm,p),v in a.items(): + if not isinstance(arm,tuple): continue + a0,a1 = str(arm[0]), str(arm[1]) + if a0 == "random": + fams.setdefault(("ctl", a1, str(p)), v) + if a0 in ("critic (planner ctl)","critic:dino(Dq)") and a1 in NS: + fams[(a0, a1, str(p))] = v + for fam,lab in (("critic (planner ctl)","pixel (planner ctl)"),("critic:dino(Dq)","DINO (Dq)")): + row={} + props={p for (f,n,p) in fams if f==fam} + for p in sorted(props): + for n in ("N=4","N=16","N=128"): + if (fam,n,p) in fams: row[n]=fams[(fam,n,p)] + ctl = fams.get(("ctl", fam, p)) + if not row: continue + def c(n): + v=row.get(n) + return f"{100*v[1]/max(v[0],1):5.1f}+-{se(v[0],v[1]):3.1f}/{v[2]}" if v else f"{'--':>14s}" + cs = f"{100*ctl[1]/max(ctl[0],1):5.1f}+-{se(ctl[0],ctl[1]):3.1f}/{ctl[2]}" if ctl else f"{'--':>14s}" + print(f"{short:8s} {lab:22s} {cs:>18s} {c('N=4'):>18s} {c('N=16'):>18s} {c('N=128'):>18s}") + table[(short,fam)] = (ctl, row) + row={} + +print() +print("-- VERDICT ON THE THREE PREDICTIONS PRE-REGISTERED 2026-09-26 14:25Z (#287), complete arms only (c>=9)") +def rate(v): return 100*v[1]/max(v[0],1) if v else None +p1=[];p2p=[];p2d=[];p3=[] +for (short,fam),(ctl,row) in sorted(table.items()): + n4, n128 = row.get("N=4"), row.get("N=128") + if not (n4 and n128 and ctl): continue + complete = n4[2]>=9 and n128[2]>=9 and ctl[2]>=9 + r4,r128,rc_ = rate(n4), rate(n128), rate(ctl) + tag = "" if complete else " [INCOMPLETE: N=4 c=%d]" % n4[2] + # P1: N=4 > N=128 wherever N=128 is below its own control + if r128 < rc_: + p1.append((short,fam,r4>r128,f"{r4:.1f} vs {r128:.1f} (ctl {rc_:.1f}){tag}")) + # P2: pixel within 2 SEM of / above its control at N=4; DINO below + s = math.sqrt(se(n4[0],n4[1])**2 + se(ctl[0],ctl[1])**2) + if fam=="critic (planner ctl)": p2p.append((short, r4 >= rc_-2*s, f"{r4:.1f} vs {rc_:.1f} (2SEM {2*s:.1f}){tag}")) + else: p2d.append((short, r4 < rc_-2*s, f"{r4:.1f} vs {rc_:.1f} (2SEM {2*s:.1f}){tag}")) + # P3: no reversal -- N=4 must not be BELOW N=128 by more than 2 SEM + s2 = math.sqrt(se(n4[0],n4[1])**2 + se(n128[0],n128[1])**2) + p3.append((short,fam, r4 >= r128-2*s2, f"{r4:.1f} vs {r128:.1f} (2SEM {2*s2:.1f}){tag}")) +for nm, lst in (("P1 N=4>N=128 where N=128= ctl-2SEM at N=4", p2p), + ("P2b DINO < ctl-2SEM at N=4", p2d), ("P3 no reversal (N=4 >= N=128-2SEM)", p3)): + ok=sum(1 for x in lst if x[-2]); print(f"\n {nm}: {ok}/{len(lst)}") + for x in lst: print(f" {'PASS' if x[-2] else 'FAIL'} {x[0]:8s} {str(x[1] if len(x)>3 else ''):22s} {x[-1]}") + +print() +print("="*118) +print("(2) EXPECTILE LEG -- IFQL tau arms and IDQL-DINO tau arms, all rows") +for task,short in ROWS: + a=agg(vt,task); got=[] + for (arm,p),v in a.items(): + if not isinstance(arm,tuple): continue + a0=str(arm[0]) + if ("t0" in a0) and "N=128" in str(arm[1]): got.append((a0,str(p),v)) + if not got: continue + print(f"-- {short} ({task})") + for a0,p,v in sorted(got): + print(f" {a0:34s} prop={p:14s} {100*v[1]/max(v[0],1):5.1f}+-{se(v[0],v[1]):4.1f} (n={v[0]:4d},c={v[2]:2d})") +PY +echo "=== reads ==="; cat $O/reads.txt +echo "=== verdict diff (first 60) ===" +grep -E "^[-+]" $O/verdict.diff | grep -vE "^\+\+\+|^---" | cut -c1-220 | head -60 +echo "=== flagship diff (first 40) ===" +grep -E "^[-+]" $O/flag.diff | grep -vE "^\+\+\+|^---" | cut -c1-230 | head -40 diff --git a/rsm_rise/scripts/rr_cpu_basetopup_run26.sh b/rsm_rise/scripts/rr_cpu_basetopup_run26.sh new file mode 100644 index 0000000000000000000000000000000000000000..81197a4a1d3eb3298053007134319b434c92b724 --- /dev/null +++ b/rsm_rise/scripts/rr_cpu_basetopup_run26.sh @@ -0,0 +1,125 @@ +#!/usr/bin/env bash +# BASE_TOPUP run 26: +# (1) THE MIRROR CURVE'S FIRST READ: the pre-registered RSM N sweep (#287 section 1.11) at whatever count +# it has reached. The arms are NOT re-derived -- each row's reported arm comes from the builder's own +# export status/chain/flagship_chain_arm.json, and its N=4 / N=16 siblings are that same arm string with +# only the N token changed, on the SAME pinned proposer. Prediction scored only on arms at c>=9. +# (2) The critic N curve at final counts, to confirm run 25's 28-cell top-up closed the partial arms. +# (3) Expectile leg progress. (4) Rebuild verdict + flagship and diff against run 24. +# RSM_EXTRA_EPOCHS is set EXPLICITLY and printed (integrity item 10). +set -uo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +source scripts/env.sh >/dev/null 2>&1 +O=status/basetopup/run26; mkdir -p $O +export PYTHONPATH=/proj/dmfexp/zwhong/rsm_rise/scripts:${PYTHONPATH:-} + +python3 scripts/verdict_table.py > $O/verdict_now.txt 2> $O/verdict_now.err; echo "verdict rc=$?" +python3 scripts/flagship_latex.py > $O/flag_now.txt 2> $O/flag_now.err; echo "flagship rc=$?" +diff -u status/basetopup/run24/verdict_now.txt $O/verdict_now.txt > $O/verdict.diff 2>/dev/null; echo "verdict diff lines: $(wc -l < $O/verdict.diff)" +diff -u status/basetopup/run24/flag_now.txt $O/flag_now.txt > $O/flag.diff 2>/dev/null; echo "flag diff lines: $(wc -l < $O/flag.diff)" + +python3 - > $O/reads.txt 2>&1 <<'PY' +import collections, json, math, os, re, importlib +os.environ["RSM_EXTRA_EPOCHS"] = "500" +print("RSM_EXTRA_EPOCHS =", os.environ["RSM_EXTRA_EPOCHS"], "(set explicitly, integrity item 10)") +import verdict_table as vt + +def se(n,k): + p=k/n if n else 0.0 + return 100*math.sqrt(max(p*(1-p),0)/n) if n else 0.0 +def agg(task): + out=collections.defaultdict(lambda:[0,0,0]) + for (arm,p,ps,es),v in vt.cells(task).items(): + a=out[(arm,p)]; a[0]+=len(v); a[1]+=sum(v); a[2]+=1 + return out +def fmt(v): + return f"{100*v[1]/max(v[0],1):5.1f}+-{se(v[0],v[1]):4.1f} (n={v[0]:4d},c={v[2]:2d})" if v else f"{'--':>26s}" +def rate(v): return 100*v[1]/max(v[0],1) if v else None + +ROWS = [("square_sub_20100","Sq-S"),("square_expert_play","Sq-C"), + ("two_piece_expert_suboptimal","Pc-S"),("two_piece_expert_play","Pc-C"), + ("mug_expert_suboptimal","Mug"),("threading_expert_play","Thr"), + ("two_piece_expert_play_tipping","Pc-tip")] +SHORT={t:s for t,s in ROWS} + +print("="*120) +print("(1) THE RSM N CURVE -- the mirror of the baseline curve, on the arm tab:flagship REPORTS on each row.") +print(" arm + proposer taken from status/chain/flagship_chain_arm.json (flagship_latex._best_arm's own export);") +print(" the N=4 / N=16 arms are that string with ONLY the N token changed.") +sel=json.load(open("status/chain/flagship_chain_arm.json")) +curve={} +for label, rec in sel.items(): + task, arm = rec["task"], rec["chain_arm"] + a=agg(task) + want={} + for n in (4,16,128): + want[n]=re.sub(r"\bN128\b", f"N{n}", arm) + # pick the proposer that carries the published N=128 arm (the pinned one), then read all three on it + props=[p for (ar,p) in a if isinstance(ar,tuple) and ar[0]=="rsm:membership" and ar[1]==want[128]] + if not props: + print(f"\n== {label}: published arm {arm!r} not found -- skipped"); continue + pol=max(props, key=lambda p: a[(("rsm:membership",want[128]),p)][2]) + print(f"\n== {label} ({task}) arm={arm!r} proposer={pol} exported rate={rec['chain_rate']:.1f}") + got={} + for n in (4,16,128): + v=a.get((("rsm:membership",want[n]),pol)) + got[n]=v + print(f" N={n:<4d} {fmt(v)} arm={want[n]!r}") + curve[SHORT[task]]=got + +print() +print("-- SCORING THE PREDICTION PRE-REGISTERED 2026-09-26 17:05Z (#287 section 3), complete arms only (c>=9).") +print(" Wording: on the rows where a CRITIC arm loses >=10 points from N=4 to N=128, RSM at N=128 is within") +print(" 2 SEM of, or above, its own N=4 value on >=3 of 4. FALSIFIED if RSM loses more than 2 SEM on >=2.") +scored=[] +for short,got in sorted(curve.items()): + n4,n128=got.get(4),got.get(128) + if not (n4 and n128) or n4[2]<9 or n128[2]<9: + print(f" PENDING {short:8s} N=4 c={n4[2] if n4 else 0}, N=128 c={n128[2] if n128 else 0}") + continue + r4,r128=rate(n4),rate(n128) + s=math.sqrt(se(n4[0],n4[1])**2+se(n128[0],n128[1])**2) + ok = r128 >= r4-2*s + scored.append((short,ok,r4,r128,2*s)) + print(f" {'HOLDS ' if ok else 'LOSES '} {short:8s} N=4 {r4:5.1f} -> N=128 {r128:5.1f} (delta {r128-r4:+5.1f}, 2SEM {2*s:4.1f})") +if scored: + print(f" complete rows: {len(scored)}; holds {sum(1 for x in scored if x[1])}, loses-by->2SEM {sum(1 for x in scored if not x[1])}") + print(" (The 4 pre-registered in-scope rows are Sq-C, Pc-S, Pc-C, Pc-tip -- the rows where a critic arm") + print(" loses >=10 points from N=4 to N=128. Verdict is stated only when all four are at c>=9.)") + +print() +print("="*120) +print("(2) THE CRITIC N CURVE AT FINAL COUNTS (run 25's 28-cell top-up). `random` = the row's N=1 control.") +NS={"N=4","N=16","N=128"} +for task,short in ROWS: + a=agg(task) + fams=collections.defaultdict(dict); ctls={} + for (arm,p),v in a.items(): + if not isinstance(arm,tuple): continue + a0,a1=str(arm[0]),str(arm[1]) + if a0=="random": ctls[(a1,str(p))]=v + if a0 in ("critic (planner ctl)","critic:dino(Dq)") and a1 in NS: fams[(a0,str(p))][a1]=v + for (fam,p),row in sorted(fams.items()): + lab="pixel" if fam=="critic (planner ctl)" else "DINO " + ctl=ctls.get((fam,p)) + cs=fmt(ctl) if ctl else f"{'--':>26s}" + print(f"{short:8s} {lab} prop={p:16s} ctl {cs} | " + + " | ".join(f"N={n.split('=')[1]:>3s} {fmt(row.get(n))}" for n in ("N=4","N=16","N=128"))) + +print() +print("="*120) +print("(3) EXPECTILE LEG -- IFQL tau arms and IDQL-DINO tau arms") +for task,short in ROWS: + a=agg(task); got=[] + for (arm,p),v in a.items(): + if not isinstance(arm,tuple): continue + if ("t0" in str(arm[0])) and "N=128" in str(arm[1]): got.append((str(arm[0]),str(p),v)) + if not got: continue + print(f"-- {short} ({task})") + for a0,p,v in sorted(got): print(f" {a0:34s} prop={p:14s} {fmt(v)}") +PY +echo "=== reads ==="; cat $O/reads.txt +echo "=== verdict diff (first 60) ===" +grep -E "^[-+]" $O/verdict.diff | grep -vE "^\+\+\+|^---" | cut -c1-220 | head -60 +echo "=== flagship diff (first 40) ===" +grep -E "^[-+]" $O/flag.diff | grep -vE "^\+\+\+|^---" | cut -c1-230 | head -40 diff --git a/rsm_rise/scripts/rr_cpu_basetopup_run26b.sh b/rsm_rise/scripts/rr_cpu_basetopup_run26b.sh new file mode 100644 index 0000000000000000000000000000000000000000..c36c76682bc7a10f235e91a2ed29e05d29c843c1 --- /dev/null +++ b/rsm_rise/scripts/rr_cpu_basetopup_run26b.sh @@ -0,0 +1,112 @@ +#!/usr/bin/env bash +# BASE_TOPUP run 26b: the SAME read-out as run 26, re-run after the second tranche landed, with NO table +# rebuild (nothing about the published tables changed since 18:22Z; only new cells landed). Output is +# timestamped at its start and end so the count it read is unambiguous. +set -uo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +source scripts/env.sh >/dev/null 2>&1 +O=status/basetopup/run26; mkdir -p $O +export PYTHONPATH=/proj/dmfexp/zwhong/rsm_rise/scripts:${PYTHONPATH:-} +echo "reads started $(date -u +%H:%M:%SZ)" +python3 - > $O/reads_b.txt 2>&1 <<'PYEOF' +import collections, json, math, os, re, importlib +os.environ["RSM_EXTRA_EPOCHS"] = "500" +print("RSM_EXTRA_EPOCHS =", os.environ["RSM_EXTRA_EPOCHS"], "(set explicitly, integrity item 10)") +import verdict_table as vt + +def se(n,k): + p=k/n if n else 0.0 + return 100*math.sqrt(max(p*(1-p),0)/n) if n else 0.0 +def agg(task): + out=collections.defaultdict(lambda:[0,0,0]) + for (arm,p,ps,es),v in vt.cells(task).items(): + a=out[(arm,p)]; a[0]+=len(v); a[1]+=sum(v); a[2]+=1 + return out +def fmt(v): + return f"{100*v[1]/max(v[0],1):5.1f}+-{se(v[0],v[1]):4.1f} (n={v[0]:4d},c={v[2]:2d})" if v else f"{'--':>26s}" +def rate(v): return 100*v[1]/max(v[0],1) if v else None + +ROWS = [("square_sub_20100","Sq-S"),("square_expert_play","Sq-C"), + ("two_piece_expert_suboptimal","Pc-S"),("two_piece_expert_play","Pc-C"), + ("mug_expert_suboptimal","Mug"),("threading_expert_play","Thr"), + ("two_piece_expert_play_tipping","Pc-tip")] +SHORT={t:s for t,s in ROWS} + +print("="*120) +print("(1) THE RSM N CURVE -- the mirror of the baseline curve, on the arm tab:flagship REPORTS on each row.") +print(" arm + proposer taken from status/chain/flagship_chain_arm.json (flagship_latex._best_arm's own export);") +print(" the N=4 / N=16 arms are that string with ONLY the N token changed.") +sel=json.load(open("status/chain/flagship_chain_arm.json")) +curve={} +for label, rec in sel.items(): + task, arm = rec["task"], rec["chain_arm"] + a=agg(task) + want={} + for n in (4,16,128): + want[n]=re.sub(r"\bN128\b", f"N{n}", arm) + # pick the proposer that carries the published N=128 arm (the pinned one), then read all three on it + props=[p for (ar,p) in a if isinstance(ar,tuple) and ar[0]=="rsm:membership" and ar[1]==want[128]] + if not props: + print(f"\n== {label}: published arm {arm!r} not found -- skipped"); continue + pol=max(props, key=lambda p: a[(("rsm:membership",want[128]),p)][2]) + print(f"\n== {label} ({task}) arm={arm!r} proposer={pol} exported rate={rec['chain_rate']:.1f}") + got={} + for n in (4,16,128): + v=a.get((("rsm:membership",want[n]),pol)) + got[n]=v + print(f" N={n:<4d} {fmt(v)} arm={want[n]!r}") + curve[SHORT[task]]=got + +print() +print("-- SCORING THE PREDICTION PRE-REGISTERED 2026-09-26 17:05Z (#287 section 3), complete arms only (c>=9).") +print(" Wording: on the rows where a CRITIC arm loses >=10 points from N=4 to N=128, RSM at N=128 is within") +print(" 2 SEM of, or above, its own N=4 value on >=3 of 4. FALSIFIED if RSM loses more than 2 SEM on >=2.") +scored=[] +for short,got in sorted(curve.items()): + n4,n128=got.get(4),got.get(128) + if not (n4 and n128) or n4[2]<9 or n128[2]<9: + print(f" PENDING {short:8s} N=4 c={n4[2] if n4 else 0}, N=128 c={n128[2] if n128 else 0}") + continue + r4,r128=rate(n4),rate(n128) + s=math.sqrt(se(n4[0],n4[1])**2+se(n128[0],n128[1])**2) + ok = r128 >= r4-2*s + scored.append((short,ok,r4,r128,2*s)) + print(f" {'HOLDS ' if ok else 'LOSES '} {short:8s} N=4 {r4:5.1f} -> N=128 {r128:5.1f} (delta {r128-r4:+5.1f}, 2SEM {2*s:4.1f})") +if scored: + print(f" complete rows: {len(scored)}; holds {sum(1 for x in scored if x[1])}, loses-by->2SEM {sum(1 for x in scored if not x[1])}") + print(" (The 4 pre-registered in-scope rows are Sq-C, Pc-S, Pc-C, Pc-tip -- the rows where a critic arm") + print(" loses >=10 points from N=4 to N=128. Verdict is stated only when all four are at c>=9.)") + +print() +print("="*120) +print("(2) THE CRITIC N CURVE AT FINAL COUNTS (run 25's 28-cell top-up). `random` = the row's N=1 control.") +NS={"N=4","N=16","N=128"} +for task,short in ROWS: + a=agg(task) + fams=collections.defaultdict(dict); ctls={} + for (arm,p),v in a.items(): + if not isinstance(arm,tuple): continue + a0,a1=str(arm[0]),str(arm[1]) + if a0=="random": ctls[(a1,str(p))]=v + if a0 in ("critic (planner ctl)","critic:dino(Dq)") and a1 in NS: fams[(a0,str(p))][a1]=v + for (fam,p),row in sorted(fams.items()): + lab="pixel" if fam=="critic (planner ctl)" else "DINO " + ctl=ctls.get((fam,p)) + cs=fmt(ctl) if ctl else f"{'--':>26s}" + print(f"{short:8s} {lab} prop={p:16s} ctl {cs} | " + + " | ".join(f"N={n.split('=')[1]:>3s} {fmt(row.get(n))}" for n in ("N=4","N=16","N=128"))) + +print() +print("="*120) +print("(3) EXPECTILE LEG -- IFQL tau arms and IDQL-DINO tau arms") +for task,short in ROWS: + a=agg(task); got=[] + for (arm,p),v in a.items(): + if not isinstance(arm,tuple): continue + if ("t0" in str(arm[0])) and "N=128" in str(arm[1]): got.append((str(arm[0]),str(p),v)) + if not got: continue + print(f"-- {short} ({task})") + for a0,p,v in sorted(got): print(f" {a0:34s} prop={p:14s} {fmt(v)}") +PYEOF +echo "reads finished $(date -u +%H:%M:%SZ)" +cat $O/reads_b.txt diff --git a/rsm_rise/scripts/rr_cpu_basetopup_run27.sh b/rsm_rise/scripts/rr_cpu_basetopup_run27.sh new file mode 100644 index 0000000000000000000000000000000000000000..35eabacc776950a12b7b8be1bde68348d2504ff6 --- /dev/null +++ b/rsm_rise/scripts/rr_cpu_basetopup_run27.sh @@ -0,0 +1,172 @@ +#!/usr/bin/env bash +# BASE_TOPUP run 27: +# (1) REBUILD verdict + flagship and diff against run 26 (the run-26 report predicted the caption's +# {search} counts would drift once more as the last N-sweep cells landed; this is where that shows). +# (2) The run-26b read-out, python block copied BYTE-FOR-BYTE out of scripts/rr_cpu_basetopup_run26b.sh by +# the generator, so run 26's and run 27's numbers cannot disagree by transcription. +# (3) NEW: score the pre-registered RSM-N condition against its 4 IN-SCOPE rows by name (Sq-C, Pc-S, Pc-C, +# Pc-tip), which is the thing run 26 deliberately would not state while Pc-C and Pc-tip were filling. +set -uo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +source scripts/env.sh >/dev/null 2>&1 +O=status/basetopup/run27; mkdir -p $O +export PYTHONPATH=/proj/dmfexp/zwhong/rsm_rise/scripts:${PYTHONPATH:-} + +python3 scripts/verdict_table.py > $O/verdict_now.txt 2> $O/verdict_now.err; echo "verdict rc=$?" +python3 scripts/flagship_latex.py > $O/flag_now.txt 2> $O/flag_now.err; echo "flagship rc=$?" +diff -u status/basetopup/run26/verdict_now.txt $O/verdict_now.txt > $O/verdict.diff 2>/dev/null; echo "verdict diff lines: $(wc -l < $O/verdict.diff)" +diff -u status/basetopup/run26/flag_now.txt $O/flag_now.txt > $O/flag.diff 2>/dev/null; echo "flag diff lines: $(wc -l < $O/flag.diff)" + +echo "reads started $(date -u +%H:%M:%SZ)" +python3 - > $O/reads.txt 2>&1 <<'PYEOF' +import collections, json, math, os, re, importlib +os.environ["RSM_EXTRA_EPOCHS"] = "500" +print("RSM_EXTRA_EPOCHS =", os.environ["RSM_EXTRA_EPOCHS"], "(set explicitly, integrity item 10)") +import verdict_table as vt + +def se(n,k): + p=k/n if n else 0.0 + return 100*math.sqrt(max(p*(1-p),0)/n) if n else 0.0 +def agg(task): + out=collections.defaultdict(lambda:[0,0,0]) + for (arm,p,ps,es),v in vt.cells(task).items(): + a=out[(arm,p)]; a[0]+=len(v); a[1]+=sum(v); a[2]+=1 + return out +def fmt(v): + return f"{100*v[1]/max(v[0],1):5.1f}+-{se(v[0],v[1]):4.1f} (n={v[0]:4d},c={v[2]:2d})" if v else f"{'--':>26s}" +def rate(v): return 100*v[1]/max(v[0],1) if v else None + +ROWS = [("square_sub_20100","Sq-S"),("square_expert_play","Sq-C"), + ("two_piece_expert_suboptimal","Pc-S"),("two_piece_expert_play","Pc-C"), + ("mug_expert_suboptimal","Mug"),("threading_expert_play","Thr"), + ("two_piece_expert_play_tipping","Pc-tip")] +SHORT={t:s for t,s in ROWS} + +print("="*120) +print("(1) THE RSM N CURVE -- the mirror of the baseline curve, on the arm tab:flagship REPORTS on each row.") +print(" arm + proposer taken from status/chain/flagship_chain_arm.json (flagship_latex._best_arm's own export);") +print(" the N=4 / N=16 arms are that string with ONLY the N token changed.") +sel=json.load(open("status/chain/flagship_chain_arm.json")) +curve={} +for label, rec in sel.items(): + task, arm = rec["task"], rec["chain_arm"] + a=agg(task) + want={} + for n in (4,16,128): + want[n]=re.sub(r"\bN128\b", f"N{n}", arm) + # pick the proposer that carries the published N=128 arm (the pinned one), then read all three on it + props=[p for (ar,p) in a if isinstance(ar,tuple) and ar[0]=="rsm:membership" and ar[1]==want[128]] + if not props: + print(f"\n== {label}: published arm {arm!r} not found -- skipped"); continue + pol=max(props, key=lambda p: a[(("rsm:membership",want[128]),p)][2]) + print(f"\n== {label} ({task}) arm={arm!r} proposer={pol} exported rate={rec['chain_rate']:.1f}") + got={} + for n in (4,16,128): + v=a.get((("rsm:membership",want[n]),pol)) + got[n]=v + print(f" N={n:<4d} {fmt(v)} arm={want[n]!r}") + curve[SHORT[task]]=got + +print() +print("-- SCORING THE PREDICTION PRE-REGISTERED 2026-09-26 17:05Z (#287 section 3), complete arms only (c>=9).") +print(" Wording: on the rows where a CRITIC arm loses >=10 points from N=4 to N=128, RSM at N=128 is within") +print(" 2 SEM of, or above, its own N=4 value on >=3 of 4. FALSIFIED if RSM loses more than 2 SEM on >=2.") +scored=[] +for short,got in sorted(curve.items()): + n4,n128=got.get(4),got.get(128) + if not (n4 and n128) or n4[2]<9 or n128[2]<9: + print(f" PENDING {short:8s} N=4 c={n4[2] if n4 else 0}, N=128 c={n128[2] if n128 else 0}") + continue + r4,r128=rate(n4),rate(n128) + s=math.sqrt(se(n4[0],n4[1])**2+se(n128[0],n128[1])**2) + ok = r128 >= r4-2*s + scored.append((short,ok,r4,r128,2*s)) + print(f" {'HOLDS ' if ok else 'LOSES '} {short:8s} N=4 {r4:5.1f} -> N=128 {r128:5.1f} (delta {r128-r4:+5.1f}, 2SEM {2*s:4.1f})") +if scored: + print(f" complete rows: {len(scored)}; holds {sum(1 for x in scored if x[1])}, loses-by->2SEM {sum(1 for x in scored if not x[1])}") + print(" (The 4 pre-registered in-scope rows are Sq-C, Pc-S, Pc-C, Pc-tip -- the rows where a critic arm") + print(" loses >=10 points from N=4 to N=128. Verdict is stated only when all four are at c>=9.)") + +print() +print("="*120) +print("(2) THE CRITIC N CURVE AT FINAL COUNTS (run 25's 28-cell top-up). `random` = the row's N=1 control.") +NS={"N=4","N=16","N=128"} +for task,short in ROWS: + a=agg(task) + fams=collections.defaultdict(dict); ctls={} + for (arm,p),v in a.items(): + if not isinstance(arm,tuple): continue + a0,a1=str(arm[0]),str(arm[1]) + if a0=="random": ctls[(a1,str(p))]=v + if a0 in ("critic (planner ctl)","critic:dino(Dq)") and a1 in NS: fams[(a0,str(p))][a1]=v + for (fam,p),row in sorted(fams.items()): + lab="pixel" if fam=="critic (planner ctl)" else "DINO " + ctl=ctls.get((fam,p)) + cs=fmt(ctl) if ctl else f"{'--':>26s}" + print(f"{short:8s} {lab} prop={p:16s} ctl {cs} | " + + " | ".join(f"N={n.split('=')[1]:>3s} {fmt(row.get(n))}" for n in ("N=4","N=16","N=128"))) + +print() +print("="*120) +print("(3) EXPECTILE LEG -- IFQL tau arms and IDQL-DINO tau arms") +for task,short in ROWS: + a=agg(task); got=[] + for (arm,p),v in a.items(): + if not isinstance(arm,tuple): continue + if ("t0" in str(arm[0])) and "N=128" in str(arm[1]): got.append((str(arm[0]),str(p),v)) + if not got: continue + print(f"-- {short} ({task})") + for a0,p,v in sorted(got): print(f" {a0:34s} prop={p:14s} {fmt(v)}") +PYEOF +echo "reads finished $(date -u +%H:%M:%SZ)" +cat $O/reads.txt + +# (3) the pre-registered condition, scored against the four IN-SCOPE rows BY NAME. +python3 - > $O/inscope.txt 2>&1 <<'PY2' +import collections, json, math, os, re +os.environ["RSM_EXTRA_EPOCHS"] = "500" +import verdict_table as vt +def se(n,k): + p=k/n if n else 0.0 + return 100*math.sqrt(max(p*(1-p),0)/n) if n else 0.0 +# in-scope = the rows where a CRITIC arm loses >=10 points from N=4 to N=128 (#287 section 3, 17:05Z) +INSCOPE = {"square_expert_play":"Sq-C", "two_piece_expert_suboptimal":"Pc-S", + "two_piece_expert_play":"Pc-C", "two_piece_expert_play_tipping":"Pc-tip"} +sel = json.load(open("status/chain/flagship_chain_arm.json")) +print("PRE-REGISTERED 2026-09-26 17:05Z: on the in-scope rows, RSM at N=128 is within 2 SEM of, or above,") +print("its own N=4 value on >=3 of 4. FALSIFIED if RSM loses by more than 2 SEM on >=2 of 4.") +rows = [] +for label, rec in sel.items(): + task, arm = rec["task"], rec["chain_arm"] + if task not in INSCOPE: continue + agg = collections.defaultdict(lambda: [0,0,0]) + for (a,p,ps,es),v in vt.cells(task).items(): + x = agg[(a,p)]; x[0]+=len(v); x[1]+=sum(v); x[2]+=1 + want = {n: re.sub(r"\bN128\b", "N%d" % n, arm) for n in (4,16,128)} + props = [p for (ar,p) in agg if isinstance(ar,tuple) and ar[0]=="rsm:membership" and ar[1]==want[128]] + if not props: + print(" %-7s published arm not found -- SKIPPED" % INSCOPE[task]); continue + pol = max(props, key=lambda p: agg[(("rsm:membership",want[128]),p)][2]) + g = {n: agg.get((("rsm:membership",want[n]),pol)) for n in (4,16,128)} + n4, n128 = g[4], g[128] + if not (n4 and n128) or n4[2] < 9 or n128[2] < 9: + print(" %-7s PENDING c(N=4)=%d c(N=128)=%d" % (INSCOPE[task], n4[2] if n4 else 0, n128[2] if n128 else 0)) + rows.append((INSCOPE[task], None)); continue + r4 = 100*n4[1]/n4[0]; r128 = 100*n128[1]/n128[0] + two = 2*math.sqrt(se(n4[0],n4[1])**2 + se(n128[0],n128[1])**2) + ok = r128 >= r4 - two + rows.append((INSCOPE[task], ok)) + print(" %-7s %s N=4 %5.1f (n=%d) -> N=128 %5.1f (n=%d) delta %+5.1f 2SEM %4.1f" + % (INSCOPE[task], "HOLDS" if ok else "LOSES", r4, n4[0], r128, n128[0], r128-r4, two)) +holds = sum(1 for r in rows if r[1] is True) +loses = sum(1 for r in rows if r[1] is False) +pend = sum(1 for r in rows if r[1] is None) +print("\nin-scope rows: %d holds %d loses-by->2SEM %d pending %d" % (len(rows), holds, loses, pend)) +if holds >= 3: + print("VERDICT: CONFIRMED at full scope -- >=3 of 4 hold, so the pending row cannot change it.") +elif loses >= 2: + print("VERDICT: FALSIFIED at full scope -- >=2 of 4 lose by more than 2 SEM.") +else: + print("VERDICT: NOT YET STATEABLE -- holds %d, loses %d, %d row(s) below c=9." % (holds, loses, pend)) +PY2 +cat $O/inscope.txt diff --git a/rsm_rise/scripts/rr_cpu_basetopup_run27b.sh b/rsm_rise/scripts/rr_cpu_basetopup_run27b.sh new file mode 100644 index 0000000000000000000000000000000000000000..0fef2706bf9e5b4085bb08aeaba3a357183ced4b --- /dev/null +++ b/rsm_rise/scripts/rr_cpu_basetopup_run27b.sh @@ -0,0 +1,176 @@ +#!/usr/bin/env bash +# BASE_TOPUP run 27b: the SAME script as run 27 (generated from it by sed, only the output dir and the two +# diff baselines changed), re-run after job 1929043 closed threading to 9/9, i.e. at 218/218 cells. This is +# the FINAL state of the RSM N sweep, so the caption counts it produces are the ones that stop drifting. +# original header follows. +# BASE_TOPUP run 27: +# (1) REBUILD verdict + flagship and diff against run 26 (the run-26 report predicted the caption's +# {search} counts would drift once more as the last N-sweep cells landed; this is where that shows). +# (2) The run-26b read-out, python block copied BYTE-FOR-BYTE out of scripts/rr_cpu_basetopup_run26b.sh by +# the generator, so run 26's and run 27's numbers cannot disagree by transcription. +# (3) NEW: score the pre-registered RSM-N condition against its 4 IN-SCOPE rows by name (Sq-C, Pc-S, Pc-C, +# Pc-tip), which is the thing run 26 deliberately would not state while Pc-C and Pc-tip were filling. +set -uo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +source scripts/env.sh >/dev/null 2>&1 +O=status/basetopup/run27b; mkdir -p $O +export PYTHONPATH=/proj/dmfexp/zwhong/rsm_rise/scripts:${PYTHONPATH:-} + +python3 scripts/verdict_table.py > $O/verdict_now.txt 2> $O/verdict_now.err; echo "verdict rc=$?" +python3 scripts/flagship_latex.py > $O/flag_now.txt 2> $O/flag_now.err; echo "flagship rc=$?" +diff -u status/basetopup/run27/verdict_now.txt $O/verdict_now.txt > $O/verdict.diff 2>/dev/null; echo "verdict diff lines: $(wc -l < $O/verdict.diff)" +diff -u status/basetopup/run27/flag_now.txt $O/flag_now.txt > $O/flag.diff 2>/dev/null; echo "flag diff lines: $(wc -l < $O/flag.diff)" + +echo "reads started $(date -u +%H:%M:%SZ)" +python3 - > $O/reads.txt 2>&1 <<'PYEOF' +import collections, json, math, os, re, importlib +os.environ["RSM_EXTRA_EPOCHS"] = "500" +print("RSM_EXTRA_EPOCHS =", os.environ["RSM_EXTRA_EPOCHS"], "(set explicitly, integrity item 10)") +import verdict_table as vt + +def se(n,k): + p=k/n if n else 0.0 + return 100*math.sqrt(max(p*(1-p),0)/n) if n else 0.0 +def agg(task): + out=collections.defaultdict(lambda:[0,0,0]) + for (arm,p,ps,es),v in vt.cells(task).items(): + a=out[(arm,p)]; a[0]+=len(v); a[1]+=sum(v); a[2]+=1 + return out +def fmt(v): + return f"{100*v[1]/max(v[0],1):5.1f}+-{se(v[0],v[1]):4.1f} (n={v[0]:4d},c={v[2]:2d})" if v else f"{'--':>26s}" +def rate(v): return 100*v[1]/max(v[0],1) if v else None + +ROWS = [("square_sub_20100","Sq-S"),("square_expert_play","Sq-C"), + ("two_piece_expert_suboptimal","Pc-S"),("two_piece_expert_play","Pc-C"), + ("mug_expert_suboptimal","Mug"),("threading_expert_play","Thr"), + ("two_piece_expert_play_tipping","Pc-tip")] +SHORT={t:s for t,s in ROWS} + +print("="*120) +print("(1) THE RSM N CURVE -- the mirror of the baseline curve, on the arm tab:flagship REPORTS on each row.") +print(" arm + proposer taken from status/chain/flagship_chain_arm.json (flagship_latex._best_arm's own export);") +print(" the N=4 / N=16 arms are that string with ONLY the N token changed.") +sel=json.load(open("status/chain/flagship_chain_arm.json")) +curve={} +for label, rec in sel.items(): + task, arm = rec["task"], rec["chain_arm"] + a=agg(task) + want={} + for n in (4,16,128): + want[n]=re.sub(r"\bN128\b", f"N{n}", arm) + # pick the proposer that carries the published N=128 arm (the pinned one), then read all three on it + props=[p for (ar,p) in a if isinstance(ar,tuple) and ar[0]=="rsm:membership" and ar[1]==want[128]] + if not props: + print(f"\n== {label}: published arm {arm!r} not found -- skipped"); continue + pol=max(props, key=lambda p: a[(("rsm:membership",want[128]),p)][2]) + print(f"\n== {label} ({task}) arm={arm!r} proposer={pol} exported rate={rec['chain_rate']:.1f}") + got={} + for n in (4,16,128): + v=a.get((("rsm:membership",want[n]),pol)) + got[n]=v + print(f" N={n:<4d} {fmt(v)} arm={want[n]!r}") + curve[SHORT[task]]=got + +print() +print("-- SCORING THE PREDICTION PRE-REGISTERED 2026-09-26 17:05Z (#287 section 3), complete arms only (c>=9).") +print(" Wording: on the rows where a CRITIC arm loses >=10 points from N=4 to N=128, RSM at N=128 is within") +print(" 2 SEM of, or above, its own N=4 value on >=3 of 4. FALSIFIED if RSM loses more than 2 SEM on >=2.") +scored=[] +for short,got in sorted(curve.items()): + n4,n128=got.get(4),got.get(128) + if not (n4 and n128) or n4[2]<9 or n128[2]<9: + print(f" PENDING {short:8s} N=4 c={n4[2] if n4 else 0}, N=128 c={n128[2] if n128 else 0}") + continue + r4,r128=rate(n4),rate(n128) + s=math.sqrt(se(n4[0],n4[1])**2+se(n128[0],n128[1])**2) + ok = r128 >= r4-2*s + scored.append((short,ok,r4,r128,2*s)) + print(f" {'HOLDS ' if ok else 'LOSES '} {short:8s} N=4 {r4:5.1f} -> N=128 {r128:5.1f} (delta {r128-r4:+5.1f}, 2SEM {2*s:4.1f})") +if scored: + print(f" complete rows: {len(scored)}; holds {sum(1 for x in scored if x[1])}, loses-by->2SEM {sum(1 for x in scored if not x[1])}") + print(" (The 4 pre-registered in-scope rows are Sq-C, Pc-S, Pc-C, Pc-tip -- the rows where a critic arm") + print(" loses >=10 points from N=4 to N=128. Verdict is stated only when all four are at c>=9.)") + +print() +print("="*120) +print("(2) THE CRITIC N CURVE AT FINAL COUNTS (run 25's 28-cell top-up). `random` = the row's N=1 control.") +NS={"N=4","N=16","N=128"} +for task,short in ROWS: + a=agg(task) + fams=collections.defaultdict(dict); ctls={} + for (arm,p),v in a.items(): + if not isinstance(arm,tuple): continue + a0,a1=str(arm[0]),str(arm[1]) + if a0=="random": ctls[(a1,str(p))]=v + if a0 in ("critic (planner ctl)","critic:dino(Dq)") and a1 in NS: fams[(a0,str(p))][a1]=v + for (fam,p),row in sorted(fams.items()): + lab="pixel" if fam=="critic (planner ctl)" else "DINO " + ctl=ctls.get((fam,p)) + cs=fmt(ctl) if ctl else f"{'--':>26s}" + print(f"{short:8s} {lab} prop={p:16s} ctl {cs} | " + + " | ".join(f"N={n.split('=')[1]:>3s} {fmt(row.get(n))}" for n in ("N=4","N=16","N=128"))) + +print() +print("="*120) +print("(3) EXPECTILE LEG -- IFQL tau arms and IDQL-DINO tau arms") +for task,short in ROWS: + a=agg(task); got=[] + for (arm,p),v in a.items(): + if not isinstance(arm,tuple): continue + if ("t0" in str(arm[0])) and "N=128" in str(arm[1]): got.append((str(arm[0]),str(p),v)) + if not got: continue + print(f"-- {short} ({task})") + for a0,p,v in sorted(got): print(f" {a0:34s} prop={p:14s} {fmt(v)}") +PYEOF +echo "reads finished $(date -u +%H:%M:%SZ)" +cat $O/reads.txt + +# (3) the pre-registered condition, scored against the four IN-SCOPE rows BY NAME. +python3 - > $O/inscope.txt 2>&1 <<'PY2' +import collections, json, math, os, re +os.environ["RSM_EXTRA_EPOCHS"] = "500" +import verdict_table as vt +def se(n,k): + p=k/n if n else 0.0 + return 100*math.sqrt(max(p*(1-p),0)/n) if n else 0.0 +# in-scope = the rows where a CRITIC arm loses >=10 points from N=4 to N=128 (#287 section 3, 17:05Z) +INSCOPE = {"square_expert_play":"Sq-C", "two_piece_expert_suboptimal":"Pc-S", + "two_piece_expert_play":"Pc-C", "two_piece_expert_play_tipping":"Pc-tip"} +sel = json.load(open("status/chain/flagship_chain_arm.json")) +print("PRE-REGISTERED 2026-09-26 17:05Z: on the in-scope rows, RSM at N=128 is within 2 SEM of, or above,") +print("its own N=4 value on >=3 of 4. FALSIFIED if RSM loses by more than 2 SEM on >=2 of 4.") +rows = [] +for label, rec in sel.items(): + task, arm = rec["task"], rec["chain_arm"] + if task not in INSCOPE: continue + agg = collections.defaultdict(lambda: [0,0,0]) + for (a,p,ps,es),v in vt.cells(task).items(): + x = agg[(a,p)]; x[0]+=len(v); x[1]+=sum(v); x[2]+=1 + want = {n: re.sub(r"\bN128\b", "N%d" % n, arm) for n in (4,16,128)} + props = [p for (ar,p) in agg if isinstance(ar,tuple) and ar[0]=="rsm:membership" and ar[1]==want[128]] + if not props: + print(" %-7s published arm not found -- SKIPPED" % INSCOPE[task]); continue + pol = max(props, key=lambda p: agg[(("rsm:membership",want[128]),p)][2]) + g = {n: agg.get((("rsm:membership",want[n]),pol)) for n in (4,16,128)} + n4, n128 = g[4], g[128] + if not (n4 and n128) or n4[2] < 9 or n128[2] < 9: + print(" %-7s PENDING c(N=4)=%d c(N=128)=%d" % (INSCOPE[task], n4[2] if n4 else 0, n128[2] if n128 else 0)) + rows.append((INSCOPE[task], None)); continue + r4 = 100*n4[1]/n4[0]; r128 = 100*n128[1]/n128[0] + two = 2*math.sqrt(se(n4[0],n4[1])**2 + se(n128[0],n128[1])**2) + ok = r128 >= r4 - two + rows.append((INSCOPE[task], ok)) + print(" %-7s %s N=4 %5.1f (n=%d) -> N=128 %5.1f (n=%d) delta %+5.1f 2SEM %4.1f" + % (INSCOPE[task], "HOLDS" if ok else "LOSES", r4, n4[0], r128, n128[0], r128-r4, two)) +holds = sum(1 for r in rows if r[1] is True) +loses = sum(1 for r in rows if r[1] is False) +pend = sum(1 for r in rows if r[1] is None) +print("\nin-scope rows: %d holds %d loses-by->2SEM %d pending %d" % (len(rows), holds, loses, pend)) +if holds >= 3: + print("VERDICT: CONFIRMED at full scope -- >=3 of 4 hold, so the pending row cannot change it.") +elif loses >= 2: + print("VERDICT: FALSIFIED at full scope -- >=2 of 4 lose by more than 2 SEM.") +else: + print("VERDICT: NOT YET STATEABLE -- holds %d, loses %d, %d row(s) below c=9." % (holds, loses, pend)) +PY2 +cat $O/inscope.txt diff --git a/rsm_rise/scripts/rr_cpu_basetopup_run28.sh b/rsm_rise/scripts/rr_cpu_basetopup_run28.sh new file mode 100644 index 0000000000000000000000000000000000000000..97390745e5caf24dfefd5d2c8679dfdb9df67bc4 --- /dev/null +++ b/rsm_rise/scripts/rr_cpu_basetopup_run28.sh @@ -0,0 +1,178 @@ +#!/usr/bin/env bash +# BASE_TOPUP run 28: the SAME script as run 27b (generated from it by sed; only the output dir and the two +# diff baselines changed -- verified by `diff` before submission), re-run after run 28's tau-leg recovery: +# job 1929035's whole 4-GPU pack landed on p3-r32-n4 and lost 7 CDQ tau cells to the read_pixels SIGABRT, +# and the launcher called them "0 missing" because the DOOMED JOB STILL OWNED THEM (run 27 section 4's +# ownership trap, second sighting). 1929035 killed, p3-r32-n4 blacklisted, 8 cells relaunched as 1929285, +# 6 IFQL t0p9 cells as 1929277. This build reads whatever has landed by its start. +# BASE_TOPUP run 27: +# (1) REBUILD verdict + flagship and diff against run 26 (the run-26 report predicted the caption's +# {search} counts would drift once more as the last N-sweep cells landed; this is where that shows). +# (2) The run-26b read-out, python block copied BYTE-FOR-BYTE out of scripts/rr_cpu_basetopup_run26b.sh by +# the generator, so run 26's and run 27's numbers cannot disagree by transcription. +# (3) NEW: score the pre-registered RSM-N condition against its 4 IN-SCOPE rows by name (Sq-C, Pc-S, Pc-C, +# Pc-tip), which is the thing run 26 deliberately would not state while Pc-C and Pc-tip were filling. +set -uo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +source scripts/env.sh >/dev/null 2>&1 +O=status/basetopup/run28; mkdir -p $O +export PYTHONPATH=/proj/dmfexp/zwhong/rsm_rise/scripts:${PYTHONPATH:-} + +python3 scripts/verdict_table.py > $O/verdict_now.txt 2> $O/verdict_now.err; echo "verdict rc=$?" +python3 scripts/flagship_latex.py > $O/flag_now.txt 2> $O/flag_now.err; echo "flagship rc=$?" +diff -u status/basetopup/run27b/verdict_now.txt $O/verdict_now.txt > $O/verdict.diff 2>/dev/null; echo "verdict diff lines: $(wc -l < $O/verdict.diff)" +diff -u status/basetopup/run27b/flag_now.txt $O/flag_now.txt > $O/flag.diff 2>/dev/null; echo "flag diff lines: $(wc -l < $O/flag.diff)" + +echo "reads started $(date -u +%H:%M:%SZ)" +python3 - > $O/reads.txt 2>&1 <<'PYEOF' +import collections, json, math, os, re, importlib +os.environ["RSM_EXTRA_EPOCHS"] = "500" +print("RSM_EXTRA_EPOCHS =", os.environ["RSM_EXTRA_EPOCHS"], "(set explicitly, integrity item 10)") +import verdict_table as vt + +def se(n,k): + p=k/n if n else 0.0 + return 100*math.sqrt(max(p*(1-p),0)/n) if n else 0.0 +def agg(task): + out=collections.defaultdict(lambda:[0,0,0]) + for (arm,p,ps,es),v in vt.cells(task).items(): + a=out[(arm,p)]; a[0]+=len(v); a[1]+=sum(v); a[2]+=1 + return out +def fmt(v): + return f"{100*v[1]/max(v[0],1):5.1f}+-{se(v[0],v[1]):4.1f} (n={v[0]:4d},c={v[2]:2d})" if v else f"{'--':>26s}" +def rate(v): return 100*v[1]/max(v[0],1) if v else None + +ROWS = [("square_sub_20100","Sq-S"),("square_expert_play","Sq-C"), + ("two_piece_expert_suboptimal","Pc-S"),("two_piece_expert_play","Pc-C"), + ("mug_expert_suboptimal","Mug"),("threading_expert_play","Thr"), + ("two_piece_expert_play_tipping","Pc-tip")] +SHORT={t:s for t,s in ROWS} + +print("="*120) +print("(1) THE RSM N CURVE -- the mirror of the baseline curve, on the arm tab:flagship REPORTS on each row.") +print(" arm + proposer taken from status/chain/flagship_chain_arm.json (flagship_latex._best_arm's own export);") +print(" the N=4 / N=16 arms are that string with ONLY the N token changed.") +sel=json.load(open("status/chain/flagship_chain_arm.json")) +curve={} +for label, rec in sel.items(): + task, arm = rec["task"], rec["chain_arm"] + a=agg(task) + want={} + for n in (4,16,128): + want[n]=re.sub(r"\bN128\b", f"N{n}", arm) + # pick the proposer that carries the published N=128 arm (the pinned one), then read all three on it + props=[p for (ar,p) in a if isinstance(ar,tuple) and ar[0]=="rsm:membership" and ar[1]==want[128]] + if not props: + print(f"\n== {label}: published arm {arm!r} not found -- skipped"); continue + pol=max(props, key=lambda p: a[(("rsm:membership",want[128]),p)][2]) + print(f"\n== {label} ({task}) arm={arm!r} proposer={pol} exported rate={rec['chain_rate']:.1f}") + got={} + for n in (4,16,128): + v=a.get((("rsm:membership",want[n]),pol)) + got[n]=v + print(f" N={n:<4d} {fmt(v)} arm={want[n]!r}") + curve[SHORT[task]]=got + +print() +print("-- SCORING THE PREDICTION PRE-REGISTERED 2026-09-26 17:05Z (#287 section 3), complete arms only (c>=9).") +print(" Wording: on the rows where a CRITIC arm loses >=10 points from N=4 to N=128, RSM at N=128 is within") +print(" 2 SEM of, or above, its own N=4 value on >=3 of 4. FALSIFIED if RSM loses more than 2 SEM on >=2.") +scored=[] +for short,got in sorted(curve.items()): + n4,n128=got.get(4),got.get(128) + if not (n4 and n128) or n4[2]<9 or n128[2]<9: + print(f" PENDING {short:8s} N=4 c={n4[2] if n4 else 0}, N=128 c={n128[2] if n128 else 0}") + continue + r4,r128=rate(n4),rate(n128) + s=math.sqrt(se(n4[0],n4[1])**2+se(n128[0],n128[1])**2) + ok = r128 >= r4-2*s + scored.append((short,ok,r4,r128,2*s)) + print(f" {'HOLDS ' if ok else 'LOSES '} {short:8s} N=4 {r4:5.1f} -> N=128 {r128:5.1f} (delta {r128-r4:+5.1f}, 2SEM {2*s:4.1f})") +if scored: + print(f" complete rows: {len(scored)}; holds {sum(1 for x in scored if x[1])}, loses-by->2SEM {sum(1 for x in scored if not x[1])}") + print(" (The 4 pre-registered in-scope rows are Sq-C, Pc-S, Pc-C, Pc-tip -- the rows where a critic arm") + print(" loses >=10 points from N=4 to N=128. Verdict is stated only when all four are at c>=9.)") + +print() +print("="*120) +print("(2) THE CRITIC N CURVE AT FINAL COUNTS (run 25's 28-cell top-up). `random` = the row's N=1 control.") +NS={"N=4","N=16","N=128"} +for task,short in ROWS: + a=agg(task) + fams=collections.defaultdict(dict); ctls={} + for (arm,p),v in a.items(): + if not isinstance(arm,tuple): continue + a0,a1=str(arm[0]),str(arm[1]) + if a0=="random": ctls[(a1,str(p))]=v + if a0 in ("critic (planner ctl)","critic:dino(Dq)") and a1 in NS: fams[(a0,str(p))][a1]=v + for (fam,p),row in sorted(fams.items()): + lab="pixel" if fam=="critic (planner ctl)" else "DINO " + ctl=ctls.get((fam,p)) + cs=fmt(ctl) if ctl else f"{'--':>26s}" + print(f"{short:8s} {lab} prop={p:16s} ctl {cs} | " + + " | ".join(f"N={n.split('=')[1]:>3s} {fmt(row.get(n))}" for n in ("N=4","N=16","N=128"))) + +print() +print("="*120) +print("(3) EXPECTILE LEG -- IFQL tau arms and IDQL-DINO tau arms") +for task,short in ROWS: + a=agg(task); got=[] + for (arm,p),v in a.items(): + if not isinstance(arm,tuple): continue + if ("t0" in str(arm[0])) and "N=128" in str(arm[1]): got.append((str(arm[0]),str(p),v)) + if not got: continue + print(f"-- {short} ({task})") + for a0,p,v in sorted(got): print(f" {a0:34s} prop={p:14s} {fmt(v)}") +PYEOF +echo "reads finished $(date -u +%H:%M:%SZ)" +cat $O/reads.txt + +# (3) the pre-registered condition, scored against the four IN-SCOPE rows BY NAME. +python3 - > $O/inscope.txt 2>&1 <<'PY2' +import collections, json, math, os, re +os.environ["RSM_EXTRA_EPOCHS"] = "500" +import verdict_table as vt +def se(n,k): + p=k/n if n else 0.0 + return 100*math.sqrt(max(p*(1-p),0)/n) if n else 0.0 +# in-scope = the rows where a CRITIC arm loses >=10 points from N=4 to N=128 (#287 section 3, 17:05Z) +INSCOPE = {"square_expert_play":"Sq-C", "two_piece_expert_suboptimal":"Pc-S", + "two_piece_expert_play":"Pc-C", "two_piece_expert_play_tipping":"Pc-tip"} +sel = json.load(open("status/chain/flagship_chain_arm.json")) +print("PRE-REGISTERED 2026-09-26 17:05Z: on the in-scope rows, RSM at N=128 is within 2 SEM of, or above,") +print("its own N=4 value on >=3 of 4. FALSIFIED if RSM loses by more than 2 SEM on >=2 of 4.") +rows = [] +for label, rec in sel.items(): + task, arm = rec["task"], rec["chain_arm"] + if task not in INSCOPE: continue + agg = collections.defaultdict(lambda: [0,0,0]) + for (a,p,ps,es),v in vt.cells(task).items(): + x = agg[(a,p)]; x[0]+=len(v); x[1]+=sum(v); x[2]+=1 + want = {n: re.sub(r"\bN128\b", "N%d" % n, arm) for n in (4,16,128)} + props = [p for (ar,p) in agg if isinstance(ar,tuple) and ar[0]=="rsm:membership" and ar[1]==want[128]] + if not props: + print(" %-7s published arm not found -- SKIPPED" % INSCOPE[task]); continue + pol = max(props, key=lambda p: agg[(("rsm:membership",want[128]),p)][2]) + g = {n: agg.get((("rsm:membership",want[n]),pol)) for n in (4,16,128)} + n4, n128 = g[4], g[128] + if not (n4 and n128) or n4[2] < 9 or n128[2] < 9: + print(" %-7s PENDING c(N=4)=%d c(N=128)=%d" % (INSCOPE[task], n4[2] if n4 else 0, n128[2] if n128 else 0)) + rows.append((INSCOPE[task], None)); continue + r4 = 100*n4[1]/n4[0]; r128 = 100*n128[1]/n128[0] + two = 2*math.sqrt(se(n4[0],n4[1])**2 + se(n128[0],n128[1])**2) + ok = r128 >= r4 - two + rows.append((INSCOPE[task], ok)) + print(" %-7s %s N=4 %5.1f (n=%d) -> N=128 %5.1f (n=%d) delta %+5.1f 2SEM %4.1f" + % (INSCOPE[task], "HOLDS" if ok else "LOSES", r4, n4[0], r128, n128[0], r128-r4, two)) +holds = sum(1 for r in rows if r[1] is True) +loses = sum(1 for r in rows if r[1] is False) +pend = sum(1 for r in rows if r[1] is None) +print("\nin-scope rows: %d holds %d loses-by->2SEM %d pending %d" % (len(rows), holds, loses, pend)) +if holds >= 3: + print("VERDICT: CONFIRMED at full scope -- >=3 of 4 hold, so the pending row cannot change it.") +elif loses >= 2: + print("VERDICT: FALSIFIED at full scope -- >=2 of 4 lose by more than 2 SEM.") +else: + print("VERDICT: NOT YET STATEABLE -- holds %d, loses %d, %d row(s) below c=9." % (holds, loses, pend)) +PY2 +cat $O/inscope.txt diff --git a/rsm_rise/scripts/rr_cpu_basetopup_run29.sh b/rsm_rise/scripts/rr_cpu_basetopup_run29.sh new file mode 100644 index 0000000000000000000000000000000000000000..1a15dbc93ae9088e475cb49f229554950ef50a46 --- /dev/null +++ b/rsm_rise/scripts/rr_cpu_basetopup_run29.sh @@ -0,0 +1,229 @@ +#!/usr/bin/env bash +# BASE_TOPUP run 28: the SAME script as run 27b (generated from it by sed; only the output dir and the two +# diff baselines changed -- verified by `diff` before submission), re-run after run 28's tau-leg recovery: +# job 1929035's whole 4-GPU pack landed on p3-r32-n4 and lost 7 CDQ tau cells to the read_pixels SIGABRT, +# and the launcher called them "0 missing" because the DOOMED JOB STILL OWNED THEM (run 27 section 4's +# ownership trap, second sighting). 1929035 killed, p3-r32-n4 blacklisted, 8 cells relaunched as 1929285, +# 6 IFQL t0p9 cells as 1929277. This build reads whatever has landed by its start. +# BASE_TOPUP run 27: +# (1) REBUILD verdict + flagship and diff against run 26 (the run-26 report predicted the caption's +# {search} counts would drift once more as the last N-sweep cells landed; this is where that shows). +# (2) The run-26b read-out, python block copied BYTE-FOR-BYTE out of scripts/rr_cpu_basetopup_run26b.sh by +# the generator, so run 26's and run 27's numbers cannot disagree by transcription. +# (3) NEW: score the pre-registered RSM-N condition against its 4 IN-SCOPE rows by name (Sq-C, Pc-S, Pc-C, +# Pc-tip), which is the thing run 26 deliberately would not state while Pc-C and Pc-tip were filling. +set -uo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +source scripts/env.sh >/dev/null 2>&1 +O=status/basetopup/run29; mkdir -p $O +export PYTHONPATH=/proj/dmfexp/zwhong/rsm_rise/scripts:${PYTHONPATH:-} + +python3 scripts/verdict_table.py > $O/verdict_now.txt 2> $O/verdict_now.err; echo "verdict rc=$?" +python3 scripts/flagship_latex.py > $O/flag_now.txt 2> $O/flag_now.err; echo "flagship rc=$?" +diff -u status/basetopup/run28/verdict_now.txt $O/verdict_now.txt > $O/verdict.diff 2>/dev/null; echo "verdict diff lines: $(wc -l < $O/verdict.diff)" +diff -u status/basetopup/run28/flag_now.txt $O/flag_now.txt > $O/flag.diff 2>/dev/null; echo "flag diff lines: $(wc -l < $O/flag.diff)" + +echo "reads started $(date -u +%H:%M:%SZ)" +python3 - > $O/reads.txt 2>&1 <<'PYEOF' +import collections, json, math, os, re, importlib +os.environ["RSM_EXTRA_EPOCHS"] = "500" +print("RSM_EXTRA_EPOCHS =", os.environ["RSM_EXTRA_EPOCHS"], "(set explicitly, integrity item 10)") +import verdict_table as vt + +def se(n,k): + p=k/n if n else 0.0 + return 100*math.sqrt(max(p*(1-p),0)/n) if n else 0.0 +def agg(task): + out=collections.defaultdict(lambda:[0,0,0]) + for (arm,p,ps,es),v in vt.cells(task).items(): + a=out[(arm,p)]; a[0]+=len(v); a[1]+=sum(v); a[2]+=1 + return out +def fmt(v): + return f"{100*v[1]/max(v[0],1):5.1f}+-{se(v[0],v[1]):4.1f} (n={v[0]:4d},c={v[2]:2d})" if v else f"{'--':>26s}" +def rate(v): return 100*v[1]/max(v[0],1) if v else None + +ROWS = [("square_sub_20100","Sq-S"),("square_expert_play","Sq-C"), + ("two_piece_expert_suboptimal","Pc-S"),("two_piece_expert_play","Pc-C"), + ("mug_expert_suboptimal","Mug"),("threading_expert_play","Thr"), + ("two_piece_expert_play_tipping","Pc-tip")] +SHORT={t:s for t,s in ROWS} + +print("="*120) +print("(1) THE RSM N CURVE -- the mirror of the baseline curve, on the arm tab:flagship REPORTS on each row.") +print(" arm + proposer taken from status/chain/flagship_chain_arm.json (flagship_latex._best_arm's own export);") +print(" the N=4 / N=16 arms are that string with ONLY the N token changed.") +sel=json.load(open("status/chain/flagship_chain_arm.json")) +curve={} +for label, rec in sel.items(): + task, arm = rec["task"], rec["chain_arm"] + a=agg(task) + want={} + for n in (4,16,128): + want[n]=re.sub(r"\bN128\b", f"N{n}", arm) + # pick the proposer that carries the published N=128 arm (the pinned one), then read all three on it + props=[p for (ar,p) in a if isinstance(ar,tuple) and ar[0]=="rsm:membership" and ar[1]==want[128]] + if not props: + print(f"\n== {label}: published arm {arm!r} not found -- skipped"); continue + pol=max(props, key=lambda p: a[(("rsm:membership",want[128]),p)][2]) + print(f"\n== {label} ({task}) arm={arm!r} proposer={pol} exported rate={rec['chain_rate']:.1f}") + got={} + for n in (4,16,128): + v=a.get((("rsm:membership",want[n]),pol)) + got[n]=v + print(f" N={n:<4d} {fmt(v)} arm={want[n]!r}") + curve[SHORT[task]]=got + +print() +print("-- SCORING THE PREDICTION PRE-REGISTERED 2026-09-26 17:05Z (#287 section 3), complete arms only (c>=9).") +print(" Wording: on the rows where a CRITIC arm loses >=10 points from N=4 to N=128, RSM at N=128 is within") +print(" 2 SEM of, or above, its own N=4 value on >=3 of 4. FALSIFIED if RSM loses more than 2 SEM on >=2.") +scored=[] +for short,got in sorted(curve.items()): + n4,n128=got.get(4),got.get(128) + if not (n4 and n128) or n4[2]<9 or n128[2]<9: + print(f" PENDING {short:8s} N=4 c={n4[2] if n4 else 0}, N=128 c={n128[2] if n128 else 0}") + continue + r4,r128=rate(n4),rate(n128) + s=math.sqrt(se(n4[0],n4[1])**2+se(n128[0],n128[1])**2) + ok = r128 >= r4-2*s + scored.append((short,ok,r4,r128,2*s)) + print(f" {'HOLDS ' if ok else 'LOSES '} {short:8s} N=4 {r4:5.1f} -> N=128 {r128:5.1f} (delta {r128-r4:+5.1f}, 2SEM {2*s:4.1f})") +if scored: + print(f" complete rows: {len(scored)}; holds {sum(1 for x in scored if x[1])}, loses-by->2SEM {sum(1 for x in scored if not x[1])}") + print(" (The 4 pre-registered in-scope rows are Sq-C, Pc-S, Pc-C, Pc-tip -- the rows where a critic arm") + print(" loses >=10 points from N=4 to N=128. Verdict is stated only when all four are at c>=9.)") + +print() +print("="*120) +print("(2) THE CRITIC N CURVE AT FINAL COUNTS (run 25's 28-cell top-up). `random` = the row's N=1 control.") +NS={"N=4","N=16","N=128"} +for task,short in ROWS: + a=agg(task) + fams=collections.defaultdict(dict); ctls={} + for (arm,p),v in a.items(): + if not isinstance(arm,tuple): continue + a0,a1=str(arm[0]),str(arm[1]) + if a0=="random": ctls[(a1,str(p))]=v + if a0 in ("critic (planner ctl)","critic:dino(Dq)") and a1 in NS: fams[(a0,str(p))][a1]=v + for (fam,p),row in sorted(fams.items()): + lab="pixel" if fam=="critic (planner ctl)" else "DINO " + ctl=ctls.get((fam,p)) + cs=fmt(ctl) if ctl else f"{'--':>26s}" + print(f"{short:8s} {lab} prop={p:16s} ctl {cs} | " + + " | ".join(f"N={n.split('=')[1]:>3s} {fmt(row.get(n))}" for n in ("N=4","N=16","N=128"))) + +print() +print("="*120) +print("(3) EXPECTILE LEG -- IFQL tau arms and IDQL-DINO tau arms") +for task,short in ROWS: + a=agg(task); got=[] + for (arm,p),v in a.items(): + if not isinstance(arm,tuple): continue + if ("t0" in str(arm[0])) and "N=128" in str(arm[1]): got.append((str(arm[0]),str(p),v)) + if not got: continue + print(f"-- {short} ({task})") + for a0,p,v in sorted(got): print(f" {a0:34s} prop={p:14s} {fmt(v)}") +PYEOF +echo "reads finished $(date -u +%H:%M:%SZ)" +cat $O/reads.txt + +# (3) the pre-registered condition, scored against the four IN-SCOPE rows BY NAME. +python3 - > $O/inscope.txt 2>&1 <<'PY2' +import collections, json, math, os, re +os.environ["RSM_EXTRA_EPOCHS"] = "500" +import verdict_table as vt +def se(n,k): + p=k/n if n else 0.0 + return 100*math.sqrt(max(p*(1-p),0)/n) if n else 0.0 +# in-scope = the rows where a CRITIC arm loses >=10 points from N=4 to N=128 (#287 section 3, 17:05Z) +INSCOPE = {"square_expert_play":"Sq-C", "two_piece_expert_suboptimal":"Pc-S", + "two_piece_expert_play":"Pc-C", "two_piece_expert_play_tipping":"Pc-tip"} +sel = json.load(open("status/chain/flagship_chain_arm.json")) +print("PRE-REGISTERED 2026-09-26 17:05Z: on the in-scope rows, RSM at N=128 is within 2 SEM of, or above,") +print("its own N=4 value on >=3 of 4. FALSIFIED if RSM loses by more than 2 SEM on >=2 of 4.") +rows = [] +for label, rec in sel.items(): + task, arm = rec["task"], rec["chain_arm"] + if task not in INSCOPE: continue + agg = collections.defaultdict(lambda: [0,0,0]) + for (a,p,ps,es),v in vt.cells(task).items(): + x = agg[(a,p)]; x[0]+=len(v); x[1]+=sum(v); x[2]+=1 + want = {n: re.sub(r"\bN128\b", "N%d" % n, arm) for n in (4,16,128)} + props = [p for (ar,p) in agg if isinstance(ar,tuple) and ar[0]=="rsm:membership" and ar[1]==want[128]] + if not props: + print(" %-7s published arm not found -- SKIPPED" % INSCOPE[task]); continue + pol = max(props, key=lambda p: agg[(("rsm:membership",want[128]),p)][2]) + g = {n: agg.get((("rsm:membership",want[n]),pol)) for n in (4,16,128)} + n4, n128 = g[4], g[128] + if not (n4 and n128) or n4[2] < 9 or n128[2] < 9: + print(" %-7s PENDING c(N=4)=%d c(N=128)=%d" % (INSCOPE[task], n4[2] if n4 else 0, n128[2] if n128 else 0)) + rows.append((INSCOPE[task], None)); continue + r4 = 100*n4[1]/n4[0]; r128 = 100*n128[1]/n128[0] + two = 2*math.sqrt(se(n4[0],n4[1])**2 + se(n128[0],n128[1])**2) + ok = r128 >= r4 - two + rows.append((INSCOPE[task], ok)) + print(" %-7s %s N=4 %5.1f (n=%d) -> N=128 %5.1f (n=%d) delta %+5.1f 2SEM %4.1f" + % (INSCOPE[task], "HOLDS" if ok else "LOSES", r4, n4[0], r128, n128[0], r128-r4, two)) +holds = sum(1 for r in rows if r[1] is True) +loses = sum(1 for r in rows if r[1] is False) +pend = sum(1 for r in rows if r[1] is None) +print("\nin-scope rows: %d holds %d loses-by->2SEM %d pending %d" % (len(rows), holds, loses, pend)) +if holds >= 3: + print("VERDICT: CONFIRMED at full scope -- >=3 of 4 hold, so the pending row cannot change it.") +elif loses >= 2: + print("VERDICT: FALSIFIED at full scope -- >=2 of 4 lose by more than 2 SEM.") +else: + print("VERDICT: NOT YET STATEABLE -- holds %d, loses %d, %d row(s) below c=9." % (holds, loses, pend)) +PY2 +cat $O/inscope.txt + +# --------------------------------------------------------------------------------------------------- +# run 29 ADDITION -- DELIVERABLE 2 COMPLETENESS AUDIT (#287): "every task has COMPLETE 3x3 `mpcd` arms +# across the H grid for DINO-WM, LeWM and DF" (owner, 2026-09-25 ~20:55 UTC). This has never been read +# out as a single table; runs 22-28 were spent on the tau/gamma legs and on the N sweep. It reports the +# CELL COUNT c per (task, family, H, M) for mpcd arms only -- 9 = a complete 3x3 -- so the top-up list is +# the set of (task, family, H) below 9. It uses verdict_table's own loader and the same "mpcd in the +# recipe tokens" test flagship_latex._wm_arm_is applies, so it cannot disagree with the published column. +python3 - > $O/d2_mpcd_completeness.txt 2>&1 <<'PY3' +import collections, os, re +os.environ["RSM_EXTRA_EPOCHS"] = "500" +import verdict_table as vt +ROWS = [("square_sub_20100","Sq-S"),("square_expert_play","Sq-C"), + ("two_piece_expert_suboptimal","Pc-S"),("two_piece_expert_play","Pc-C"), + ("mug_expert_suboptimal","Mug"),("threading_expert_play","Thr"), + ("two_piece_expert_play_tipping","Pc-tip")] +FAMS = ("wm:dinowm","wm:lewm","wm:df") +print("DELIVERABLE 2 -- completeness of the `mpcd` (discounted-sum) world-model arms, 3x3 = 9 cells.") +print("c = number of (proposer-seed x eval-seed) cells that have landed; n = episodes.") +print("An arm is `mpcd` iff its recipe starts with H and has the token 'mpcd' -- flagship_latex._wm_arm_is.\n") +grand = collections.defaultdict(lambda: collections.defaultdict(lambda: [0,0,0])) +for task, short in ROWS: + a = collections.defaultdict(lambda: [0,0,0]) + for (arm,p,ps,es),v in vt.cells(task).items(): + if not isinstance(arm, tuple): continue + fam, rec = str(arm[0]), str(arm[1]) + if fam not in FAMS: continue + if not (rec[:1]=="H" and "mpcd" in rec.split()): continue + H = rec.split()[0][1:] + M = "M1" + m = re.search(r"M(\d+)", rec) + if m: M = "M"+m.group(1) + x = a[(fam,H,M)]; x[0]+=len(v); x[1]+=sum(v); x[2]+=1 + g = grand[(fam,H,M)]; g[0]+=len(v); g[1]+=sum(v); g[2]+=1 + print("== %-7s (%s)" % (short, task)) + if not a: + print(" (no mpcd arms at all)") + continue + for (fam,H,M) in sorted(a, key=lambda k:(k[0], int(k[1]), k[2])): + v = a[(fam,H,M)] + flag = "" if v[2]>=9 else (" <-- INCOMPLETE (%d/9)" % v[2]) + print(" %-11s H=%-4s %-5s c=%2d n=%4d rate=%5.1f%s" % + (fam, H, M, v[2], v[0], 100*v[1]/max(v[0],1), flag)) + print() +print("="*100) +print("ROLLED UP OVER THE 7 TASKS (a complete (family,H,M) leg = 63 cells = 7 tasks x 9):") +for (fam,H,M) in sorted(grand, key=lambda k:(k[0], int(k[1]), k[2])): + v = grand[(fam,H,M)] + print(" %-11s H=%-4s %-5s cells=%2d/63 %s" % (fam,H,M,v[2], "COMPLETE" if v[2]>=63 else "")) +PY3 +cat $O/d2_mpcd_completeness.txt diff --git a/rsm_rise/scripts/rr_cpu_basetopup_run30.sh b/rsm_rise/scripts/rr_cpu_basetopup_run30.sh new file mode 100644 index 0000000000000000000000000000000000000000..f69bebcae15b10e9b81273b9fdf6d2f63b5ca334 --- /dev/null +++ b/rsm_rise/scripts/rr_cpu_basetopup_run30.sh @@ -0,0 +1,273 @@ +#!/usr/bin/env bash +# BASE_TOPUP run 28: the SAME script as run 27b (generated from it by sed; only the output dir and the two +# diff baselines changed -- verified by `diff` before submission), re-run after run 28's tau-leg recovery: +# job 1929035's whole 4-GPU pack landed on p3-r32-n4 and lost 7 CDQ tau cells to the read_pixels SIGABRT, +# and the launcher called them "0 missing" because the DOOMED JOB STILL OWNED THEM (run 27 section 4's +# ownership trap, second sighting). 1929035 killed, p3-r32-n4 blacklisted, 8 cells relaunched as 1929285, +# 6 IFQL t0p9 cells as 1929277. This build reads whatever has landed by its start. +# BASE_TOPUP run 27: +# (1) REBUILD verdict + flagship and diff against run 26 (the run-26 report predicted the caption's +# {search} counts would drift once more as the last N-sweep cells landed; this is where that shows). +# (2) The run-26b read-out, python block copied BYTE-FOR-BYTE out of scripts/rr_cpu_basetopup_run26b.sh by +# the generator, so run 26's and run 27's numbers cannot disagree by transcription. +# (3) NEW: score the pre-registered RSM-N condition against its 4 IN-SCOPE rows by name (Sq-C, Pc-S, Pc-C, +# Pc-tip), which is the thing run 26 deliberately would not state while Pc-C and Pc-tip were filling. +set -uo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +source scripts/env.sh >/dev/null 2>&1 +O=status/basetopup/run30; mkdir -p $O +export PYTHONPATH=/proj/dmfexp/zwhong/rsm_rise/scripts:${PYTHONPATH:-} + +python3 scripts/verdict_table.py > $O/verdict_now.txt 2> $O/verdict_now.err; echo "verdict rc=$?" +python3 scripts/flagship_latex.py > $O/flag_now.txt 2> $O/flag_now.err; echo "flagship rc=$?" +diff -u status/basetopup/run29/verdict_now.txt $O/verdict_now.txt > $O/verdict.diff 2>/dev/null; echo "verdict diff lines: $(wc -l < $O/verdict.diff)" +diff -u status/basetopup/run29/flag_now.txt $O/flag_now.txt > $O/flag.diff 2>/dev/null; echo "flag diff lines: $(wc -l < $O/flag.diff)" + +echo "reads started $(date -u +%H:%M:%SZ)" +python3 - > $O/reads.txt 2>&1 <<'PYEOF' +import collections, json, math, os, re, importlib +os.environ["RSM_EXTRA_EPOCHS"] = "500" +print("RSM_EXTRA_EPOCHS =", os.environ["RSM_EXTRA_EPOCHS"], "(set explicitly, integrity item 10)") +import verdict_table as vt + +def se(n,k): + p=k/n if n else 0.0 + return 100*math.sqrt(max(p*(1-p),0)/n) if n else 0.0 +def agg(task): + out=collections.defaultdict(lambda:[0,0,0]) + for (arm,p,ps,es),v in vt.cells(task).items(): + a=out[(arm,p)]; a[0]+=len(v); a[1]+=sum(v); a[2]+=1 + return out +def fmt(v): + return f"{100*v[1]/max(v[0],1):5.1f}+-{se(v[0],v[1]):4.1f} (n={v[0]:4d},c={v[2]:2d})" if v else f"{'--':>26s}" +def rate(v): return 100*v[1]/max(v[0],1) if v else None + +ROWS = [("square_sub_20100","Sq-S"),("square_expert_play","Sq-C"), + ("two_piece_expert_suboptimal","Pc-S"),("two_piece_expert_play","Pc-C"), + ("mug_expert_suboptimal","Mug"),("threading_expert_play","Thr"), + ("two_piece_expert_play_tipping","Pc-tip")] +SHORT={t:s for t,s in ROWS} + +print("="*120) +print("(1) THE RSM N CURVE -- the mirror of the baseline curve, on the arm tab:flagship REPORTS on each row.") +print(" arm + proposer taken from status/chain/flagship_chain_arm.json (flagship_latex._best_arm's own export);") +print(" the N=4 / N=16 arms are that string with ONLY the N token changed.") +sel=json.load(open("status/chain/flagship_chain_arm.json")) +curve={} +for label, rec in sel.items(): + task, arm = rec["task"], rec["chain_arm"] + a=agg(task) + want={} + for n in (4,16,128): + want[n]=re.sub(r"\bN128\b", f"N{n}", arm) + # pick the proposer that carries the published N=128 arm (the pinned one), then read all three on it + props=[p for (ar,p) in a if isinstance(ar,tuple) and ar[0]=="rsm:membership" and ar[1]==want[128]] + if not props: + print(f"\n== {label}: published arm {arm!r} not found -- skipped"); continue + pol=max(props, key=lambda p: a[(("rsm:membership",want[128]),p)][2]) + print(f"\n== {label} ({task}) arm={arm!r} proposer={pol} exported rate={rec['chain_rate']:.1f}") + got={} + for n in (4,16,128): + v=a.get((("rsm:membership",want[n]),pol)) + got[n]=v + print(f" N={n:<4d} {fmt(v)} arm={want[n]!r}") + curve[SHORT[task]]=got + +print() +print("-- SCORING THE PREDICTION PRE-REGISTERED 2026-09-26 17:05Z (#287 section 3), complete arms only (c>=9).") +print(" Wording: on the rows where a CRITIC arm loses >=10 points from N=4 to N=128, RSM at N=128 is within") +print(" 2 SEM of, or above, its own N=4 value on >=3 of 4. FALSIFIED if RSM loses more than 2 SEM on >=2.") +scored=[] +for short,got in sorted(curve.items()): + n4,n128=got.get(4),got.get(128) + if not (n4 and n128) or n4[2]<9 or n128[2]<9: + print(f" PENDING {short:8s} N=4 c={n4[2] if n4 else 0}, N=128 c={n128[2] if n128 else 0}") + continue + r4,r128=rate(n4),rate(n128) + s=math.sqrt(se(n4[0],n4[1])**2+se(n128[0],n128[1])**2) + ok = r128 >= r4-2*s + scored.append((short,ok,r4,r128,2*s)) + print(f" {'HOLDS ' if ok else 'LOSES '} {short:8s} N=4 {r4:5.1f} -> N=128 {r128:5.1f} (delta {r128-r4:+5.1f}, 2SEM {2*s:4.1f})") +if scored: + print(f" complete rows: {len(scored)}; holds {sum(1 for x in scored if x[1])}, loses-by->2SEM {sum(1 for x in scored if not x[1])}") + print(" (The 4 pre-registered in-scope rows are Sq-C, Pc-S, Pc-C, Pc-tip -- the rows where a critic arm") + print(" loses >=10 points from N=4 to N=128. Verdict is stated only when all four are at c>=9.)") + +print() +print("="*120) +print("(2) THE CRITIC N CURVE AT FINAL COUNTS (run 25's 28-cell top-up). `random` = the row's N=1 control.") +NS={"N=4","N=16","N=128"} +for task,short in ROWS: + a=agg(task) + fams=collections.defaultdict(dict); ctls={} + for (arm,p),v in a.items(): + if not isinstance(arm,tuple): continue + a0,a1=str(arm[0]),str(arm[1]) + if a0=="random": ctls[(a1,str(p))]=v + if a0 in ("critic (planner ctl)","critic:dino(Dq)") and a1 in NS: fams[(a0,str(p))][a1]=v + for (fam,p),row in sorted(fams.items()): + lab="pixel" if fam=="critic (planner ctl)" else "DINO " + ctl=ctls.get((fam,p)) + cs=fmt(ctl) if ctl else f"{'--':>26s}" + print(f"{short:8s} {lab} prop={p:16s} ctl {cs} | " + + " | ".join(f"N={n.split('=')[1]:>3s} {fmt(row.get(n))}" for n in ("N=4","N=16","N=128"))) + +print() +print("="*120) +print("(3) EXPECTILE LEG -- IFQL tau arms and IDQL-DINO tau arms") +for task,short in ROWS: + a=agg(task); got=[] + for (arm,p),v in a.items(): + if not isinstance(arm,tuple): continue + if ("t0" in str(arm[0])) and "N=128" in str(arm[1]): got.append((str(arm[0]),str(p),v)) + if not got: continue + print(f"-- {short} ({task})") + for a0,p,v in sorted(got): print(f" {a0:34s} prop={p:14s} {fmt(v)}") +PYEOF +echo "reads finished $(date -u +%H:%M:%SZ)" +cat $O/reads.txt + +# (3) the pre-registered condition, scored against the four IN-SCOPE rows BY NAME. +python3 - > $O/inscope.txt 2>&1 <<'PY2' +import collections, json, math, os, re +os.environ["RSM_EXTRA_EPOCHS"] = "500" +import verdict_table as vt +def se(n,k): + p=k/n if n else 0.0 + return 100*math.sqrt(max(p*(1-p),0)/n) if n else 0.0 +# in-scope = the rows where a CRITIC arm loses >=10 points from N=4 to N=128 (#287 section 3, 17:05Z) +INSCOPE = {"square_expert_play":"Sq-C", "two_piece_expert_suboptimal":"Pc-S", + "two_piece_expert_play":"Pc-C", "two_piece_expert_play_tipping":"Pc-tip"} +sel = json.load(open("status/chain/flagship_chain_arm.json")) +print("PRE-REGISTERED 2026-09-26 17:05Z: on the in-scope rows, RSM at N=128 is within 2 SEM of, or above,") +print("its own N=4 value on >=3 of 4. FALSIFIED if RSM loses by more than 2 SEM on >=2 of 4.") +rows = [] +for label, rec in sel.items(): + task, arm = rec["task"], rec["chain_arm"] + if task not in INSCOPE: continue + agg = collections.defaultdict(lambda: [0,0,0]) + for (a,p,ps,es),v in vt.cells(task).items(): + x = agg[(a,p)]; x[0]+=len(v); x[1]+=sum(v); x[2]+=1 + want = {n: re.sub(r"\bN128\b", "N%d" % n, arm) for n in (4,16,128)} + props = [p for (ar,p) in agg if isinstance(ar,tuple) and ar[0]=="rsm:membership" and ar[1]==want[128]] + if not props: + print(" %-7s published arm not found -- SKIPPED" % INSCOPE[task]); continue + pol = max(props, key=lambda p: agg[(("rsm:membership",want[128]),p)][2]) + g = {n: agg.get((("rsm:membership",want[n]),pol)) for n in (4,16,128)} + n4, n128 = g[4], g[128] + if not (n4 and n128) or n4[2] < 9 or n128[2] < 9: + print(" %-7s PENDING c(N=4)=%d c(N=128)=%d" % (INSCOPE[task], n4[2] if n4 else 0, n128[2] if n128 else 0)) + rows.append((INSCOPE[task], None)); continue + r4 = 100*n4[1]/n4[0]; r128 = 100*n128[1]/n128[0] + two = 2*math.sqrt(se(n4[0],n4[1])**2 + se(n128[0],n128[1])**2) + ok = r128 >= r4 - two + rows.append((INSCOPE[task], ok)) + print(" %-7s %s N=4 %5.1f (n=%d) -> N=128 %5.1f (n=%d) delta %+5.1f 2SEM %4.1f" + % (INSCOPE[task], "HOLDS" if ok else "LOSES", r4, n4[0], r128, n128[0], r128-r4, two)) +holds = sum(1 for r in rows if r[1] is True) +loses = sum(1 for r in rows if r[1] is False) +pend = sum(1 for r in rows if r[1] is None) +print("\nin-scope rows: %d holds %d loses-by->2SEM %d pending %d" % (len(rows), holds, loses, pend)) +if holds >= 3: + print("VERDICT: CONFIRMED at full scope -- >=3 of 4 hold, so the pending row cannot change it.") +elif loses >= 2: + print("VERDICT: FALSIFIED at full scope -- >=2 of 4 lose by more than 2 SEM.") +else: + print("VERDICT: NOT YET STATEABLE -- holds %d, loses %d, %d row(s) below c=9." % (holds, loses, pend)) +PY2 +cat $O/inscope.txt + +# --------------------------------------------------------------------------------------------------- +# run 29 ADDITION -- DELIVERABLE 2 COMPLETENESS AUDIT (#287): "every task has COMPLETE 3x3 `mpcd` arms +# across the H grid for DINO-WM, LeWM and DF" (owner, 2026-09-25 ~20:55 UTC). This has never been read +# out as a single table; runs 22-28 were spent on the tau/gamma legs and on the N sweep. It reports the +# CELL COUNT c per (task, family, H, M) for mpcd arms only -- 9 = a complete 3x3 -- so the top-up list is +# the set of (task, family, H) below 9. It uses verdict_table's own loader and the same "mpcd in the +# recipe tokens" test flagship_latex._wm_arm_is applies, so it cannot disagree with the published column. +python3 - > $O/d2_mpcd_completeness.txt 2>&1 <<'PY3' +import collections, os, re +os.environ["RSM_EXTRA_EPOCHS"] = "500" +import verdict_table as vt +ROWS = [("square_sub_20100","Sq-S"),("square_expert_play","Sq-C"), + ("two_piece_expert_suboptimal","Pc-S"),("two_piece_expert_play","Pc-C"), + ("mug_expert_suboptimal","Mug"),("threading_expert_play","Thr"), + ("two_piece_expert_play_tipping","Pc-tip")] +FAMS = ("wm:dinowm","wm:lewm","wm:df") +print("DELIVERABLE 2 -- completeness of the `mpcd` (discounted-sum) world-model arms, 3x3 = 9 cells.") +print("c = number of (proposer-seed x eval-seed) cells that have landed; n = episodes.") +print("An arm is `mpcd` iff its recipe starts with H and has the token 'mpcd' -- flagship_latex._wm_arm_is.\n") +grand = collections.defaultdict(lambda: [0,0,0]) +for task, short in ROWS: + a = collections.defaultdict(lambda: [0,0,0]) + for (arm,p,ps,es),v in vt.cells(task).items(): + if not isinstance(arm, tuple): continue + fam, rec = str(arm[0]), str(arm[1]) + if fam not in FAMS: continue + if not (rec[:1]=="H" and "mpcd" in rec.split()): continue + H = rec.split()[0][1:] + M = "M1" + m = re.search(r"M(\d+)", rec) + if m: M = "M"+m.group(1) + x = a[(fam,H,M)]; x[0]+=len(v); x[1]+=sum(v); x[2]+=1 + g = grand[(fam,H,M)]; g[0]+=len(v); g[1]+=sum(v); g[2]+=1 + print("== %-7s (%s)" % (short, task)) + if not a: + print(" (no mpcd arms at all)") + continue + for (fam,H,M) in sorted(a, key=lambda k:(k[0], int(k[1]), k[2])): + v = a[(fam,H,M)] + flag = "" if v[2]>=9 else (" <-- INCOMPLETE (%d/9)" % v[2]) + print(" %-11s H=%-4s %-5s c=%2d n=%4d rate=%5.1f%s" % + (fam, H, M, v[2], v[0], 100*v[1]/max(v[0],1), flag)) + print() +print("="*100) +print("ROLLED UP OVER THE 7 TASKS (a complete (family,H,M) leg = 63 cells = 7 tasks x 9):") +for (fam,H,M) in sorted(grand, key=lambda k:(k[0], int(k[1]), k[2])): + v = grand[(fam,H,M)] + print(" %-11s H=%-4s %-5s cells=%2d/63 %s" % (fam,H,M,v[2], "COMPLETE" if v[2]>=63 else "")) +PY3 +cat $O/d2_mpcd_completeness.txt + +# ------------------------------------------------------------------------------------------------ +# run 30 ADDITION -- DELIVERABLE 1 READ-OUT: every IQL-critic arm on the PINNED proposer, per task. +# Run 29's flagship census read `RISE (DINO) 0/0/0/0/0/9/0`: the published column follows the LIVE +# per-step-ViT family (`critic:dino`), which has cells on threading only, while the fast path +# (`critic:dino(Dq)`, the precomputed pooled DINO state RSM reads -- owner 2026-09-26 05:00Z) has +# landed on all 7 rows at 900 episodes and was invisible to every table. This prints both families +# beside the pixel critic they isolate the representation against, at MATCHED N, so the deliverable-1 +# comparison can be read without the table's best-over-configurations convention in the way. +python3 - > $O/d1_critic_readout.txt 2>&1 <<'PY4' +import collections, os +os.environ["RSM_EXTRA_EPOCHS"] = "500" +import verdict_table as vt +import flagship_latex as fl +# The flagship's Sq-S row is square_sub_20100, NOT verdict_table's square_expert_suboptimal +# (flagship_latex.FLAGSHIP_VARIANT) -- a long-standing discrepancy flagged on #287. Read BOTH so the +# read-out cannot silently miss the row the paper prints. +TASKS = [fl.FLAGSHIP_VARIANT.get(t, (t,))[0] for t, _ in vt.TASKS] + ["square_expert_suboptimal"] +print("DELIVERABLE 1 -- IQL-critic arms on the pinned proposer (flagship task list).") +print("fams: `critic` = published pixel RISE critic; `critic (planner ctl)` = same pixel critic routed") +print(" through OUR planner; `critic:dino` = live per-step ViT; `critic:dino(Dq)` = precomputed") +print(" cache features + critic-only (the fast path). c = cells (3x3 = 9 complete).\n") +for task in TASKS: + pin = fl.PROPOSER_BY_TASK.get(task) + print("== %-32s pinned proposer: %s" % (task, pin)) + a = collections.defaultdict(lambda: [0, 0, 0]) + try: + C = vt.cells(task) + except Exception as e: + print(" (loader error: %s)" % e); continue + for (arm, p, ps, es), v in C.items(): + if not isinstance(arm, tuple): continue + fam, rec = str(arm[0]), str(arm[1]) + if not fam.startswith("critic"): continue + x = a[(fam, rec, str(p))]; x[0] += len(v); x[1] += sum(v); x[2] += 1 + if not a: + print(" (no critic arms)"); continue + for k in sorted(a): + v = a[k] + print(" %-26s %-10s / %-22s c=%2d n=%4d rate=%5.1f" % + (k[0], k[1], k[2], v[2], v[0], 100 * v[1] / max(v[0], 1))) + print() +PY4 +cat $O/d1_critic_readout.txt diff --git a/rsm_rise/scripts/rr_cpu_basetopup_run31.sh b/rsm_rise/scripts/rr_cpu_basetopup_run31.sh new file mode 100644 index 0000000000000000000000000000000000000000..63338f31516d280c6c085bb147f6dc0ae6381f69 --- /dev/null +++ b/rsm_rise/scripts/rr_cpu_basetopup_run31.sh @@ -0,0 +1,273 @@ +#!/usr/bin/env bash +# BASE_TOPUP run 28: the SAME script as run 27b (generated from it by sed; only the output dir and the two +# diff baselines changed -- verified by `diff` before submission), re-run after run 28's tau-leg recovery: +# job 1929035's whole 4-GPU pack landed on p3-r32-n4 and lost 7 CDQ tau cells to the read_pixels SIGABRT, +# and the launcher called them "0 missing" because the DOOMED JOB STILL OWNED THEM (run 27 section 4's +# ownership trap, second sighting). 1929035 killed, p3-r32-n4 blacklisted, 8 cells relaunched as 1929285, +# 6 IFQL t0p9 cells as 1929277. This build reads whatever has landed by its start. +# BASE_TOPUP run 27: +# (1) REBUILD verdict + flagship and diff against run 26 (the run-26 report predicted the caption's +# {search} counts would drift once more as the last N-sweep cells landed; this is where that shows). +# (2) The run-26b read-out, python block copied BYTE-FOR-BYTE out of scripts/rr_cpu_basetopup_run26b.sh by +# the generator, so run 26's and run 27's numbers cannot disagree by transcription. +# (3) NEW: score the pre-registered RSM-N condition against its 4 IN-SCOPE rows by name (Sq-C, Pc-S, Pc-C, +# Pc-tip), which is the thing run 26 deliberately would not state while Pc-C and Pc-tip were filling. +set -uo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +source scripts/env.sh >/dev/null 2>&1 +O=status/basetopup/run31; mkdir -p $O +export PYTHONPATH=/proj/dmfexp/zwhong/rsm_rise/scripts:${PYTHONPATH:-} + +python3 scripts/verdict_table.py > $O/verdict_now.txt 2> $O/verdict_now.err; echo "verdict rc=$?" +python3 scripts/flagship_latex.py > $O/flag_now.txt 2> $O/flag_now.err; echo "flagship rc=$?" +diff -u status/basetopup/run30/verdict_now.txt $O/verdict_now.txt > $O/verdict.diff 2>/dev/null; echo "verdict diff lines: $(wc -l < $O/verdict.diff)" +diff -u status/basetopup/run30/flag_now.txt $O/flag_now.txt > $O/flag.diff 2>/dev/null; echo "flag diff lines: $(wc -l < $O/flag.diff)" + +echo "reads started $(date -u +%H:%M:%SZ)" +python3 - > $O/reads.txt 2>&1 <<'PYEOF' +import collections, json, math, os, re, importlib +os.environ["RSM_EXTRA_EPOCHS"] = "500" +print("RSM_EXTRA_EPOCHS =", os.environ["RSM_EXTRA_EPOCHS"], "(set explicitly, integrity item 10)") +import verdict_table as vt + +def se(n,k): + p=k/n if n else 0.0 + return 100*math.sqrt(max(p*(1-p),0)/n) if n else 0.0 +def agg(task): + out=collections.defaultdict(lambda:[0,0,0]) + for (arm,p,ps,es),v in vt.cells(task).items(): + a=out[(arm,p)]; a[0]+=len(v); a[1]+=sum(v); a[2]+=1 + return out +def fmt(v): + return f"{100*v[1]/max(v[0],1):5.1f}+-{se(v[0],v[1]):4.1f} (n={v[0]:4d},c={v[2]:2d})" if v else f"{'--':>26s}" +def rate(v): return 100*v[1]/max(v[0],1) if v else None + +ROWS = [("square_sub_20100","Sq-S"),("square_expert_play","Sq-C"), + ("two_piece_expert_suboptimal","Pc-S"),("two_piece_expert_play","Pc-C"), + ("mug_expert_suboptimal","Mug"),("threading_expert_play","Thr"), + ("two_piece_expert_play_tipping","Pc-tip")] +SHORT={t:s for t,s in ROWS} + +print("="*120) +print("(1) THE RSM N CURVE -- the mirror of the baseline curve, on the arm tab:flagship REPORTS on each row.") +print(" arm + proposer taken from status/chain/flagship_chain_arm.json (flagship_latex._best_arm's own export);") +print(" the N=4 / N=16 arms are that string with ONLY the N token changed.") +sel=json.load(open("status/chain/flagship_chain_arm.json")) +curve={} +for label, rec in sel.items(): + task, arm = rec["task"], rec["chain_arm"] + a=agg(task) + want={} + for n in (4,16,128): + want[n]=re.sub(r"\bN128\b", f"N{n}", arm) + # pick the proposer that carries the published N=128 arm (the pinned one), then read all three on it + props=[p for (ar,p) in a if isinstance(ar,tuple) and ar[0]=="rsm:membership" and ar[1]==want[128]] + if not props: + print(f"\n== {label}: published arm {arm!r} not found -- skipped"); continue + pol=max(props, key=lambda p: a[(("rsm:membership",want[128]),p)][2]) + print(f"\n== {label} ({task}) arm={arm!r} proposer={pol} exported rate={rec['chain_rate']:.1f}") + got={} + for n in (4,16,128): + v=a.get((("rsm:membership",want[n]),pol)) + got[n]=v + print(f" N={n:<4d} {fmt(v)} arm={want[n]!r}") + curve[SHORT[task]]=got + +print() +print("-- SCORING THE PREDICTION PRE-REGISTERED 2026-09-26 17:05Z (#287 section 3), complete arms only (c>=9).") +print(" Wording: on the rows where a CRITIC arm loses >=10 points from N=4 to N=128, RSM at N=128 is within") +print(" 2 SEM of, or above, its own N=4 value on >=3 of 4. FALSIFIED if RSM loses more than 2 SEM on >=2.") +scored=[] +for short,got in sorted(curve.items()): + n4,n128=got.get(4),got.get(128) + if not (n4 and n128) or n4[2]<9 or n128[2]<9: + print(f" PENDING {short:8s} N=4 c={n4[2] if n4 else 0}, N=128 c={n128[2] if n128 else 0}") + continue + r4,r128=rate(n4),rate(n128) + s=math.sqrt(se(n4[0],n4[1])**2+se(n128[0],n128[1])**2) + ok = r128 >= r4-2*s + scored.append((short,ok,r4,r128,2*s)) + print(f" {'HOLDS ' if ok else 'LOSES '} {short:8s} N=4 {r4:5.1f} -> N=128 {r128:5.1f} (delta {r128-r4:+5.1f}, 2SEM {2*s:4.1f})") +if scored: + print(f" complete rows: {len(scored)}; holds {sum(1 for x in scored if x[1])}, loses-by->2SEM {sum(1 for x in scored if not x[1])}") + print(" (The 4 pre-registered in-scope rows are Sq-C, Pc-S, Pc-C, Pc-tip -- the rows where a critic arm") + print(" loses >=10 points from N=4 to N=128. Verdict is stated only when all four are at c>=9.)") + +print() +print("="*120) +print("(2) THE CRITIC N CURVE AT FINAL COUNTS (run 25's 28-cell top-up). `random` = the row's N=1 control.") +NS={"N=4","N=16","N=128"} +for task,short in ROWS: + a=agg(task) + fams=collections.defaultdict(dict); ctls={} + for (arm,p),v in a.items(): + if not isinstance(arm,tuple): continue + a0,a1=str(arm[0]),str(arm[1]) + if a0=="random": ctls[(a1,str(p))]=v + if a0 in ("critic (planner ctl)","critic:dino(Dq)") and a1 in NS: fams[(a0,str(p))][a1]=v + for (fam,p),row in sorted(fams.items()): + lab="pixel" if fam=="critic (planner ctl)" else "DINO " + ctl=ctls.get((fam,p)) + cs=fmt(ctl) if ctl else f"{'--':>26s}" + print(f"{short:8s} {lab} prop={p:16s} ctl {cs} | " + + " | ".join(f"N={n.split('=')[1]:>3s} {fmt(row.get(n))}" for n in ("N=4","N=16","N=128"))) + +print() +print("="*120) +print("(3) EXPECTILE LEG -- IFQL tau arms and IDQL-DINO tau arms") +for task,short in ROWS: + a=agg(task); got=[] + for (arm,p),v in a.items(): + if not isinstance(arm,tuple): continue + if ("t0" in str(arm[0])) and "N=128" in str(arm[1]): got.append((str(arm[0]),str(p),v)) + if not got: continue + print(f"-- {short} ({task})") + for a0,p,v in sorted(got): print(f" {a0:34s} prop={p:14s} {fmt(v)}") +PYEOF +echo "reads finished $(date -u +%H:%M:%SZ)" +cat $O/reads.txt + +# (3) the pre-registered condition, scored against the four IN-SCOPE rows BY NAME. +python3 - > $O/inscope.txt 2>&1 <<'PY2' +import collections, json, math, os, re +os.environ["RSM_EXTRA_EPOCHS"] = "500" +import verdict_table as vt +def se(n,k): + p=k/n if n else 0.0 + return 100*math.sqrt(max(p*(1-p),0)/n) if n else 0.0 +# in-scope = the rows where a CRITIC arm loses >=10 points from N=4 to N=128 (#287 section 3, 17:05Z) +INSCOPE = {"square_expert_play":"Sq-C", "two_piece_expert_suboptimal":"Pc-S", + "two_piece_expert_play":"Pc-C", "two_piece_expert_play_tipping":"Pc-tip"} +sel = json.load(open("status/chain/flagship_chain_arm.json")) +print("PRE-REGISTERED 2026-09-26 17:05Z: on the in-scope rows, RSM at N=128 is within 2 SEM of, or above,") +print("its own N=4 value on >=3 of 4. FALSIFIED if RSM loses by more than 2 SEM on >=2 of 4.") +rows = [] +for label, rec in sel.items(): + task, arm = rec["task"], rec["chain_arm"] + if task not in INSCOPE: continue + agg = collections.defaultdict(lambda: [0,0,0]) + for (a,p,ps,es),v in vt.cells(task).items(): + x = agg[(a,p)]; x[0]+=len(v); x[1]+=sum(v); x[2]+=1 + want = {n: re.sub(r"\bN128\b", "N%d" % n, arm) for n in (4,16,128)} + props = [p for (ar,p) in agg if isinstance(ar,tuple) and ar[0]=="rsm:membership" and ar[1]==want[128]] + if not props: + print(" %-7s published arm not found -- SKIPPED" % INSCOPE[task]); continue + pol = max(props, key=lambda p: agg[(("rsm:membership",want[128]),p)][2]) + g = {n: agg.get((("rsm:membership",want[n]),pol)) for n in (4,16,128)} + n4, n128 = g[4], g[128] + if not (n4 and n128) or n4[2] < 9 or n128[2] < 9: + print(" %-7s PENDING c(N=4)=%d c(N=128)=%d" % (INSCOPE[task], n4[2] if n4 else 0, n128[2] if n128 else 0)) + rows.append((INSCOPE[task], None)); continue + r4 = 100*n4[1]/n4[0]; r128 = 100*n128[1]/n128[0] + two = 2*math.sqrt(se(n4[0],n4[1])**2 + se(n128[0],n128[1])**2) + ok = r128 >= r4 - two + rows.append((INSCOPE[task], ok)) + print(" %-7s %s N=4 %5.1f (n=%d) -> N=128 %5.1f (n=%d) delta %+5.1f 2SEM %4.1f" + % (INSCOPE[task], "HOLDS" if ok else "LOSES", r4, n4[0], r128, n128[0], r128-r4, two)) +holds = sum(1 for r in rows if r[1] is True) +loses = sum(1 for r in rows if r[1] is False) +pend = sum(1 for r in rows if r[1] is None) +print("\nin-scope rows: %d holds %d loses-by->2SEM %d pending %d" % (len(rows), holds, loses, pend)) +if holds >= 3: + print("VERDICT: CONFIRMED at full scope -- >=3 of 4 hold, so the pending row cannot change it.") +elif loses >= 2: + print("VERDICT: FALSIFIED at full scope -- >=2 of 4 lose by more than 2 SEM.") +else: + print("VERDICT: NOT YET STATEABLE -- holds %d, loses %d, %d row(s) below c=9." % (holds, loses, pend)) +PY2 +cat $O/inscope.txt + +# --------------------------------------------------------------------------------------------------- +# run 29 ADDITION -- DELIVERABLE 2 COMPLETENESS AUDIT (#287): "every task has COMPLETE 3x3 `mpcd` arms +# across the H grid for DINO-WM, LeWM and DF" (owner, 2026-09-25 ~20:55 UTC). This has never been read +# out as a single table; runs 22-28 were spent on the tau/gamma legs and on the N sweep. It reports the +# CELL COUNT c per (task, family, H, M) for mpcd arms only -- 9 = a complete 3x3 -- so the top-up list is +# the set of (task, family, H) below 9. It uses verdict_table's own loader and the same "mpcd in the +# recipe tokens" test flagship_latex._wm_arm_is applies, so it cannot disagree with the published column. +python3 - > $O/d2_mpcd_completeness.txt 2>&1 <<'PY3' +import collections, os, re +os.environ["RSM_EXTRA_EPOCHS"] = "500" +import verdict_table as vt +ROWS = [("square_sub_20100","Sq-S"),("square_expert_play","Sq-C"), + ("two_piece_expert_suboptimal","Pc-S"),("two_piece_expert_play","Pc-C"), + ("mug_expert_suboptimal","Mug"),("threading_expert_play","Thr"), + ("two_piece_expert_play_tipping","Pc-tip")] +FAMS = ("wm:dinowm","wm:lewm","wm:df") +print("DELIVERABLE 2 -- completeness of the `mpcd` (discounted-sum) world-model arms, 3x3 = 9 cells.") +print("c = number of (proposer-seed x eval-seed) cells that have landed; n = episodes.") +print("An arm is `mpcd` iff its recipe starts with H and has the token 'mpcd' -- flagship_latex._wm_arm_is.\n") +grand = collections.defaultdict(lambda: [0,0,0]) +for task, short in ROWS: + a = collections.defaultdict(lambda: [0,0,0]) + for (arm,p,ps,es),v in vt.cells(task).items(): + if not isinstance(arm, tuple): continue + fam, rec = str(arm[0]), str(arm[1]) + if fam not in FAMS: continue + if not (rec[:1]=="H" and "mpcd" in rec.split()): continue + H = rec.split()[0][1:] + M = "M1" + m = re.search(r"M(\d+)", rec) + if m: M = "M"+m.group(1) + x = a[(fam,H,M)]; x[0]+=len(v); x[1]+=sum(v); x[2]+=1 + g = grand[(fam,H,M)]; g[0]+=len(v); g[1]+=sum(v); g[2]+=1 + print("== %-7s (%s)" % (short, task)) + if not a: + print(" (no mpcd arms at all)") + continue + for (fam,H,M) in sorted(a, key=lambda k:(k[0], int(k[1]), k[2])): + v = a[(fam,H,M)] + flag = "" if v[2]>=9 else (" <-- INCOMPLETE (%d/9)" % v[2]) + print(" %-11s H=%-4s %-5s c=%2d n=%4d rate=%5.1f%s" % + (fam, H, M, v[2], v[0], 100*v[1]/max(v[0],1), flag)) + print() +print("="*100) +print("ROLLED UP OVER THE 7 TASKS (a complete (family,H,M) leg = 63 cells = 7 tasks x 9):") +for (fam,H,M) in sorted(grand, key=lambda k:(k[0], int(k[1]), k[2])): + v = grand[(fam,H,M)] + print(" %-11s H=%-4s %-5s cells=%2d/63 %s" % (fam,H,M,v[2], "COMPLETE" if v[2]>=63 else "")) +PY3 +cat $O/d2_mpcd_completeness.txt + +# ------------------------------------------------------------------------------------------------ +# run 30 ADDITION -- DELIVERABLE 1 READ-OUT: every IQL-critic arm on the PINNED proposer, per task. +# Run 29's flagship census read `RISE (DINO) 0/0/0/0/0/9/0`: the published column follows the LIVE +# per-step-ViT family (`critic:dino`), which has cells on threading only, while the fast path +# (`critic:dino(Dq)`, the precomputed pooled DINO state RSM reads -- owner 2026-09-26 05:00Z) has +# landed on all 7 rows at 900 episodes and was invisible to every table. This prints both families +# beside the pixel critic they isolate the representation against, at MATCHED N, so the deliverable-1 +# comparison can be read without the table's best-over-configurations convention in the way. +python3 - > $O/d1_critic_readout.txt 2>&1 <<'PY4' +import collections, os +os.environ["RSM_EXTRA_EPOCHS"] = "500" +import verdict_table as vt +import flagship_latex as fl +# The flagship's Sq-S row is square_sub_20100, NOT verdict_table's square_expert_suboptimal +# (flagship_latex.FLAGSHIP_VARIANT) -- a long-standing discrepancy flagged on #287. Read BOTH so the +# read-out cannot silently miss the row the paper prints. +TASKS = [fl.FLAGSHIP_VARIANT.get(t, (t,))[0] for t, _ in vt.TASKS] + ["square_expert_suboptimal"] +print("DELIVERABLE 1 -- IQL-critic arms on the pinned proposer (flagship task list).") +print("fams: `critic` = published pixel RISE critic; `critic (planner ctl)` = same pixel critic routed") +print(" through OUR planner; `critic:dino` = live per-step ViT; `critic:dino(Dq)` = precomputed") +print(" cache features + critic-only (the fast path). c = cells (3x3 = 9 complete).\n") +for task in TASKS: + pin = fl.PROPOSER_BY_TASK.get(task) + print("== %-32s pinned proposer: %s" % (task, pin)) + a = collections.defaultdict(lambda: [0, 0, 0]) + try: + C = vt.cells(task) + except Exception as e: + print(" (loader error: %s)" % e); continue + for (arm, p, ps, es), v in C.items(): + if not isinstance(arm, tuple): continue + fam, rec = str(arm[0]), str(arm[1]) + if not fam.startswith("critic"): continue + x = a[(fam, rec, str(p))]; x[0] += len(v); x[1] += sum(v); x[2] += 1 + if not a: + print(" (no critic arms)"); continue + for k in sorted(a): + v = a[k] + print(" %-26s %-10s / %-22s c=%2d n=%4d rate=%5.1f" % + (k[0], k[1], k[2], v[2], v[0], 100 * v[1] / max(v[0], 1))) + print() +PY4 +cat $O/d1_critic_readout.txt diff --git a/rsm_rise/scripts/rr_cpu_basetopup_run32.sh b/rsm_rise/scripts/rr_cpu_basetopup_run32.sh new file mode 100644 index 0000000000000000000000000000000000000000..cf69da7b0014a7f28a3dbbe9144fbc3f6233e36d --- /dev/null +++ b/rsm_rise/scripts/rr_cpu_basetopup_run32.sh @@ -0,0 +1,280 @@ +#!/usr/bin/env bash +# BASE_TOPUP run 32. Generated from scripts/rr_cpu_basetopup_run31.sh: everything from the first +# `verdict_table` call down is that file with `run30` -> `run31` (the diff baselines) and the output dir +# changed, so the read-out numbers cannot differ from run 31's by transcription. +# +# NEW THIS RUN -- owner 2026-09-26 04:30Z item (b): "Keep the builder able to print BOTH +# (published-discount column and best-over-gamma column)". `flagship_latex` gained an env-gated +# SEVENTH scorer column (RR_IFQL_BESTG=1 -> `critic:ifql(bestg)`, a union over {published 0.9999} u +# {pure gamma variants}, tau variants deliberately excluded). Two builds, in this order: +# (1) the GATED build, whose stdout also discloses which discount won on each row; +# (2) the DEFAULT build LAST, so the .tex files left on disk are the published ones and never the +# gated variant -- the gated column must not be able to reach a paper table by being built last. +# The default build's diff against run 31 is the proof that no published number moved. +set -uo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +source scripts/env.sh >/dev/null 2>&1 +O=status/basetopup/run32; mkdir -p $O +export PYTHONPATH=/proj/dmfexp/zwhong/rsm_rise/scripts:${PYTHONPATH:-} + +echo "=== (1) GATED build: RR_IFQL_BESTG=1 (writes .tex, overwritten by step 2 below) ===" +RR_IFQL_BESTG=1 python3 scripts/flagship_latex.py > $O/flag_bestg.txt 2> $O/flag_bestg.err; echo "gated rc=$?" +grep -E "RR_IFQL_BESTG|best-gamma|SEVENTH" $O/flag_bestg.txt | head -40 +echo "--- the gated column as the all-table renders it (IFQL (best) header + row cells):" +grep -nE "IFQL \(best" docs/tex/*.tex | head -10 +cp -p docs/tex/tab_rise_flagship_all.tex $O/all_bestg.tex 2>/dev/null || true + +echo "=== (2) DEFAULT build LAST -- this is what stays on disk ===" +python3 scripts/verdict_table.py > $O/verdict_now.txt 2> $O/verdict_now.err; echo "verdict rc=$?" +python3 scripts/flagship_latex.py > $O/flag_now.txt 2> $O/flag_now.err; echo "flagship rc=$?" +diff -u status/basetopup/run31/verdict_now.txt $O/verdict_now.txt > $O/verdict.diff 2>/dev/null; echo "verdict diff lines: $(wc -l < $O/verdict.diff)" +diff -u status/basetopup/run31/flag_now.txt $O/flag_now.txt > $O/flag.diff 2>/dev/null; echo "flag diff lines: $(wc -l < $O/flag.diff)" + +echo "reads started $(date -u +%H:%M:%SZ)" +python3 - > $O/reads.txt 2>&1 <<'PYEOF' +import collections, json, math, os, re, importlib +os.environ["RSM_EXTRA_EPOCHS"] = "500" +print("RSM_EXTRA_EPOCHS =", os.environ["RSM_EXTRA_EPOCHS"], "(set explicitly, integrity item 10)") +import verdict_table as vt + +def se(n,k): + p=k/n if n else 0.0 + return 100*math.sqrt(max(p*(1-p),0)/n) if n else 0.0 +def agg(task): + out=collections.defaultdict(lambda:[0,0,0]) + for (arm,p,ps,es),v in vt.cells(task).items(): + a=out[(arm,p)]; a[0]+=len(v); a[1]+=sum(v); a[2]+=1 + return out +def fmt(v): + return f"{100*v[1]/max(v[0],1):5.1f}+-{se(v[0],v[1]):4.1f} (n={v[0]:4d},c={v[2]:2d})" if v else f"{'--':>26s}" +def rate(v): return 100*v[1]/max(v[0],1) if v else None + +ROWS = [("square_sub_20100","Sq-S"),("square_expert_play","Sq-C"), + ("two_piece_expert_suboptimal","Pc-S"),("two_piece_expert_play","Pc-C"), + ("mug_expert_suboptimal","Mug"),("threading_expert_play","Thr"), + ("two_piece_expert_play_tipping","Pc-tip")] +SHORT={t:s for t,s in ROWS} + +print("="*120) +print("(1) THE RSM N CURVE -- the mirror of the baseline curve, on the arm tab:flagship REPORTS on each row.") +print(" arm + proposer taken from status/chain/flagship_chain_arm.json (flagship_latex._best_arm's own export);") +print(" the N=4 / N=16 arms are that string with ONLY the N token changed.") +sel=json.load(open("status/chain/flagship_chain_arm.json")) +curve={} +for label, rec in sel.items(): + task, arm = rec["task"], rec["chain_arm"] + a=agg(task) + want={} + for n in (4,16,128): + want[n]=re.sub(r"\bN128\b", f"N{n}", arm) + # pick the proposer that carries the published N=128 arm (the pinned one), then read all three on it + props=[p for (ar,p) in a if isinstance(ar,tuple) and ar[0]=="rsm:membership" and ar[1]==want[128]] + if not props: + print(f"\n== {label}: published arm {arm!r} not found -- skipped"); continue + pol=max(props, key=lambda p: a[(("rsm:membership",want[128]),p)][2]) + print(f"\n== {label} ({task}) arm={arm!r} proposer={pol} exported rate={rec['chain_rate']:.1f}") + got={} + for n in (4,16,128): + v=a.get((("rsm:membership",want[n]),pol)) + got[n]=v + print(f" N={n:<4d} {fmt(v)} arm={want[n]!r}") + curve[SHORT[task]]=got + +print() +print("-- SCORING THE PREDICTION PRE-REGISTERED 2026-09-26 17:05Z (#287 section 3), complete arms only (c>=9).") +print(" Wording: on the rows where a CRITIC arm loses >=10 points from N=4 to N=128, RSM at N=128 is within") +print(" 2 SEM of, or above, its own N=4 value on >=3 of 4. FALSIFIED if RSM loses more than 2 SEM on >=2.") +scored=[] +for short,got in sorted(curve.items()): + n4,n128=got.get(4),got.get(128) + if not (n4 and n128) or n4[2]<9 or n128[2]<9: + print(f" PENDING {short:8s} N=4 c={n4[2] if n4 else 0}, N=128 c={n128[2] if n128 else 0}") + continue + r4,r128=rate(n4),rate(n128) + s=math.sqrt(se(n4[0],n4[1])**2+se(n128[0],n128[1])**2) + ok = r128 >= r4-2*s + scored.append((short,ok,r4,r128,2*s)) + print(f" {'HOLDS ' if ok else 'LOSES '} {short:8s} N=4 {r4:5.1f} -> N=128 {r128:5.1f} (delta {r128-r4:+5.1f}, 2SEM {2*s:4.1f})") +if scored: + print(f" complete rows: {len(scored)}; holds {sum(1 for x in scored if x[1])}, loses-by->2SEM {sum(1 for x in scored if not x[1])}") + print(" (The 4 pre-registered in-scope rows are Sq-C, Pc-S, Pc-C, Pc-tip -- the rows where a critic arm") + print(" loses >=10 points from N=4 to N=128. Verdict is stated only when all four are at c>=9.)") + +print() +print("="*120) +print("(2) THE CRITIC N CURVE AT FINAL COUNTS (run 25's 28-cell top-up). `random` = the row's N=1 control.") +NS={"N=4","N=16","N=128"} +for task,short in ROWS: + a=agg(task) + fams=collections.defaultdict(dict); ctls={} + for (arm,p),v in a.items(): + if not isinstance(arm,tuple): continue + a0,a1=str(arm[0]),str(arm[1]) + if a0=="random": ctls[(a1,str(p))]=v + if a0 in ("critic (planner ctl)","critic:dino(Dq)") and a1 in NS: fams[(a0,str(p))][a1]=v + for (fam,p),row in sorted(fams.items()): + lab="pixel" if fam=="critic (planner ctl)" else "DINO " + ctl=ctls.get((fam,p)) + cs=fmt(ctl) if ctl else f"{'--':>26s}" + print(f"{short:8s} {lab} prop={p:16s} ctl {cs} | " + + " | ".join(f"N={n.split('=')[1]:>3s} {fmt(row.get(n))}" for n in ("N=4","N=16","N=128"))) + +print() +print("="*120) +print("(3) EXPECTILE LEG -- IFQL tau arms and IDQL-DINO tau arms") +for task,short in ROWS: + a=agg(task); got=[] + for (arm,p),v in a.items(): + if not isinstance(arm,tuple): continue + if ("t0" in str(arm[0])) and "N=128" in str(arm[1]): got.append((str(arm[0]),str(p),v)) + if not got: continue + print(f"-- {short} ({task})") + for a0,p,v in sorted(got): print(f" {a0:34s} prop={p:14s} {fmt(v)}") +PYEOF +echo "reads finished $(date -u +%H:%M:%SZ)" +cat $O/reads.txt + +# (3) the pre-registered condition, scored against the four IN-SCOPE rows BY NAME. +python3 - > $O/inscope.txt 2>&1 <<'PY2' +import collections, json, math, os, re +os.environ["RSM_EXTRA_EPOCHS"] = "500" +import verdict_table as vt +def se(n,k): + p=k/n if n else 0.0 + return 100*math.sqrt(max(p*(1-p),0)/n) if n else 0.0 +# in-scope = the rows where a CRITIC arm loses >=10 points from N=4 to N=128 (#287 section 3, 17:05Z) +INSCOPE = {"square_expert_play":"Sq-C", "two_piece_expert_suboptimal":"Pc-S", + "two_piece_expert_play":"Pc-C", "two_piece_expert_play_tipping":"Pc-tip"} +sel = json.load(open("status/chain/flagship_chain_arm.json")) +print("PRE-REGISTERED 2026-09-26 17:05Z: on the in-scope rows, RSM at N=128 is within 2 SEM of, or above,") +print("its own N=4 value on >=3 of 4. FALSIFIED if RSM loses by more than 2 SEM on >=2 of 4.") +rows = [] +for label, rec in sel.items(): + task, arm = rec["task"], rec["chain_arm"] + if task not in INSCOPE: continue + agg = collections.defaultdict(lambda: [0,0,0]) + for (a,p,ps,es),v in vt.cells(task).items(): + x = agg[(a,p)]; x[0]+=len(v); x[1]+=sum(v); x[2]+=1 + want = {n: re.sub(r"\bN128\b", "N%d" % n, arm) for n in (4,16,128)} + props = [p for (ar,p) in agg if isinstance(ar,tuple) and ar[0]=="rsm:membership" and ar[1]==want[128]] + if not props: + print(" %-7s published arm not found -- SKIPPED" % INSCOPE[task]); continue + pol = max(props, key=lambda p: agg[(("rsm:membership",want[128]),p)][2]) + g = {n: agg.get((("rsm:membership",want[n]),pol)) for n in (4,16,128)} + n4, n128 = g[4], g[128] + if not (n4 and n128) or n4[2] < 9 or n128[2] < 9: + print(" %-7s PENDING c(N=4)=%d c(N=128)=%d" % (INSCOPE[task], n4[2] if n4 else 0, n128[2] if n128 else 0)) + rows.append((INSCOPE[task], None)); continue + r4 = 100*n4[1]/n4[0]; r128 = 100*n128[1]/n128[0] + two = 2*math.sqrt(se(n4[0],n4[1])**2 + se(n128[0],n128[1])**2) + ok = r128 >= r4 - two + rows.append((INSCOPE[task], ok)) + print(" %-7s %s N=4 %5.1f (n=%d) -> N=128 %5.1f (n=%d) delta %+5.1f 2SEM %4.1f" + % (INSCOPE[task], "HOLDS" if ok else "LOSES", r4, n4[0], r128, n128[0], r128-r4, two)) +holds = sum(1 for r in rows if r[1] is True) +loses = sum(1 for r in rows if r[1] is False) +pend = sum(1 for r in rows if r[1] is None) +print("\nin-scope rows: %d holds %d loses-by->2SEM %d pending %d" % (len(rows), holds, loses, pend)) +if holds >= 3: + print("VERDICT: CONFIRMED at full scope -- >=3 of 4 hold, so the pending row cannot change it.") +elif loses >= 2: + print("VERDICT: FALSIFIED at full scope -- >=2 of 4 lose by more than 2 SEM.") +else: + print("VERDICT: NOT YET STATEABLE -- holds %d, loses %d, %d row(s) below c=9." % (holds, loses, pend)) +PY2 +cat $O/inscope.txt + +# --------------------------------------------------------------------------------------------------- +# run 29 ADDITION -- DELIVERABLE 2 COMPLETENESS AUDIT (#287): "every task has COMPLETE 3x3 `mpcd` arms +# across the H grid for DINO-WM, LeWM and DF" (owner, 2026-09-25 ~20:55 UTC). This has never been read +# out as a single table; runs 22-28 were spent on the tau/gamma legs and on the N sweep. It reports the +# CELL COUNT c per (task, family, H, M) for mpcd arms only -- 9 = a complete 3x3 -- so the top-up list is +# the set of (task, family, H) below 9. It uses verdict_table's own loader and the same "mpcd in the +# recipe tokens" test flagship_latex._wm_arm_is applies, so it cannot disagree with the published column. +python3 - > $O/d2_mpcd_completeness.txt 2>&1 <<'PY3' +import collections, os, re +os.environ["RSM_EXTRA_EPOCHS"] = "500" +import verdict_table as vt +ROWS = [("square_sub_20100","Sq-S"),("square_expert_play","Sq-C"), + ("two_piece_expert_suboptimal","Pc-S"),("two_piece_expert_play","Pc-C"), + ("mug_expert_suboptimal","Mug"),("threading_expert_play","Thr"), + ("two_piece_expert_play_tipping","Pc-tip")] +FAMS = ("wm:dinowm","wm:lewm","wm:df") +print("DELIVERABLE 2 -- completeness of the `mpcd` (discounted-sum) world-model arms, 3x3 = 9 cells.") +print("c = number of (proposer-seed x eval-seed) cells that have landed; n = episodes.") +print("An arm is `mpcd` iff its recipe starts with H and has the token 'mpcd' -- flagship_latex._wm_arm_is.\n") +grand = collections.defaultdict(lambda: [0,0,0]) +for task, short in ROWS: + a = collections.defaultdict(lambda: [0,0,0]) + for (arm,p,ps,es),v in vt.cells(task).items(): + if not isinstance(arm, tuple): continue + fam, rec = str(arm[0]), str(arm[1]) + if fam not in FAMS: continue + if not (rec[:1]=="H" and "mpcd" in rec.split()): continue + H = rec.split()[0][1:] + M = "M1" + m = re.search(r"M(\d+)", rec) + if m: M = "M"+m.group(1) + x = a[(fam,H,M)]; x[0]+=len(v); x[1]+=sum(v); x[2]+=1 + g = grand[(fam,H,M)]; g[0]+=len(v); g[1]+=sum(v); g[2]+=1 + print("== %-7s (%s)" % (short, task)) + if not a: + print(" (no mpcd arms at all)") + continue + for (fam,H,M) in sorted(a, key=lambda k:(k[0], int(k[1]), k[2])): + v = a[(fam,H,M)] + flag = "" if v[2]>=9 else (" <-- INCOMPLETE (%d/9)" % v[2]) + print(" %-11s H=%-4s %-5s c=%2d n=%4d rate=%5.1f%s" % + (fam, H, M, v[2], v[0], 100*v[1]/max(v[0],1), flag)) + print() +print("="*100) +print("ROLLED UP OVER THE 7 TASKS (a complete (family,H,M) leg = 63 cells = 7 tasks x 9):") +for (fam,H,M) in sorted(grand, key=lambda k:(k[0], int(k[1]), k[2])): + v = grand[(fam,H,M)] + print(" %-11s H=%-4s %-5s cells=%2d/63 %s" % (fam,H,M,v[2], "COMPLETE" if v[2]>=63 else "")) +PY3 +cat $O/d2_mpcd_completeness.txt + +# ------------------------------------------------------------------------------------------------ +# run 30 ADDITION -- DELIVERABLE 1 READ-OUT: every IQL-critic arm on the PINNED proposer, per task. +# Run 29's flagship census read `RISE (DINO) 0/0/0/0/0/9/0`: the published column follows the LIVE +# per-step-ViT family (`critic:dino`), which has cells on threading only, while the fast path +# (`critic:dino(Dq)`, the precomputed pooled DINO state RSM reads -- owner 2026-09-26 05:00Z) has +# landed on all 7 rows at 900 episodes and was invisible to every table. This prints both families +# beside the pixel critic they isolate the representation against, at MATCHED N, so the deliverable-1 +# comparison can be read without the table's best-over-configurations convention in the way. +python3 - > $O/d1_critic_readout.txt 2>&1 <<'PY4' +import collections, os +os.environ["RSM_EXTRA_EPOCHS"] = "500" +import verdict_table as vt +import flagship_latex as fl +# The flagship's Sq-S row is square_sub_20100, NOT verdict_table's square_expert_suboptimal +# (flagship_latex.FLAGSHIP_VARIANT) -- a long-standing discrepancy flagged on #287. Read BOTH so the +# read-out cannot silently miss the row the paper prints. +TASKS = [fl.FLAGSHIP_VARIANT.get(t, (t,))[0] for t, _ in vt.TASKS] + ["square_expert_suboptimal"] +print("DELIVERABLE 1 -- IQL-critic arms on the pinned proposer (flagship task list).") +print("fams: `critic` = published pixel RISE critic; `critic (planner ctl)` = same pixel critic routed") +print(" through OUR planner; `critic:dino` = live per-step ViT; `critic:dino(Dq)` = precomputed") +print(" cache features + critic-only (the fast path). c = cells (3x3 = 9 complete).\n") +for task in TASKS: + pin = fl.PROPOSER_BY_TASK.get(task) + print("== %-32s pinned proposer: %s" % (task, pin)) + a = collections.defaultdict(lambda: [0, 0, 0]) + try: + C = vt.cells(task) + except Exception as e: + print(" (loader error: %s)" % e); continue + for (arm, p, ps, es), v in C.items(): + if not isinstance(arm, tuple): continue + fam, rec = str(arm[0]), str(arm[1]) + if not fam.startswith("critic"): continue + x = a[(fam, rec, str(p))]; x[0] += len(v); x[1] += sum(v); x[2] += 1 + if not a: + print(" (no critic arms)"); continue + for k in sorted(a): + v = a[k] + print(" %-26s %-10s / %-22s c=%2d n=%4d rate=%5.1f" % + (k[0], k[1], k[2], v[2], v[0], 100 * v[1] / max(v[0], 1))) + print() +PY4 +cat $O/d1_critic_readout.txt diff --git a/rsm_rise/scripts/rr_cpu_basetopup_run33.sh b/rsm_rise/scripts/rr_cpu_basetopup_run33.sh new file mode 100644 index 0000000000000000000000000000000000000000..235c5aea9f09f12072f178d28dba978b7053b75f --- /dev/null +++ b/rsm_rise/scripts/rr_cpu_basetopup_run33.sh @@ -0,0 +1,322 @@ +#!/usr/bin/env bash +# BASE_TOPUP run 33. Generated from scripts/rr_cpu_basetopup_run32.sh: everything from the first +# `verdict_table` call down is that file with `run30` -> `run32` (the diff baselines) and the output dir +# changed, so the read-out numbers cannot differ from run 32's by transcription. +# +# NEW THIS RUN -- owner 2026-09-26 04:30Z item (b): "Keep the builder able to print BOTH +# (published-discount column and best-over-gamma column)". `flagship_latex` gained an env-gated +# SEVENTH scorer column (RR_IFQL_BESTG=1 -> `critic:ifql(bestg)`, a union over {published 0.9999} u +# {pure gamma variants}, tau variants deliberately excluded). Two builds, in this order: +# (1) the GATED build, whose stdout also discloses which discount won on each row; +# (2) the DEFAULT build LAST, so the .tex files left on disk are the published ones and never the +# gated variant -- the gated column must not be able to reach a paper table by being built last. +# The default build's diff against run 32 is the proof that no published number moved. +set -uo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +source scripts/env.sh >/dev/null 2>&1 +O=status/basetopup/run33; mkdir -p $O +export PYTHONPATH=/proj/dmfexp/zwhong/rsm_rise/scripts:${PYTHONPATH:-} + +echo "=== (1) GATED build: RR_IFQL_BESTG=1 (writes .tex, overwritten by step 2 below) ===" +RR_IFQL_BESTG=1 python3 scripts/flagship_latex.py > $O/flag_bestg.txt 2> $O/flag_bestg.err; echo "gated rc=$?" +grep -E "RR_IFQL_BESTG|best-gamma|SEVENTH" $O/flag_bestg.txt | head -40 +echo "--- the gated column as the all-table renders it (IFQL (best) header + row cells):" +grep -nE "IFQL \(best" docs/tex/*.tex | head -10 +cp -p docs/tex/tab_rise_flagship_all.tex $O/all_bestg.tex 2>/dev/null || true + +echo "=== (2) DEFAULT build LAST -- this is what stays on disk ===" +python3 scripts/verdict_table.py > $O/verdict_now.txt 2> $O/verdict_now.err; echo "verdict rc=$?" +python3 scripts/flagship_latex.py > $O/flag_now.txt 2> $O/flag_now.err; echo "flagship rc=$?" +diff -u status/basetopup/run32/verdict_now.txt $O/verdict_now.txt > $O/verdict.diff 2>/dev/null; echo "verdict diff lines: $(wc -l < $O/verdict.diff)" +diff -u status/basetopup/run32/flag_now.txt $O/flag_now.txt > $O/flag.diff 2>/dev/null; echo "flag diff lines: $(wc -l < $O/flag.diff)" + +echo "reads started $(date -u +%H:%M:%SZ)" +python3 - > $O/reads.txt 2>&1 <<'PYEOF' +import collections, json, math, os, re, importlib +os.environ["RSM_EXTRA_EPOCHS"] = "500" +print("RSM_EXTRA_EPOCHS =", os.environ["RSM_EXTRA_EPOCHS"], "(set explicitly, integrity item 10)") +import verdict_table as vt + +def se(n,k): + p=k/n if n else 0.0 + return 100*math.sqrt(max(p*(1-p),0)/n) if n else 0.0 +def agg(task): + out=collections.defaultdict(lambda:[0,0,0]) + for (arm,p,ps,es),v in vt.cells(task).items(): + a=out[(arm,p)]; a[0]+=len(v); a[1]+=sum(v); a[2]+=1 + return out +def fmt(v): + return f"{100*v[1]/max(v[0],1):5.1f}+-{se(v[0],v[1]):4.1f} (n={v[0]:4d},c={v[2]:2d})" if v else f"{'--':>26s}" +def rate(v): return 100*v[1]/max(v[0],1) if v else None + +ROWS = [("square_sub_20100","Sq-S"),("square_expert_play","Sq-C"), + ("two_piece_expert_suboptimal","Pc-S"),("two_piece_expert_play","Pc-C"), + ("mug_expert_suboptimal","Mug"),("threading_expert_play","Thr"), + ("two_piece_expert_play_tipping","Pc-tip")] +SHORT={t:s for t,s in ROWS} + +print("="*120) +print("(1) THE RSM N CURVE -- the mirror of the baseline curve, on the arm tab:flagship REPORTS on each row.") +print(" arm + proposer taken from status/chain/flagship_chain_arm.json (flagship_latex._best_arm's own export);") +print(" the N=4 / N=16 arms are that string with ONLY the N token changed.") +sel=json.load(open("status/chain/flagship_chain_arm.json")) +curve={} +for label, rec in sel.items(): + task, arm = rec["task"], rec["chain_arm"] + a=agg(task) + want={} + for n in (4,16,128): + want[n]=re.sub(r"\bN128\b", f"N{n}", arm) + # pick the proposer that carries the published N=128 arm (the pinned one), then read all three on it + props=[p for (ar,p) in a if isinstance(ar,tuple) and ar[0]=="rsm:membership" and ar[1]==want[128]] + if not props: + print(f"\n== {label}: published arm {arm!r} not found -- skipped"); continue + pol=max(props, key=lambda p: a[(("rsm:membership",want[128]),p)][2]) + print(f"\n== {label} ({task}) arm={arm!r} proposer={pol} exported rate={rec['chain_rate']:.1f}") + got={} + for n in (4,16,128): + v=a.get((("rsm:membership",want[n]),pol)) + got[n]=v + print(f" N={n:<4d} {fmt(v)} arm={want[n]!r}") + curve[SHORT[task]]=got + +print() +print("-- SCORING THE PREDICTION PRE-REGISTERED 2026-09-26 17:05Z (#287 section 3), complete arms only (c>=9).") +print(" Wording: on the rows where a CRITIC arm loses >=10 points from N=4 to N=128, RSM at N=128 is within") +print(" 2 SEM of, or above, its own N=4 value on >=3 of 4. FALSIFIED if RSM loses more than 2 SEM on >=2.") +scored=[] +for short,got in sorted(curve.items()): + n4,n128=got.get(4),got.get(128) + if not (n4 and n128) or n4[2]<9 or n128[2]<9: + print(f" PENDING {short:8s} N=4 c={n4[2] if n4 else 0}, N=128 c={n128[2] if n128 else 0}") + continue + r4,r128=rate(n4),rate(n128) + s=math.sqrt(se(n4[0],n4[1])**2+se(n128[0],n128[1])**2) + ok = r128 >= r4-2*s + scored.append((short,ok,r4,r128,2*s)) + print(f" {'HOLDS ' if ok else 'LOSES '} {short:8s} N=4 {r4:5.1f} -> N=128 {r128:5.1f} (delta {r128-r4:+5.1f}, 2SEM {2*s:4.1f})") +if scored: + print(f" complete rows: {len(scored)}; holds {sum(1 for x in scored if x[1])}, loses-by->2SEM {sum(1 for x in scored if not x[1])}") + print(" (The 4 pre-registered in-scope rows are Sq-C, Pc-S, Pc-C, Pc-tip -- the rows where a critic arm") + print(" loses >=10 points from N=4 to N=128. Verdict is stated only when all four are at c>=9.)") + +print() +print("="*120) +print("(2) THE CRITIC N CURVE AT FINAL COUNTS (run 25's 28-cell top-up). `random` = the row's N=1 control.") +NS={"N=4","N=16","N=128"} +for task,short in ROWS: + a=agg(task) + fams=collections.defaultdict(dict); ctls={} + for (arm,p),v in a.items(): + if not isinstance(arm,tuple): continue + a0,a1=str(arm[0]),str(arm[1]) + if a0=="random": ctls[(a1,str(p))]=v + if a0 in ("critic (planner ctl)","critic:dino(Dq)") and a1 in NS: fams[(a0,str(p))][a1]=v + for (fam,p),row in sorted(fams.items()): + lab="pixel" if fam=="critic (planner ctl)" else "DINO " + ctl=ctls.get((fam,p)) + cs=fmt(ctl) if ctl else f"{'--':>26s}" + print(f"{short:8s} {lab} prop={p:16s} ctl {cs} | " + + " | ".join(f"N={n.split('=')[1]:>3s} {fmt(row.get(n))}" for n in ("N=4","N=16","N=128"))) + +print() +print("="*120) +print("(3) EXPECTILE LEG -- IFQL tau arms and IDQL-DINO tau arms") +for task,short in ROWS: + a=agg(task); got=[] + for (arm,p),v in a.items(): + if not isinstance(arm,tuple): continue + if ("t0" in str(arm[0])) and "N=128" in str(arm[1]): got.append((str(arm[0]),str(p),v)) + if not got: continue + print(f"-- {short} ({task})") + for a0,p,v in sorted(got): print(f" {a0:34s} prop={p:14s} {fmt(v)}") +PYEOF +echo "reads finished $(date -u +%H:%M:%SZ)" +cat $O/reads.txt + +# (3) the pre-registered condition, scored against the four IN-SCOPE rows BY NAME. +python3 - > $O/inscope.txt 2>&1 <<'PY2' +import collections, json, math, os, re +os.environ["RSM_EXTRA_EPOCHS"] = "500" +import verdict_table as vt +def se(n,k): + p=k/n if n else 0.0 + return 100*math.sqrt(max(p*(1-p),0)/n) if n else 0.0 +# in-scope = the rows where a CRITIC arm loses >=10 points from N=4 to N=128 (#287 section 3, 17:05Z) +INSCOPE = {"square_expert_play":"Sq-C", "two_piece_expert_suboptimal":"Pc-S", + "two_piece_expert_play":"Pc-C", "two_piece_expert_play_tipping":"Pc-tip"} +sel = json.load(open("status/chain/flagship_chain_arm.json")) +print("PRE-REGISTERED 2026-09-26 17:05Z: on the in-scope rows, RSM at N=128 is within 2 SEM of, or above,") +print("its own N=4 value on >=3 of 4. FALSIFIED if RSM loses by more than 2 SEM on >=2 of 4.") +rows = [] +for label, rec in sel.items(): + task, arm = rec["task"], rec["chain_arm"] + if task not in INSCOPE: continue + agg = collections.defaultdict(lambda: [0,0,0]) + for (a,p,ps,es),v in vt.cells(task).items(): + x = agg[(a,p)]; x[0]+=len(v); x[1]+=sum(v); x[2]+=1 + want = {n: re.sub(r"\bN128\b", "N%d" % n, arm) for n in (4,16,128)} + props = [p for (ar,p) in agg if isinstance(ar,tuple) and ar[0]=="rsm:membership" and ar[1]==want[128]] + if not props: + print(" %-7s published arm not found -- SKIPPED" % INSCOPE[task]); continue + pol = max(props, key=lambda p: agg[(("rsm:membership",want[128]),p)][2]) + g = {n: agg.get((("rsm:membership",want[n]),pol)) for n in (4,16,128)} + n4, n128 = g[4], g[128] + if not (n4 and n128) or n4[2] < 9 or n128[2] < 9: + print(" %-7s PENDING c(N=4)=%d c(N=128)=%d" % (INSCOPE[task], n4[2] if n4 else 0, n128[2] if n128 else 0)) + rows.append((INSCOPE[task], None)); continue + r4 = 100*n4[1]/n4[0]; r128 = 100*n128[1]/n128[0] + two = 2*math.sqrt(se(n4[0],n4[1])**2 + se(n128[0],n128[1])**2) + ok = r128 >= r4 - two + rows.append((INSCOPE[task], ok)) + print(" %-7s %s N=4 %5.1f (n=%d) -> N=128 %5.1f (n=%d) delta %+5.1f 2SEM %4.1f" + % (INSCOPE[task], "HOLDS" if ok else "LOSES", r4, n4[0], r128, n128[0], r128-r4, two)) +holds = sum(1 for r in rows if r[1] is True) +loses = sum(1 for r in rows if r[1] is False) +pend = sum(1 for r in rows if r[1] is None) +print("\nin-scope rows: %d holds %d loses-by->2SEM %d pending %d" % (len(rows), holds, loses, pend)) +if holds >= 3: + print("VERDICT: CONFIRMED at full scope -- >=3 of 4 hold, so the pending row cannot change it.") +elif loses >= 2: + print("VERDICT: FALSIFIED at full scope -- >=2 of 4 lose by more than 2 SEM.") +else: + print("VERDICT: NOT YET STATEABLE -- holds %d, loses %d, %d row(s) below c=9." % (holds, loses, pend)) +PY2 +cat $O/inscope.txt + +# --------------------------------------------------------------------------------------------------- +# run 29 ADDITION -- DELIVERABLE 2 COMPLETENESS AUDIT (#287): "every task has COMPLETE 3x3 `mpcd` arms +# across the H grid for DINO-WM, LeWM and DF" (owner, 2026-09-25 ~20:55 UTC). This has never been read +# out as a single table; runs 22-28 were spent on the tau/gamma legs and on the N sweep. It reports the +# CELL COUNT c per (task, family, H, M) for mpcd arms only -- 9 = a complete 3x3 -- so the top-up list is +# the set of (task, family, H) below 9. It uses verdict_table's own loader and the same "mpcd in the +# recipe tokens" test flagship_latex._wm_arm_is applies, so it cannot disagree with the published column. +python3 - > $O/d2_mpcd_completeness.txt 2>&1 <<'PY3' +import collections, os, re +os.environ["RSM_EXTRA_EPOCHS"] = "500" +import verdict_table as vt +ROWS = [("square_sub_20100","Sq-S"),("square_expert_play","Sq-C"), + ("two_piece_expert_suboptimal","Pc-S"),("two_piece_expert_play","Pc-C"), + ("mug_expert_suboptimal","Mug"),("threading_expert_play","Thr"), + ("two_piece_expert_play_tipping","Pc-tip")] +FAMS = ("wm:dinowm","wm:lewm","wm:df") +print("DELIVERABLE 2 -- completeness of the `mpcd` (discounted-sum) world-model arms, 3x3 = 9 cells.") +print("c = number of (proposer-seed x eval-seed) cells that have landed; n = episodes.") +print("An arm is `mpcd` iff its recipe starts with H and has the token 'mpcd' -- flagship_latex._wm_arm_is.\n") +grand = collections.defaultdict(lambda: [0,0,0]) +for task, short in ROWS: + a = collections.defaultdict(lambda: [0,0,0]) + for (arm,p,ps,es),v in vt.cells(task).items(): + if not isinstance(arm, tuple): continue + fam, rec = str(arm[0]), str(arm[1]) + if fam not in FAMS: continue + if not (rec[:1]=="H" and "mpcd" in rec.split()): continue + H = rec.split()[0][1:] + M = "M1" + m = re.search(r"M(\d+)", rec) + if m: M = "M"+m.group(1) + x = a[(fam,H,M)]; x[0]+=len(v); x[1]+=sum(v); x[2]+=1 + g = grand[(fam,H,M)]; g[0]+=len(v); g[1]+=sum(v); g[2]+=1 + print("== %-7s (%s)" % (short, task)) + if not a: + print(" (no mpcd arms at all)") + continue + for (fam,H,M) in sorted(a, key=lambda k:(k[0], int(k[1]), k[2])): + v = a[(fam,H,M)] + flag = "" if v[2]>=9 else (" <-- INCOMPLETE (%d/9)" % v[2]) + print(" %-11s H=%-4s %-5s c=%2d n=%4d rate=%5.1f%s" % + (fam, H, M, v[2], v[0], 100*v[1]/max(v[0],1), flag)) + print() +print("="*100) +print("ROLLED UP OVER THE 7 TASKS (a complete (family,H,M) leg = 63 cells = 7 tasks x 9):") +for (fam,H,M) in sorted(grand, key=lambda k:(k[0], int(k[1]), k[2])): + v = grand[(fam,H,M)] + print(" %-11s H=%-4s %-5s cells=%2d/63 %s" % (fam,H,M,v[2], "COMPLETE" if v[2]>=63 else "")) +PY3 +cat $O/d2_mpcd_completeness.txt + +# ------------------------------------------------------------------------------------------------ +# run 30 ADDITION -- DELIVERABLE 1 READ-OUT: every IQL-critic arm on the PINNED proposer, per task. +# Run 29's flagship census read `RISE (DINO) 0/0/0/0/0/9/0`: the published column follows the LIVE +# per-step-ViT family (`critic:dino`), which has cells on threading only, while the fast path +# (`critic:dino(Dq)`, the precomputed pooled DINO state RSM reads -- owner 2026-09-26 05:00Z) has +# landed on all 7 rows at 900 episodes and was invisible to every table. This prints both families +# beside the pixel critic they isolate the representation against, at MATCHED N, so the deliverable-1 +# comparison can be read without the table's best-over-configurations convention in the way. +python3 - > $O/d1_critic_readout.txt 2>&1 <<'PY4' +import collections, os +os.environ["RSM_EXTRA_EPOCHS"] = "500" +import verdict_table as vt +import flagship_latex as fl +# The flagship's Sq-S row is square_sub_20100, NOT verdict_table's square_expert_suboptimal +# (flagship_latex.FLAGSHIP_VARIANT) -- a long-standing discrepancy flagged on #287. Read BOTH so the +# read-out cannot silently miss the row the paper prints. +TASKS = [fl.FLAGSHIP_VARIANT.get(t, (t,))[0] for t, _ in vt.TASKS] + ["square_expert_suboptimal"] +print("DELIVERABLE 1 -- IQL-critic arms on the pinned proposer (flagship task list).") +print("fams: `critic` = published pixel RISE critic; `critic (planner ctl)` = same pixel critic routed") +print(" through OUR planner; `critic:dino` = live per-step ViT; `critic:dino(Dq)` = precomputed") +print(" cache features + critic-only (the fast path). c = cells (3x3 = 9 complete).\n") +for task in TASKS: + pin = fl.PROPOSER_BY_TASK.get(task) + print("== %-32s pinned proposer: %s" % (task, pin)) + a = collections.defaultdict(lambda: [0, 0, 0]) + try: + C = vt.cells(task) + except Exception as e: + print(" (loader error: %s)" % e); continue + for (arm, p, ps, es), v in C.items(): + if not isinstance(arm, tuple): continue + fam, rec = str(arm[0]), str(arm[1]) + if not fam.startswith("critic"): continue + x = a[(fam, rec, str(p))]; x[0] += len(v); x[1] += sum(v); x[2] += 1 + if not a: + print(" (no critic arms)"); continue + for k in sorted(a): + v = a[k] + print(" %-26s %-10s / %-22s c=%2d n=%4d rate=%5.1f" % + (k[0], k[1], k[2], v[2], v[0], 100 * v[1] / max(v[0], 1))) + print() +PY4 +cat $O/d1_critic_readout.txt + +# ------------------------------------------------------------------------------------------------ +# run 33 ADDITION -- the PINNED-PROPOSER gamma legs for Mug and Thr (run 32 section 3). All 252 IFQL +# gamma cells had been launched on the RISE actor only; the two rows whose flagship proposer is pinned +# elsewhere (Mug -> BC-expert S3H1, Thr -> IDQL policy S0Aidql@500) therefore contributed NOTHING to a +# best-over-gamma read-out and its disclosed search read 1, not 5. 72 cells were launched on the +# pinned proposers (jobs 1930200-1930202, 1930204-1930206, all DONE 23:4xZ). This prints every +# `critic:ifql` arm BY PROPOSER on those two rows, so "the cells exist and the loader attributes them +# to the pinned proposer" is a measurement and not an inference from the filenames. +python3 - > $O/r33_ifql_by_proposer.txt 2>&1 <<'PY5' +import collections, os +os.environ["RSM_EXTRA_EPOCHS"] = "500" +import verdict_table as vt +import flagship_latex as fl +ROWS = [("mug_expert_suboptimal","Mug"), ("threading_expert_play","Thr"), + ("square_sub_20100","Sq-S")] # Sq-S as the control: it was already on the pinned proposer +print("IFQL critic arms BY PROPOSER (c = cells; a complete 3x3 = 9).") +print("The flagship reads ONLY the pinned proposer, so a gamma arm on any other proposer is invisible") +print("to tab:flagship no matter how many cells it has.\n") +for task, short in ROWS: + pin = fl.PROPOSER_BY_TASK.get(task) + print("== %-7s (%-30s) pinned proposer: %s" % (short, task, pin)) + a = collections.defaultdict(lambda: [0,0,0]) + try: + C = vt.cells(task) + except Exception as e: + print(" (loader error: %s)" % e); continue + for (arm,p,ps,es),v in C.items(): + if not isinstance(arm, tuple): continue + fam, rec = str(arm[0]), str(arm[1]) + if not fam.startswith("critic:ifql"): continue + x = a[(fam,str(p))]; x[0]+=len(v); x[1]+=sum(v); x[2]+=1 + if not a: + print(" (no critic:ifql arms)"); continue + for k in sorted(a): + v = a[k] + mark = " <== PINNED" if k[1] == str(pin) else "" + print(" %-28s prop=%-22s c=%2d n=%4d rate=%5.1f%s" % + (k[0], k[1], v[2], v[0], 100*v[1]/max(v[0],1), mark)) + print() +PY5 +cat $O/r33_ifql_by_proposer.txt diff --git a/rsm_rise/scripts/rr_cpu_basetopup_run34.sh b/rsm_rise/scripts/rr_cpu_basetopup_run34.sh new file mode 100644 index 0000000000000000000000000000000000000000..216b3db49b29aae995fdcf2c86724b12e3aef06d --- /dev/null +++ b/rsm_rise/scripts/rr_cpu_basetopup_run34.sh @@ -0,0 +1,378 @@ +#!/usr/bin/env bash +# BASE_TOPUP run 34. Generated from scripts/rr_cpu_basetopup_run33.sh: everything from the first +# `verdict_table` call down is that file with `run30` -> `run32` (the diff baselines) and the output dir +# changed, so the read-out numbers cannot differ from run 32's by transcription. +# +# NEW THIS RUN -- owner 2026-09-26 04:30Z item (b): "Keep the builder able to print BOTH +# (published-discount column and best-over-gamma column)". `flagship_latex` gained an env-gated +# SEVENTH scorer column (RR_IFQL_BESTG=1 -> `critic:ifql(bestg)`, a union over {published 0.9999} u +# {pure gamma variants}, tau variants deliberately excluded). Two builds, in this order: +# (1) the GATED build, whose stdout also discloses which discount won on each row; +# (2) the DEFAULT build LAST, so the .tex files left on disk are the published ones and never the +# gated variant -- the gated column must not be able to reach a paper table by being built last. +# The default build's diff against run 32 is the proof that no published number moved. +set -uo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +source scripts/env.sh >/dev/null 2>&1 +O=status/basetopup/run34; mkdir -p $O +export PYTHONPATH=/proj/dmfexp/zwhong/rsm_rise/scripts:${PYTHONPATH:-} + +echo "=== (1) GATED build: RR_IFQL_BESTG=1 (writes .tex, overwritten by step 2 below) ===" +RR_IFQL_BESTG=1 python3 scripts/flagship_latex.py > $O/flag_bestg.txt 2> $O/flag_bestg.err; echo "gated rc=$?" +grep -E "RR_IFQL_BESTG|best-gamma|SEVENTH" $O/flag_bestg.txt | head -40 +echo "--- the gated column as the all-table renders it (IFQL (best) header + row cells):" +grep -nE "IFQL \(best" docs/tex/*.tex | head -10 +cp -p docs/tex/tab_rise_flagship_all.tex $O/all_bestg.tex 2>/dev/null || true + +echo "=== (2) DEFAULT build LAST -- this is what stays on disk ===" +python3 scripts/verdict_table.py > $O/verdict_now.txt 2> $O/verdict_now.err; echo "verdict rc=$?" +python3 scripts/flagship_latex.py > $O/flag_now.txt 2> $O/flag_now.err; echo "flagship rc=$?" +diff -u status/basetopup/run33/verdict_now.txt $O/verdict_now.txt > $O/verdict.diff 2>/dev/null; echo "verdict diff lines: $(wc -l < $O/verdict.diff)" +diff -u status/basetopup/run33/flag_now.txt $O/flag_now.txt > $O/flag.diff 2>/dev/null; echo "flag diff lines: $(wc -l < $O/flag.diff)" + +echo "reads started $(date -u +%H:%M:%SZ)" +python3 - > $O/reads.txt 2>&1 <<'PYEOF' +import collections, json, math, os, re, importlib +os.environ["RSM_EXTRA_EPOCHS"] = "500" +print("RSM_EXTRA_EPOCHS =", os.environ["RSM_EXTRA_EPOCHS"], "(set explicitly, integrity item 10)") +import verdict_table as vt + +def se(n,k): + p=k/n if n else 0.0 + return 100*math.sqrt(max(p*(1-p),0)/n) if n else 0.0 +def agg(task): + out=collections.defaultdict(lambda:[0,0,0]) + for (arm,p,ps,es),v in vt.cells(task).items(): + a=out[(arm,p)]; a[0]+=len(v); a[1]+=sum(v); a[2]+=1 + return out +def fmt(v): + return f"{100*v[1]/max(v[0],1):5.1f}+-{se(v[0],v[1]):4.1f} (n={v[0]:4d},c={v[2]:2d})" if v else f"{'--':>26s}" +def rate(v): return 100*v[1]/max(v[0],1) if v else None + +ROWS = [("square_sub_20100","Sq-S"),("square_expert_play","Sq-C"), + ("two_piece_expert_suboptimal","Pc-S"),("two_piece_expert_play","Pc-C"), + ("mug_expert_suboptimal","Mug"),("threading_expert_play","Thr"), + ("two_piece_expert_play_tipping","Pc-tip")] +SHORT={t:s for t,s in ROWS} + +print("="*120) +print("(1) THE RSM N CURVE -- the mirror of the baseline curve, on the arm tab:flagship REPORTS on each row.") +print(" arm + proposer taken from status/chain/flagship_chain_arm.json (flagship_latex._best_arm's own export);") +print(" the N=4 / N=16 arms are that string with ONLY the N token changed.") +sel=json.load(open("status/chain/flagship_chain_arm.json")) +curve={} +for label, rec in sel.items(): + task, arm = rec["task"], rec["chain_arm"] + a=agg(task) + want={} + for n in (4,16,128): + want[n]=re.sub(r"\bN128\b", f"N{n}", arm) + # pick the proposer that carries the published N=128 arm (the pinned one), then read all three on it + props=[p for (ar,p) in a if isinstance(ar,tuple) and ar[0]=="rsm:membership" and ar[1]==want[128]] + if not props: + print(f"\n== {label}: published arm {arm!r} not found -- skipped"); continue + pol=max(props, key=lambda p: a[(("rsm:membership",want[128]),p)][2]) + print(f"\n== {label} ({task}) arm={arm!r} proposer={pol} exported rate={rec['chain_rate']:.1f}") + got={} + for n in (4,16,128): + v=a.get((("rsm:membership",want[n]),pol)) + got[n]=v + print(f" N={n:<4d} {fmt(v)} arm={want[n]!r}") + curve[SHORT[task]]=got + +print() +print("-- SCORING THE PREDICTION PRE-REGISTERED 2026-09-26 17:05Z (#287 section 3), complete arms only (c>=9).") +print(" Wording: on the rows where a CRITIC arm loses >=10 points from N=4 to N=128, RSM at N=128 is within") +print(" 2 SEM of, or above, its own N=4 value on >=3 of 4. FALSIFIED if RSM loses more than 2 SEM on >=2.") +scored=[] +for short,got in sorted(curve.items()): + n4,n128=got.get(4),got.get(128) + if not (n4 and n128) or n4[2]<9 or n128[2]<9: + print(f" PENDING {short:8s} N=4 c={n4[2] if n4 else 0}, N=128 c={n128[2] if n128 else 0}") + continue + r4,r128=rate(n4),rate(n128) + s=math.sqrt(se(n4[0],n4[1])**2+se(n128[0],n128[1])**2) + ok = r128 >= r4-2*s + scored.append((short,ok,r4,r128,2*s)) + print(f" {'HOLDS ' if ok else 'LOSES '} {short:8s} N=4 {r4:5.1f} -> N=128 {r128:5.1f} (delta {r128-r4:+5.1f}, 2SEM {2*s:4.1f})") +if scored: + print(f" complete rows: {len(scored)}; holds {sum(1 for x in scored if x[1])}, loses-by->2SEM {sum(1 for x in scored if not x[1])}") + print(" (The 4 pre-registered in-scope rows are Sq-C, Pc-S, Pc-C, Pc-tip -- the rows where a critic arm") + print(" loses >=10 points from N=4 to N=128. Verdict is stated only when all four are at c>=9.)") + +print() +print("="*120) +print("(2) THE CRITIC N CURVE AT FINAL COUNTS (run 25's 28-cell top-up). `random` = the row's N=1 control.") +NS={"N=4","N=16","N=128"} +for task,short in ROWS: + a=agg(task) + fams=collections.defaultdict(dict); ctls={} + for (arm,p),v in a.items(): + if not isinstance(arm,tuple): continue + a0,a1=str(arm[0]),str(arm[1]) + if a0=="random": ctls[(a1,str(p))]=v + if a0 in ("critic (planner ctl)","critic:dino(Dq)") and a1 in NS: fams[(a0,str(p))][a1]=v + for (fam,p),row in sorted(fams.items()): + lab="pixel" if fam=="critic (planner ctl)" else "DINO " + ctl=ctls.get((fam,p)) + cs=fmt(ctl) if ctl else f"{'--':>26s}" + print(f"{short:8s} {lab} prop={p:16s} ctl {cs} | " + + " | ".join(f"N={n.split('=')[1]:>3s} {fmt(row.get(n))}" for n in ("N=4","N=16","N=128"))) + +print() +print("="*120) +print("(3) EXPECTILE LEG -- IFQL tau arms and IDQL-DINO tau arms") +for task,short in ROWS: + a=agg(task); got=[] + for (arm,p),v in a.items(): + if not isinstance(arm,tuple): continue + if ("t0" in str(arm[0])) and "N=128" in str(arm[1]): got.append((str(arm[0]),str(p),v)) + if not got: continue + print(f"-- {short} ({task})") + for a0,p,v in sorted(got): print(f" {a0:34s} prop={p:14s} {fmt(v)}") +PYEOF +echo "reads finished $(date -u +%H:%M:%SZ)" +cat $O/reads.txt + +# (3) the pre-registered condition, scored against the four IN-SCOPE rows BY NAME. +python3 - > $O/inscope.txt 2>&1 <<'PY2' +import collections, json, math, os, re +os.environ["RSM_EXTRA_EPOCHS"] = "500" +import verdict_table as vt +def se(n,k): + p=k/n if n else 0.0 + return 100*math.sqrt(max(p*(1-p),0)/n) if n else 0.0 +# in-scope = the rows where a CRITIC arm loses >=10 points from N=4 to N=128 (#287 section 3, 17:05Z) +INSCOPE = {"square_expert_play":"Sq-C", "two_piece_expert_suboptimal":"Pc-S", + "two_piece_expert_play":"Pc-C", "two_piece_expert_play_tipping":"Pc-tip"} +sel = json.load(open("status/chain/flagship_chain_arm.json")) +print("PRE-REGISTERED 2026-09-26 17:05Z: on the in-scope rows, RSM at N=128 is within 2 SEM of, or above,") +print("its own N=4 value on >=3 of 4. FALSIFIED if RSM loses by more than 2 SEM on >=2 of 4.") +rows = [] +for label, rec in sel.items(): + task, arm = rec["task"], rec["chain_arm"] + if task not in INSCOPE: continue + agg = collections.defaultdict(lambda: [0,0,0]) + for (a,p,ps,es),v in vt.cells(task).items(): + x = agg[(a,p)]; x[0]+=len(v); x[1]+=sum(v); x[2]+=1 + want = {n: re.sub(r"\bN128\b", "N%d" % n, arm) for n in (4,16,128)} + props = [p for (ar,p) in agg if isinstance(ar,tuple) and ar[0]=="rsm:membership" and ar[1]==want[128]] + if not props: + print(" %-7s published arm not found -- SKIPPED" % INSCOPE[task]); continue + pol = max(props, key=lambda p: agg[(("rsm:membership",want[128]),p)][2]) + g = {n: agg.get((("rsm:membership",want[n]),pol)) for n in (4,16,128)} + n4, n128 = g[4], g[128] + if not (n4 and n128) or n4[2] < 9 or n128[2] < 9: + print(" %-7s PENDING c(N=4)=%d c(N=128)=%d" % (INSCOPE[task], n4[2] if n4 else 0, n128[2] if n128 else 0)) + rows.append((INSCOPE[task], None)); continue + r4 = 100*n4[1]/n4[0]; r128 = 100*n128[1]/n128[0] + two = 2*math.sqrt(se(n4[0],n4[1])**2 + se(n128[0],n128[1])**2) + ok = r128 >= r4 - two + rows.append((INSCOPE[task], ok)) + print(" %-7s %s N=4 %5.1f (n=%d) -> N=128 %5.1f (n=%d) delta %+5.1f 2SEM %4.1f" + % (INSCOPE[task], "HOLDS" if ok else "LOSES", r4, n4[0], r128, n128[0], r128-r4, two)) +holds = sum(1 for r in rows if r[1] is True) +loses = sum(1 for r in rows if r[1] is False) +pend = sum(1 for r in rows if r[1] is None) +print("\nin-scope rows: %d holds %d loses-by->2SEM %d pending %d" % (len(rows), holds, loses, pend)) +if holds >= 3: + print("VERDICT: CONFIRMED at full scope -- >=3 of 4 hold, so the pending row cannot change it.") +elif loses >= 2: + print("VERDICT: FALSIFIED at full scope -- >=2 of 4 lose by more than 2 SEM.") +else: + print("VERDICT: NOT YET STATEABLE -- holds %d, loses %d, %d row(s) below c=9." % (holds, loses, pend)) +PY2 +cat $O/inscope.txt + +# --------------------------------------------------------------------------------------------------- +# run 29 ADDITION -- DELIVERABLE 2 COMPLETENESS AUDIT (#287): "every task has COMPLETE 3x3 `mpcd` arms +# across the H grid for DINO-WM, LeWM and DF" (owner, 2026-09-25 ~20:55 UTC). This has never been read +# out as a single table; runs 22-28 were spent on the tau/gamma legs and on the N sweep. It reports the +# CELL COUNT c per (task, family, H, M) for mpcd arms only -- 9 = a complete 3x3 -- so the top-up list is +# the set of (task, family, H) below 9. It uses verdict_table's own loader and the same "mpcd in the +# recipe tokens" test flagship_latex._wm_arm_is applies, so it cannot disagree with the published column. +python3 - > $O/d2_mpcd_completeness.txt 2>&1 <<'PY3' +import collections, os, re +os.environ["RSM_EXTRA_EPOCHS"] = "500" +import verdict_table as vt +ROWS = [("square_sub_20100","Sq-S"),("square_expert_play","Sq-C"), + ("two_piece_expert_suboptimal","Pc-S"),("two_piece_expert_play","Pc-C"), + ("mug_expert_suboptimal","Mug"),("threading_expert_play","Thr"), + ("two_piece_expert_play_tipping","Pc-tip")] +FAMS = ("wm:dinowm","wm:lewm","wm:df") +print("DELIVERABLE 2 -- completeness of the `mpcd` (discounted-sum) world-model arms, 3x3 = 9 cells.") +print("c = number of (proposer-seed x eval-seed) cells that have landed; n = episodes.") +print("An arm is `mpcd` iff its recipe starts with H and has the token 'mpcd' -- flagship_latex._wm_arm_is.\n") +grand = collections.defaultdict(lambda: [0,0,0]) +for task, short in ROWS: + a = collections.defaultdict(lambda: [0,0,0]) + for (arm,p,ps,es),v in vt.cells(task).items(): + if not isinstance(arm, tuple): continue + fam, rec = str(arm[0]), str(arm[1]) + if fam not in FAMS: continue + if not (rec[:1]=="H" and "mpcd" in rec.split()): continue + H = rec.split()[0][1:] + M = "M1" + m = re.search(r"M(\d+)", rec) + if m: M = "M"+m.group(1) + x = a[(fam,H,M)]; x[0]+=len(v); x[1]+=sum(v); x[2]+=1 + g = grand[(fam,H,M)]; g[0]+=len(v); g[1]+=sum(v); g[2]+=1 + print("== %-7s (%s)" % (short, task)) + if not a: + print(" (no mpcd arms at all)") + continue + for (fam,H,M) in sorted(a, key=lambda k:(k[0], int(k[1]), k[2])): + v = a[(fam,H,M)] + flag = "" if v[2]>=9 else (" <-- INCOMPLETE (%d/9)" % v[2]) + print(" %-11s H=%-4s %-5s c=%2d n=%4d rate=%5.1f%s" % + (fam, H, M, v[2], v[0], 100*v[1]/max(v[0],1), flag)) + print() +print("="*100) +print("ROLLED UP OVER THE 7 TASKS (a complete (family,H,M) leg = 63 cells = 7 tasks x 9):") +for (fam,H,M) in sorted(grand, key=lambda k:(k[0], int(k[1]), k[2])): + v = grand[(fam,H,M)] + print(" %-11s H=%-4s %-5s cells=%2d/63 %s" % (fam,H,M,v[2], "COMPLETE" if v[2]>=63 else "")) +PY3 +cat $O/d2_mpcd_completeness.txt + +# ------------------------------------------------------------------------------------------------ +# run 30 ADDITION -- DELIVERABLE 1 READ-OUT: every IQL-critic arm on the PINNED proposer, per task. +# Run 29's flagship census read `RISE (DINO) 0/0/0/0/0/9/0`: the published column follows the LIVE +# per-step-ViT family (`critic:dino`), which has cells on threading only, while the fast path +# (`critic:dino(Dq)`, the precomputed pooled DINO state RSM reads -- owner 2026-09-26 05:00Z) has +# landed on all 7 rows at 900 episodes and was invisible to every table. This prints both families +# beside the pixel critic they isolate the representation against, at MATCHED N, so the deliverable-1 +# comparison can be read without the table's best-over-configurations convention in the way. +python3 - > $O/d1_critic_readout.txt 2>&1 <<'PY4' +import collections, os +os.environ["RSM_EXTRA_EPOCHS"] = "500" +import verdict_table as vt +import flagship_latex as fl +# The flagship's Sq-S row is square_sub_20100, NOT verdict_table's square_expert_suboptimal +# (flagship_latex.FLAGSHIP_VARIANT) -- a long-standing discrepancy flagged on #287. Read BOTH so the +# read-out cannot silently miss the row the paper prints. +TASKS = [fl.FLAGSHIP_VARIANT.get(t, (t,))[0] for t, _ in vt.TASKS] + ["square_expert_suboptimal"] +print("DELIVERABLE 1 -- IQL-critic arms on the pinned proposer (flagship task list).") +print("fams: `critic` = published pixel RISE critic; `critic (planner ctl)` = same pixel critic routed") +print(" through OUR planner; `critic:dino` = live per-step ViT; `critic:dino(Dq)` = precomputed") +print(" cache features + critic-only (the fast path). c = cells (3x3 = 9 complete).\n") +for task in TASKS: + pin = fl.PROPOSER_BY_TASK.get(task) + print("== %-32s pinned proposer: %s" % (task, pin)) + a = collections.defaultdict(lambda: [0, 0, 0]) + try: + C = vt.cells(task) + except Exception as e: + print(" (loader error: %s)" % e); continue + for (arm, p, ps, es), v in C.items(): + if not isinstance(arm, tuple): continue + fam, rec = str(arm[0]), str(arm[1]) + if not fam.startswith("critic"): continue + x = a[(fam, rec, str(p))]; x[0] += len(v); x[1] += sum(v); x[2] += 1 + if not a: + print(" (no critic arms)"); continue + for k in sorted(a): + v = a[k] + print(" %-26s %-10s / %-22s c=%2d n=%4d rate=%5.1f" % + (k[0], k[1], k[2], v[2], v[0], 100 * v[1] / max(v[0], 1))) + print() +PY4 +cat $O/d1_critic_readout.txt + +# ------------------------------------------------------------------------------------------------ +# run 33 ADDITION -- the PINNED-PROPOSER gamma legs for Mug and Thr (run 32 section 3). All 252 IFQL +# gamma cells had been launched on the RISE actor only; the two rows whose flagship proposer is pinned +# elsewhere (Mug -> BC-expert S3H1, Thr -> IDQL policy S0Aidql@500) therefore contributed NOTHING to a +# best-over-gamma read-out and its disclosed search read 1, not 5. 72 cells were launched on the +# pinned proposers (jobs 1930200-1930202, 1930204-1930206, all DONE 23:4xZ). This prints every +# `critic:ifql` arm BY PROPOSER on those two rows, so "the cells exist and the loader attributes them +# to the pinned proposer" is a measurement and not an inference from the filenames. +python3 - > $O/r33_ifql_by_proposer.txt 2>&1 <<'PY5' +import collections, os +os.environ["RSM_EXTRA_EPOCHS"] = "500" +import verdict_table as vt +import flagship_latex as fl +ROWS = [("mug_expert_suboptimal","Mug"), ("threading_expert_play","Thr"), + ("square_sub_20100","Sq-S")] # Sq-S as the control: it was already on the pinned proposer +print("IFQL critic arms BY PROPOSER (c = cells; a complete 3x3 = 9).") +print("The flagship reads ONLY the pinned proposer, so a gamma arm on any other proposer is invisible") +print("to tab:flagship no matter how many cells it has.\n") +for task, short in ROWS: + pin = fl.PROPOSER_BY_TASK.get(task) + print("== %-7s (%-30s) pinned proposer: %s" % (short, task, pin)) + a = collections.defaultdict(lambda: [0,0,0]) + try: + C = vt.cells(task) + except Exception as e: + print(" (loader error: %s)" % e); continue + for (arm,p,ps,es),v in C.items(): + if not isinstance(arm, tuple): continue + fam, rec = str(arm[0]), str(arm[1]) + if not fam.startswith("critic:ifql"): continue + x = a[(fam,str(p))]; x[0]+=len(v); x[1]+=sum(v); x[2]+=1 + if not a: + print(" (no critic:ifql arms)"); continue + for k in sorted(a): + v = a[k] + mark = " <== PINNED" if k[1] == str(pin) else "" + print(" %-28s prop=%-22s c=%2d n=%4d rate=%5.1f%s" % + (k[0], k[1], v[2], v[0], 100*v[1]/max(v[0],1), mark)) + print() +PY5 +cat $O/r33_ifql_by_proposer.txt + +# ------------------------------------------------------------------------------------------------ +# run 34 ADDITION -- the PINNED-PROPOSER *TAU* legs for Mug and Thr. Run 33 closed the gamma axis on +# the pinned proposers (36 cells/row, best-gamma = the published 0.9999 on both) and launched the tau +# analogue: jobs 1930579 / 1930580 / 1930582, all DONE with every slot exit=0, 9/9 cells on each of +# IFQLCRITS3H1T0P{7,9} and IFQLCRITS0AidqlE500T0P{7,9}. Run 33's read-out saw only 3 of the 9 per arm +# (it was built at 00:15Z, mid-flight) and the partial Mug t0p7 number was 20.7 -- ABOVE that row's +# published 18.4. This section reads the completed arms, so the question "does the expectile axis give +# a pinned row a variant above its published point (unlike the gamma axis)?" is answered from 9 cells. +# It uses verdict_table's loader and flagship_latex.PROPOSER_BY_TASK, never a hand-rolled scan. +python3 - > $O/r34_ifql_tau_pinned.txt 2>&1 <<'PY6' +import collections, os +os.environ["RSM_EXTRA_EPOCHS"] = "500" +import verdict_table as vt +import flagship_latex as fl +ROWS = [("mug_expert_suboptimal","Mug"), ("threading_expert_play","Thr"), + ("square_sub_20100","Sq-S")] # Sq-S: already on its own proposer, the control +print("IFQL critic arms on the PINNED proposer only -- gamma AND tau axes side by side.") +print("c = cells (a complete 3x3 = 9); rate = pooled success over n episodes.") +print("A tau arm above the published row would mean the expectile axis behaves DIFFERENTLY from the") +print("discount axis on the pinned proposers, where run 33 found best-gamma == published on both.\n") +for task, short in ROWS: + pin = fl.PROPOSER_BY_TASK.get(task) + print("== %-6s (%-30s) pinned proposer: %s" % (short, task, pin)) + try: + C = vt.cells(task) + except Exception as e: + print(" (loader error: %s)" % e); continue + a = collections.defaultdict(lambda: [0,0,0]) + for (arm,p,ps,es),v in C.items(): + if not isinstance(arm, tuple): continue + fam = str(arm[0]) + if not fam.startswith("critic:ifql"): continue + if str(p) != str(pin): continue + x = a[fam]; x[0]+=len(v); x[1]+=sum(v); x[2]+=1 + if not a: + print(" (no critic:ifql arms on the pinned proposer)\n"); continue + pub = a.get("critic:ifql") + pubrate = 100*pub[1]/max(pub[0],1) if pub else None + for k in sorted(a, key=lambda k: (0 if k=="critic:ifql" else 1, k)): + v = a[k]; r = 100*v[1]/max(v[0],1) + tag = "PUBLISHED" if k == "critic:ifql" else ("ABOVE published" if pubrate is not None and r > pubrate + 1e-9 else "") + axis = "tau " if "[t" in k else ("gamma" if "[g" in k else " ") + print(" %-28s %s c=%2d n=%4d rate=%5.1f %s" % (k, axis, v[2], v[0], r, tag)) + # the two "best-over-axis" read-outs, complete-arms-only (c==9), so a 3-cell arm cannot win + for axis, pred in (("gamma", lambda k: k.startswith("critic:ifql [g") and "_t" not in k), + ("tau", lambda k: k.startswith("critic:ifql [t"))): + cand = {k: a[k] for k in a if pred(k) and a[k][2] >= 9} + if pub and pub[2] >= 9: cand["critic:ifql"] = pub + if not cand: print(" best-over-%-5s : (no complete arm)" % axis); continue + bk = max(cand, key=lambda k: cand[k][1]/max(cand[k][0],1)) + print(" best-over-%-5s : %-24s rate=%5.1f searched=%d complete arm(s)" + % (axis, bk, 100*cand[bk][1]/max(cand[bk][0],1), len(cand))) + print() +PY6 +cat $O/r34_ifql_tau_pinned.txt diff --git a/rsm_rise/scripts/rr_cpu_basetopup_run35.sh b/rsm_rise/scripts/rr_cpu_basetopup_run35.sh new file mode 100644 index 0000000000000000000000000000000000000000..8c184ac58a7b78c3b1b02ad5ac0dbbf65cb0566b --- /dev/null +++ b/rsm_rise/scripts/rr_cpu_basetopup_run35.sh @@ -0,0 +1,384 @@ +#!/usr/bin/env bash +# BASE_TOPUP run 35. Generated from scripts/rr_cpu_basetopup_run33.sh: everything from the first +# `verdict_table` call down is that file with `run30` -> `run32` (the diff baselines) and the output dir +# changed, so the read-out numbers cannot differ from run 32's by transcription. +# +# NEW THIS RUN -- owner 2026-09-26 04:30Z item (b): "Keep the builder able to print BOTH +# (published-discount column and best-over-gamma column)". `flagship_latex` gained an env-gated +# SEVENTH scorer column (RR_IFQL_BESTG=1 -> `critic:ifql(bestg)`, a union over {published 0.9999} u +# {pure gamma variants}, tau variants deliberately excluded). Two builds, in this order: +# (1) the GATED build, whose stdout also discloses which discount won on each row; +# (2) the DEFAULT build LAST, so the .tex files left on disk are the published ones and never the +# gated variant -- the gated column must not be able to reach a paper table by being built last. +# The default build's diff against run 32 is the proof that no published number moved. +set -uo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +source scripts/env.sh >/dev/null 2>&1 +O=status/basetopup/run35; mkdir -p $O +export PYTHONPATH=/proj/dmfexp/zwhong/rsm_rise/scripts:${PYTHONPATH:-} + +echo "=== (1) GATED build: RR_IFQL_BESTG=1 (writes .tex, overwritten by step 2 below) ===" +RR_IFQL_BESTG=1 python3 scripts/flagship_latex.py > $O/flag_bestg.txt 2> $O/flag_bestg.err; echo "gated rc=$?" +grep -E "RR_IFQL_BESTG|best-gamma|SEVENTH" $O/flag_bestg.txt | head -40 +echo "--- the gated column as the all-table renders it (IFQL (best) header + row cells):" +grep -nE "IFQL \(best" docs/tex/*.tex | head -10 +cp -p docs/tex/tab_rise_flagship_all.tex $O/all_bestg.tex 2>/dev/null || true + +echo "=== (2) DEFAULT build LAST -- this is what stays on disk ===" +python3 scripts/verdict_table.py > $O/verdict_now.txt 2> $O/verdict_now.err; echo "verdict rc=$?" +python3 scripts/flagship_latex.py > $O/flag_now.txt 2> $O/flag_now.err; echo "flagship rc=$?" +diff -u status/basetopup/run34/verdict_now.txt $O/verdict_now.txt > $O/verdict.diff 2>/dev/null; echo "verdict diff lines: $(wc -l < $O/verdict.diff)" +diff -u status/basetopup/run34/flag_now.txt $O/flag_now.txt > $O/flag.diff 2>/dev/null; echo "flag diff lines: $(wc -l < $O/flag.diff)" + +echo "reads started $(date -u +%H:%M:%SZ)" +python3 - > $O/reads.txt 2>&1 <<'PYEOF' +import collections, json, math, os, re, importlib +os.environ["RSM_EXTRA_EPOCHS"] = "500" +print("RSM_EXTRA_EPOCHS =", os.environ["RSM_EXTRA_EPOCHS"], "(set explicitly, integrity item 10)") +import verdict_table as vt + +def se(n,k): + p=k/n if n else 0.0 + return 100*math.sqrt(max(p*(1-p),0)/n) if n else 0.0 +def agg(task): + out=collections.defaultdict(lambda:[0,0,0]) + for (arm,p,ps,es),v in vt.cells(task).items(): + a=out[(arm,p)]; a[0]+=len(v); a[1]+=sum(v); a[2]+=1 + return out +def fmt(v): + return f"{100*v[1]/max(v[0],1):5.1f}+-{se(v[0],v[1]):4.1f} (n={v[0]:4d},c={v[2]:2d})" if v else f"{'--':>26s}" +def rate(v): return 100*v[1]/max(v[0],1) if v else None + +ROWS = [("square_sub_20100","Sq-S"),("square_expert_play","Sq-C"), + ("two_piece_expert_suboptimal","Pc-S"),("two_piece_expert_play","Pc-C"), + ("mug_expert_suboptimal","Mug"),("threading_expert_play","Thr"), + ("two_piece_expert_play_tipping","Pc-tip")] +SHORT={t:s for t,s in ROWS} + +print("="*120) +print("(1) THE RSM N CURVE -- the mirror of the baseline curve, on the arm tab:flagship REPORTS on each row.") +print(" arm + proposer taken from status/chain/flagship_chain_arm.json (flagship_latex._best_arm's own export);") +print(" the N=4 / N=16 arms are that string with ONLY the N token changed.") +sel=json.load(open("status/chain/flagship_chain_arm.json")) +curve={} +for label, rec in sel.items(): + task, arm = rec["task"], rec["chain_arm"] + a=agg(task) + want={} + for n in (4,16,128): + want[n]=re.sub(r"\bN128\b", f"N{n}", arm) + # pick the proposer that carries the published N=128 arm (the pinned one), then read all three on it + props=[p for (ar,p) in a if isinstance(ar,tuple) and ar[0]=="rsm:membership" and ar[1]==want[128]] + if not props: + print(f"\n== {label}: published arm {arm!r} not found -- skipped"); continue + pol=max(props, key=lambda p: a[(("rsm:membership",want[128]),p)][2]) + print(f"\n== {label} ({task}) arm={arm!r} proposer={pol} exported rate={rec['chain_rate']:.1f}") + got={} + for n in (4,16,128): + v=a.get((("rsm:membership",want[n]),pol)) + got[n]=v + print(f" N={n:<4d} {fmt(v)} arm={want[n]!r}") + curve[SHORT[task]]=got + +print() +print("-- SCORING THE PREDICTION PRE-REGISTERED 2026-09-26 17:05Z (#287 section 3), complete arms only (c>=9).") +print(" Wording: on the rows where a CRITIC arm loses >=10 points from N=4 to N=128, RSM at N=128 is within") +print(" 2 SEM of, or above, its own N=4 value on >=3 of 4. FALSIFIED if RSM loses more than 2 SEM on >=2.") +scored=[] +for short,got in sorted(curve.items()): + n4,n128=got.get(4),got.get(128) + if not (n4 and n128) or n4[2]<9 or n128[2]<9: + print(f" PENDING {short:8s} N=4 c={n4[2] if n4 else 0}, N=128 c={n128[2] if n128 else 0}") + continue + r4,r128=rate(n4),rate(n128) + s=math.sqrt(se(n4[0],n4[1])**2+se(n128[0],n128[1])**2) + ok = r128 >= r4-2*s + scored.append((short,ok,r4,r128,2*s)) + print(f" {'HOLDS ' if ok else 'LOSES '} {short:8s} N=4 {r4:5.1f} -> N=128 {r128:5.1f} (delta {r128-r4:+5.1f}, 2SEM {2*s:4.1f})") +if scored: + print(f" complete rows: {len(scored)}; holds {sum(1 for x in scored if x[1])}, loses-by->2SEM {sum(1 for x in scored if not x[1])}") + print(" (The 4 pre-registered in-scope rows are Sq-C, Pc-S, Pc-C, Pc-tip -- the rows where a critic arm") + print(" loses >=10 points from N=4 to N=128. Verdict is stated only when all four are at c>=9.)") + +print() +print("="*120) +print("(2) THE CRITIC N CURVE AT FINAL COUNTS (run 25's 28-cell top-up). `random` = the row's N=1 control.") +NS={"N=4","N=16","N=128"} +for task,short in ROWS: + a=agg(task) + fams=collections.defaultdict(dict); ctls={} + for (arm,p),v in a.items(): + if not isinstance(arm,tuple): continue + a0,a1=str(arm[0]),str(arm[1]) + if a0=="random": ctls[(a1,str(p))]=v + if a0 in ("critic (planner ctl)","critic:dino(Dq)") and a1 in NS: fams[(a0,str(p))][a1]=v + for (fam,p),row in sorted(fams.items()): + lab="pixel" if fam=="critic (planner ctl)" else "DINO " + ctl=ctls.get((fam,p)) + cs=fmt(ctl) if ctl else f"{'--':>26s}" + print(f"{short:8s} {lab} prop={p:16s} ctl {cs} | " + + " | ".join(f"N={n.split('=')[1]:>3s} {fmt(row.get(n))}" for n in ("N=4","N=16","N=128"))) + +print() +print("="*120) +print("(3) EXPECTILE LEG -- IFQL tau arms and IDQL-DINO tau arms") +for task,short in ROWS: + a=agg(task); got=[] + for (arm,p),v in a.items(): + if not isinstance(arm,tuple): continue + if ("t0" in str(arm[0])) and "N=128" in str(arm[1]): got.append((str(arm[0]),str(p),v)) + if not got: continue + print(f"-- {short} ({task})") + for a0,p,v in sorted(got): print(f" {a0:34s} prop={p:14s} {fmt(v)}") +PYEOF +echo "reads finished $(date -u +%H:%M:%SZ)" +cat $O/reads.txt + +# (3) the pre-registered condition, scored against the four IN-SCOPE rows BY NAME. +python3 - > $O/inscope.txt 2>&1 <<'PY2' +import collections, json, math, os, re +os.environ["RSM_EXTRA_EPOCHS"] = "500" +import verdict_table as vt +def se(n,k): + p=k/n if n else 0.0 + return 100*math.sqrt(max(p*(1-p),0)/n) if n else 0.0 +# in-scope = the rows where a CRITIC arm loses >=10 points from N=4 to N=128 (#287 section 3, 17:05Z) +INSCOPE = {"square_expert_play":"Sq-C", "two_piece_expert_suboptimal":"Pc-S", + "two_piece_expert_play":"Pc-C", "two_piece_expert_play_tipping":"Pc-tip"} +sel = json.load(open("status/chain/flagship_chain_arm.json")) +print("PRE-REGISTERED 2026-09-26 17:05Z: on the in-scope rows, RSM at N=128 is within 2 SEM of, or above,") +print("its own N=4 value on >=3 of 4. FALSIFIED if RSM loses by more than 2 SEM on >=2 of 4.") +rows = [] +for label, rec in sel.items(): + task, arm = rec["task"], rec["chain_arm"] + if task not in INSCOPE: continue + agg = collections.defaultdict(lambda: [0,0,0]) + for (a,p,ps,es),v in vt.cells(task).items(): + x = agg[(a,p)]; x[0]+=len(v); x[1]+=sum(v); x[2]+=1 + want = {n: re.sub(r"\bN128\b", "N%d" % n, arm) for n in (4,16,128)} + props = [p for (ar,p) in agg if isinstance(ar,tuple) and ar[0]=="rsm:membership" and ar[1]==want[128]] + if not props: + print(" %-7s published arm not found -- SKIPPED" % INSCOPE[task]); continue + pol = max(props, key=lambda p: agg[(("rsm:membership",want[128]),p)][2]) + g = {n: agg.get((("rsm:membership",want[n]),pol)) for n in (4,16,128)} + n4, n128 = g[4], g[128] + if not (n4 and n128) or n4[2] < 9 or n128[2] < 9: + print(" %-7s PENDING c(N=4)=%d c(N=128)=%d" % (INSCOPE[task], n4[2] if n4 else 0, n128[2] if n128 else 0)) + rows.append((INSCOPE[task], None)); continue + r4 = 100*n4[1]/n4[0]; r128 = 100*n128[1]/n128[0] + two = 2*math.sqrt(se(n4[0],n4[1])**2 + se(n128[0],n128[1])**2) + ok = r128 >= r4 - two + rows.append((INSCOPE[task], ok)) + print(" %-7s %s N=4 %5.1f (n=%d) -> N=128 %5.1f (n=%d) delta %+5.1f 2SEM %4.1f" + % (INSCOPE[task], "HOLDS" if ok else "LOSES", r4, n4[0], r128, n128[0], r128-r4, two)) +holds = sum(1 for r in rows if r[1] is True) +loses = sum(1 for r in rows if r[1] is False) +pend = sum(1 for r in rows if r[1] is None) +print("\nin-scope rows: %d holds %d loses-by->2SEM %d pending %d" % (len(rows), holds, loses, pend)) +if holds >= 3: + print("VERDICT: CONFIRMED at full scope -- >=3 of 4 hold, so the pending row cannot change it.") +elif loses >= 2: + print("VERDICT: FALSIFIED at full scope -- >=2 of 4 lose by more than 2 SEM.") +else: + print("VERDICT: NOT YET STATEABLE -- holds %d, loses %d, %d row(s) below c=9." % (holds, loses, pend)) +PY2 +cat $O/inscope.txt + +# --------------------------------------------------------------------------------------------------- +# run 29 ADDITION -- DELIVERABLE 2 COMPLETENESS AUDIT (#287): "every task has COMPLETE 3x3 `mpcd` arms +# across the H grid for DINO-WM, LeWM and DF" (owner, 2026-09-25 ~20:55 UTC). This has never been read +# out as a single table; runs 22-28 were spent on the tau/gamma legs and on the N sweep. It reports the +# CELL COUNT c per (task, family, H, M) for mpcd arms only -- 9 = a complete 3x3 -- so the top-up list is +# the set of (task, family, H) below 9. It uses verdict_table's own loader and the same "mpcd in the +# recipe tokens" test flagship_latex._wm_arm_is applies, so it cannot disagree with the published column. +python3 - > $O/d2_mpcd_completeness.txt 2>&1 <<'PY3' +import collections, os, re +os.environ["RSM_EXTRA_EPOCHS"] = "500" +import verdict_table as vt +ROWS = [("square_sub_20100","Sq-S"),("square_expert_play","Sq-C"), + ("two_piece_expert_suboptimal","Pc-S"),("two_piece_expert_play","Pc-C"), + ("mug_expert_suboptimal","Mug"),("threading_expert_play","Thr"), + ("two_piece_expert_play_tipping","Pc-tip")] +FAMS = ("wm:dinowm","wm:lewm","wm:df") +print("DELIVERABLE 2 -- completeness of the `mpcd` (discounted-sum) world-model arms, 3x3 = 9 cells.") +print("c = number of (proposer-seed x eval-seed) cells that have landed; n = episodes.") +print("An arm is `mpcd` iff its recipe starts with H and has the token 'mpcd' -- flagship_latex._wm_arm_is.\n") +grand = collections.defaultdict(lambda: [0,0,0]) +for task, short in ROWS: + a = collections.defaultdict(lambda: [0,0,0]) + for (arm,p,ps,es),v in vt.cells(task).items(): + if not isinstance(arm, tuple): continue + fam, rec = str(arm[0]), str(arm[1]) + if fam not in FAMS: continue + if not (rec[:1]=="H" and "mpcd" in rec.split()): continue + H = rec.split()[0][1:] + M = "M1" + m = re.search(r"M(\d+)", rec) + if m: M = "M"+m.group(1) + x = a[(fam,H,M)]; x[0]+=len(v); x[1]+=sum(v); x[2]+=1 + g = grand[(fam,H,M)]; g[0]+=len(v); g[1]+=sum(v); g[2]+=1 + print("== %-7s (%s)" % (short, task)) + if not a: + print(" (no mpcd arms at all)") + continue + for (fam,H,M) in sorted(a, key=lambda k:(k[0], int(k[1]), k[2])): + v = a[(fam,H,M)] + flag = "" if v[2]>=9 else (" <-- INCOMPLETE (%d/9)" % v[2]) + print(" %-11s H=%-4s %-5s c=%2d n=%4d rate=%5.1f%s" % + (fam, H, M, v[2], v[0], 100*v[1]/max(v[0],1), flag)) + print() +print("="*100) +print("ROLLED UP OVER THE 7 TASKS (a complete (family,H,M) leg = 63 cells = 7 tasks x 9):") +for (fam,H,M) in sorted(grand, key=lambda k:(k[0], int(k[1]), k[2])): + v = grand[(fam,H,M)] + print(" %-11s H=%-4s %-5s cells=%2d/63 %s" % (fam,H,M,v[2], "COMPLETE" if v[2]>=63 else "")) +PY3 +cat $O/d2_mpcd_completeness.txt + +# ------------------------------------------------------------------------------------------------ +# run 30 ADDITION -- DELIVERABLE 1 READ-OUT: every IQL-critic arm on the PINNED proposer, per task. +# Run 29's flagship census read `RISE (DINO) 0/0/0/0/0/9/0`: the published column follows the LIVE +# per-step-ViT family (`critic:dino`), which has cells on threading only, while the fast path +# (`critic:dino(Dq)`, the precomputed pooled DINO state RSM reads -- owner 2026-09-26 05:00Z) has +# landed on all 7 rows at 900 episodes and was invisible to every table. This prints both families +# beside the pixel critic they isolate the representation against, at MATCHED N, so the deliverable-1 +# comparison can be read without the table's best-over-configurations convention in the way. +python3 - > $O/d1_critic_readout.txt 2>&1 <<'PY4' +import collections, os +os.environ["RSM_EXTRA_EPOCHS"] = "500" +import verdict_table as vt +import flagship_latex as fl +# The flagship's Sq-S row is square_sub_20100, NOT verdict_table's square_expert_suboptimal +# (flagship_latex.FLAGSHIP_VARIANT) -- a long-standing discrepancy flagged on #287. Read BOTH so the +# read-out cannot silently miss the row the paper prints. +TASKS = [fl.FLAGSHIP_VARIANT.get(t, (t,))[0] for t, _ in vt.TASKS] + ["square_expert_suboptimal"] +print("DELIVERABLE 1 -- IQL-critic arms on the pinned proposer (flagship task list).") +print("fams: `critic` = published pixel RISE critic; `critic (planner ctl)` = same pixel critic routed") +print(" through OUR planner; `critic:dino` = live per-step ViT; `critic:dino(Dq)` = precomputed") +print(" cache features + critic-only (the fast path). c = cells (3x3 = 9 complete).\n") +for task in TASKS: + pin = fl.PROPOSER_BY_TASK.get(task) + print("== %-32s pinned proposer: %s" % (task, pin)) + a = collections.defaultdict(lambda: [0, 0, 0]) + try: + C = vt.cells(task) + except Exception as e: + print(" (loader error: %s)" % e); continue + for (arm, p, ps, es), v in C.items(): + if not isinstance(arm, tuple): continue + fam, rec = str(arm[0]), str(arm[1]) + if not fam.startswith("critic"): continue + x = a[(fam, rec, str(p))]; x[0] += len(v); x[1] += sum(v); x[2] += 1 + if not a: + print(" (no critic arms)"); continue + for k in sorted(a): + v = a[k] + print(" %-26s %-10s / %-22s c=%2d n=%4d rate=%5.1f" % + (k[0], k[1], k[2], v[2], v[0], 100 * v[1] / max(v[0], 1))) + print() +PY4 +cat $O/d1_critic_readout.txt + +# ------------------------------------------------------------------------------------------------ +# run 33 ADDITION -- the PINNED-PROPOSER gamma legs for Mug and Thr (run 32 section 3). All 252 IFQL +# gamma cells had been launched on the RISE actor only; the two rows whose flagship proposer is pinned +# elsewhere (Mug -> BC-expert S3H1, Thr -> IDQL policy S0Aidql@500) therefore contributed NOTHING to a +# best-over-gamma read-out and its disclosed search read 1, not 5. 72 cells were launched on the +# pinned proposers (jobs 1930200-1930202, 1930204-1930206, all DONE 23:4xZ). This prints every +# `critic:ifql` arm BY PROPOSER on those two rows, so "the cells exist and the loader attributes them +# to the pinned proposer" is a measurement and not an inference from the filenames. +python3 - > $O/r33_ifql_by_proposer.txt 2>&1 <<'PY5' +import collections, os +os.environ["RSM_EXTRA_EPOCHS"] = "500" +import verdict_table as vt +import flagship_latex as fl +ROWS = [("mug_expert_suboptimal","Mug"), ("threading_expert_play","Thr"), + ("square_sub_20100","Sq-S")] # Sq-S as the control: it was already on the pinned proposer +print("IFQL critic arms BY PROPOSER (c = cells; a complete 3x3 = 9).") +print("The flagship reads ONLY the pinned proposer, so a gamma arm on any other proposer is invisible") +print("to tab:flagship no matter how many cells it has.\n") +for task, short in ROWS: + pin = fl.PROPOSER_BY_TASK.get(task) + print("== %-7s (%-30s) pinned proposer: %s" % (short, task, pin)) + a = collections.defaultdict(lambda: [0,0,0]) + try: + C = vt.cells(task) + except Exception as e: + print(" (loader error: %s)" % e); continue + for (arm,p,ps,es),v in C.items(): + if not isinstance(arm, tuple): continue + fam, rec = str(arm[0]), str(arm[1]) + if not fam.startswith("critic:ifql"): continue + x = a[(fam,str(p))]; x[0]+=len(v); x[1]+=sum(v); x[2]+=1 + if not a: + print(" (no critic:ifql arms)"); continue + for k in sorted(a): + v = a[k] + mark = " <== PINNED" if k[1] == str(pin) else "" + print(" %-28s prop=%-22s c=%2d n=%4d rate=%5.1f%s" % + (k[0], k[1], v[2], v[0], 100*v[1]/max(v[0],1), mark)) + print() +PY5 +cat $O/r33_ifql_by_proposer.txt + +# ------------------------------------------------------------------------------------------------ +# run 34 ADDITION -- the PINNED-PROPOSER *TAU* legs for Mug and Thr. Run 33 closed the gamma axis on +# the pinned proposers (36 cells/row, best-gamma = the published 0.9999 on both) and launched the tau +# analogue: jobs 1930579 / 1930580 / 1930582, all DONE with every slot exit=0, 9/9 cells on each of +# IFQLCRITS3H1T0P{7,9} and IFQLCRITS0AidqlE500T0P{7,9}. Run 33's read-out saw only 3 of the 9 per arm +# (it was built at 00:15Z, mid-flight) and the partial Mug t0p7 number was 20.7 -- ABOVE that row's +# published 18.4. This section reads the completed arms, so the question "does the expectile axis give +# a pinned row a variant above its published point (unlike the gamma axis)?" is answered from 9 cells. +# It uses verdict_table's loader and flagship_latex.PROPOSER_BY_TASK, never a hand-rolled scan. +python3 - > $O/r34_ifql_tau_pinned.txt 2>&1 <<'PY6' +import collections, os +os.environ["RSM_EXTRA_EPOCHS"] = "500" +import verdict_table as vt +import flagship_latex as fl +ROWS = [("mug_expert_suboptimal","Mug"), ("threading_expert_play","Thr"), + ("square_sub_20100","Sq-S")] # Sq-S: already on its own proposer, the control +print("IFQL critic arms on the PINNED proposer only -- gamma AND tau axes side by side.") +print("c = cells (a complete 3x3 = 9); rate = pooled success over n episodes.") +print("A tau arm above the published row would mean the expectile axis behaves DIFFERENTLY from the") +print("discount axis on the pinned proposers, where run 33 found best-gamma == published on both.\n") +for task, short in ROWS: + # run 35 fix: a row with no PROPOSER_BY_TASK entry is NOT a row with no proposer -- the table reads + # its DEFAULT proposer (flagship_latex.proposer_for -> RSM_PROPOSER). Run 34 filtered on the raw + # pin, so Sq-S (unpinned) matched no cell and printed "(no critic:ifql arms on the pinned proposer)", + # which reads like "no cells exist" when in fact the control row has full gamma/tau arms. + pin = fl.PROPOSER_BY_TASK.get(task) + prop = pin if pin is not None else fl.proposer_for(task) + print("== %-6s (%-30s) proposer: %-22s [%s]" + % (short, task, prop, "PINNED" if pin is not None else "table default (no pin)")) + try: + C = vt.cells(task) + except Exception as e: + print(" (loader error: %s)" % e); continue + a = collections.defaultdict(lambda: [0,0,0]) + for (arm,p,ps,es),v in C.items(): + if not isinstance(arm, tuple): continue + fam = str(arm[0]) + if not fam.startswith("critic:ifql"): continue + if str(p) != str(prop): continue + x = a[fam]; x[0]+=len(v); x[1]+=sum(v); x[2]+=1 + if not a: + print(" (no critic:ifql arms on proposer %s)\n" % prop); continue + pub = a.get("critic:ifql") + pubrate = 100*pub[1]/max(pub[0],1) if pub else None + for k in sorted(a, key=lambda k: (0 if k=="critic:ifql" else 1, k)): + v = a[k]; r = 100*v[1]/max(v[0],1) + tag = "PUBLISHED" if k == "critic:ifql" else ("ABOVE published" if pubrate is not None and r > pubrate + 1e-9 else "") + axis = "tau " if "[t" in k else ("gamma" if "[g" in k else " ") + print(" %-28s %s c=%2d n=%4d rate=%5.1f %s" % (k, axis, v[2], v[0], r, tag)) + # the two "best-over-axis" read-outs, complete-arms-only (c==9), so a 3-cell arm cannot win + for axis, pred in (("gamma", lambda k: k.startswith("critic:ifql [g") and "_t" not in k), + ("tau", lambda k: k.startswith("critic:ifql [t"))): + cand = {k: a[k] for k in a if pred(k) and a[k][2] >= 9} + if pub and pub[2] >= 9: cand["critic:ifql"] = pub + if not cand: print(" best-over-%-5s : (no complete arm)" % axis); continue + bk = max(cand, key=lambda k: cand[k][1]/max(cand[k][0],1)) + print(" best-over-%-5s : %-24s rate=%5.1f searched=%d complete arm(s)" + % (axis, bk, 100*cand[bk][1]/max(cand[bk][0],1), len(cand))) + print() +PY6 +cat $O/r34_ifql_tau_pinned.txt diff --git a/rsm_rise/scripts/rr_cpu_basetopup_run35b.sh b/rsm_rise/scripts/rr_cpu_basetopup_run35b.sh new file mode 100644 index 0000000000000000000000000000000000000000..ff9abdd4b266b26f20950731c8c389ff25666c45 --- /dev/null +++ b/rsm_rise/scripts/rr_cpu_basetopup_run35b.sh @@ -0,0 +1,96 @@ +#!/usr/bin/env bash +# BASE_TOPUP run 35b. The run-35 control fix (§4 item 11) turned the Sq-S block from +# "(no critic:ifql arms on the pinned proposer)" into a real control -- and the control does NOT +# behave like the two pinned rows: FOUR arms sit above its published point (g0p98 47.8, g0p995 52.0, +# t0p7 47.8, t0p9 49.8 vs published 46.7). Runs 33/34 concluded "published wins on both axes" from +# the two PINNED rows only. This read-out asks the same question on ALL 7 rows, on the proposer the +# flagship actually reports for that row (flagship_latex.proposer_for), complete arms only (c>=9), +# with the gamma and tau axes side by side and their UNION -- because the builder's gated +# best-over-gamma column deliberately EXCLUDES tau, so if the owner picks "best over the grid" the +# disclosure has to say which axes were searched. No hand-rolled loader: verdict_table.cells only. +set -uo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +source scripts/env.sh >/dev/null 2>&1 +O=status/basetopup/run35; mkdir -p $O +export PYTHONPATH=/proj/dmfexp/zwhong/rsm_rise/scripts:${PYTHONPATH:-} +python3 - > $O/r35_ifql_axes_all7.txt 2>&1 <<'PY' +import collections, math, os +os.environ["RSM_EXTRA_EPOCHS"] = "500" # integrity item 10: set it explicitly, print it +print("RSM_EXTRA_EPOCHS =", os.environ["RSM_EXTRA_EPOCHS"]) +import verdict_table as vt +import flagship_latex as fl + +ROWS = [("square_sub_20100","Sq-S"),("square_expert_play","Sq-C"), + ("two_piece_expert_suboptimal","Pc-S"),("two_piece_expert_play","Pc-C"), + ("mug_expert_suboptimal","Mug"),("threading_expert_play","Thr"), + ("two_piece_expert_play_tipping","Pc-tip")] + +def se(n,k): + p=k/n if n else 0.0 + return 100*math.sqrt(max(p*(1-p),0)/n) if n else 0.0 + +print("\nIFQL critic: published vs best-over-gamma vs best-over-tau, ON THE ROW'S REPORTED PROPOSER.") +print("Complete arms only (c>=9) may WIN; incomplete arms are printed as screens and cannot win.") +print("z = (best - published) / sqrt(SEM^2 + SEM^2) on pooled episodes -- a rough two-proportion z, not a test\n") +hdr = "%-7s %-22s %-11s %-26s %-26s %s" % ("row","proposer","published","best-over-gamma","best-over-tau","union best") +print(hdr); print("-"*len(hdr)) +summary=[] +for task, short in ROWS: + pin = fl.PROPOSER_BY_TASK.get(task) + prop = pin if pin is not None else fl.proposer_for(task) + a = collections.defaultdict(lambda: [0,0,0]) + for (arm,p,ps,es),v in vt.cells(task).items(): + if not isinstance(arm, tuple): continue + fam = str(arm[0]) + if not fam.startswith("critic:ifql"): continue + if str(p) != str(prop): continue + x=a[fam]; x[0]+=len(v); x[1]+=sum(v); x[2]+=1 + pub = a.get("critic:ifql") + if not pub: + print("%-7s %-22s (no published critic:ifql arm on this proposer)" % (short, prop)); continue + rate = lambda v: 100*v[1]/max(v[0],1) + pr = rate(pub) + def best(pred): + c = {k:a[k] for k in a if pred(k) and a[k][2]>=9} + if not c: return None, None + bk = max(c, key=lambda k: rate(c[k])) + return bk, c[bk] + gk,gv = best(lambda k: k.startswith("critic:ifql [g") and "_t" not in k) + tk,tv = best(lambda k: k.startswith("critic:ifql [t")) + cands = [("published",pub)]+[(x,y) for x,y in ((gk,gv),(tk,tv)) if y] + uk,uv = max(cands, key=lambda kv: rate(kv[1])) + def cell(k,v): + if not v: return "%-26s" % "(none complete)" + return "%-16s %5.1f" % (k.replace("critic:ifql","").strip() or "published", rate(v)) + print("%-7s %-22s %5.1f%s %-26s %-26s %-16s %5.1f" % + (short, str(prop), pr, "" if pin is None else "*", cell(gk,gv), cell(tk,tv), + (uk.replace("critic:ifql","").strip() or "published"), rate(uv))) + z = None + if uv is not pub: + s = math.sqrt(se(pub[0],pub[1])**2 + se(uv[0],uv[1])**2) + z = (rate(uv)-pr)/s if s else None + summary.append((short, pr, gk, rate(gv) if gv else None, tk, rate(tv) if tv else None, + uk, rate(uv), z, pin is not None)) +print("\n* = proposer PINNED by flagship_latex.PROPOSER_BY_TASK; the others use the table default.") + +print("\nWHICH AXIS MOVES WHICH ROW (this is the fixed-vs-best decision's actual cost):") +nb_g = nb_t = 0 +for short, pr, gk, gr, tk, tr, uk, ur, z, pinned in summary: + ag = (gr is not None and gr > pr + 1e-9); at = (tr is not None and tr > pr + 1e-9) + nb_g += ag; nb_t += at + print(" %-7s published %5.1f | gamma %s | tau %s | union %5.1f%s %s" % + (short, pr, + ("%5.1f ABOVE" % gr) if ag else ("%5.1f -- " % gr if gr is not None else " none "), + ("%5.1f ABOVE" % tr) if at else ("%5.1f -- " % tr if tr is not None else " none "), + ur, (" (z=%.2f)" % z) if z is not None else "", + "[PINNED row]" if pinned else "")) +print("\n rows where best-over-GAMMA beats published: %d of %d" % (nb_g, len(summary))) +print(" rows where best-over-TAU beats published: %d of %d" % (nb_t, len(summary))) +print("\nWhy this matters for the open fixed-vs-best decision: the builder's gated column") +print("(RR_IFQL_BESTG=1) is a union over {published} u {pure gamma variants} and EXCLUDES tau by") +print("design (run 8's label fix). If the reported rule becomes best-over-grid, either tau joins the") +print("union -- changing rows it currently cannot reach -- or the disclosed search must say that the") +print("tau axis was searched and then NOT used. Both are defensible; they are not the same table.") +print("Nothing in the builder was changed by this read-out.") +PY +cat $O/r35_ifql_axes_all7.txt diff --git a/rsm_rise/scripts/rr_cpu_basetopup_run37.sh b/rsm_rise/scripts/rr_cpu_basetopup_run37.sh new file mode 100644 index 0000000000000000000000000000000000000000..6a485b09a205e466fd06a38e5cf2eb3ab3f1d6c9 --- /dev/null +++ b/rsm_rise/scripts/rr_cpu_basetopup_run37.sh @@ -0,0 +1,99 @@ +#!/usr/bin/env bash +# BASE_TOPUP run 37. The owner's open decision (i) -- stop or finish the LIVE gamma grid (163 GPU-h left, +# critical path Sep 27 22:48Z) -- has been asked 14 times without the one number that prices it: how far +# apart the LIVE DINO path (`critic:dino`, per-step DinoV2Core on crop-randomised frames) and the FAST +# cache path (`critic:dino(Dq)`, the pooled features RSM reads) actually land AT THE SAME GAMMA. +# It was measured once, on threading only (6.0 vs 7.2, n=900 each). Both columns are now complete on +# all 7 rows at gamma 0.99, so the paired 7-row version is free -- and it is exactly what decides whether +# the live GAMMA grid is a necessary control or a redundant one. No hand-rolled loader: verdict_table.cells. +set -uo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +source scripts/env.sh >/dev/null 2>&1 +O=status/basetopup/run37; mkdir -p $O +export PYTHONPATH=/proj/dmfexp/zwhong/rsm_rise/scripts:${PYTHONPATH:-} +python3 - > $O/r37_live_vs_dq.txt 2>&1 <<'PY' +import collections, math, os +os.environ["RSM_EXTRA_EPOCHS"] = "500" +print("RSM_EXTRA_EPOCHS =", os.environ["RSM_EXTRA_EPOCHS"]) +import verdict_table as vt +import flagship_latex as fl + +ROWS = [("square_sub_20100","Sq-S"),("square_expert_play","Sq-C"), + ("two_piece_expert_suboptimal","Pc-S"),("two_piece_expert_play","Pc-C"), + ("mug_expert_suboptimal","Mug"),("threading_expert_play","Thr"), + ("two_piece_expert_play_tipping","Pc-tip")] + +# ---------- 1. INVENTORY: print the full arm tuple, not just the family, so a mismatched N or read-out +# cannot hide inside a family name that looks matched. +print("\n=== 1. EVERY critic:dino* ARM, FULL TUPLE (task, arm, proposer, cells, episodes, rate) ===") +inv = collections.defaultdict(dict) +for task, short in ROWS: + for (arm,p,ps,es),v in vt.cells(task).items(): + if not isinstance(arm, tuple): continue + if not str(arm[0]).startswith("critic:dino"): continue + k=(arm,str(p)) + x=inv[task].setdefault(k,[0,0,0]); x[0]+=len(v); x[1]+=sum(v); x[2]+=1 + if not inv[task]: + print(f"-- {short}: none"); continue + print(f"-- {short} ({task})") + for (arm,p),x in sorted(inv[task].items(), key=lambda kv: str(kv[0])): + print(f" {str(arm):<58} prop={p:<12} cells={x[2]:>2} n={x[0]:>4} rate={100*x[1]/max(x[0],1):5.1f}") + +# ---------- 2. PAIRED live vs (Dq) at gamma 0.99, matched on EVERY other component of the arm tuple. +# The two families differ only in the token `dino` vs `dino(Dq)` in arm[0]; a pair is formed only when the +# rest of the tuple (read-out, N, argmax, ...) and the proposer are identical, so nothing is compared across +# a different N or a different proposer. +def se(n,k): + p=k/n if n else 0.0 + return 100*math.sqrt(max(p*(1-p),0)/n) if n else 0.0 + +print("\n=== 2. PAIRED live `critic:dino` vs fast `critic:dino(Dq)` at gamma 0.99 ===") +print("A pair needs the SAME proposer and the SAME arm tuple apart from the family token, and BOTH sides") +print("complete (cells>=9). Incomplete sides are listed underneath and cannot enter the paired mean.\n") +hdr="%-7s %-30s %8s %8s %8s %7s" % ("row","matched arm (minus family)","live","(Dq)","delta","z") +print(hdr); print("-"*len(hdr)) +deltas=[]; partial=[] +for task, short in ROWS: + byrest=collections.defaultdict(dict) + for (arm,p),x in inv[task].items(): + fam=str(arm[0]) + if " g0." in fam or " t0." in fam: continue # gamma/tau variants are NOT the 0.99 point + rest=(tuple(arm[1:]), p) + if fam=="critic:dino": byrest[rest]["live"]=x + elif fam=="critic:dino(Dq)": byrest[rest]["dq"]=x + for rest,d in sorted(byrest.items(), key=lambda kv: str(kv[0])): + lv, dq = d.get("live"), d.get("dq") + lbl=str(rest[0])[:30] + if not (lv and dq): + partial.append((short,lbl,"live only" if lv else "(Dq) only", (lv or dq)[2])) + continue + if lv[2]<9 or dq[2]<9: + partial.append((short,lbl,f"incomplete live c={lv[2]} dq c={dq[2]}",min(lv[2],dq[2]))) + continue + rl=100*lv[1]/lv[0]; rd=100*dq[1]/dq[0] + s=math.sqrt(se(lv[0],lv[1])**2+se(dq[0],dq[1])**2) + z=(rd-rl)/s if s else float("nan") + print("%-7s %-30s %7.1f%% %7.1f%% %+7.1f %7.2f" % (short,lbl,rl,rd,rd-rl,z)) + deltas.append((short,rl,rd,rd-rl,s,lv[0],dq[0])) +if deltas: + m=sum(d[3] for d in deltas)/len(deltas) + sd=math.sqrt(sum((d[3]-m)**2 for d in deltas)/max(len(deltas)-1,1)) if len(deltas)>1 else float("nan") + sem=sd/math.sqrt(len(deltas)) if len(deltas)>1 else float("nan") + print("\nPAIRED MEAN delta ((Dq) - live) over %d matched row/arm pairs = %+.2f pp"%(len(deltas),m)) + print("paired SD %.2f, paired SEM %.2f -> t = %.2f" % (sd,sem,(m/sem if sem==sem and sem else float("nan")))) + worst=max(deltas,key=lambda d:abs(d[3])) + print("largest single-row |delta| = %s %+.1f pp (live %.1f vs (Dq) %.1f, n=%d/%d)"%(worst[0],worst[3],worst[1],worst[2],worst[5],worst[6])) +else: + print("\nNO matched complete pair -- the comparison is not available; say that, do not estimate it.") +if partial: + print("\nNot paired (screens only, cannot enter the mean):") + for row in partial: print(" ", row) + +# ---------- 3. What the live GAMMA grid would add that the (Dq) gamma arms do not already have. +print("\n=== 3. gamma arms that already exist on the FAST path, vs what the live grid is still computing ===") +for task, short in ROWS: + fams=sorted({str(a[0]) for (a,p) in inv[task] if " g0." in str(a[0])}) + print(f"-- {short}: " + (", ".join(fams) if fams else "no gamma arms")) +PY +echo "== read-out written to $O/r37_live_vs_dq.txt" +tail -n 200 $O/r37_live_vs_dq.txt diff --git a/rsm_rise/scripts/rr_cpu_basetopup_run40.sh b/rsm_rise/scripts/rr_cpu_basetopup_run40.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6113bc49e5070afd527a2a23e3a206787294d3 --- /dev/null +++ b/rsm_rise/scripts/rr_cpu_basetopup_run40.sh @@ -0,0 +1,89 @@ +#!/usr/bin/env bash +# BASE_TOPUP run 40: (a) the 7-row live-vs-fast(Dq) critic-path parity at MATCHED critic epoch 500, +# read with verdict_table's own guards (canon region, mug/thread criterion, horizon 400) and its own +# paired test; (b) rebuild + diff so the newly landed cells are accounted for. +# Diagnostic by construction: critic e500 != proposer e5000, so no published column can move. +set -uo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +source scripts/env.sh >/dev/null 2>&1 +O=status/basetopup/run40; mkdir -p $O +export PYTHONPATH=/proj/dmfexp/zwhong/rsm_rise/scripts:${PYTHONPATH:-} + +python3 - <<'PY' > $O/parity_e500.txt 2> $O/parity_e500.err +import glob, json, math, re, sys +sys.path.insert(0, "/proj/dmfexp/zwhong/rsm_rise/scripts") +from verdict_table import in_canon_region, mcnemar, rate # sanctioned guards + paired test +ROOT = "/proj/dmfexp/zwhong/rsm_rise" +TASKS = ["mug_expert_suboptimal","square_expert_play","square_sub_20100","threading_expert_play", + "two_piece_expert_play","two_piece_expert_play_tipping","two_piece_expert_suboptimal"] +SHORT = dict(zip(TASKS,["Mug","Sq-S","Sq-C","Thr","Pc-S","Pc-tip","Pc-C"])) +# arm label -> the critic the cell scored with. CDINO = live per-step DinoV2Core; CDQ = cached +# pooled DINO state (path D); CPIX = the matched pixel control. All three at critic epoch 500. +ARMS = {"CDINO":"live-DINO", "CDQ":"fast-DINO(Dq)", "CPIX":"pixel-ctrl"} + +def load(task, arm): + """-> {(critic_seed, eval_seed): [per-episode success]} (same keying mcnemar pairs on)""" + g = {} + pat = f"{ROOT}/runs/{task}/eval_cdino/S3H4-N128-{arm}-e500-es*-s*.json" + for f in sorted(glob.glob(pat)): + m = re.search(r"-e500-es(\d)-s(\d)\.json$", f) + if not m: continue + try: j = json.load(open(f)) + except Exception: continue + if j.get("rollout_horizon") != 400: continue + if task.startswith("mug") and ((j.get("success_criterion") or {}).get("mug") != "in_drawer"): continue + if task.startswith("thread") and (((j.get("success_criterion") or {}).get("thread") or "stock") != "stock"): continue + if not in_canon_region(task, j): continue + eps = j.get("episodes") or [] + if not eps or not isinstance(eps[0], dict): continue + es, cs = m.group(1), m.group(2) + g[(cs, es)] = [bool(e.get("success")) for e in eps] + return g + +print("=== critic-path parity at MATCHED critic epoch 500 (N=128, each row on its PINNED proposer per status/fairaudit/proposer.json, canon region) ===") +print(f"{'row':7s} {'live-DINO':>16s} {'fast-DINO(Dq)':>16s} {'pixel-ctrl':>16s} paired Dq-vs-live") +rows = [] +for t in TASKS: + gs = {a: load(t, a) for a in ARMS} + cells_n = {a: len(gs[a]) for a in ARMS} + r = {a: rate(gs[a]) for a in ARMS} + mc = mcnemar(gs["CDINO"], gs["CDQ"]) + def fmt(a): + v, n = r[a] + return "--" if not n else f"{v:5.1f} ({cells_n[a]}c n={n})" + pr = "--" if not mc else f"Dq-live={mc['b']-mc['a']:+5.1f} pairs={mc['pairs']} n={mc['n']} p={mc['p']:.3f}" + print(f"{SHORT[t]:7s} {fmt('CDINO'):>16s} {fmt('CDQ'):>16s} {fmt('CPIX'):>16s} {pr}") + if mc and cells_n["CDINO"] and cells_n["CDQ"]: + rows.append((SHORT[t], mc['b']-mc['a'], mc)) + +# 7-ROW PAIRED SIGN TEST -- the only read of this table (run 33 read 3 cells row-by-row and was 3.8 pts off) +print() +if rows: + pos = sum(1 for _, d, _ in rows if d > 0); neg = sum(1 for _, d, _ in rows if d < 0) + n = pos + neg + p = 1.0 if n == 0 else min(1.0, 2*sum(math.comb(n,k) for k in range(min(pos,neg)+1))/2**n) + mean = sum(d for _, d, _ in rows)/len(rows) + print(f"SIGN TEST over {len(rows)} complete-enough rows: fast>live on {pos}, live>fast on {neg}, " + f"ties {len(rows)-n}, two-sided p={p:.3f}; mean signed gap {mean:+.2f} pts") + print("per-row signed gap (fast - live):", ", ".join(f"{s}{d:+.1f}" for s, d, _ in rows)) + print() + print("READ: this is the ONLY licensed read-out of this leg. A row-by-row reading of an incomplete") + print("arm over-read a landing arm by 3.8 pts on 2026-09-27 (run 33), so rows with <9 cells on either") + print("side are reported with their cell count and are NOT quoted on their own.") +else: + print("SIGN TEST: no row has both sides yet.") +PY +echo "parity rc=$?" + +python3 scripts/verdict_table.py > $O/verdict_now.txt 2> $O/verdict_now.err; echo "verdict rc=$?" +python3 scripts/flagship_latex.py > $O/flag_now.txt 2> $O/flag_now.err; echo "flagship rc=$?" +PREV=$(ls -d status/basetopup/run3[0-9] status/basetopup/run2[0-9] 2>/dev/null | grep -v run40 | tail -1) +echo "prev build dir: $PREV" +for f in verdict flag; do + if [ -s "$PREV/${f}_now.txt" ]; then diff -u "$PREV/${f}_now.txt" "$O/${f}_now.txt" > $O/$f.diff; echo "$f diff lines: $(wc -l < $O/$f.diff)"; fi +done +echo "=== parity table ==="; cat $O/parity_e500.txt +echo "=== parity stderr (tail) ==="; tail -5 $O/parity_e500.err +echo "=== critic:dino rows in verdict ==="; grep -E "critic:dino" $O/verdict_now.txt | cut -c1-200 +echo "=== verdict lines that moved ==="; grep -E "^[-+]\|" $O/verdict.diff 2>/dev/null | cut -c1-230 | head -30 +echo "=== flagship lines that moved ==="; grep -E "^[-+]" $O/flag.diff 2>/dev/null | grep -vE "^\+\+\+|^---" | cut -c1-240 | head -20 diff --git a/rsm_rise/scripts/rr_cpu_basetopup_run41.sh b/rsm_rise/scripts/rr_cpu_basetopup_run41.sh new file mode 100644 index 0000000000000000000000000000000000000000..936e3d4756872f9db224a8a05167fefca63164fa --- /dev/null +++ b/rsm_rise/scripts/rr_cpu_basetopup_run41.sh @@ -0,0 +1,172 @@ +#!/usr/bin/env bash +# BASE_TOPUP run 41. +# (1) THE 7th ROW. Run 40 reported the critic:dino gamma sweep on SIX rows and flagged the flagship's +# square row as "did not surface". Cause found on the login node this run and it is NOT a data gap +# and NOT a read-out bug: `verdict_table.TASKS` (scripts/verdict_table.py:94) lists +# `square_expert_suboptimal`, whose `runs//eval_cdino/` is EMPTY, while every critic:dino cell +# for that row lives under `runs/square_sub_20100/` -- the 20/100 variant that only +# `flagship_latex.FLAGSHIP_VARIANT` (scripts/flagship_latex.py:79) maps in. So VERDICT.md structurally +# cannot show this row's critic arms; the FLAGSHIP can. Read here with `verdict_table.cells`, the same +# loader both builders use, on the variant dir -- exactly what flagship_latex does. +# (2) THE LABELS WERE SWAPPED. Run 40's parity + gamma tables called square_sub_20100 "Sq-C" and +# square_expert_play "Sq-S". The paper is the other way round: FLAGSHIP_VARIANT maps +# square_expert_suboptimal -> square_sub_20100 = "Square (Sub.)", and square_expert_play = +# "Square (Cov.)". Cross-checked three ways: the owner's 03:00Z table (Square (Sub.) IFQL 52.0, +# Square (Cov.) IFQL 2.0 -- the 50-ish row is square_sub_20100), status/fairaudit/proposer.json +# (square_sub_20100 published_chain_rate 54.0 == the paper's Square (Sub.) RSM cell), and +# verdict_table's own section titles. Numbers unchanged; every label reprinted correctly. +set -uo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +source scripts/env.sh >/dev/null 2>&1 +O=status/basetopup/run41; mkdir -p $O +export PYTHONPATH=/proj/dmfexp/zwhong/rsm_rise/scripts:${PYTHONPATH:-} + +python3 - <<'PY' > $O/critic_axes_all7.txt 2> $O/critic_axes_all7.err +import sys, math +sys.path.insert(0, "/proj/dmfexp/zwhong/rsm_rise/scripts") +from verdict_table import cells, pool, rate, mcnemar # sanctioned loader + paired test +import json, pathlib + +# (task dir actually holding the cells, paper row name, short tag). square_sub_20100 is the flagship's +# variant for square-peg (Suboptimal); square_expert_play is square-peg (Coverage). +ROWS = [("square_sub_20100", "Square (Sub.)", "Sq-S"), + ("square_expert_play", "Square (Cov.)", "Sq-C"), + ("two_piece_expert_suboptimal", "Piece (Sub.)", "Pc-S"), + ("two_piece_expert_play", "Piece (Cov.)", "Pc-C"), + ("two_piece_expert_play_tipping","Piece-tip (Cov.)", "Pc-tip"), + ("mug_expert_suboptimal", "Mug (Sub.)", "Mug"), + ("threading_expert_play", "Thread (Cov.)", "Thr")] +# NOTE the Pc-S / Pc-C mapping too: two_piece_expert_suboptimal = Piece (Sub.), two_piece_expert_play = +# Piece (Cov.). Run 40 printed Pc-C for two_piece_expert_suboptimal; same class of error, corrected here. + +PIN = json.load(open("/proj/dmfexp/zwhong/rsm_rise/status/fairaudit/proposer.json")) +AXES = [("0.99 (published)", "critic:dino(Dq) [N=128]"), + ("g0.95", "critic:dino(Dq) g0.95 [N=128]"), + ("g0.98", "critic:dino(Dq) g0.98 [N=128]"), + ("g0.995", "critic:dino(Dq) g0.995 [N=128]"), + ("t0.5", "critic:dino(Dq) t0.5 [N=128]"), + ("t0.7", "critic:dino(Dq) t0.7 [N=128]")] + +def arm_groups(task): + """-> {(arm_label_string, policy): group} using verdict_table.cells + pool, no hand-rolled glob.""" + c = cells(task) + keys = sorted({(a[0] if isinstance(a, tuple) else str(a), p) for (a, p, ps, es) in c}) + return c, keys + +print("=== critic:dino(Dq) gamma / expectile axes, ALL SEVEN PAPER ROWS, on each row's PINNED proposer ===") +print(" loader: verdict_table.cells (canon region, horizon 400, mug/threading criteria, epoch gate)") +print() +hdr = f"{'row':16s} {'proposer':14s} " + " ".join(f"{n:>16s}" for n, _ in AXES) + " best-published" +print(hdr); print("-"*len(hdr)) +tab = {} +for task, nice, short in ROWS: + c, keys = arm_groups(task) + pin = (PIN.get(task) or {}).get("pinned_proposer") + # threading's critic:dino row is scored against its pinned IDQL proposer at epoch 500 + cands = sorted({p for (lab, p) in keys if lab.startswith("critic:dino(Dq)")}) + pol = pin if pin in cands else (cands[0] if cands else None) + cellsn, vals = {}, {} + for nm, lab in AXES: + g = pool(c, lambda a, p, _l=lab, _p=pol: (a[0] if isinstance(a, tuple) else str(a)) == _l and p == _p) + v, n = rate(g) + vals[nm] = (v, n, len(g)) + base = vals["0.99 (published)"][0] + cmpl = {nm: v for nm, (v, n, k) in vals.items() if k >= 9} # complete arms only (9 cells) + best = max(cmpl.items(), key=lambda kv: kv[1]) if cmpl else None + def f(nm): + v, n, k = vals[nm] + return "--" if not n else f"{v:5.1f}({k}c)" + delta = "--" if (best is None or not (base == base)) else f"{best[0]} {best[1]-base:+5.1f}" + print(f"{short:16s} {str(pol):14s} " + " ".join(f"{f(nm):>16s}" for nm, _ in AXES) + f" {delta}") + tab[short] = {"task": task, "row": nice, "proposer": pol, + "vals": {k: {"rate": v[0], "n": v[1], "cells": v[2]} for k, v in vals.items()}} +print() +print("cells: (Nc) = number of 9 expected (3 critic seeds x 3 eval seeds). Arms with <9 cells are NOT") +print("eligible for the best-published column (the 1-cell over-read of runs 33 and 40, 3.0-3.8 pts).") +pathlib.Path("/proj/dmfexp/zwhong/rsm_rise/status/basetopup/run41/critic_axes_all7.json").write_text(json.dumps(tab, indent=1)) + +# ---- the fixed-vs-best size, now on all seven rows ------------------------------------------------- +print() +comp = [(s, d["vals"]) for s, d in tab.items()] +gains = [] +for s, v in comp: + base = v["0.99 (published)"]["rate"] + ok = {k: x["rate"] for k, x in v.items() if x["cells"] >= 9} + if not ok or base != base: continue + bk = max(ok, key=lambda k: ok[k]) + gains.append((s, bk, ok[bk] - base, base, ok[bk])) +print("fixed(gamma=0.99, tau=0.9) vs best-over-axis, complete arms only:") +for s, bk, d, b, w in sorted(gains, key=lambda x: -x[2]): + print(f" {s:8s} published {b:5.1f} -> best {w:5.1f} at {bk:18s} {d:+5.1f}") +if gains: + print(f" rows where 0.99/0.9 is NOT the best: {sum(1 for g in gains if g[2] > 0.05)} of {len(gains)}; " + f"largest gap {max(g[2] for g in gains):+.1f} pts") +PY +echo "axes rc=$?" + +# ---- run 40's parity table, REPRINTED WITH THE CORRECT ROW LABELS (numbers identical) --------------- +python3 - <<'PY' > $O/parity_e500_relabelled.txt 2> $O/parity_e500_relabelled.err +import glob, json, math, re, sys +sys.path.insert(0, "/proj/dmfexp/zwhong/rsm_rise/scripts") +from verdict_table import in_canon_region, mcnemar, rate +ROOT = "/proj/dmfexp/zwhong/rsm_rise" +ROWS = [("mug_expert_suboptimal","Mug"), ("square_expert_play","Sq-C"), ("square_sub_20100","Sq-S"), + ("threading_expert_play","Thr"), ("two_piece_expert_suboptimal","Pc-S"), + ("two_piece_expert_play","Pc-C"), ("two_piece_expert_play_tipping","Pc-tip")] +ARMS = {"CDINO":"live-DINO", "CDQ":"fast-DINO(Dq)", "CPIX":"pixel-ctrl"} +def load(task, arm): + g = {} + for f in sorted(glob.glob(f"{ROOT}/runs/{task}/eval_cdino/S3H4-N128-{arm}-e500-es*-s*.json")): + m = re.search(r"-e500-es(\d)-s(\d)\.json$", f) + if not m: continue + try: j = json.load(open(f)) + except Exception: continue + if j.get("rollout_horizon") != 400: continue + if task.startswith("mug") and ((j.get("success_criterion") or {}).get("mug") != "in_drawer"): continue + if task.startswith("thread") and (((j.get("success_criterion") or {}).get("thread") or "stock") != "stock"): continue + if not in_canon_region(task, j): continue + eps = j.get("episodes") or [] + if not eps or not isinstance(eps[0], dict): continue + g[(m.group(2), m.group(1))] = [bool(e.get("success")) for e in eps] + return g +print("=== critic-path parity at MATCHED critic epoch 500 -- RELABELLED (run 40 swapped Sq-S/Sq-C and Pc-S/Pc-C) ===") +print("Each row on its own PINNED proposer; both arms of every pair share that checkpoint and the critic epoch.") +print(f"{'row':7s} {'live-DINO':>16s} {'fast-DINO(Dq)':>16s} {'pixel-ctrl':>16s} paired Dq-vs-live") +rows=[] +for t, short in ROWS: + gs = {a: load(t,a) for a in ARMS}; r = {a: rate(gs[a]) for a in ARMS} + mc = mcnemar(gs["CDINO"], gs["CDQ"]) + def fmt(a): + v,n = r[a]; return "--" if not n else f"{v:5.1f} ({len(gs[a])}c n={n})" + pr = "--" if not mc else f"Dq-live={mc['b']-mc['a']:+5.1f} pairs={mc['pairs']} n={mc['n']} p={mc['p']:.3f}" + print(f"{short:7s} {fmt('CDINO'):>16s} {fmt('CDQ'):>16s} {fmt('CPIX'):>16s} {pr}") + if mc and gs["CDINO"] and gs["CDQ"]: rows.append((short, mc['b']-mc['a'])) +pos=sum(1 for _,d in rows if d>0); neg=sum(1 for _,d in rows if d<0); n=pos+neg +p=1.0 if n==0 else min(1.0, 2*sum(math.comb(n,k) for k in range(min(pos,neg)+1))/2**n) +print() +print(f"SIGN TEST over {len(rows)} pairable rows: fast>live {pos}, live>fast {neg}, ties {len(rows)-n}, " + f"two-sided p={p:.3f}; mean signed gap {sum(d for _,d in rows)/max(1,len(rows)):+.2f} pts") +print("per-row (fast - live):", ", ".join(f"{s}{d:+.1f}" for s,d in rows)) +PY +echo "parity rc=$?" + +echo "== sweep (drain): launches any missing eval cell for this stream's tags" +bash scripts/basetopup/tau_sweep.sh --drain > $O/sweep.txt 2>&1; echo "sweep rc=$?" +tail -25 $O/sweep.txt + +python3 scripts/verdict_table.py > $O/verdict_now.txt 2> $O/verdict_now.err; echo "verdict rc=$?" +python3 scripts/flagship_latex.py > $O/flag_now.txt 2> $O/flag_now.err; echo "flagship rc=$?" +# run 40's PREV picker used `ls -d run3[0-9] run2[0-9] | tail -1`, which returns run29 -- brace/glob order, +# not mtime. Pick the newest build that actually has a non-empty artefact. +for f in verdict flag; do + PREV=$(ls -t status/basetopup/*/${f}_now.txt 2>/dev/null | grep -v "/run41/" | head -1) + if [ -s "$PREV" ] && [ -s "$O/${f}_now.txt" ]; then + diff -u "$PREV" "$O/${f}_now.txt" > $O/$f.diff + echo "$f: prev=$PREV diff lines: $(wc -l < $O/$f.diff)" + else echo "$f: no diff (prev='$PREV')"; fi +done +echo "=== axes table ==="; cat $O/critic_axes_all7.txt +echo "=== parity (relabelled) ==="; cat $O/parity_e500_relabelled.txt +echo "=== verdict moved ==="; grep -E "^[-+]" $O/verdict.diff 2>/dev/null | grep -vE "^(\+\+\+|---)" | cut -c1-210 | head -30 +echo "=== flagship moved ==="; grep -E "^[-+]" $O/flag.diff 2>/dev/null | grep -vE "^(\+\+\+|---)" | cut -c1-210 | head -20 +echo "=== axes stderr ==="; tail -5 $O/critic_axes_all7.err diff --git a/rsm_rise/scripts/rr_cpu_basetopup_run41b.sh b/rsm_rise/scripts/rr_cpu_basetopup_run41b.sh new file mode 100644 index 0000000000000000000000000000000000000000..039583f8a164109c1b77a5b5d5e2808db061d8b4 --- /dev/null +++ b/rsm_rise/scripts/rr_cpu_basetopup_run41b.sh @@ -0,0 +1,103 @@ +#!/usr/bin/env bash +# BASE_TOPUP run 41b. Run 41's axes table matched the arm by the string verdict_table PRINTS +# ("critic:dino(Dq) g0.95 [N=128]") rather than by the KEY it pools on: `cells()` keys the arm as the +# TUPLE (label, "N=") (scripts/verdict_table.py:883), so "[N=128]" is display formatting, not part of +# the label. Every cell therefore matched nothing and the whole table printed "--". Matched on the +# tuple here, and the discovered (label, policy, cells) inventory is DUMPED FIRST so a future mismatch is +# visible instead of silent -- a vacuous filter printing "--" is the same class of failure as a vacuous +# filter printing a number, and this stream has hit it before. +set -uo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +source scripts/env.sh >/dev/null 2>&1 +O=status/basetopup/run41; mkdir -p $O +export PYTHONPATH=/proj/dmfexp/zwhong/rsm_rise/scripts:${PYTHONPATH:-} + +python3 - <<'PY' > $O/critic_axes_all7.txt 2> $O/critic_axes_all7.err +import sys, json, pathlib +sys.path.insert(0, "/proj/dmfexp/zwhong/rsm_rise/scripts") +from verdict_table import cells, pool, rate + +ROWS = [("square_sub_20100", "Square (Sub.)", "Sq-S"), + ("square_expert_play", "Square (Cov.)", "Sq-C"), + ("two_piece_expert_suboptimal", "Piece (Sub.)", "Pc-S"), + ("two_piece_expert_play", "Piece (Cov.)", "Pc-C"), + ("two_piece_expert_play_tipping","Piece-tip (Cov.)", "Pc-tip"), + ("mug_expert_suboptimal", "Mug (Sub.)", "Mug"), + ("threading_expert_play", "Thread (Cov.)", "Thr")] +PIN = json.load(open("/proj/dmfexp/zwhong/rsm_rise/status/fairaudit/proposer.json")) +AXES = [("0.99 pub", "critic:dino(Dq)"), ("g0.95", "critic:dino(Dq) g0.95"), + ("g0.98", "critic:dino(Dq) g0.98"), ("g0.995", "critic:dino(Dq) g0.995"), + ("t0.5", "critic:dino(Dq) t0.5"), ("t0.7", "critic:dino(Dq) t0.7")] + +C = {} +print("=== INVENTORY: every critic:dino* arm the loader actually found (label | proposer | cells) ===") +for task, nice, short in ROWS: + c = cells(task); C[task] = c + inv = {} + for (a, p, ps, es) in c: + lab = a[0] if isinstance(a, tuple) else str(a) + if not lab.startswith("critic:dino"): continue + n = a[1] if isinstance(a, tuple) and len(a) > 1 else "" + inv[(lab, n, p)] = inv.get((lab, n, p), 0) + 1 + print(f"-- {short} ({task})") + for (lab, n, p), k in sorted(inv.items()): + print(f" {lab:28s} {str(n):8s} {p:16s} {k:3d} cells") + if not inv: print(" (none)") + +print() +print("=== critic:dino(Dq) gamma / expectile axes, ALL SEVEN PAPER ROWS, each on its PINNED proposer ===") +hdr = f"{'row':8s} {'proposer':16s} " + " ".join(f"{n:>13s}" for n, _ in AXES) + " best-published" +print(hdr); print("-"*len(hdr)) +tab = {} +for task, nice, short in ROWS: + c = C[task] + keyed = {} + for (a, p, ps, es) in c: + lab = a[0] if isinstance(a, tuple) else str(a) + nn = a[1] if isinstance(a, tuple) and len(a) > 1 else "" + if lab.startswith("critic:dino(Dq)") and nn == "N=128": + keyed[p] = keyed.get(p, 0) + 1 + pin = (PIN.get(task) or {}).get("pinned_proposer") + # threading's row is scored against its pinned IDQL proposer at epoch 500, whose POL label carries + # the epoch ("IDQL policy@500"); match on prefix so the pin still selects it. + pol = next((p for p in keyed if p == pin), None) \ + or next((p for p in sorted(keyed) if pin and p.startswith(pin)), None) \ + or (max(keyed, key=keyed.get) if keyed else None) + vals = {} + for nm, lab in AXES: + g = pool(c, lambda a, p, _l=lab, _p=pol: isinstance(a, tuple) and a[0] == _l and a[1] == "N=128" and p == _p) + v, n = rate(g); vals[nm] = (v, n, len(g)) + base = vals["0.99 pub"][0] + cmpl = {nm: v for nm, (v, n, k) in vals.items() if k >= 9} + best = max(cmpl.items(), key=lambda kv: kv[1]) if cmpl else None + def f(nm): + v, n, k = vals[nm] + return "--" if not n else f"{v:5.1f}({k}c)" + d = "--" if (best is None or base != base) else f"{best[0]} {best[1]-base:+5.1f}" + print(f"{short:8s} {str(pol):16s} " + " ".join(f"{f(nm):>13s}" for nm, _ in AXES) + f" {d}") + tab[short] = {"task": task, "row": nice, "proposer": pol, + "vals": {k: {"rate": v[0], "n": v[1], "cells": v[2]} for k, v in vals.items()}} +print() +print("(Nc) = cells of the 9 expected (3 critic seeds x 3 eval seeds). Arms with <9 cells are NOT") +print("eligible for best-published: a 1-cell arm over-read by 3.0-3.8 pts twice in this stream (runs 33, 40).") +pathlib.Path("/proj/dmfexp/zwhong/rsm_rise/status/basetopup/run41/critic_axes_all7.json").write_text(json.dumps(tab, indent=1)) + +print() +print("=== fixed (gamma=0.99, tau=0.9) vs best-over-axis, complete arms only ===") +gains = [] +for s, d in tab.items(): + v = d["vals"]; base = v["0.99 pub"]["rate"] + ok = {k: x["rate"] for k, x in v.items() if x["cells"] >= 9} + if not ok or base != base: + print(f" {s:8s} SKIPPED (published arm incomplete or no complete arm)"); continue + bk = max(ok, key=lambda k: ok[k]) + gains.append((s, bk, ok[bk]-base, base, ok[bk])) +for s, bk, d, b, w in sorted(gains, key=lambda x: -x[2]): + print(f" {s:8s} published {b:5.1f} -> best {w:5.1f} at {bk:10s} {d:+5.1f}") +if gains: + print(f" NOT best at the fixed point on {sum(1 for g in gains if g[2] > 0.05)} of {len(gains)} rows; " + f"largest gap {max(g[2] for g in gains):+.1f} pts (row {max(gains, key=lambda g: g[2])[0]})") +PY +echo "axes rc=$?" +echo "=== axes ==="; cat $O/critic_axes_all7.txt +echo "=== stderr tail ==="; tail -3 $O/critic_axes_all7.err diff --git a/rsm_rise/scripts/rr_cpu_basetopup_run41c.sh b/rsm_rise/scripts/rr_cpu_basetopup_run41c.sh new file mode 100644 index 0000000000000000000000000000000000000000..d60f6e20841cc919a80944fbefd734683c28d8e1 --- /dev/null +++ b/rsm_rise/scripts/rr_cpu_basetopup_run41c.sh @@ -0,0 +1,49 @@ +#!/usr/bin/env bash +# BASE_TOPUP run 41c -- the threading row of the axes table. +# run41b printed "(none)" for threading and the cause is NOT a missing cell: `verdict_table._allowed_epochs` +# (scripts/verdict_table.py:199-209) admits policy epoch 5000 only, unless RSM_EXTRA_EPOCHS names another -- +# which `flagship_latex` sets from PROPOSER_BY_TASK because threading's pinned IDQL proposer is at epoch 500 +# (a 28 % proposer at 500 vs 13.8 % at 5000). A standalone caller that does not set it silently drops every +# threading cell. Set here for the threading call ONLY, so no other row can admit an off-epoch cell. +set -uo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +source scripts/env.sh >/dev/null 2>&1 +O=status/basetopup/run41; mkdir -p $O +export PYTHONPATH=/proj/dmfexp/zwhong/rsm_rise/scripts:${PYTHONPATH:-} +export RSM_EXTRA_EPOCHS=500 + +python3 - <<'PY' > $O/critic_axes_thr.txt 2> $O/critic_axes_thr.err +import sys, json, pathlib +sys.path.insert(0, "/proj/dmfexp/zwhong/rsm_rise/scripts") +from verdict_table import cells, pool, rate, _allowed_epochs +print("epoch gate admits:", sorted(_allowed_epochs())) +AXES = [("0.99 pub", "critic:dino(Dq)"), ("g0.95", "critic:dino(Dq) g0.95"), + ("g0.98", "critic:dino(Dq) g0.98"), ("g0.995", "critic:dino(Dq) g0.995"), + ("t0.5", "critic:dino(Dq) t0.5"), ("t0.7", "critic:dino(Dq) t0.7")] +task = "threading_expert_play" +c = cells(task) +keyed = {} +for (a, p, ps, es) in c: + if isinstance(a, tuple) and a[0].startswith("critic:dino(Dq)") and a[1] == "N=128": + keyed[p] = keyed.get(p, 0) + 1 +print("proposers carrying critic:dino(Dq) N=128 cells:", keyed) +pol = max(keyed, key=keyed.get) if keyed else None +vals = {} +for nm, lab in AXES: + g = pool(c, lambda a, p, _l=lab, _p=pol: isinstance(a, tuple) and a[0] == _l and a[1] == "N=128" and p == _p) + v, n = rate(g); vals[nm] = (v, n, len(g)) + print(f" {nm:10s} {v:6.2f} n={n:5d} cells={len(g)}") +base = vals["0.99 pub"][0] +cmpl = {nm: v for nm, (v, n, k) in vals.items() if k >= 9} +best = max(cmpl.items(), key=lambda kv: kv[1]) if cmpl else None +print(f"Thr on {pol}: published {base:.1f} -> best {best[1]:.1f} at {best[0]} {best[1]-base:+.1f}" if best else "Thr: no complete arm") +# merge into the 7-row artefact written by run41b +p = pathlib.Path("/proj/dmfexp/zwhong/rsm_rise/status/basetopup/run41/critic_axes_all7.json") +tab = json.loads(p.read_text()) +tab["Thr"] = {"task": task, "row": "Thread (Cov.)", "proposer": pol, + "vals": {k: {"rate": v[0], "n": v[1], "cells": v[2]} for k, v in vals.items()}} +p.write_text(json.dumps(tab, indent=1)) +print("merged into", p) +PY +echo "thr rc=$?" +cat $O/critic_axes_thr.txt diff --git a/rsm_rise/scripts/rr_cpu_basetopup_run8.sh b/rsm_rise/scripts/rr_cpu_basetopup_run8.sh new file mode 100644 index 0000000000000000000000000000000000000000..c39acccba8f5166b3406781d7fb3e4146f09f4e8 --- /dev/null +++ b/rsm_rise/scripts/rr_cpu_basetopup_run8.sh @@ -0,0 +1,47 @@ +#!/usr/bin/env bash +# BASE_TOPUP run 8: (a) acceptance test for run 7's fix 3 -- each IFQL gamma must appear as ONE +# three-seed arm with 9 cells, not three one-seed arms; (b) the gamma sweep's first read-out +# (deliverable 3); (c) current state of the critic:dino column. +set -uo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +source scripts/env.sh >/dev/null 2>&1 +O=status/basetopup/run8 +mkdir -p $O +export PYTHONPATH=/proj/dmfexp/zwhong/rsm_rise/scripts:${PYTHONPATH:-} + +# flagship_latex sets RSM_EXTRA_EPOCHS from PROPOSER_BY_TASK, which is what admits threading's +# epoch-500 proposer; a bare verdict_table drops those cells (run 7 sec.4). +python3 scripts/flagship_latex.py > $O/flagship.txt 2> $O/flagship.err; echo "flagship rc=$?" +RSM_EXTRA_EPOCHS=500 python3 scripts/verdict_table.py > $O/verdict.txt 2> $O/verdict.err; echo "verdict rc=$?" + +echo "=== every IFQL arm (label + n), from the verdict table ===" +grep -nE "ifql|IFQL" $O/verdict.txt | head -60 +echo +echo "=== every critic arm ===" +grep -nE "critic" $O/verdict.txt | head -60 +echo +echo "=== flagship: the RISE (DINO) column ===" +grep -nE "RISE \(DINO\)|CDINO|critic:dino" $O/flagship.txt | head -30 +echo +echo "=== raw cell census straight off disk (independent of the loader) ===" +python3 - <<'PY' +import glob, json, os, re, collections +root="/proj/dmfexp/zwhong/rsm_rise" +c=collections.Counter(); sr=collections.defaultdict(list) +for f in glob.glob(root+"/runs/*/eval_ifql/*IFQLCRITG*.json"): + task=f.split("/runs/")[1].split("/")[0] + g=re.search(r"IFQLCRITG(0P\d+)",f).group(1).lower().replace("p",".").replace("0.","0.") + m=re.search(r"IFQLg(0p\d+)s(\d)",f) + c[(task,g)]+=1 + try: + d=json.load(open(f)); sr[(task,g)].append(d.get("success_rate", d.get("sr"))) + except Exception as e: pass +print(f"{'task':32s} " + " ".join(f"{k:>12s}" for k in ("g0.95","g0.98","g0.99","g0.995"))) +for task in sorted({t for t,_ in c}): + row=f"{task:32s} " + for g in ("0.95","0.98","0.99","0.995"): + vals=[v for v in sr[(task,g)] if v is not None] + mean=sum(vals)/len(vals) if vals else float('nan') + row+=f" {c[(task,g)]:2d}c {mean*100:6.1f}%" + print(row) +PY diff --git a/rsm_rise/scripts/rr_cpu_basetopup_run8b.sh b/rsm_rise/scripts/rr_cpu_basetopup_run8b.sh new file mode 100644 index 0000000000000000000000000000000000000000..fe5d07e3fb0d7c0f56320ef29ee10eb7ea92f709 --- /dev/null +++ b/rsm_rise/scripts/rr_cpu_basetopup_run8b.sh @@ -0,0 +1,41 @@ +#!/usr/bin/env bash +# BASE_TOPUP run 8b: PRE/POST for moving the IFQL variant tag from the arm RECIPE into the arm LABEL. +# PRE = the code as it was at the start of run 8 (the backup), POST = fixed. Same JSONs on disk, so +# every difference is the fix. Both copies must live in scripts/ -- the builders import each other by +# module name (run 7 learned this the expensive way). +set -uo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +source scripts/env.sh >/dev/null 2>&1 +O=status/basetopup/run8b +mkdir -p $O +export PYTHONPATH=/proj/dmfexp/zwhong/rsm_rise/scripts:${PYTHONPATH:-} + +cp scripts/verdict_table.py.bak.20260926_ifqlvariantlabel scripts/_vt_pre_run8.py +# flagship_latex imports verdict_table by name, so the PRE flagship build needs the PRE verdict_table +# in that name. Swap the module aside, build, swap back -- and verify the swap-back by checksum. +md5sum scripts/verdict_table.py > $O/post_md5.txt +cp scripts/verdict_table.py scripts/_vt_post_keep.py +cp scripts/_vt_pre_run8.py scripts/verdict_table.py +python3 scripts/verdict_table.py > $O/verdict_pre.txt 2> $O/verdict_pre.err; echo "verdict_pre rc=$?" +python3 scripts/flagship_latex.py > $O/flag_pre.txt 2> $O/flag_pre.err; echo "flag_pre rc=$?" +cp scripts/_vt_post_keep.py scripts/verdict_table.py +md5sum -c $O/post_md5.txt && echo "verdict_table.py restored EXACTLY" +python3 scripts/verdict_table.py > $O/verdict_post.txt 2> $O/verdict_post.err; echo "verdict_post rc=$?" +python3 scripts/flagship_latex.py > $O/flag_post.txt 2> $O/flag_post.err; echo "flag_post rc=$?" +rm -f scripts/_vt_pre_run8.py scripts/_vt_post_keep.py + +diff -u $O/verdict_pre.txt $O/verdict_post.txt > $O/verdict.diff +diff -u $O/flag_pre.txt $O/flag_post.txt > $O/flag.diff +echo "verdict.diff lines: $(wc -l < $O/verdict.diff) flag.diff lines: $(wc -l < $O/flag.diff)" + +echo "=== the prelim flagship row block, PRE then POST (IFQL is column 6) ===" +for w in pre post; do echo "--- $w"; awk '/^Task & RISE-g/{f=1} f&&/^(Square|Piece|Mug|Thread)/{print} /^\\bottomrule/{if(f)f=0}' $O/flag_$w.txt | tail -8; done + +echo +echo "=== every IFQL baseline row, PRE then POST (n must go 2250 -> 450) ===" +for w in pre post; do echo "--- $w"; grep -oE "\| baseline \| IFQL [^|]*\|" $O/verdict_$w.txt >/dev/null; \ + awk -F'|' '/IFQL \(published\)|IFQL critic \/ RISE actor|IFQL policy/{gsub(/^ +| +$/,"",$3);gsub(/^ +| +$/,"",$5);gsub(/^ +| +$/,"",$7); print $3" SR="$5" n="$7}' $O/verdict_$w.txt; done + +echo +echo "=== gamma-variant arms now visible as their OWN arms (POST only) ===" +grep -oE "critic:ifql \[[a-z0-9_]+\]" $O/verdict_post.txt | sort | uniq -c diff --git a/rsm_rise/scripts/rr_cpu_basetopup_verdict7.sh b/rsm_rise/scripts/rr_cpu_basetopup_verdict7.sh new file mode 100644 index 0000000000000000000000000000000000000000..57287185ee4e8b1fb92affd67dfaf8e6adf074f1 --- /dev/null +++ b/rsm_rise/scripts/rr_cpu_basetopup_verdict7.sh @@ -0,0 +1,28 @@ +#!/usr/bin/env bash +# BASE_TOPUP run 7: build the verdict table BEFORE and AFTER the gamma-aware critic arm key, and extract +# the threading critic:dino row (deliverable 1's first complete row). +set -uo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +source scripts/env.sh >/dev/null 2>&1 +O=status/basetopup/verdict7 +mkdir -p $O + +# PRE: the code as it was before this run's key fix (the backup), same JSONs on disk. +# verdict_table imports its siblings (flagship_latex) by module name, so both copies must live IN +# scripts/ -- copying to /tmp broke the import and produced two empty tables in 3 s. +cp scripts/verdict_table.py.bak.20260926_gammaarm scripts/_vt_pre_run7.py +export PYTHONPATH=/proj/dmfexp/zwhong/rsm_rise/scripts:${PYTHONPATH:-} +python3 scripts/_vt_pre_run7.py > $O/pre.txt 2> $O/pre.err; echo "pre rc=$?" +python3 scripts/verdict_table.py > $O/post.txt 2> $O/post.err; echo "post rc=$?" +rm -f scripts/_vt_pre_run7.py + +diff -u $O/pre.txt $O/post.txt > $O/verdict.diff; echo "diff lines: $(wc -l < $O/verdict.diff)" + +echo "=== threading rows mentioning critic ===" +grep -nE "critic" $O/post.txt | grep -iE "thread|dino" | head -40 +echo "=== every critic:dino arm in the table ===" +grep -nE "critic:dino" $O/post.txt | head -40 +echo "=== published critic arm lines (must be unchanged pre vs post) ===" +grep -nE "\bcritic\b" $O/pre.txt | head -20 > $O/pre_critic.txt +grep -nE "\bcritic\b" $O/post.txt | head -20 > $O/post_critic.txt +diff -u $O/pre_critic.txt $O/post_critic.txt && echo "PUBLISHED CRITIC ARM: IDENTICAL pre/post" diff --git a/rsm_rise/scripts/rr_cpu_beta_patterns.sh b/rsm_rise/scripts/rr_cpu_beta_patterns.sh new file mode 100644 index 0000000000000000000000000000000000000000..187b188931841da142d7c26842249f625eb158a9 --- /dev/null +++ b/rsm_rise/scripts/rr_cpu_beta_patterns.sh @@ -0,0 +1,9 @@ +#!/usr/bin/env bash +set -uo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +source scripts/env.sh 2>/dev/null || true +# threading_expert_play pins its proposer at epoch 500 (RISE-IDQL is a 28% proposer there at 500 and +# 13.8% at 5000), so verdict_table._allowed_epochs must be told to admit it; _pol_label carries the +# epoch, so epoch-500 cells can never pool with epoch-5000 cells of the same family. +export RSM_EXTRA_EPOCHS=500 +python3 scripts/beta_patterns_analyze.py diff --git a/rsm_rise/scripts/rr_cpu_beta_sweep_best.sh b/rsm_rise/scripts/rr_cpu_beta_sweep_best.sh new file mode 100644 index 0000000000000000000000000000000000000000..06995f3dab817d2cfec7d67b779343bb1bb2d897 --- /dev/null +++ b/rsm_rise/scripts/rr_cpu_beta_sweep_best.sh @@ -0,0 +1,6 @@ +#!/usr/bin/env bash +set -uo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +source scripts/env.sh 2>/dev/null || true +export RSM_EXTRA_EPOCHS=500 +python3 scripts/plot_beta_sweep_best.py diff --git a/rsm_rise/scripts/rr_cpu_build_sq20100.sh b/rsm_rise/scripts/rr_cpu_build_sq20100.sh new file mode 100644 index 0000000000000000000000000000000000000000..a29605efe79d13c48593b38184d5d678e653f471 --- /dev/null +++ b/rsm_rise/scripts/rr_cpu_build_sq20100.sh @@ -0,0 +1,4 @@ +#!/usr/bin/env bash +set -euo pipefail +ROOT=/proj/dmfexp/zwhong/rsm_rise; source $ROOT/scripts/env.sh +exec python -u $ROOT/scripts/build_square_sub_20_100.py diff --git a/rsm_rise/scripts/rr_cpu_build_sqsub2.sh b/rsm_rise/scripts/rr_cpu_build_sqsub2.sh new file mode 100644 index 0000000000000000000000000000000000000000..749cb66c30151d984aa0f1fa8b0a3abd6a01977e --- /dev/null +++ b/rsm_rise/scripts/rr_cpu_build_sqsub2.sh @@ -0,0 +1,4 @@ +#!/usr/bin/env bash +set -euo pipefail +ROOT=/proj/dmfexp/zwhong/rsm_rise; source $ROOT/scripts/env.sh +exec python -u $ROOT/scripts/build_square_sub_paper_v2.py diff --git a/rsm_rise/scripts/rr_cpu_build_subpaper_derived.sh b/rsm_rise/scripts/rr_cpu_build_subpaper_derived.sh new file mode 100644 index 0000000000000000000000000000000000000000..6cca7b921c84e6e0cd06980ff72a6d2da360f487 --- /dev/null +++ b/rsm_rise/scripts/rr_cpu_build_subpaper_derived.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +set -uo pipefail +ROOT=/proj/dmfexp/zwhong/rsm_rise +source $ROOT/scripts/env.sh +exec python $ROOT/scripts/build_square_sub_paper_expert.py diff --git a/rsm_rise/scripts/rr_cpu_check_ssp.sh b/rsm_rise/scripts/rr_cpu_check_ssp.sh new file mode 100644 index 0000000000000000000000000000000000000000..0e8e860a42fefa5ee5e1563846ea4aee47339d58 --- /dev/null +++ b/rsm_rise/scripts/rr_cpu_check_ssp.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +set -euo pipefail +exec /proj/dmfexp/zwhong/rsm_rise/venv_rsm/bin/python /proj/dmfexp/zwhong/rsm_rise/scripts/check_square_sub_paper_h5.py diff --git a/rsm_rise/scripts/rr_cpu_chunk_videos.sh b/rsm_rise/scripts/rr_cpu_chunk_videos.sh new file mode 100644 index 0000000000000000000000000000000000000000..110e9ba90d59df48b05771aa477d82b0aec87582 --- /dev/null +++ b/rsm_rise/scripts/rr_cpu_chunk_videos.sh @@ -0,0 +1,33 @@ +#!/usr/bin/env bash +# CPU job: split a rendered dataset folder into <=LIMIT-MB tar.gz chunks that fit the chat upload limit. +# usage: rr_cpu_chunk_videos.sh +set -uo pipefail +ROOT=/proj/dmfexp/zwhong/rsm_rise; export PATH=$ROOT/env/bin:$PATH +python - "$@" <<'PY' +import sys, os, glob, subprocess, shutil, math +src, prefix, limit = sys.argv[1], sys.argv[2], float(sys.argv[3]) * 1024 * 1024 +files = [] +for sub in ("expert", "suboptimal", "play"): + d = os.path.join(src, sub) + if os.path.isdir(d): + files += [(sub, f) for f in sorted(glob.glob(d + "/*.mp4"))] +extra = [x for x in ("README.txt", "INDEX.json") if os.path.exists(os.path.join(src, x))] +chunks, cur, sz = [], [], 0 +for sub, f in files: + s = os.path.getsize(f) + if cur and sz + s > limit * 0.92: + chunks.append(cur); cur, sz = [], 0 + cur.append((sub, f)); sz += s +if cur: chunks.append(cur) +for i, ch in enumerate(chunks, 1): + stage = os.path.join(os.path.dirname(src), f".chunk_{os.getpid()}_{i}", os.path.basename(src)) + for sub, f in ch: + os.makedirs(os.path.join(stage, sub), exist_ok=True) + try: os.link(f, os.path.join(stage, sub, os.path.basename(f))) + except OSError: os.symlink(os.path.abspath(f), os.path.join(stage, sub, os.path.basename(f))) + for x in extra: shutil.copy(os.path.join(src, x), stage) + out = f"{prefix}_{i:02d}of{len(chunks):02d}.tgz" + subprocess.run(["tar", "czhf", out, "-C", os.path.dirname(stage), os.path.basename(stage)], check=True) + print(f"[chunk] {out} {len(ch)} clips {os.path.getsize(out)//1024//1024} MB", flush=True) + shutil.rmtree(os.path.dirname(stage), ignore_errors=True) +PY diff --git a/rsm_rise/scripts/rr_cpu_code_diff.sh b/rsm_rise/scripts/rr_cpu_code_diff.sh new file mode 100644 index 0000000000000000000000000000000000000000..c13f693c8fefb7478c1dfffdd0d65425a367f820 --- /dev/null +++ b/rsm_rise/scripts/rr_cpu_code_diff.sh @@ -0,0 +1,18 @@ +#!/usr/bin/env bash +# Diff our RISE / robomimic / mimicgen trees against the exact upstream commits. +set -u +ROOT=/proj/dmfexp/zwhong/rsm_rise; W=$ROOT/logs/code_diff; mkdir -p $W $ROOT/docs/diff; cd $W +clone() { [ -d $2 ] || git clone -q https://github.com/$1.git $2; git -C $2 fetch -q origin; git -C $2 checkout -q $3; } +clone UWRobotLearning/RISE rise_upstream f251e27 +clone UWRobotLearning/robomimic robomimic_upstream 5070abf +clone UWRobotLearning/mimicgen_environments mimicgen_upstream 14d8eb5 +X='--exclude=__pycache__ --exclude=*.egg-info --exclude=*.pyc --exclude=.git --exclude=*.pdf --exclude=*.txt --exclude=*.png --exclude=a.out --exclude=outputs --exclude=*.bak* --exclude=wandb --exclude=*.log' +diff -ruN $X rise_upstream/sim_pipeline $ROOT/code/rise_code/sim_pipeline > $ROOT/docs/diff/sim_pipeline.patch +diff -ruN $X rise_upstream/scripts $ROOT/code/rise_code/scripts > $ROOT/docs/diff/rise_scripts.patch +diff -ruN $X robomimic_upstream/robomimic $ROOT/code/rise_robomimic/robomimic > $ROOT/docs/diff/robomimic.patch +diff -ruN $X mimicgen_upstream/mimicgen_envs $ROOT/code/mimicgen_environments/mimicgen_envs > $ROOT/docs/diff/mimicgen_envs.patch +cd $ROOT/docs/diff +{ echo "# Code diff vs upstream (RISE f251e27, robomimic 5070abf, mimicgen_environments 14d8eb5) — $(date -u)"; echo; + for p in sim_pipeline rise_scripts robomimic mimicgen_envs; do echo "## $p.patch"; echo '```'; grep -E "^diff -ruN" $p.patch | sed -E 's#.*upstream/##; s# .*##' | while read f; do a=$(awk -v f="$f" '$0 ~ "^diff -ruN" && index($0,f){p=1;next} /^diff -ruN/{p=0} p&&/^\+[^+]/{a++} p&&/^-[^-]/{d++} END{print a+0" added, "d+0" removed"}' $p.patch); echo "$f: $a"; done; echo '```'; echo; done; + echo "## Files under our trees that do NOT exist upstream (new files)"; echo '```'; for p in sim_pipeline rise_scripts robomimic mimicgen_envs; do grep -E "^\+\+\+ /proj" $p.patch | awk '{print $2}' | while read f; do grep -qE "^--- .*upstream.*$(basename $f)" $p.patch || true; done; done; grep -hE "^--- /dev/null|^--- .*1970" *.patch | wc -l | sed 's/^/new-file hunks: /'; echo '```'; } > SUMMARY.md +wc -l *.patch >> SUMMARY.md; echo "[diff] done $(date -u)" diff --git a/rsm_rise/scripts/rr_cpu_diff_bundle.sh b/rsm_rise/scripts/rr_cpu_diff_bundle.sh new file mode 100644 index 0000000000000000000000000000000000000000..ecccca6ae3155c85b39a10894c841262d48ae170 --- /dev/null +++ b/rsm_rise/scripts/rr_cpu_diff_bundle.sh @@ -0,0 +1,22 @@ +#!/usr/bin/env bash +set -u +ROOT=/proj/dmfexp/zwhong/rsm_rise; W=$ROOT/logs/code_diff; B=$W/rsm_rise_code_diff; rm -rf $B; mkdir -p $B; cd $B +X="--exclude=__pycache__ --exclude=*.egg-info --exclude=*.pyc --exclude=.git --exclude=*.pdf --exclude=*.png --exclude=a.out --exclude=outputs --exclude=*.bak* --exclude=wandb --exclude=*.log --exclude=*.hdf5 --exclude=*.npz --exclude=*.pt --exclude=*.pth" +git init -q -b upstream . +rsync -a $X $W/rise_upstream/sim_pipeline/ sim_pipeline/; rsync -a $X $W/rise_upstream/scripts/ rise_scripts/ +rsync -a $X $W/robomimic_upstream/robomimic/ robomimic/; rsync -a $X $W/mimicgen_upstream/mimicgen_envs/ mimicgen_envs/ +git add -A && git -c user.name=rsm_rise -c user.email=rsm_rise@local commit -q -m "upstream: RISE f251e27 sim_pipeline+scripts, robomimic 5070abf, mimicgen_environments 14d8eb5" +rsync -a --delete $X $ROOT/code/rise_code/sim_pipeline/ sim_pipeline/; rsync -a --delete $X $ROOT/code/rise_code/scripts/ rise_scripts/ +rsync -a --delete $X $ROOT/code/rise_robomimic/robomimic/ robomimic/; rsync -a --delete $X $ROOT/code/mimicgen_environments/mimicgen_envs/ mimicgen_envs/ +git add -N . 2>/dev/null; git diff --stat > DIFF_STAT.txt +cat > README_DIFF.md <<'EOT' +# rsm_rise code diff bundle +The single commit on branch `upstream` is the pristine upstream code (RISE f251e27 `sim_pipeline/` + `scripts/` -> `rise_scripts/`, +UWRobotLearning/robomimic 5070abf -> `robomimic/`, UWRobotLearning/mimicgen_environments 14d8eb5 -> `mimicgen_envs/`). +The WORKING TREE is the code rsm_rise actually runs. Every change is therefore an uncommitted diff: + cursor . # then open the Source Control panel: each changed/new file shows the diff inline + git diff --stat # summary; git diff -- robomimic/utils/dataset.py for one file +New files (rsm_scorer.py, rsm_planner.py, tests, the tipped env config) appear as untracked. +Large data/checkpoint files are excluded. +EOT +cd $W && tar czf $ROOT/docs/diff/rsm_rise_code_diff.tgz rsm_rise_code_diff && ls -la $ROOT/docs/diff/rsm_rise_code_diff.tgz && cat $B/DIFF_STAT.txt | tail -5 diff --git a/rsm_rise/scripts/rr_cpu_drive_sync.sh b/rsm_rise/scripts/rr_cpu_drive_sync.sh new file mode 100644 index 0000000000000000000000000000000000000000..640c8504be579b3a4b21c2b8b528be2549a635b0 --- /dev/null +++ b/rsm_rise/scripts/rr_cpu_drive_sync.sh @@ -0,0 +1,8 @@ +#!/usr/bin/env bash +# CPU-only LSF job: sync the RISE Drive folder into data/raw with validation. +set -uo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +export PATH=/proj/dmfexp/zwhong/rsm_rise/env/bin:$PATH +echo "[job] host $(hostname) start $(date -u)" +python scripts/drive_sync.py +echo "[job] exit=$? end $(date -u)" diff --git a/rsm_rise/scripts/rr_cpu_evtab.sh b/rsm_rise/scripts/rr_cpu_evtab.sh new file mode 100644 index 0000000000000000000000000000000000000000..f93d8ad59c7a1e8a6a53fb876a896c8828be1e3e --- /dev/null +++ b/rsm_rise/scripts/rr_cpu_evtab.sh @@ -0,0 +1,4 @@ +#!/usr/bin/env bash +# gate-eval table refresh in one CPU job. usage: rr_cpu_evtab.sh +cd /proj/dmfexp/zwhong/rsm_rise +python3 scripts/stage0_eval_table.py --write 2>&1 diff --git a/rsm_rise/scripts/rr_cpu_gate_eval_watch.sh b/rsm_rise/scripts/rr_cpu_gate_eval_watch.sh new file mode 100644 index 0000000000000000000000000000000000000000..52e13bfa3aa9feec7ad779951f734a98f971b7e8 --- /dev/null +++ b/rsm_rise/scripts/rr_cpu_gate_eval_watch.sh @@ -0,0 +1,34 @@ +#!/usr/bin/env bash +# CPU job: watch for model_epoch_5000.pth checkpoints and submit the Stage 0 GATE evals as soon as they +# appear, so the gate numbers do not wait for the next agent run. Idempotent -- launch_stage0_evals.sh +# skips any (cell, seed, eval-seed) that already has a JSON or a live job. +# usage: scripts/rr_cpu_gate_eval_watch.sh [hours] [max_concurrent_evals] +# Throttled: never submits while >= MAXEV rr_ev_ jobs are RUN/PEND (the admins killed long GPU jobs twice +# on 2026-09-18; keep the eval burst modest). Also refreshes the bad-eval-host blacklist every pass. +set -uo pipefail +ROOT=/proj/dmfexp/zwhong/rsm_rise +HOURS=${1:-6}; MAXEV=${2:-40} +TASKS="square_expert_play mug_expert_suboptimal square_expert_suboptimal threading_expert_play \ +two_piece_expert_play two_piece_expert_suboptimal two_piece_expert_play_tipping square_sub_paper +threading_paper mug_paper piecesub_paper piecetip_paper" +end=$(( $(date +%s) + HOURS*3600 )) +while [ "$(date +%s)" -lt $end ]; do + n=$(bjobs -w 2>/dev/null | grep -c rr_ev_) + echo "[gate_watch] $(date -u +%H:%M:%S) live evals=$n" + if [ "$n" -lt "$MAXEV" ]; then + bash $ROOT/scripts/eval_host_stats.sh --write >/dev/null 2>&1 + for t in $TASKS; do + have=$(ls $ROOT/runs/$t/policy/*/*/*/models/model_epoch_5000.pth 2>/dev/null | wc -l) + [ "$have" -gt 0 ] || continue + echo "[gate_watch] $t has $have epoch-5000 checkpoints -> launching gate evals" + bash $ROOT/scripts/launch_stage0_evals.sh $t + # VALIDATION set too (checkpoint selection): the watcher used to launch only the TEST gate evals, so + # quarantining a bad eval_val JSON did not regenerate it (found 2026-09-18 19:10 UTC when the + # pre-patch two-piece eval_val files were moved to eval_val/prepatch/). RR_WATCH_VAL=0 disables. + [ "${RR_WATCH_VAL:-1}" = 1 ] && RR_VAL=1 RR_CELLS="S0A S0B S3H1" bash $ROOT/scripts/launch_stage0_evals.sh $t + [ "$(bjobs -w 2>/dev/null | grep -c rr_ev_)" -ge "$MAXEV" ] && break + done + fi + sleep 300 +done +echo "[gate_watch] done $(date -u)" diff --git a/rsm_rise/scripts/rr_cpu_get_mimicgen.sh b/rsm_rise/scripts/rr_cpu_get_mimicgen.sh new file mode 100644 index 0000000000000000000000000000000000000000..706f40610fd0b4f7c3e416775654e9fdae4e3783 --- /dev/null +++ b/rsm_rise/scripts/rr_cpu_get_mimicgen.sh @@ -0,0 +1,31 @@ +#!/usr/bin/env bash +# CPU job: fetch MimicGen core datasets by Drive id with gdown (our robomimic fork has no download helper). +# usage: rr_cpu_get_mimicgen.sh [ ...] +set -uo pipefail +cd /proj/dmfexp/zwhong/rsm_rise; export PATH=/proj/dmfexp/zwhong/rsm_rise/env/bin:$PATH +mkdir -p data/mimicgen +echo "[job] host $(hostname) start $(date -u)" +python - "$@" <<'PY' +import sys, os, re, time +import gdown +IDS = {"square_d0": "1FFMWZPzliM4QoiBxbuU69DGfZ4rmt9LL", + "square_d1": "1LJfdITKFQTfPmETVVUjj9YTwiFcmDleZ", + "square_d2": "1X8KCL1eSLT0aieIbFFWOMDb3H2z_czv5", + "mug_cleanup_d0": "1VV2PkvlTT0fGmc6MwwJR8bAtop0hpjIJ", + "mug_cleanup_d1": "1bxJyN2c2yZsgn2FOGWFJsxlgHXWD3eiI"} +out = "/proj/dmfexp/zwhong/rsm_rise/data/mimicgen" +for task in sys.argv[1:]: + dst = os.path.join(out, task + ".hdf5") + if os.path.exists(dst) and os.path.getsize(dst) > 1e6: + print(f"[dl] {task}: already have {os.path.getsize(dst)//1024//1024} MB", flush=True); continue + for attempt in range(3): + try: + print(f"[dl] {task} attempt {attempt+1} -> {dst}", flush=True) + gdown.download(f"https://drive.google.com/uc?id={IDS[task]}", dst, quiet=False) + if os.path.exists(dst) and os.path.getsize(dst) > 1e6: + print(f"[dl] {task}: {os.path.getsize(dst)//1024//1024} MB", flush=True); break + except Exception as e: + print(f"[dl] {task} failed: {str(e)[:200]}", flush=True); time.sleep(30) +PY +ls -la data/mimicgen | awk '{print int($5/1024/1024)"MB", $9}' +echo "[job] end $(date -u)" diff --git a/rsm_rise/scripts/rr_cpu_get_mimicgen_mug.sh b/rsm_rise/scripts/rr_cpu_get_mimicgen_mug.sh new file mode 100644 index 0000000000000000000000000000000000000000..f170575d2af8eb408864753aa7c9e965ef138c04 --- /dev/null +++ b/rsm_rise/scripts/rr_cpu_get_mimicgen_mug.sh @@ -0,0 +1,25 @@ +#!/usr/bin/env bash +# CPU-only LSF job: fetch MimicGen's mug_cleanup_d0 core dataset (1000 generated demos in MugCleanup_D0, which +# is a verbatim rename of MugCleanup with identical placement bounds -- i.e. the very env RISE evaluates mug in). +# Goal: give mug-cleanup an expert pool larger than the 20 demos in the released RISE file. +set -uo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +export PATH=/proj/dmfexp/zwhong/rsm_rise/env/bin:$PATH +OUT=/proj/dmfexp/zwhong/rsm_rise/data/mimicgen +mkdir -p $OUT +echo "[job] host $(hostname) start $(date -u)" +python - <<'PY' +import os, sys +sys.path.insert(0, "/proj/dmfexp/zwhong/rsm_rise/code/mimicgen_environments") +from mimicgen_envs import DATASET_REGISTRY +import robomimic.utils.file_utils as FileUtils +out = "/proj/dmfexp/zwhong/rsm_rise/data/mimicgen" +for task in ("mug_cleanup_d0",): + url = DATASET_REGISTRY["core"][task]["url"] + print(f"[dl] {task} horizon={DATASET_REGISTRY['core'][task]['horizon']} url={url}", flush=True) + FileUtils.download_url_from_gdrive(url=url, download_dir=out, check_overwrite=False) +print("[dl] done", flush=True) +PY +rc=$? +ls -la $OUT 2>/dev/null | awk '{print $5,$9}' +echo "[job] exit=$rc end $(date -u)" diff --git a/rsm_rise/scripts/rr_cpu_get_mimicgen_square.sh b/rsm_rise/scripts/rr_cpu_get_mimicgen_square.sh new file mode 100644 index 0000000000000000000000000000000000000000..8e85fb90e63f8f5c7265a8b554383736b72af00a --- /dev/null +++ b/rsm_rise/scripts/rr_cpu_get_mimicgen_square.sh @@ -0,0 +1,22 @@ +#!/usr/bin/env bash +# CPU job: fetch MimicGen square_d0 / square_d1 (1000 generated demos each). D0's nut start box is EXACTLY +# RISE's expert sliver (x -0.115..-0.11, y 0.11..0.225); D1 widens the nut to x -0.115..0.115, y -0.255..0.255, +# which is what we need to cover a real fraction of the coverage evaluation box. +set -uo pipefail +cd /proj/dmfexp/zwhong/rsm_rise; export PATH=/proj/dmfexp/zwhong/rsm_rise/env/bin:$PATH +mkdir -p data/mimicgen +echo "[job] host $(hostname) start $(date -u)" +python - <<'PY' +import sys +sys.path.insert(0, "/proj/dmfexp/zwhong/rsm_rise/code/mimicgen_environments") +from mimicgen_envs import DATASET_REGISTRY +import robomimic.utils.file_utils as FileUtils +out = "/proj/dmfexp/zwhong/rsm_rise/data/mimicgen" +for task in ("square_d0", "square_d1"): + url = DATASET_REGISTRY["core"][task]["url"] + print(f"[dl] {task} -> {out}", flush=True) + FileUtils.download_url_from_gdrive(url=url, download_dir=out, check_overwrite=False) +print("[dl] done", flush=True) +PY +ls -la data/mimicgen | awk '{print $5,$9}' +echo "[job] end $(date -u)" diff --git a/rsm_rise/scripts/rr_cpu_idx.sh b/rsm_rise/scripts/rr_cpu_idx.sh new file mode 100644 index 0000000000000000000000000000000000000000..ce7830f33b7bd0719374448969bca4dfbb4ff2eb --- /dev/null +++ b/rsm_rise/scripts/rr_cpu_idx.sh @@ -0,0 +1,29 @@ +#!/usr/bin/env bash +# CPU job: the routine stream-A refresh bundle. usage: bsub_cpu.sh rr_cpu_idx_ scripts/rr_cpu_idx.sh +# Runs: stage0 training table (--write), checkpoint index (--write), S0A ETAs (--write), livelock regression scan, +# and the gate-eval dry-run over ALL tasks (primary + *_paper) so TEST/VAL gaps are enumerated, not guessed. +set -uo pipefail +ROOT=/proj/dmfexp/zwhong/rsm_rise +TAG=${1:-$(date -u +%H%M)} +source $ROOT/scripts/env.sh +export MUJOCO_GL=disable OMP_NUM_THREADS=8 MKL_NUM_THREADS=8 +cd $ROOT +echo "===== stage0_status =====" +python3 scripts/stage0_status.py --write 2>&1 | tee status/stage0_status_$TAG.txt | tail -5 +echo "===== ckpt_index =====" +bash scripts/ckpt_index.sh --write 2>&1 | tail -40 +echo "===== s0a_eta =====" +python3 scripts/s0a_eta.py --cells S0A,S0B --epochs 4000,5000 --write 2>&1 | tail -30 +echo "===== livelock_scan =====" +bash scripts/livelock_scan.sh 2>&1 | tee status/livelock_$TAG.txt | tail -30 +echo "===== eval dryrun (TEST) =====" +for t in $(ls $ROOT/runs); do + case $t in _*|smoke*) continue;; esac + echo "--- $t"; RR_DRYRUN=1 bash scripts/launch_stage0_evals.sh "$t" 2>&1 | tail -40 +done +echo "===== eval dryrun (VAL) =====" +for t in $(ls $ROOT/runs); do + case $t in _*|smoke*) continue;; esac + echo "--- $t"; RR_DRYRUN=1 RR_VAL=1 bash scripts/launch_stage0_evals.sh "$t" 2>&1 | tail -40 +done +echo "[rr_cpu_idx] done $(date -u)" diff --git a/rsm_rise/scripts/rr_cpu_init_dump.sh b/rsm_rise/scripts/rr_cpu_init_dump.sh new file mode 100644 index 0000000000000000000000000000000000000000..4bbd1344ae55b776cbe0b533c4febe8c9ebd761c --- /dev/null +++ b/rsm_rise/scripts/rr_cpu_init_dump.sh @@ -0,0 +1,8 @@ +#!/usr/bin/env bash +# CPU job: dump per-episode initial object/eef state for the tasks whose eval-env init distribution +# still has to be checked against the training data (see status/A_env_stage0.md 17:00 UTC). +set -euo pipefail +ROOT=/proj/dmfexp/zwhong/rsm_rise +source $ROOT/scripts/env.sh +cd $ROOT +python scripts/dump_init_states.py "$@" diff --git a/rsm_rise/scripts/rr_cpu_inspect_rewards.py b/rsm_rise/scripts/rr_cpu_inspect_rewards.py new file mode 100644 index 0000000000000000000000000000000000000000..79e162c80621a52700f33ba52af3f5c051e6940b --- /dev/null +++ b/rsm_rise/scripts/rr_cpu_inspect_rewards.py @@ -0,0 +1,25 @@ +import h5py, numpy as np, json, sys +out = {} +for task in ["mug_expert_suboptimal", "square_expert_suboptimal", "square_expert_play"]: + with h5py.File(f"data/raw/{task}.hdf5", "r") as h: + d = h["data"]; keys = list(d.keys()) + rec = {"episodes": len(keys), "attrs": {k: str(v)[:200] for k, v in d.attrs.items()}} + pats = {"const0": 0, "const1": 0, "step_up": 0, "other": 0} + first_r, dones_pat, tail = [], {"none": 0, "last_only": 0, "from_success": 0, "other": 0}, [] + for k in keys: + r = d[k]["rewards"][:]; dn = d[k]["dones"][:] if "dones" in d[k] else None + if r.max() == 0: pats["const0"] += 1 + elif r.min() == 1: pats["const1"] += 1 + elif np.all(np.diff(r) >= 0): pats["step_up"] += 1; first_r.append(int(np.argmax(r > 0))); tail.append(len(r) - int(np.argmax(r > 0))) + else: pats["other"] += 1 + if dn is not None: + if dn.max() == 0: dones_pat["none"] += 1 + elif dn.sum() == 1 and dn[-1] == 1: dones_pat["last_only"] += 1 + elif np.array_equal(dn.astype(np.uint8), (r > 0).astype(np.uint8)): dones_pat["from_success"] += 1 + else: dones_pat["other"] += 1 + rec["reward_patterns"] = pats; rec["dones_patterns"] = dones_pat + if first_r: rec["step_up_first_reward_frame_mean"] = float(np.mean(first_r)); rec["frames_after_first_reward_mean"] = float(np.mean(tail)) + ep0 = d[keys[0]]; rec["ep0_keys"] = list(ep0.keys()); rec["ep0_reward_head"] = ep0["rewards"][:8].tolist(); rec["ep0_reward_tail"] = ep0["rewards"][-8:].tolist() + out[task] = rec + print(task, json.dumps(rec)[:900], flush=True) +json.dump(out, open("data/raw/REWARD_INSPECT.json", "w"), indent=1) diff --git a/rsm_rise/scripts/rr_cpu_inspect_rewards.sh b/rsm_rise/scripts/rr_cpu_inspect_rewards.sh new file mode 100644 index 0000000000000000000000000000000000000000..0e9d861a4648bb2981eb29e87dba7d9f6b108942 --- /dev/null +++ b/rsm_rise/scripts/rr_cpu_inspect_rewards.sh @@ -0,0 +1,2 @@ +#!/usr/bin/env bash +cd /proj/dmfexp/zwhong/rsm_rise && /proj/dmfexp/zwhong/rsm_rise/venv_rsm/bin/python scripts/rr_cpu_inspect_rewards.py diff --git a/rsm_rise/scripts/rr_cpu_nb46_closeoff.sh b/rsm_rise/scripts/rr_cpu_nb46_closeoff.sh new file mode 100644 index 0000000000000000000000000000000000000000..346bea184def475c19fd04d27e96a793096913cd --- /dev/null +++ b/rsm_rise/scripts/rr_cpu_nb46_closeoff.sh @@ -0,0 +1,17 @@ +#!/usr/bin/env bash +# gen_q#274 run 46 -- rebuild the DF guidance close-off after SLURM 42147 landed the two cells +# run 44 lost to the p1-r04-n2 read_pixels SIGABRT: mug arm B g=12.0 and threading arm A g=3.0. +set -uo pipefail +ROOT=/proj/dmfexp/zwhong/rsm_rise +cd $ROOT || exit 9 +source $ROOT/scripts/env.sh +python $ROOT/scripts/nb/df_guid_closeoff_tab.py > $ROOT/status/nb/df_guid_closeoff.txt.new 2> $ROOT/status/nb/df_guid_closeoff.err +rc=$? +echo "[nb46_closeoff] builder exit=$rc" +if [ "$rc" = "0" ] && [ -s $ROOT/status/nb/df_guid_closeoff.txt.new ]; then + mv $ROOT/status/nb/df_guid_closeoff.txt.new $ROOT/status/nb/df_guid_closeoff.txt + echo "[nb46_closeoff] published status/nb/df_guid_closeoff.txt" +else + echo "[nb46_closeoff] REFUSING to publish -- exit=$rc, stderr follows"; cat $ROOT/status/nb/df_guid_closeoff.err +fi +exit $rc diff --git a/rsm_rise/scripts/rr_cpu_nb46_rho.sh b/rsm_rise/scripts/rr_cpu_nb46_rho.sh new file mode 100644 index 0000000000000000000000000000000000000000..3cac8b3cb0713070f6100ec571d09fe779af1395 --- /dev/null +++ b/rsm_rise/scripts/rr_cpu_nb46_rho.sh @@ -0,0 +1,32 @@ +#!/usr/bin/env bash +# gen_q#274 run 46-main -- rebuild the cfg(a)-vs-DINO-WM rank-correlation table (BLOCKER item 3). +# WHY NOW: status/nb/td_dwm_rho.txt was built 16:42Z, when the SWAPPED block had two seeds per task. +# Seeds 2 and 3 landed 18:47-18:48Z (td_dwm_rho_swap_{threading,mug}_g095_s{2,3}.json). The table's +# own caveat says the matched-anchor rho "is not yet pinned" BECAUSE each row is one seed of 50 +# decisions and the seeds disagree; four seeds per task is the direct answer to that caveat. +set -uo pipefail +ROOT=/proj/dmfexp/zwhong/rsm_rise +cd $ROOT || exit 9 +source $ROOT/scripts/env.sh +python $ROOT/scripts/nb/td_dwm_rho_tab.py > $ROOT/status/nb/td_dwm_rho.txt.new 2> $ROOT/status/nb/td_dwm_rho.err +rc=$? +echo "[nb46_rho] builder exit=$rc" +if [ "$rc" = "0" ] && [ -s $ROOT/status/nb/td_dwm_rho.txt.new ]; then + # NON-VACUITY: refuse to publish a table built from FEWER artefacts than the one on disk. The + # builder prints its own artefact list on the last line; a shrink means a glob or a parser broke, + # and a silently smaller table would read as a weaker result rather than as a defect. + oldn=$(grep -c "td_dwm_rho" $ROOT/status/nb/td_dwm_rho.txt 2>/dev/null || echo 0) + newn=$(grep -c "td_dwm_rho" $ROOT/status/nb/td_dwm_rho.txt.new 2>/dev/null || echo 0) + olda=$(tail -1 $ROOT/status/nb/td_dwm_rho.txt 2>/dev/null | grep -oE "^built .* from [0-9]+" | grep -oE "[0-9]+$") + newa=$(tail -1 $ROOT/status/nb/td_dwm_rho.txt.new | grep -oE "^built .* from [0-9]+" | grep -oE "[0-9]+$") + echo "[nb46_rho] artefacts old=${olda:-?} new=${newa:-?}" + if [ -n "${olda:-}" ] && [ -n "${newa:-}" ] && [ "$newa" -lt "$olda" ]; then + echo "[nb46_rho] REFUSING: artefact count SHRANK $olda -> $newa"; exit 4 + fi + mv $ROOT/status/nb/td_dwm_rho.txt.new $ROOT/status/nb/td_dwm_rho.txt + echo "[nb46_rho] published status/nb/td_dwm_rho.txt" + tail -1 $ROOT/status/nb/td_dwm_rho.txt +else + echo "[nb46_rho] REFUSING to publish -- exit=$rc"; cat $ROOT/status/nb/td_dwm_rho.err +fi +exit $rc diff --git a/rsm_rise/scripts/rr_cpu_nb47_dftab.sh b/rsm_rise/scripts/rr_cpu_nb47_dftab.sh new file mode 100644 index 0000000000000000000000000000000000000000..fffad4efe9d263ba164824017461c2d25633f9ae --- /dev/null +++ b/rsm_rise/scripts/rr_cpu_nb47_dftab.sh @@ -0,0 +1,18 @@ +#!/usr/bin/env bash +# gen_q#274 run 47 -- rebuild status/nb/df_table.txt now that the PAPER-SCALE reproduction gate has +# landed a verdict at the paper branch's own step floor (LSF 1904769, step 100000). +set -uo pipefail +ROOT=/proj/dmfexp/zwhong/rsm_rise +cd $ROOT || exit 9 +source $ROOT/scripts/env.sh +python $ROOT/scripts/nb/df_table.py > $ROOT/status/nb/df_table.txt.new 2> $ROOT/status/nb/df_table.err +rc=$? +echo "[nb47_dftab] builder exit=$rc" +if [ "$rc" = "0" ] && [ -s $ROOT/status/nb/df_table.txt.new ]; then + mv $ROOT/status/nb/df_table.txt.new $ROOT/status/nb/df_table.txt + echo "[nb47_dftab] published status/nb/df_table.txt" + sed -n '1,60p' $ROOT/status/nb/df_table.txt +else + echo "[nb47_dftab] REFUSING to publish -- exit=$rc"; cat $ROOT/status/nb/df_table.err +fi +exit $rc diff --git a/rsm_rise/scripts/rr_cpu_nb47_jsplit.sh b/rsm_rise/scripts/rr_cpu_nb47_jsplit.sh new file mode 100644 index 0000000000000000000000000000000000000000..6f8e7fb6669a9cda23e519ea7a0fd9d3758aa1c2 --- /dev/null +++ b/rsm_rise/scripts/rr_cpu_nb47_jsplit.sh @@ -0,0 +1,17 @@ +#!/usr/bin/env bash +# gen_q#274 run 47 -- build status/nb/td_jsplit.txt from the LSF 1904934 decomposition artefacts. +set -uo pipefail +ROOT=/proj/dmfexp/zwhong/rsm_rise +cd $ROOT || exit 9 +source $ROOT/scripts/env.sh +python $ROOT/scripts/nb/td_jsplit_tab.py > $ROOT/status/nb/td_jsplit.txt.new 2> $ROOT/status/nb/td_jsplit.err +rc=$? +echo "[nb47_jsplit] builder exit=$rc" +if [ "$rc" = "0" ] && [ -s $ROOT/status/nb/td_jsplit.txt.new ]; then + mv $ROOT/status/nb/td_jsplit.txt.new $ROOT/status/nb/td_jsplit.txt + echo "[nb47_jsplit] published status/nb/td_jsplit.txt" + cat $ROOT/status/nb/td_jsplit.txt +else + echo "[nb47_jsplit] REFUSING to publish -- exit=$rc"; cat $ROOT/status/nb/td_jsplit.err +fi +exit $rc diff --git a/rsm_rise/scripts/rr_cpu_nb48_resumeaudit.sh b/rsm_rise/scripts/rr_cpu_nb48_resumeaudit.sh new file mode 100644 index 0000000000000000000000000000000000000000..8aaf93e8efbc0ab211154801783bd14c2e90cbc1 --- /dev/null +++ b/rsm_rise/scripts/rr_cpu_nb48_resumeaudit.sh @@ -0,0 +1,16 @@ +#!/bin/bash +# run 48-main: project-wide resume-truncation audit of planner health. +set -u +cd /proj/dmfexp/zwhong/rsm_rise +echo "[nb48_resumeaudit] start $(date -u) host=$(hostname)" +: > status/nb/resume_audit.err +python scripts/nb/resume_audit.py > status/nb/resume_audit.stdout 2> status/nb/resume_audit.err +rc=$? +echo "[nb48_resumeaudit] rc=$rc" +if [ $rc -ne 0 ]; then + echo "[nb48_resumeaudit] REFUSED -- stderr:"; cat status/nb/resume_audit.err + exit $rc +fi +test -s status/nb/resume_audit.txt || { echo "[nb48_resumeaudit] no txt landed"; exit 4; } +echo "[nb48_resumeaudit] LANDED $(wc -l < status/nb/resume_audit.txt) lines" +echo "[nb48_resumeaudit] done $(date -u)" diff --git a/rsm_rise/scripts/rr_cpu_nb48_tdtab.sh b/rsm_rise/scripts/rr_cpu_nb48_tdtab.sh new file mode 100644 index 0000000000000000000000000000000000000000..3c5121ab1cba47eb8e237040720b0bd33051d34f --- /dev/null +++ b/rsm_rise/scripts/rr_cpu_nb48_tdtab.sh @@ -0,0 +1,20 @@ +#!/bin/bash +# run 48-main: rebuild status/nb/td_table.{txt,json} with the resume-coverage check. +# Publish-or-refuse: the old table is kept if the builder fails. +set -u +cd /proj/dmfexp/zwhong/rsm_rise +echo "[nb48_tdtab] start $(date -u) host=$(hostname)" +cp -p status/nb/td_table.txt status/nb/td_table.txt.bak.20260924_run48main 2>/dev/null +cp -p status/nb/td_table.json status/nb/td_table.json.bak.20260924_run48main 2>/dev/null +: > status/nb/td_table.err +python scripts/nb/td_table.py > status/nb/td_table.stdout 2> status/nb/td_table.err +rc=$? +echo "[nb48_tdtab] rc=$rc" +if [ $rc -ne 0 ]; then + echo "[nb48_tdtab] REFUSED -- restoring previous table"; cat status/nb/td_table.err + cp -p status/nb/td_table.txt.bak.20260924_run48main status/nb/td_table.txt 2>/dev/null + cp -p status/nb/td_table.json.bak.20260924_run48main status/nb/td_table.json 2>/dev/null + exit $rc +fi +grep -c "HEALTH-PARTIAL" status/nb/td_table.txt | sed 's/^/[nb48_tdtab] HEALTH-PARTIAL lines: /' +echo "[nb48_tdtab] done $(date -u)" diff --git a/rsm_rise/scripts/rr_cpu_nb49_tdresume.sh b/rsm_rise/scripts/rr_cpu_nb49_tdresume.sh new file mode 100644 index 0000000000000000000000000000000000000000..dc048dd3b8c33f4ba595e176c8008ac3ac66a938 --- /dev/null +++ b/rsm_rise/scripts/rr_cpu_nb49_tdresume.sh @@ -0,0 +1,23 @@ +#!/usr/bin/env bash +# gen_q#274 run 49-main -- the CPU gate for FINDING AK (cfg(b)'s episode-level resume). +# Publish-or-refuse: the .txt is only replaced when the whole suite passes, so a failing run cannot +# leave a file that reads like a pass. +set -uo pipefail +R=/proj/dmfexp/zwhong/rsm_rise +cd $R || exit 9 +OUT=$R/status/nb/td_resume_test.txt +TMP=$(mktemp) +$R/venv_tdmpc2/bin/python $R/scripts/nb/test_td_resume.py > "$TMP" 2>&1 +rc=$? +cat "$TMP" +if [ "$rc" = 0 ]; then + { echo "== gen_q#274 FINDING AK -- configuration (b) episode-level resume, test gate $(date -u)" + echo " under test: code/tdmpc2_rise/td_policy.py state_dump/state_load + inner._rr_td_planner" + echo " code/rise_code/sim_pipeline/eval/eval.py _df_planner (now also _rr_td_planner)" + echo ""; cat "$TMP"; } > "$OUT" + echo "[nb49_tdresume] PUBLISHED $OUT" +else + echo "[nb49_tdresume] REFUSING to publish: suite rc=$rc (previous $OUT, if any, kept)" +fi +rm -f "$TMP" +exit $rc diff --git a/rsm_rise/scripts/rr_cpu_nb50_gammaarm.sh b/rsm_rise/scripts/rr_cpu_nb50_gammaarm.sh new file mode 100644 index 0000000000000000000000000000000000000000..2a0d06833278a00ff6fd322879f1b20a23e3c9e9 --- /dev/null +++ b/rsm_rise/scripts/rr_cpu_nb50_gammaarm.sh @@ -0,0 +1,17 @@ +#!/usr/bin/env bash +# gen_q#274 run 50-main -- build status/nb/td_gamma_arm.txt, publish-or-refuse. +set -uo pipefail +ROOT=/proj/dmfexp/zwhong/rsm_rise +cd $ROOT || exit 9 +source $ROOT/scripts/env.sh +python $ROOT/scripts/nb/td_gamma_arm.py > $ROOT/status/nb/td_gamma_arm.txt.new 2> $ROOT/status/nb/td_gamma_arm.err +rc=$? +echo "[nb50_gammaarm] builder exit=$rc" +if [ "$rc" = "0" ] && [ -s $ROOT/status/nb/td_gamma_arm.txt.new ]; then + mv $ROOT/status/nb/td_gamma_arm.txt.new $ROOT/status/nb/td_gamma_arm.txt + echo "[nb50_gammaarm] published status/nb/td_gamma_arm.txt" + cat $ROOT/status/nb/td_gamma_arm.txt +else + echo "[nb50_gammaarm] REFUSING to publish -- exit=$rc"; cat $ROOT/status/nb/td_gamma_arm.err +fi +exit $rc diff --git a/rsm_rise/scripts/rr_cpu_nb51_ctlpairs.sh b/rsm_rise/scripts/rr_cpu_nb51_ctlpairs.sh new file mode 100644 index 0000000000000000000000000000000000000000..9e1d96e4db07ba3b9b43341328d88af7606756b3 --- /dev/null +++ b/rsm_rise/scripts/rr_cpu_nb51_ctlpairs.sh @@ -0,0 +1,71 @@ +#!/usr/bin/env bash +# gen_q#274 run 51-main -- rebuild td_ctl_pairs with the EVAL-SEED AXIS, behind an old-vs-new +# regression gate. PUBLISH-OR-REFUSE: if any cell the pre-run-51 builder published has moved, the +# old outputs are restored and this exits non-zero, so a silent change can never land. +set -uo pipefail +R=/proj/dmfexp/zwhong/rsm_rise +PY=$R/venv_rsm/bin/python +cd $R +S=status/nb +echo "[nb51_ctlpairs] $(date -u) host=$(hostname)" + +# keep whatever is currently published, so a refusal restores it byte for byte +for e in txt json; do [ -s $S/td_ctl_pairs.$e ] && cp $S/td_ctl_pairs.$e $S/td_ctl_pairs.$e.prerun51; done + +echo "=== OLD BUILDER (scripts/nb/td_ctl_pairs.py.bak.20260925_run51main_seedaxis) ===" +$PY scripts/nb/td_ctl_pairs.py.bak.20260925_run51main_seedaxis > $S/td_ctl_pairs_OLD.txt 2>&1 +echo "old rc=$?" +cp $S/td_ctl_pairs.json $S/td_ctl_pairs_OLD.json 2>/dev/null + +echo "=== NEW BUILDER ===" +$PY scripts/nb/td_ctl_pairs.py > $S/td_ctl_pairs_NEW.stdout 2>&1 +nrc=$? +echo "new rc=$nrc" +if [ "$nrc" != 0 ]; then + sed -n 1,60p $S/td_ctl_pairs_NEW.stdout + echo "[nb51_ctlpairs] NEW BUILDER FAILED -- restoring the published outputs" + for e in txt json; do [ -s $S/td_ctl_pairs.$e.prerun51 ] && cp $S/td_ctl_pairs.$e.prerun51 $S/td_ctl_pairs.$e; done + exit 1 +fi + +echo "=== REGRESSION GATE: every cell the OLD builder published must be unchanged in the NEW one ===" +$PY - <<'PYEOF' +import json, sys +S="/proj/dmfexp/zwhong/rsm_rise/status/nb" +old=json.load(open(f"{S}/td_ctl_pairs_OLD.json")) +new=json.load(open(f"{S}/td_ctl_pairs.json")) +# the old builder had no eval_seed field; every one of its cells was eval seed 0 by construction +key=lambda r:(r["task"], r["gamma"]) +o={key(r):r for r in old["rows"]} +n={(r["task"],r["gamma"]):r for r in new["rows"] if r["eval_seed"]==0} +bad=[] +for k,r in o.items(): + if k not in n: + bad.append(f"OLD cell {k} VANISHED from the new builder"); continue + for f in ("sr_argmax","n_argmax","sr_random","n_random","k_argmax","k_random", + "argmax_file","random_file"): + if r[f]!=n[k][f]: + bad.append(f"{k} field {f}: old {r[f]!r} -> new {n[k][f]!r}") +added=sorted(set(n)-set(o)) +print(f"old paired cells {len(o)} new paired cells (es0) {len(n)} new total {len(new['rows'])}") +print(f"CELLS THE OLD BUILDER SILENTLY DROPPED: {added if added else 'none'}") +po=old["pooled"]; pn=new["pooled_all_cells"] +print(f"old pooled argmax {po['k_argmax']}/{po['n_argmax']} = {po['sr_argmax']:.4f} " + f"random {po['k_random']}/{po['n_random']} = {po['sr_random']:.4f}") +print(f"new pooled argmax {pn['k_argmax']}/{pn['n_argmax']} = {pn['sr_argmax']:.4f} " + f"random {pn['k_random']}/{pn['n_random']} = {pn['sr_random']:.4f}") +print(f"seeds present {new['seeds_present']} distinct states {new['distinct_states']}") +print(f"independent-states row: {new['pooled_independent_states']}") +if bad: + print("GATE FAIL:"); [print(" "+b) for b in bad]; sys.exit(1) +print("GATE PASS -- no cell the old builder published has moved; the only change is coverage.") +PYEOF +grc=$? +if [ "$grc" != 0 ]; then + echo "[nb51_ctlpairs] REGRESSION GATE FAILED -- restoring the published outputs" + for e in txt json; do [ -s $S/td_ctl_pairs.$e.prerun51 ] && cp $S/td_ctl_pairs.$e.prerun51 $S/td_ctl_pairs.$e; done + exit 1 +fi +echo "=== PUBLISHED status/nb/td_ctl_pairs.txt ===" +cat $S/td_ctl_pairs.txt +echo "[nb51_ctlpairs] DONE $(date -u)" diff --git a/rsm_rise/scripts/rr_cpu_nb51_dfrebuild.sh b/rsm_rise/scripts/rr_cpu_nb51_dfrebuild.sh new file mode 100644 index 0000000000000000000000000000000000000000..186e0d37eb93cea613cc45dba3cdc7db955d5a6e --- /dev/null +++ b/rsm_rise/scripts/rr_cpu_nb51_dfrebuild.sh @@ -0,0 +1,53 @@ +#!/usr/bin/env bash +# gen_q#274 run 51-main -- rebuild the two DF tables with the health-coverage refusal wired in. +# df_idm_tab.py had NO coverage check and it AVERAGES up to 9 cells per row, so the 16 df274idm cells +# that resume_audit flags as partial were entering published means unmarked and unrefused. It also +# printed only to stdout with no persisted file, so its numbers were not traceable to a named file -- +# fixed here by capturing to status/nb/df_idm_tab.txt. +# PUBLISH-OR-REFUSE on both. +set -uo pipefail +R=/proj/dmfexp/zwhong/rsm_rise +PY=$R/venv_rsm/bin/python +cd $R +S=status/nb +echo "[nb51_dfrebuild] $(date -u) host=$(hostname)" +fail=0 + +echo; echo "=== df_table (control-side pairing claim now conditioned on the CONTROL's coverage) ===" +cp $S/df_table.txt $S/df_table.txt.pre51c 2>/dev/null +$PY scripts/nb/df_table.py > /dev/null 2>$S/.e; rc=$? +echo "rc=$rc" +if [ "$rc" != 0 ]; then + sed -n 1,40p $S/.e; cp $S/df_table.txt.pre51c $S/df_table.txt 2>/dev/null; fail=1 +else + echo "HEALTH-PARTIAL arm blocks: $(grep -c 'HEALTH-PARTIAL' $S/df_table.txt || true)" + echo "controls whose pairing claim is now WITHDRAWN: $(grep -c 'NOT the identical-candidate control' $S/df_table.txt || true)" + echo "controls still claiming 'same plans, same initial states': $(grep -c 'same plans, same initial states' $S/df_table.txt || true)" + echo "--- one withdrawn control in context ---" + grep -m1 -A3 "NOT the identical-candidate control" $S/df_table.txt || echo "(none)" + echo "--- the FAIL banner must survive ---" + grep -m1 -n "REPRODUCTION GATE" $S/df_table.txt +fi + +echo; echo "=== df_idm_tab (coverage refusal + a persisted file for the first time) ===" +[ -s $S/df_idm_tab.txt ] && cp $S/df_idm_tab.txt $S/df_idm_tab.txt.pre51 +$PY scripts/nb/df_idm_tab.py > $S/df_idm_tab.txt.new 2>$S/.e2; rc=$? +echo "rc=$rc" +if [ "$rc" != 0 ]; then + sed -n 1,40p $S/.e2; rm -f $S/df_idm_tab.txt.new; fail=1 +else + mv $S/df_idm_tab.txt.new $S/df_idm_tab.txt + echo "--- the refusal summary line ---" + grep -m1 -A3 "HEALTH-COVERAGE REFUSALS" $S/df_idm_tab.txt + echo "--- rows whose mean MOVED because partial cells are no longer averaged in ---" + grep -c "REFUSED for partial health" $S/df_idm_tab.txt || true + grep -m6 "REFUSED for partial health" $S/df_idm_tab.txt || echo "(none)" + echo "--- header + first data rows ---" + sed -n 1,6p $S/df_idm_tab.txt + echo "--- UNPARSED cells (stderr) ---" + grep -c UNPARSED $S/.e2 || true +fi + +rm -f $S/.e $S/.e2 +echo; echo "[nb51_dfrebuild] fail=$fail $(date -u)" +exit $fail diff --git a/rsm_rise/scripts/rr_cpu_nb51_freshdiff.sh b/rsm_rise/scripts/rr_cpu_nb51_freshdiff.sh new file mode 100644 index 0000000000000000000000000000000000000000..2e813f2039ccfa39d3e18560d03427646d896306 --- /dev/null +++ b/rsm_rise/scripts/rr_cpu_nb51_freshdiff.sh @@ -0,0 +1,47 @@ +#!/usr/bin/env bash +# gen_q#274 run 51-main -- FRESH vs QUARANTINED for the four cfg(b) cells re-run by LSF 1907326. +# The quarantined cells published health over episodes [k:] beside a score over [0:] and, under +# FINDING AJ/AK, their resumed tail flew MPPI noise a fresh run will not reproduce. So the claim +# being tested is "that number was not reproducible", and the size of the move IS the evidence. +# Every field read from status/nb/td_quarantine_run49.json and from the cells themselves. +set -uo pipefail +R=/proj/dmfexp/zwhong/rsm_rise +cd $R +$R/venv_rsm/bin/python - <<'PYEOF' +import json, os +R="/proj/dmfexp/zwhong/rsm_rise" +q=json.load(open(f"{R}/status/nb/td_quarantine_run49.json")) +print("quarantine manifest:", q["when"], f"{len(q['cells'])} cells") +print() +print(" %-52s %5s %7s %7s %7s %-28s" % ("cell","k/n","quar","fresh","delta","health coverage quar->fresh")) +moved=0 +for c in q["cells"]: + orig=c["orig_path"]; name=os.path.basename(orig) + qp=[m for m in c["moved"] if m.endswith(".json") and not m.endswith(".diag.json")][0] + old=json.load(open(f"{R}/{qp}")) + try: + new=json.load(open(f"{R}/{orig}")) + except Exception as e: + print(" %-52s FRESH CELL MISSING (%s)" % (name[:52], type(e).__name__)); continue + so,sn=old.get("success_rate"),new.get("success_rate") + # fresh coverage, from the fresh cell's own diag, via the shared invariant + import sys; sys.path.insert(0,f"{R}/scripts/nb") + from resume_cov import resume_coverage + dp=f"{R}/{orig}"[:-5]+".diag.json" + diag=json.load(open(dp)) if os.path.exists(dp) else {} + rc=resume_coverage(new,diag) + cov = "n/a" if rc is None else "%s %.0f%%"%(rc["verdict"],100*(rc["coverage"] or 0)) + d = "--" if (so is None or sn is None) else "%+.3f"%(sn-so) + if so is not None and sn is not None and abs(sn-so)>1e-12: moved+=1 + print(" %-52s %2d/%-2d %7s %7s %7s %.0f%% -> %s" + % (name[:52], c["resumed_from"], c["n_ep"], + "%.3f"%so if so is not None else "--", "%.3f"%sn if sn is not None else "--", d, + 100*c["frac_of_full"], cov)) + print(" plans quar %d of %d implied; fresh resumed_from=%s" + % (c["plans"], c["expected_all"], new.get("resumed_from_episode"))) +print() +print(f"cells whose score MOVED on a fresh run: {moved} of {len(q['cells'])}") +print("A cell that did NOT move is not thereby vindicated: the quarantine reason was that its health") +print("did not cover its score and its tail was not reproducible, and both are true regardless of") +print("whether the fresh score happens to land on the same value. All four are now FULL-coverage.") +PYEOF diff --git a/rsm_rise/scripts/rr_cpu_nb51_rebuild.sh b/rsm_rise/scripts/rr_cpu_nb51_rebuild.sh new file mode 100644 index 0000000000000000000000000000000000000000..308f435bcb3a123775937109d49448681319fbc5 --- /dev/null +++ b/rsm_rise/scripts/rr_cpu_nb51_rebuild.sh @@ -0,0 +1,72 @@ +#!/usr/bin/env bash +# gen_q#274 run 51-main -- rebuild every builder this run touched, each PUBLISH-OR-REFUSE. +# 1. td_ctl_pairs.py eval-seed axis + horizon read off the cell name (regression-gated already) +# 2. td_table.py resume_coverage() now IMPORTED from scripts/nb/resume_cov.py. Gated +# BYTE-FOR-BYTE against its pre-refactor text: a pure refactor must not move +# a single character of the published table. +# 3. df_table.py the health-coverage refusal wired in for the first time (run 50 item (e)) +# 4. td_dynrange.py / td_dwm_rho_report.py stop RETYPING td_ctl_pairs' numbers into prose +set -uo pipefail +R=/proj/dmfexp/zwhong/rsm_rise +PY=$R/venv_rsm/bin/python +cd $R +S=status/nb +echo "[nb51_rebuild] $(date -u) host=$(hostname)" +fail=0 + +echo; echo "=== 1. td_ctl_pairs (seed axis, labelling fix) ===" +cp $S/td_ctl_pairs.txt $S/td_ctl_pairs.txt.pre51b 2>/dev/null +$PY scripts/nb/td_ctl_pairs.py > /dev/null 2>$S/.e1; rc=$? +echo "rc=$rc"; [ "$rc" != 0 ] && { cat $S/.e1; cp $S/td_ctl_pairs.txt.pre51b $S/td_ctl_pairs.txt; fail=1; } +sed -n '/INDEPENDENT-STATES ROW/,/^$/p' $S/td_ctl_pairs.txt + +echo; echo "=== 2. td_table BYTE-FOR-BYTE GATE (pure refactor: shared resume_cov) ===" +cp $S/td_table.txt $S/td_table.txt.pre51 2>/dev/null +$PY scripts/nb/td_table.py.bak.20260925_run51main_sharedcov > /dev/null 2>$S/.e2a; rca=$? +cp $S/td_table.txt $S/td_table_PREREFACTOR.txt 2>/dev/null +$PY scripts/nb/td_table.py > /dev/null 2>$S/.e2b; rcb=$? +echo "old rc=$rca new rc=$rcb" +if [ "$rca" != 0 ] || [ "$rcb" != 0 ]; then + echo "A BUILDER FAILED"; sed -n 1,30p $S/.e2a; sed -n 1,30p $S/.e2b + cp $S/td_table.txt.pre51 $S/td_table.txt 2>/dev/null; fail=1 +elif diff -q $S/td_table_PREREFACTOR.txt $S/td_table.txt >/dev/null; then + echo "GATE PASS -- td_table.txt is BYTE-IDENTICAL pre- and post-refactor ($(wc -l < $S/td_table.txt) lines)." +else + echo "GATE FAIL -- the refactor MOVED the published table. Restoring and refusing." + diff $S/td_table_PREREFACTOR.txt $S/td_table.txt | head -40 + cp $S/td_table.txt.pre51 $S/td_table.txt 2>/dev/null; fail=1 +fi + +echo; echo "=== 3. df_table with the health-coverage refusal ===" +cp $S/df_table.txt $S/df_table.txt.pre51 2>/dev/null +$PY scripts/nb/df_table.py > /dev/null 2>$S/.e3; rc=$? +echo "rc=$rc" +if [ "$rc" != 0 ]; then + sed -n 1,40p $S/.e3; cp $S/df_table.txt.pre51 $S/df_table.txt 2>/dev/null; fail=1 +else + n=$(grep -c "HEALTH-PARTIAL" $S/df_table.txt || true) + m=$(grep -c "HEALTH COVERAGE NOT COMPUTABLE" $S/df_table.txt || true) + echo "df_table.txt now carries $n HEALTH-PARTIAL refusal block(s) and $m NOT-COMPUTABLE block(s)." + echo "--- the banner must still be there (the DF repro gate FAILED) ---" + grep -m3 -n -i "REPRODUCTION\|UNREPORTABLE\|NOT REPORTABLE" $S/df_table.txt | head -5 + echo "--- first refusal in context ---" + grep -m1 -B3 -A6 "HEALTH-PARTIAL" $S/df_table.txt || echo "(none)" +fi + +echo; echo "=== 4. the two prose consumers now READ td_ctl_pairs.json ===" +for b in td_dynrange td_dwm_rho_report; do + cp $S/$b.txt $S/$b.txt.pre51 2>/dev/null + $PY scripts/nb/$b.py > /dev/null 2>$S/.e4; rc=$? + echo "$b rc=$rc" + if [ "$rc" != 0 ]; then sed -n 1,30p $S/.e4; cp $S/$b.txt.pre51 $S/$b.txt 2>/dev/null; fail=1; fi +done +echo "--- stale literals must be GONE from both (8 PAIRED / 10\/400 / 0.4531) ---" +for b in td_dynrange td_dwm_rho_report; do + echo -n " $b.txt: " + if grep -qE "the 8 PAIRED|10/400|p = 0\.4531" $S/$b.txt; then echo "STALE LITERAL STILL PRESENT"; fail=1; else echo "clean"; fi + grep -m1 -A6 "td_ctl_pairs" $S/$b.txt | head -8 +done + +rm -f $S/.e1 $S/.e2a $S/.e2b $S/.e3 $S/.e4 +echo; echo "[nb51_rebuild] fail=$fail $(date -u)" +exit $fail diff --git a/rsm_rise/scripts/rr_cpu_nb51_tdbland.sh b/rsm_rise/scripts/rr_cpu_nb51_tdbland.sh new file mode 100644 index 0000000000000000000000000000000000000000..6fa8051ae7b0b523628ac3f0e068d351ef7bd0be --- /dev/null +++ b/rsm_rise/scripts/rr_cpu_nb51_tdbland.sh @@ -0,0 +1,62 @@ +#!/usr/bin/env bash +# gen_q#274 run 51-main -- the four quarantined cfg(b) cells were re-run FRESH by LSF 1907326 and all +# four report CELL LANDED AND HEALTH-COMPLETE. Rebuild td_table and check three things: +# 1. the cfg(b) column is back to its full row count (it was 15 where it should be 19), +# 2. NO HEALTH-PARTIAL block survives for a cfg(b) row, +# 3. the fresh score vs the QUARANTINED partial-health score, side by side -- the point of the +# re-run is that the old number was not reproducible, so the size of the move is the evidence. +set -uo pipefail +R=/proj/dmfexp/zwhong/rsm_rise +PY=$R/venv_rsm/bin/python +cd $R +S=status/nb +echo "[nb51_tdbland] $(date -u) host=$(hostname)" +cp $S/td_table.txt $S/td_table.txt.pre51d 2>/dev/null +$PY scripts/nb/td_table.py > /dev/null 2>$S/.e; rc=$? +echo "td_table rc=$rc" +if [ "$rc" != 0 ]; then sed -n 1,40p $S/.e; cp $S/td_table.txt.pre51d $S/td_table.txt; exit 1; fi + +echo; echo "=== cfg(b) row count and surviving refusals ===" +$PY - <<'PYEOF' +import json +d=json.load(open('/proj/dmfexp/zwhong/rsm_rise/status/nb/td_table.json')) +nb=na=part=0 +for t,v in d.items(): + for c in v.get('cells',[]): + if c['cfg']=='b': + nb+=1 + r=c.get('resume') + if r is not None and r['verdict']!='FULL': + part+=1 + print(" STILL PARTIAL:",c['task'] if 'task' in c else t,c['cell'][:64],r['verdict'],r['resumed_from']) + elif c['cfg']=='a': + na+=1 +print(f"cfg(b) rows = {nb} cfg(a) rows = {na} cfg(b) rows still HEALTH-PARTIAL = {part}") +PYEOF +echo "HEALTH-PARTIAL blocks anywhere in td_table.txt: $(grep -c 'HEALTH-PARTIAL' $S/td_table.txt || true)" + +echo; echo "=== FRESH vs QUARANTINED (the same cell, re-run after the AK fix) ===" +$PY - <<'PYEOF' +import json, glob, os +R="/proj/dmfexp/zwhong/rsm_rise" +q=json.load(open(f"{R}/status/nb/td_quarantine_run49.json")) +rows = q if isinstance(q,list) else (q.get("cells") or q.get("moved") or []) +print(" %-58s %8s %8s %8s" % ("cell","quar","fresh","delta")) +for r in rows: + nm = r.get("cell") or os.path.basename(r.get("src",""))[:-5] + qp = r.get("dst") or r.get("quarantined") + task = r.get("task") + fp = f"{R}/runs/{task}/eval_onactor/td274/{nm}.json" + try: + old=json.load(open(qp if qp and os.path.isabs(qp) else f"{R}/{qp}"))["success_rate"] + except Exception as e: + old=None + try: + new=json.load(open(fp))["success_rate"] + except Exception: + new=None + ds = "--" if (old is None or new is None) else "%+.3f"%(new-old) + print(" %-58s %8s %8s %8s" % (nm[:58], + "--" if old is None else "%.3f"%old, "--" if new is None else "%.3f"%new, ds)) +PYEOF +echo; echo "[nb51_tdbland] DONE $(date -u)" diff --git a/rsm_rise/scripts/rr_cpu_nb52_ctlseed.sh b/rsm_rise/scripts/rr_cpu_nb52_ctlseed.sh new file mode 100644 index 0000000000000000000000000000000000000000..dc37d61cac65c330dfdcbb7b4836d032e6271f47 --- /dev/null +++ b/rsm_rise/scripts/rr_cpu_nb52_ctlseed.sh @@ -0,0 +1,98 @@ +#!/usr/bin/env bash +# gen_q#274 run 52-main -- the eval-seed axis on the RANDOM-OF-128 control, plus the build ORDER. +# +# TWO DEFECTS, both surfaced by the very first es1 cell landing: +# (1) td_table.py indexed the controls on (gamma, scale) with NO eval seed. The es1 arm was +# therefore printed beside the es0 control under the words "same draw, uniform pick", which is +# false -- a different eval seed is different initial states AND a different candidate draw. +# Worse, when the es1/es2 controls land they would have REPLACED the es0 control under the +# already-published es0 arms without a word. +# (2) BUILD ORDER: td_table.py reads status/nb/nb274_health.json for the scorer-health columns. +# run 52-main's first job rebuilt td_table BEFORE nb274_health, so the newly restored es1 cell +# printed "NO-HEALTH (not quotable)" purely because the health file predated it. A health +# refusal that is really a stale-input artefact is the worst kind: it looks like a measurement. +# +# GATE: every control pairing that existed before this change must be UNCHANGED. The only legal +# differences are the new es1 row and the seed annotation on the control lines. +set -uo pipefail +R=/proj/dmfexp/zwhong/rsm_rise +PY=$R/venv_rsm/bin/python +cd $R +S=status/nb +echo "[nb52_ctlseed] $(date -u) host=$(hostname)" +cp $S/td_table.txt $S/td_table.txt.pre52b +fail=0 + +echo; echo "=== 1. nb274_health FIRST (td_table depends on it) ===" +$PY scripts/nb/nb274_health.py > $S/.oh 2>$S/.eh; rc=$?; echo " nb274_health rc=$rc" +[ "$rc" != 0 ] && { sed -n 1,20p $S/.eh; fail=1; } + +echo; echo "=== 2. td_table with the seed-keyed control index ===" +$PY scripts/nb/td_table.py > $S/.ot 2>$S/.et; rc=$?; echo " td_table rc=$rc" +if [ "$rc" != 0 ]; then sed -n 1,25p $S/.et; cp $S/td_table.txt.pre52b $S/td_table.txt; fail=1; fi + +if [ "$fail" = 0 ]; then +echo; echo "=== 3. GATE: no PRE-EXISTING pairing may have changed partner ===" +$PY - <<'PYX' +import re, sys +R = "/proj/dmfexp/zwhong/rsm_rise/status/nb" +def pairs(path): + """map arm cell -> the control cell printed under it (or a refusal token).""" + out, arm = {}, None + for ln in open(path): + m = re.search(r"(E1-TDMPC2-\S*tdq-128-(?:argmax|random)\S*)\s*$", ln) + if m and "CONTROL" not in ln: + arm = m.group(1); continue + if arm and "RANDOM-OF-128 CONTROL" in ln: + c = re.search(r"(E1-TDMPC2-\S+)", ln) + out[arm] = c.group(1) if c else "NOT-MEASURED" + arm = None + return out +def es(name): + m = re.search(r"-es(\d+)-", name or "") + return m.group(1) if m else None + +old, new = pairs(f"{R}/td_table.txt.pre52b"), pairs(f"{R}/td_table.txt") +changed = {k: (old[k], new.get(k)) for k in old if new.get(k) != old[k]} +added = {k: v for k, v in new.items() if k not in old} +print(f" arms with a control line: before={len(old)} after={len(new)}") +print(f" pairings that changed partner: {len(changed)}") + +# EXACTLY ONE legal change, stated as a rule rather than as a loosened threshold: a pairing may be +# WITHDRAWN when its old partner was at a DIFFERENT eval seed from the arm -- that pairing was +# false, and withdrawing it is the entire point of this patch. Anything else -- a same-seed +# pairing that moved, or a withdrawal replaced by another cross-seed partner -- is a violation. +legal, viol = [], [] +for k, (a, b) in changed.items(): + if es(a) is not None and es(k) is not None and es(a) != es(k) and ( + b == "NOT-MEASURED" or es(b) == es(k)): + legal.append((k, a, b)) + else: + viol.append((k, a, b)) +for k, a, b in legal: + print(f" LEGAL (cross-seed pairing withdrawn) {k}") + print(f" arm is es{es(k)}; old partner was es{es(a)} -- not the same states, not the") + print(f" same candidate draw, so it was never the paired control it was printed as") + print(f" now {b}") +for k, a, b in viol: + print(f" !! VIOLATION {k}\n was {a}\n now {b}") +print(f" newly paired arms: {len(added)}") +for k, v in added.items(): + print(f" {k} -> {v}") +sys.exit(1 if viol else 0) +PYX +rc=$?; echo " gate rc=$rc"; [ "$rc" != 0 ] && { echo " GATE FAIL -- restoring"; cp $S/td_table.txt.pre52b $S/td_table.txt; fail=1; } +fi + +echo; echo "=== 4. THE es1 ROW AS IT NOW PRINTS ===" +grep -A3 "tdq-128-argmax-TD274a-es1" $S/td_table.txt | head -8 +echo +echo " control lines that assert a SAME-eval-seed pairing (each one must really be same-seed):" +grep -c "same draw, uniform pick, SAME eval" $S/td_table.txt +echo " control lines still using the OLD unqualified 'same draw' wording (must be 0):" +grep -c "same draw, uniform pick): " $S/td_table.txt +echo " NO-HEALTH rows remaining:" +grep -c "NO-HEALTH" $S/td_table.txt + +echo; echo "[nb52_ctlseed] DONE fail=$fail $(date -u)" +exit $fail diff --git a/rsm_rise/scripts/rr_cpu_nb52_gate.sh b/rsm_rise/scripts/rr_cpu_nb52_gate.sh new file mode 100644 index 0000000000000000000000000000000000000000..24f1aa3fbbf7e5e57fd15966b09e37f439a8635f --- /dev/null +++ b/rsm_rise/scripts/rr_cpu_nb52_gate.sh @@ -0,0 +1,67 @@ +#!/usr/bin/env bash +# gen_q#274 run 52-main -- the health gate was asking cfg(a) cells the WRONG QUESTION, and it is the +# one consumer of the invariant that MOVES FILES. Sequence, publish-or-refuse throughout: +# 1. regression sweep: OLD verdict vs NEW verdict on every #274 cell. Conservative property -- +# nothing may go PASS -> FAIL; the only legal move is NOT-COMPUTABLE -> measured. If the +# property is violated the patch is reverted and nothing downstream runs. +# 2. un-quarantine, gated on the corrected verdict AND on the live name being free. +# 3. rebuild td_table / td_ctl_pairs / nb274_health so the cfg(a) rows stop printing +# "health coverage: NOT COMPUTABLE" when it is, in fact, computable and 100%. +set -uo pipefail +R=/proj/dmfexp/zwhong/rsm_rise +PY=$R/venv_rsm/bin/python +cd $R +S=status/nb +echo "[nb52_gate] $(date -u) host=$(hostname)" +fail=0 + +echo; echo "=== 1. GATE REGRESSION SWEEP (the conservative property) ===" +$PY scripts/nb/gate_sweep.py; rc=$? +echo "sweep rc=$rc" +if [ "$rc" = 3 ]; then + echo "[nb52_gate] the sweep could not RUN (rc=3). That is a statement about the sweep, not about" + echo "[nb52_gate] the patch, so the patch is LEFT IN PLACE and nothing downstream runs. Fix the" + echo "[nb52_gate] sweep and re-submit; do not revert a patch on the strength of a broken check." + exit 3 +fi +if [ "$rc" != 0 ]; then + echo "[nb52_gate] PROPERTY VIOLATED -- REVERTING the patch and refusing to touch anything else." + cp scripts/nb/resume_cov.py.bak.20260925_run52main_scorecells scripts/nb/resume_cov.py + cp scripts/nb/assert_health_covers.py.bak.20260925_run52main_scorecells scripts/nb/assert_health_covers.py + echo "[nb52_gate] REVERTED. The live packs go back to the old gate; the false quarantine stands." + exit 1 +fi + +echo; echo "=== 2. UN-QUARANTINE (corrected verdict FULL + live name free) ===" +$PY scripts/nb/gate_unquarantine.py; rc=$? +echo "unquarantine rc=$rc"; [ "$rc" != 0 ] && fail=1 + +echo; echo "=== 3. REBUILDS ===" +for b in td_table td_ctl_pairs nb274_health; do + cp $S/$b.txt $S/$b.txt.pre52 2>/dev/null + cp $S/$b.json $S/$b.json.pre52 2>/dev/null # run 53: the score check needs the BEFORE structure + $PY scripts/nb/$b.py > $S/.o_$b 2>$S/.e_$b; rc=$? + echo " $b rc=$rc" + if [ "$rc" != 0 ]; then + sed -n 1,25p $S/.e_$b; cp $S/$b.txt.pre52 $S/$b.txt 2>/dev/null; fail=1 + fi +done + +echo; echo "=== 4. WHAT MOVED IN td_table ===" +echo " cfg(a) rows printing NOT COMPUTABLE: before=$(grep -c 'NOT COMPUTABLE' $S/td_table.txt.pre52 2>/dev/null) after=$(grep -c 'NOT COMPUTABLE' $S/td_table.txt)" +echo " HEALTH-PARTIAL blocks: before=$(grep -c 'HEALTH-PARTIAL' $S/td_table.txt.pre52 2>/dev/null) after=$(grep -c 'HEALTH-PARTIAL' $S/td_table.txt)" +echo " td_table.txt lines: before=$(wc -l < $S/td_table.txt.pre52 2>/dev/null) after=$(wc -l < $S/td_table.txt)" +echo " SUCCESS RATES UNCHANGED CHECK (no score may move -- this run touched only coverage):" +# run 53-main: the block that used to sit here printed "cells in the rebuilt table: 0" and exited 0, +# having compared nothing (no BEFORE snapshot) with an accessor that could not read td_table.json's +# per-task nesting anyway. A vacuous check that reads as a pass is worse than no check. +$PY scripts/nb/td_scores_unmoved.py $S/td_table.json.pre52 $S/td_table.json +src=$? +case $src in + 0) ;; + 1) echo " -> FAILING THE JOB: a score moved, or a cell left the table."; fail=1 ;; + *) echo " -> FAILING THE JOB: the score check could not run (rc=$src). Not treated as a pass."; fail=1 ;; +esac + +echo; echo "[nb52_gate] DONE fail=$fail $(date -u)" +exit $fail diff --git a/rsm_rise/scripts/rr_cpu_nb53_egl.sh b/rsm_rise/scripts/rr_cpu_nb53_egl.sh new file mode 100644 index 0000000000000000000000000000000000000000..e68bd00a9cdcc6834a4c19cb7fc39dafce3d2c20 --- /dev/null +++ b/rsm_rise/scripts/rr_cpu_nb53_egl.sh @@ -0,0 +1,12 @@ +#!/usr/bin/env bash +# gen_q#274 run 53-main -- rebuild the EGL census with the exhaustive taxonomy. +# PUBLISH-OR-REFUSE: the previous status/nb/egl_census.txt is kept as a .bak, and if the rebuild +# fails the old file stays -- but the old file's CONCLUSION is known-unsupported (run 53 sec 1), so +# a failure here is reported as a failure and not as "the old reading stands". +set -uo pipefail +cd /proj/dmfexp/zwhong/rsm_rise || exit 9 +[ -f status/nb/egl_census.txt ] && cp status/nb/egl_census.txt status/nb/egl_census.txt.bak.20260925_run52_detector +python3 scripts/nb/egl_census.py +rc=$? +echo "[nb53_egl] egl_census.py rc=$rc" +exit $rc diff --git a/rsm_rise/scripts/rr_cpu_nb53_scorechk.sh b/rsm_rise/scripts/rr_cpu_nb53_scorechk.sh new file mode 100644 index 0000000000000000000000000000000000000000..76b1a0f780189984541bd996ad2bf37e79990104 --- /dev/null +++ b/rsm_rise/scripts/rr_cpu_nb53_scorechk.sh @@ -0,0 +1,55 @@ +#!/usr/bin/env bash +# gen_q#274 run 53-main -- prove scripts/nb/td_scores_unmoved.py DETECTS, not just that it passes. +# The check it replaces also "passed"; that is exactly why passing is not evidence. Four cases, +# each with the expected rc written down BEFORE the run, and the job fails if any rc differs. +set -uo pipefail +cd /proj/dmfexp/zwhong/rsm_rise || exit 9 +PY=venv_rsm/bin/python +[ -x "$PY" ] || PY=python3 +T=$(mktemp -d); trap 'rm -rf $T' EXIT +S=status/nb +fail=0 +chk () { #