rsm_rise code snapshot (HF_PUSH_ALL) (part 8)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- gen_q_rsm/rsm_rise/pipeline/scripts/launch_e1_grid.pyAdded+521
- gen_q_rsm/rsm_rise/pipeline/scripts/launch_flagship_topup.pyAdded+299
- gen_q_rsm/rsm_rise/pipeline/scripts/launch_hopfam_on_actor.pyAdded+67
- gen_q_rsm/rsm_rise/pipeline/scripts/launch_ifql.pyAdded+238
- gen_q_rsm/rsm_rise/pipeline/scripts/launch_lewm_on_actor.pyAdded+89
- gen_q_rsm/rsm_rise/pipeline/scripts/launch_problog_on_actor.pyAdded+171
- gen_q_rsm/rsm_rise/pipeline/scripts/launch_readout_on_actor.pyAdded+76
- gen_q_rsm/rsm_rise/pipeline/scripts/launch_rsm_on_actor.pyAdded+186
- gen_q_rsm/rsm_rise/pipeline/scripts/launch_tdflow_on_actor.pyAdded+168
- gen_q_rsm/rsm_rise/pipeline/scripts/launch_temp_on_actor.pyAdded+94
- gen_q_rsm/rsm_rise/pipeline/scripts/lewm_gate.shAdded+54
- gen_q_rsm/rsm_rise/pipeline/scripts/lewm_smoke.shAdded+47
- gen_q_rsm/rsm_rise/pipeline/scripts/master_table.pyAdded+1189
- gen_q_rsm/rsm_rise/pipeline/scripts/mc_target_spread.pyAdded+69
- gen_q_rsm/rsm_rise/pipeline/scripts/parity_sweep.pyAdded+106
- gen_q_rsm/rsm_rise/pipeline/scripts/problog_table.pyAdded+195
- gen_q_rsm/rsm_rise/pipeline/scripts/problog_watcher.shAdded+34
- gen_q_rsm/rsm_rise/pipeline/scripts/real/build_2x2_table.pyAdded+45
- gen_q_rsm/rsm_rise/pipeline/scripts/real/build_decisive_tables.pyAdded+244
- gen_q_rsm/rsm_rise/pipeline/scripts/real/build_real_report_tables.pyAdded+270
- gen_q_rsm/rsm_rise/pipeline/scripts/real/build_reward_study2.pyAdded+199
- gen_q_rsm/rsm_rise/pipeline/scripts/real/build_reward_tables.pyAdded+276
- gen_q_rsm/rsm_rise/pipeline/scripts/real/build_successor_tables.pyAdded+232
- gen_q_rsm/rsm_rise/pipeline/scripts/real/cam_dlt.pyAdded+307
- gen_q_rsm/rsm_rise/pipeline/scripts/real/cam_dump_frames.pyAdded+77
- gen_q_rsm/rsm_rise/pipeline/scripts/real/decisive_reward.pyAdded+197
- gen_q_rsm/rsm_rise/pipeline/scripts/real/destiny_route_split.pyAdded+65
- gen_q_rsm/rsm_rise/pipeline/scripts/real/destiny_test.pyAdded+324
- gen_q_rsm/rsm_rise/pipeline/scripts/real/dirdump_screen.shAdded+25
- gen_q_rsm/rsm_rise/pipeline/scripts/real/edge_AD_read.pyAdded+337
- gen_q_rsm/rsm_rise/pipeline/scripts/real/edge_AH_read.pyAdded+256
- gen_q_rsm/rsm_rise/pipeline/scripts/real/edge_AJ_read.pyAdded+222
- gen_q_rsm/rsm_rise/pipeline/scripts/real/edge_arrival_check.pyAdded+88
- gen_q_rsm/rsm_rise/pipeline/scripts/real/edge_candidate_gate.pyAdded+79
- gen_q_rsm/rsm_rise/pipeline/scripts/real/edge_ceiling2.pyAdded+128
- gen_q_rsm/rsm_rise/pipeline/scripts/real/edge_ceiling_route.pyAdded+118
- gen_q_rsm/rsm_rise/pipeline/scripts/real/edge_dirfig.pyAdded+204
- gen_q_rsm/rsm_rise/pipeline/scripts/real/edge_field.pyAdded+283
- gen_q_rsm/rsm_rise/pipeline/scripts/real/edge_field_validate.pyAdded+173
- gen_q_rsm/rsm_rise/pipeline/scripts/real/edge_flip_audit.pyAdded+306
- gen_q_rsm/rsm_rise/pipeline/scripts/real/edge_goalbound_auc.pyAdded+246
- gen_q_rsm/rsm_rise/pipeline/scripts/real/edge_interaction_AA.pyAdded+98
- gen_q_rsm/rsm_rise/pipeline/scripts/real/edge_matched_AA.pyAdded+123
- gen_q_rsm/rsm_rise/pipeline/scripts/real/edge_matched_AB.pyAdded+183
- gen_q_rsm/rsm_rise/pipeline/scripts/real/edge_matched_AC.pyAdded+135
- gen_q_rsm/rsm_rise/pipeline/scripts/real/edge_matched_U.pyAdded+93
- gen_q_rsm/rsm_rise/pipeline/scripts/real/edge_matched_V.pyAdded+110
- gen_q_rsm/rsm_rise/pipeline/scripts/real/edge_matched_W.pyAdded+132
- gen_q_rsm/rsm_rise/pipeline/scripts/real/edge_matched_X.pyAdded+136
- gen_q_rsm/rsm_rise/pipeline/scripts/real/edge_matched_Y.pyAdded+141
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521#!/usr/bin/env python3"""Launch the rsm_rise E1 evaluation grid (best-of-N planning over pi_beta with an RSM scorer) on LSF.
One cell = one eval of one pi_beta seed checkpoint with one planner configuration; its result isruns/<task>/eval/<cell>.json (scripts/eval_cell.sh -> scripts/eval.py, exp.results_json). Cells whose JSONalready exists are skipped (resubmit-missing pattern); `--pack K` runs K cells sequentially in one GPU job.
Cell names E1-<model>-R<beta>-<L>[-rec]-N<n>-<rule>-s<seed> e.g. E1-M-R0.95-2-N64-argmax-s0 E1-<model>-R<beta>-<L>-N<n>-<rule>-s<seed> with rule in {argmax, softmax0.05, softmax0.2, topk8, random, permuted}; controls: BC-s<seed> (plan_n=1), S3H4-N64-s<seed> (IQL critic of an S0A ckpt).
Usage (see --help): launch_e1_grid.py --task square_expert_play --env robomimic_square_coverage \ --model M=runs/square_expert_play/rsm/M/ckpt_best.pt:mlp \ --model L40=runs/square_expert_play/rsm/L40/ckpt_best.pt:mlp \ --model DWM=runs/square_expert_play/rsm/DWM/ckpt_best.pt:dwm \ --hop runs/square_expert_play/hop/gauss/policy_r1.pt \ --policy s0=runs/square_expert_play/policy/S0B_seed0 --policy s1=... --policy s2=... \ --s0a s0=runs/square_expert_play/policy/S0A_seed0 ... \ --grid a b c controls --pack 4 --queue preemptable [--dry-run] [--print-only]
--grid a : full factorial on the first --model (16 read-outs x N{8,16,64,128,256} x rules{argmax,softmax0.05, softmax0.2,topk8} x seeds) --grid b : models x read-outs at N=--n-primary (128) argmax (all --model entries after the first; --b-all-models: all) --grid c : recursive read-outs (0.90,0.95,0.98)x{2,3} at N=--n-primary argmax, all mlp models (dwm has no recursive) --grid d : N x rule at --best "<model>:<beta>:<L>" (repeatable), the E1 winner of L40/DWM --grid controls : BC (plan_n=1), S3H2 random, S3H3 permuted, S3H4 IQL critic (needs --s0a), all at N=--n-primary; --mc <blob> adds S3H5 (MC critic) --cells : explicit cell specs "model,beta,L,mode,n,rule,seed" (comma-separated, repeatable) for ad-hoc runs"""from __future__ import annotations
import argparseimport itertoolsimport jsonimport osimport reimport shleximport subprocessimport sysfrom pathlib import Path
ROOT = Path("/proj/dmfexp/zwhong/rsm_rise")BETAS = (0.90, 0.95, 0.98, 0.99)DEPTHS = (1, 2, 3, 4)REC_BETAS = (0.90, 0.95, 0.98)REC_DEPTHS = (2, 3)N_LIST = (8, 16, 64, 128, 256) # 128 = RISE's released eval setting (critic argmax over 128 samples); 64 = paperRULES = ("argmax", "softmax0.05", "softmax0.2", "topk8")ENV_OF = {"square_expert_play": "robomimic_square_coverage", "mug_expert_suboptimal": "robomimic_mug", "square_expert_suboptimal": "robomimic_square", # orchestrator 15:38: paper-regime square suboptimal (20 expert + 80 suboptimal, no augmentation); # same eval env as the released-file task, its own runs/ tree so the numbers never mix. "square_sub_paper": "robomimic_square", "square_sub_paper2": "robomimic_square", "square_sub_20100": "robomimic_square", # orchestrator 17:16: the released HDF5s hold more demos than Table IV, so every task gets a # <task>_paper sibling subsampled to the Table IV amounts (stream A builds the files). The eval env # is the same as the released-file task it comes from -- only the TRAINING data differs. "threading_expert_play": "robomimic_threading_coverage", "threading_paper": "robomimic_threading_coverage", "mug_paper": "robomimic_mug", "two_piece_expert_suboptimal": "robomimic_three_piece_assembly_top_right", "piecesub_paper": "robomimic_three_piece_assembly_top_right", # FIXED 2026-09-19 05:10 (stream D). This read `_top_right` -- the EXPERT's own quadrant # (p0) -- which is the one thing a COVERAGE eval must not be: the whole point of the play/ # coverage task is that p_test = the whole table while the expert data lives in the top-right. # stream A settled this in status/A_env_stage0.md:500 ("Piece1 x,y in [-0.22,0.22] = whole # table = p_test; expert p0 = top right"), scripts/all_init_region.py agrees, and # launch_stage0_evals.sh:52 always used the stock config -- so the grids disagreed with the # policy evals and every two_piece_expert_play planner cell was measured on p0. The value # below was almost certainly copied from the two_piece_expert_SUBOPTIMAL line above, whose # top-right eval IS correct (the paper evaluates the suboptimal tasks from p0). "two_piece_expert_play": "robomimic_three_piece_assembly", "two_piece_expert_play_tipping": "robomimic_three_piece_assembly_tipped", "piecetip_paper": "robomimic_three_piece_assembly_tipped"}
def _busy_cells(out_dir): """Cells owned by a PEND/RUN LSF job right now.
Since eval.py resumes from `<cell>.json.partial`, two concurrent jobs on the same cell would interleave writes to the same resume state and pool each other's episodes. The grid skips finished cells by JSON, which is not enough for a cell that is merely *running*, so the owning job's script (jobs/<jname>.sh, which carries one `exp.eval_cell=<name>` per packed cell) is consulted as well. --force overrides. """ try: r = subprocess.run(["bjobs", "-o", "stat job_name", "-noheader"], capture_output=True, text=True, timeout=120) except Exception: return set() busy = set() for line in r.stdout.splitlines(): f = line.split() if len(f) < 2 or f[0] not in ("PEND", "RUN", "PSUSP", "USUSP", "SSUSP"): continue sh = Path(out_dir) / "jobs" / f"{f[1]}.sh" if sh.is_file(): txt = sh.read_text() busy.update(re.findall(r"exp\.eval_cell=(\S+)", txt)) _BUSY_ARMS.update(_arm_keys(txt)) return busy
# Semantic keys of the cells inside live jobs, for the different-TAG duplicate warning below._BUSY_ARMS = {}
def _arm_key(line): """What a cell MEASURES, independent of the --tag its name carries.
(policy checkpoint, eval seed, plan_n, rule, backend) is the whole measurement for a control arm: the eval seed fixes the init states and the checkpoint fixes the policy, so two cells agreeing on these replay the same episodes no matter what they are called. """ def g(pat, default=None): m = re.search(pat, line) return m.group(1) if m else default # The policy checkpoint reaches eval_cell.sh as a POSITIONAL argument, not as `ckpt=` -- matching on # `ckpt=` found it only on S3H4 lines (where it doubles as `training.rsm_ckpt`), so three cells of every # four-cell control job were invisible to the duplicate check. Match the path itself. pol = g(r"(/\S*/policy/\S+\.pth)") if pol is None: return None n, rule = g(r"\bplan_n=(\d+)"), g(r"\bplan_rule=(\S+)", "argmax") # Everything else the planner was configured with, so two cells of one (beta, L) grid are never called # duplicates of each other. Collected generically -- a knob added later (plan_rescore_top, # plan_temperature, plan_lcb_quantile, ...) enters the key without touching this function. knobs = frozenset((k, v) for k, v in re.findall(r"\b(?:training\.)?((?:plan|rsm)_[a-z_]+)=(\S+)", line) if k not in ("plan_n", "plan_rule")) # The value function is part of the measurement -- the RISE flagship (rsm_backend=iql) and an RSM cell # on the same policy share (n, rule) but rank with different critics, so the backend and the successor # checkpoint must be in the key or the two get called duplicates of each other. They drop OUT of the key # when nothing is ranked (plan_n=1) or when the rule is `random`, because the scorer is then never built # -- so a `random-of-N` control launched from the M grid and one from the L40 grid ARE duplicates. inert = rule == "random" or n in (None, "1") backend = "-" if inert else g(r"\b(?:plan|rsm)_backend=(\S+)", "rsm") vf = "-" if inert else g(r"\brsm_ckpt=(\S+)", "-") # The IQL critic (the RISE flagship) is a single-step Q over (obs, action): the successor knobs on its # command line (plan_particles, plan_score, plan_beta, ...) are carried by the launcher but never read, # so two flagship cells that differ only there are the same 100 episodes under two tags. return (pol, g(r"\beval_seed=(\d+)"), n, rule, backend, vf, frozenset() if inert or backend == "iql" else knobs)
def _arm_keys(txt): """{arm key: cell name} for every cell in one job script.""" out = {} for line in txt.splitlines(): m = re.search(r"exp\.eval_cell=(\S+)", line) k = _arm_key(line) if m else None if k is not None: out[k] = m.group(1) return out
def _excl_hosts(a): """Hosts whose MuJoCo/EGL renderer SIGABRTs (exit 134, no traceback), to keep out of select[].
The failure is host-correlated, not cell-correlated: as of 17:25 the blacklist holds 36 hosts and one of them (p4-r09-n3) alone ate 22 eval cells. List regenerated by scripts/eval_host_stats.sh --write, which now counts rr_e1_* cells as well as stream A's rr_ev_* policy evals. RR_EXCL_HOSTS overrides the file; --no-excl-hosts turns the mechanism off. """ if getattr(a, "no_excl_hosts", False): return [] env = os.environ.get("RR_EXCL_HOSTS") if env is not None: return env.split() f = ROOT / "status" / "bad_eval_hosts.txt" return f.read_text().split() if f.is_file() else []
def _res(a): sel = " && ".join(f"hname!='{h}'" for h in _excl_hosts(a)) return (f"select[{sel}] " if sel else "") + f"rusage[mem={a.mem}]"
def _abs(p): """eval_cell.sh cd's into code/rise_code before scripts/eval.py runs, so every path override must be absolute.""" return str(Path(p).expanduser().resolve()) if p else p
def rule_overrides(rule): if rule.startswith("softmax"): return {"plan_rule": "softmax", "plan_temp": float(rule[len("softmax"):])} if rule.startswith("topk"): return {"plan_rule": "topk_uniform", "plan_topk": int(rule[len("topk"):])} return {"plan_rule": rule}
def readout_overrides(beta, L, mode): # COIN CHAIN (gen_q#267): in chain mode `L` is not a fold depth, it is the TRUNCATION CAP, and it is # passed through as plan_chain_cap so the cell name and the run can never disagree. The launcher # computes it with rsm_scorer.chain_cap(beta, gamma) -- it is never hard-coded, and a value that is not # the computed cap only ever appears when the cap itself is being swept. plan_depth is meaningless # here and is pinned to 1 so a stale depth cannot leak into the read-out. if mode in ("chain", "chain_rb"): return {"plan_mode": mode, "plan_depth": 1, "plan_beta": float(beta), "plan_chain_cap": int(L)} return {"plan_mode": mode, "plan_depth": int(L), "plan_beta": float(beta)}
def seed_tag(seed): """seed labels may be given as 0/1/2 or s0/s1/s2; cells always end in -s<k>.""" s = str(seed) return s if s.startswith("s") else f"s{s}"
def cell_name(model, beta, L, mode, n, rule, seed, tag=""): """tag (--tag) is inserted before the seed so that otherwise identical read-outs that differ only in an --extra override (particles, plan_score, temperature, ...) land in different JSONs.""" # The chain gets its OWN tag so the loader can never confuse a chain cell with a fold cell of the same # (model, beta, number). Extending the key, not reusing the fold's, is the point (owner 2026-09-22). rec = {"recursive": "-rec", "chain": "-ch", "chain_rb": "-chrb"}.get(mode, "") t = f"-{tag}" if tag else "" return f"E1-{model}-R{beta:.2f}-{L}{rec}-N{n}-{rule}{t}-{seed_tag(seed)}"
class Grid: def __init__(self, a): self.a = a self.models = {} # name -> (path, backend) for m in a.model: name, rest = m.split("=", 1) parts = rest.split(":") self.models[name] = (parts[0], parts[1] if len(parts) > 1 else "mlp") self.policies = {k: _abs(v) for k, v in (p.split("=", 1) for p in a.policy)} # seed label -> S0B ckpt/dir self.s0a = {k: _abs(v) for k, v in (p.split("=", 1) for p in (a.s0a or []))} self.seeds = sorted(self.policies) self.tag = a.tag or "" self.cells = {} # name -> dict(overrides)
def tagged(self, base, seed): """control-cell names: <base>[-<tag>]-s<seed>""" t = f"-{self.tag}" if self.tag else "" return f"{base}{t}-{seed_tag(seed)}"
def add(self, name, overrides, seed, backend_model=None): if name in self.cells: return ov = dict(overrides) ov["policy"] = self.policies[seed] self.cells[name] = ov
def model_ov(self, model): path, backend = self.models[model] ov = {"rsm_backend": backend, "rsm_ckpt": _abs(path), "rsm_feat_stats": str(ROOT / "cache" / self.a.task / "feat_stats.npz")} if self.a.hop: ov["rsm_hop_ckpt"] = _abs(self.a.hop) return ov
def e1(self, model, beta, L, mode, n, rule, seed): ov = {"plan_n": n, **rule_overrides(rule), **readout_overrides(beta, L, mode), **self.model_ov(model)} self.add(cell_name(model, beta, L, mode, n, rule, seed, self.tag), ov, seed)
def grid_a(self): model = list(self.models)[0] for beta, L, n, rule, seed in itertools.product(BETAS, DEPTHS, N_LIST, RULES, self.seeds): self.e1(model, beta, L, "d1" if L == 1 else "fold", n, rule, seed)
def grid_b(self): models = list(self.models)[1:] if not self.a.b_all_models else list(self.models) for model in models: for beta, L, seed in itertools.product(BETAS, DEPTHS, self.seeds): self.e1(model, beta, L, "d1" if L == 1 else "fold", self.a.n_primary, "argmax", seed)
def grid_c(self): for model, (_, backend) in self.models.items(): if backend == "dwm": continue for beta, L, seed in itertools.product(REC_BETAS, REC_DEPTHS, self.seeds): self.e1(model, beta, L, "recursive", self.a.n_primary, "argmax", seed)
def grid_d(self): for best in self.a.best or []: model, beta, L = best.split(":") beta, L = float(beta), int(L) for n, rule, seed in itertools.product(N_LIST, RULES, self.seeds): if n == self.a.n_primary and rule == "argmax": continue # already in b self.e1(model, beta, L, "d1" if L == 1 else "fold", n, rule, seed)
def controls(self): model = list(self.models)[0] beta, L = self.a.primary_beta, self.a.primary_depth mode = "d1" if L == 1 else "fold" want = self.a.controls_subset for seed in self.seeds: if "bc" in want: self.add(self.tagged("BC", seed), {"plan_n": 1}, seed) if "random" in want: self.e1(model, beta, L, mode, self.a.n_primary, "random", seed) # S3H2 if "permuted" in want: self.e1(model, beta, L, mode, self.a.n_primary, "permuted", seed) # S3H3 if seed in self.s0a and "s3h4" in want: # S3H4: the paper's IDQL best-of-64 self.add(self.tagged(f"S3H4-N{self.a.n_primary}", seed), {"plan_n": self.a.n_primary, "plan_rule": "argmax", "rsm_backend": "iql", "rsm_ckpt": self.s0a[seed]}, seed)
def s3h5(self): if not self.a.mc: return for seed in self.seeds: self.add(self.tagged(f"S3H5-N{self.a.n_primary}", seed), {"plan_n": self.a.n_primary, "plan_rule": "argmax", "rsm_backend": "mc", "rsm_ckpt": _abs(self.a.mc), "rsm_feat_stats": str(ROOT / "cache" / self.a.task / "feat_stats.npz")}, seed)
def explicit(self): for spec in self.a.cells or []: model, beta, L, mode, n, rule, seed = spec.split(",") self.e1(model, float(beta), int(L), mode, int(n), rule, seed)
def hydra_overrides(ov): out = [] for k, v in ov.items(): if k == "policy": continue if isinstance(v, bool): v = str(v) out.append(f"training.{k}={v}") return out
# INERT-KNOB GUARD (2026-09-21). A whole 54-cell temperature sweep was spent on `training.plan_temp` -- the# softmax-RULE temperature on Qbar, read only when plan_rule=softmax -- when the sigmoid read-out T that# c_k = sigma(R(z_k)/T) uses is `training.plan_temperature`. Every cell ran at the checkpoint default and# was a duplicate of the arm it was meant to vary; it was caught only because two settings produced# bit-identical tie counts. Hydra accepts any `training.*` key the config defines, so the config cannot# reject it. This guard refuses, before a single job is submitted, (a) a `training.plan_*` override that is# not a real planner field and (b) the small set of fields that are inert under the rule the cells use.# It is in the CONSUMER of --extra (this script), not in each launcher, so a new launcher inherits it._PLAN_INERT_UNDER = {"plan_temp": ("softmax",), "plan_topk": ("topk_uniform", "topk")}
def _check_extra(a): import ast as _ast, re as _re # The field set is read by AST, NOT by import: `import robomimic.algo.rsm_planner` needs torch + # torchvision, which exist in the JOB env and not on the submit host, so an import-based guard # silently degraded to "accept everything" -- the same silent no-op it exists to prevent. A guard # that cannot establish its reference must fail, so an unreadable source is an error here. _src = ROOT / "code/rise_robomimic/robomimic/algo/rsm_planner.py" known = set() for _n in _ast.walk(_ast.parse(_src.read_text())): if isinstance(_n, _ast.Assign) and any( getattr(t, "id", "") in ("PLANNER_DEFAULTS", "ADV_DEFAULTS") for t in _n.targets): v = _n.value known |= {kw.arg for kw in getattr(v, "keywords", []) if kw.arg} known |= {k.value for k in getattr(v, "keys", []) or [] if isinstance(k, _ast.Constant)} if not any(k.startswith("plan_") for k in known): raise SystemExit(f"launch_e1_grid: cannot read planner fields from {_src}; refusing to submit " "rather than accept any --extra unchecked") rules = {c.split(",")[5] for c in (a.cells or []) if len(c.split(",")) > 5} modes = {c.split(",")[3] for c in (a.cells or []) if len(c.split(",")) > 3} bad = [] # Same lesson as the plan_temp sweep, for the coin chain: in chain mode the read-out's only length # parameter is the CAP (plan_chain_cap). plan_depth is carried and never read, so a "depth sweep" on # chain cells would be 4 bit-identical duplicates of one arm. Refuse it before it is submitted. if modes and modes <= {"chain", "chain_rb"}: for ov in a.extra: if _re.match(r"^training\.plan_depth=", ov): bad.append("plan_depth: INERT in chain mode (the chain's length parameter is the cap, " "training.plan_chain_cap) -- the sweep would duplicate one arm") for ov in a.extra: m = _re.match(r"^training\.(plan_[A-Za-z0-9_]+)=", ov) if not m: continue f = m.group(1) if known is not None and f not in known: bad.append(f"{f}: not a planner field (nearest: " f"{sorted(k for k in known if k[:9] == f[:9])[:4]})") continue need = _PLAN_INERT_UNDER.get(f) if need and rules and not (rules & set(need)): bad.append(f"{f}: read only when plan_rule in {need}, but these cells use {sorted(rules)} " f"-- it would be INERT and the sweep would silently duplicate one arm") if bad: raise SystemExit("launch_e1_grid: refusing to submit, inert/unknown --extra override(s):\n " + "\n ".join(bad))
def main(): ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) ap.add_argument("--task", required=True) ap.add_argument("--env", default=None, help="hydra env config; default from the task") ap.add_argument("--model", action="append", default=[], help="NAME=path[:backend] (first = grid a's model)") ap.add_argument("--hop", default="", help="hop head policy_r1.pt (needed for L>=2)") ap.add_argument("--policy", action="append", default=[], help="SEED=S0B checkpoint (.pth or run dir)") ap.add_argument("--s0a", action="append", default=[], help="SEED=S0A checkpoint for S3H4") ap.add_argument("--grid", nargs="*", default=[], choices=["a", "b", "c", "d", "controls"]) ap.add_argument("--controls-subset", default="bc,random,permuted,s3h4", type=lambda v: {x.strip().lower() for x in v.split(",") if x.strip()}, help="which --grid controls rows to emit (bc,random,permuted,s3h4)") ap.add_argument("--best", action="append", default=[], help="grid d: MODEL:beta:L") ap.add_argument("--cells", action="append", default=[], help="explicit cells model,beta,L,mode,n,rule,seed") ap.add_argument("--n-primary", type=int, default=128, help="N of grids b/c and the controls (128 = RISE eval setting)") ap.add_argument("--b-all-models", action="store_true", help="grid b on every --model (default: all but the first)") ap.add_argument("--mc", default="", help="MC critic blob for S3H5 (scripts/mc_critic.py) -> S3H5-N<n>-s<k> cells") ap.add_argument("--primary-beta", type=float, default=0.95) ap.add_argument("--primary-depth", type=int, default=2) ap.add_argument("--num-rollouts", type=int, default=100) ap.add_argument("--horizon", type=int, default=400, help="exp.rollout_horizon (eval_cell.sh default 400)") ap.add_argument("--eval-seed", type=int, default=0) ap.add_argument("--extra", nargs="*", default=[], help="extra hydra overrides for every cell") ap.add_argument("--tag", default="", help="name tag inserted before -s<seed> in every cell name; use it " "whenever --extra changes the recipe (e.g. --tag P4096-logit)") ap.add_argument("--pack", type=int, default=4, help="cells per GPU job (sequential)") ap.add_argument("--queue", default="preemptable") ap.add_argument("--no-excl-hosts", action="store_true", help="do not exclude status/bad_eval_hosts.txt from select[] (see _excl_hosts)") ap.add_argument("--group", default=None, help="LSF -G; default grp_preemptable for the preemptable queue, else grp_runtime") ap.add_argument("--mem", default="64G") ap.add_argument("--out-dir", default=None, help="default runs/<task>/eval") ap.add_argument("--dry-run", action="store_true", help="print the bsub commands, submit nothing") ap.add_argument("--print-only", action="store_true", help="list the cells and exit") ap.add_argument("--force", action="store_true", help="resubmit cells whose JSON exists") ap.add_argument("--max-jobs", type=int, default=0, help="submit at most this many jobs (0 = all)") a = ap.parse_args() _check_extra(a) env = a.env or ENV_OF[a.task] out_dir = Path(a.out_dir).resolve() if a.out_dir else ROOT / "runs" / a.task / "eval" out_dir.mkdir(parents=True, exist_ok=True)
g = Grid(a) for which in a.grid: {"a": g.grid_a, "b": g.grid_b, "c": g.grid_c, "d": g.grid_d, "controls": g.controls}[which]() g.s3h5() g.explicit()
todo = [] busy = set() if a.force else _busy_cells(out_dir) n_busy = 0 for name, ov in g.cells.items(): js = out_dir / f"{name}.json" if js.exists() and not a.force: continue if name in busy: n_busy += 1 continue todo.append((name, ov, js)) print(f"[launch_e1] {len(g.cells)} cells in the grid, {len(todo)} missing" + (f" ({n_busy} skipped: already PEND/RUN)" if n_busy else ""), file=sys.stderr)
# The busy check above matches on the cell NAME, which carries --tag -- so the SAME measurement launched # under a second tag looks like a new cell and is submitted again. This is not hypothetical: on # 2026-09-19 `BC-s0a-e5000-...-es0` and `S3H4-N128-s0a-e5000-...-es0` were queued on square play while a # live packed job already held `BC-FLAG5000-es0-s0a` and `S3H4-N128-FLAG5000-es0-s0a` -- the same policy # checkpoint, eval seed and rule, i.e. the same 100 episodes. Warn rather than skip: a deliberate # re-measurement is legitimate, but it must not happen by accident. for name, ov, js in todo: line = " ".join(hydra_overrides(ov) + [f"eval_seed={a.eval_seed}", f"ckpt={ov['policy']}"]) k = _arm_key(line) other = _BUSY_ARMS.get(k) if k else None if other and other != name: print(f"[launch_e1] WARNING {name} measures the same arm as the live cell {other} " f"(same policy ckpt, eval seed {a.eval_seed}, rule) -- duplicate episodes, not new " f"evidence. Use --force only if you mean to re-measure it.", file=sys.stderr) if a.print_only: # --extra MUST be printed too. It was omitted, so a dry run of the temperature sweep showed a # command with no temperature in it at all and still looked correct; the one override that # distinguished 54 cells from the flagship arm was the one the dry run hid. for name, ov, js in todo: print(name, " ".join([*hydra_overrides(ov), *a.extra])) return
log_dir = ROOT / "logs" / "lsf" log_dir.mkdir(parents=True, exist_ok=True) jobs = 0 for i in range(0, len(todo), max(a.pack, 1)): chunk = todo[i:i + max(a.pack, 1)] lines = ["#!/usr/bin/env bash", "set -uo pipefail", f"cd {ROOT}", "rc_all=0", f"mkdir -p {shlex.quote(str(out_dir / 'logs'))}", "echo \"[launch_e1] host=$(hostname) job=${LSB_JOBID:-none} gpu=$(nvidia-smi --query-gpu=name,memory.used --format=csv,noheader | head -1)\""] for name, ov, js in chunk: cmd = [str(ROOT / "scripts" / "eval_cell.sh"), a.task, ov["policy"], env, str(js), f"exp.num_rollouts={a.num_rollouts}", f"exp.rollout_horizon={a.horizon}", f"exp.eval_seed={a.eval_seed}", f"exp.eval_cell={name}", f"exp.eval_task={a.task}", *hydra_overrides(ov), *a.extra] q = shlex.quote log = out_dir / "logs" / f"{name}.log" # one cell: run, tee to a per-cell log. On failure the per-episode partial is KEPT (eval_cell.sh # moves it to <js>.partial_best and eval.py resumes from it on the next attempt -- LSF reruns # preempted jobs, `-r` below), only the atomic-write .tmp is cleaned up. OOM is reported explicitly. lines.append( f"if [ -f {q(str(js))} ]; then echo \"[launch_e1] {name} exists, skip\"; else\n" f" {' '.join(q(c) for c in cmd)} 2>&1 | tee {q(str(log))}; rc=${{PIPESTATUS[0]}}\n" f" if [ -f {q(str(js))} ]; then python {ROOT}/scripts/wandb_log_eval.py {q(str(js))} || true\n" f" else rm -f {q(str(js) + '.tmp')}; rc_all=${{rc:-1}}\n" f" if grep -qE \"CUDA out of memory|CUDA error|cudaErrorMemoryAllocation\" {q(str(log))}; then " f"echo \"[launch_e1] CUDA OOM/error in {name} (rc=$rc) -> partial removed, resubmit\"; " f"nvidia-smi --query-gpu=memory.used,memory.total --format=csv,noheader; " f"else echo \"[launch_e1] {name} FAILED rc=$rc -> partial removed\"; fi\n" f" fi\nfi") lines.append("exit $rc_all") script = "\n".join(lines) + "\n" first = chunk[0][0] jname = f"rr_e1_{a.task}_{first}" + (f"_p{len(chunk)}" if len(chunk) > 1 else "") sh = out_dir / "jobs" / f"{jname}.sh" sh.parent.mkdir(parents=True, exist_ok=True) sh.write_text(script) sh.chmod(0o755) group = a.group or ("grp_preemptable" if a.queue == "preemptable" else "grp_runtime") # -Q "EXCLUDE(99)": eval_cell.sh exits 99 to mean "this HOST is unusable for me" (EGL 0x8cdd, # repeated read_pixels SIGABRT, CUDA-unknown-error at init). bsub_gpu.sh has always passed it; # this launcher did not, so every such cell simply DIED instead of being requeued elsewhere # (stream D 08:2x UTC: jobs 1781538/1781540, both on p2-r03-n1, exit 99 after 58 s). bsub = ["bsub", "-G", group, "-q", a.queue, "-gpu", "num=1:j_exclusive=yes:mode=shared", "-n", "8", "-M", a.mem, "-R", _res(a), "-r", "-Q", "EXCLUDE(99)", "-J", jname, "-o", str(log_dir / f"{jname}.%J.out"), "-e", str(log_dir / f"{jname}.%J.err"), str(sh)] print(" ".join(shlex.quote(c) for c in bsub)) if not a.dry_run: subprocess.run(bsub, check=False) jobs += 1 if a.max_jobs and jobs >= a.max_jobs: break print(f"[launch_e1] {jobs} jobs {'would be ' if a.dry_run else ''}submitted " f"({len(todo)} cells, pack {a.pack}, queue {a.queue})", file=sys.stderr)
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299#!/usr/bin/env python3"""Top up the FLAGSHIP arms of docs/MASTER_TABLE.md to 3 training seeds x 3 eval seeds.
The flagship admits the best matched-reward arm whatever its seed count (user 2026-09-20: "for flagship wecan admit the best numbers and config if seed needs to be refilled -- we top up"), so the rows that carrythe paper's claim are exactly the rows that must be filled in. This driver takes ONE arm per task -- thearm the table is currently reporting -- and submits only the (policy seed, eval seed) cells that aremissing, skipping anything a live job already owns.
The arm identity is (successor ckpt, beta, depth, N, proposer family); pooling in verdict_table.cells() isby that identity plus the policy checkpoint, NOT by cell name or directory, so a top-up cell pools with theoriginals no matter which --tag or --out-dir it lands in.
usage: launch_flagship_topup.py [task ...] [--print-only] [--queue preemptable]"""import argparse, glob, json, math, os, re, subprocess, sysfrom pathlib import Path
ROOT = Path("/proj/dmfexp/zwhong/rsm_rise")sys.path.insert(0, str(Path(__file__).resolve().parent))POLF = {"BC-unified": "S0B", "BC-expert": "S3H1", "RISE policy": "S0A", "IDQL policy": "S0Aidql"}POLF_INV = POLF
# task -> (env config, model label, rsm ckpt, beta, depth, proposer family)# The env MUST be the one the task's canonical region declares, or verdict_table drops every new cell:# square_expert_play -> the OOD box (user: "by default use robomimic square image ood")# two_piece_expert_play-> the WHOLE TABLE (the _top_right launcher bug, fixed 2026-09-19)# two_piece_expert_suboptimal -> top_right IS correct; the paper evaluates suboptimal from p0# EVALUATION ENVIRONMENT per task. This stays explicit because it is a CORRECTNESS constraint that is# not derivable from the arm: verdict_table drops every cell measured outside the task's canonical# region, so a top-up launched into the wrong env silently produces nothing the table will read.# square_expert_play -> the OOD box (user: "by default use robomimic square image ood")# two_piece_expert_play -> the WHOLE TABLE (the _top_right launcher bug, fixed 2026-09-19)# two_piece_expert_suboptimal -> top_right IS correct; the paper evaluates suboptimal from p0ENVS = { "square_sub_20100": "robomimic_square", "square_expert_play": "robomimic_square_image_ood", "two_piece_expert_suboptimal": "robomimic_three_piece_assembly_top_right", "two_piece_expert_play": "robomimic_three_piece_assembly", "mug_expert_suboptimal": "robomimic_mug", "threading_expert_play": "robomimic_threading_coverage", "two_piece_expert_play_tipping": "robomimic_three_piece_assembly_tipped", # rsm_rise #267: MimicGen-generated variants (same eval envs as the released rows they replace) "mug_mgen": "robomimic_mug", "threading_mgen": "robomimic_threading_coverage",}# Cell names encode BOTH the successor model and WHICH checkpoint of it, matching the names already on# disk (Mb = M@best, Ms1b = M_s1@best, L40b = L40@best, Ms100k = M@s100000). Labelling an# `M@s100000` arm "Mb" would name the cell after ckpt_best while pointing at ckpt_s100000 -- the path# is passed explicitly so it would still evaluate correctly, but the JSON would be misfiled for anyone# reading cell names later.BASE_LABEL = {"M": "M", "M_s1": "Ms1", "M_s2": "Ms2", "L40": "L40", "L40_s1": "L40s1"}
def _ck_suffix(ck): if ck == "best": return "b" m = re.fullmatch(r"s(\d+)", ck) if m and int(m.group(1)) % 1000 == 0: return f"s{int(m.group(1)) // 1000}k" return ck
# READ-OUT SCOPE (gen_q#267, 2026-09-23). This launcher SPENDS GPU: it nominates under-seeded arms# and runs them at 3x3. It pooled every `rsm:membership` arm at any read-out, so it kept seeding arms# of the RETIRED deterministic fold -- 9 cells each for an estimator that appears only in the paper's# ablation table. Chain-only by default, matching the column the flagship prints; set# RSM_TOPUP_READOUT=any (or =fold) to seed the ablation deliberately.import os as _os_READOUT = _os.environ.get("RSM_TOPUP_READOUT", "chain")
def _readout_ok(arm_str): if _READOUT == "any": return True from flagship_latex import _recipe_is_chain as _isch return _isch(arm_str) == (_READOUT == "chain")
def _refuse(task, arm_str): r"""THIS LAUNCHER CANNOT TOP UP A CHAIN ARM, AND MUST SAY SO (gen_q#267, found 2026-09-23 12:15Z).
The arm-key regex above matches only the fold grammar `b<beta> L<depth> N<n>`, and the cell spec it emits hardcodes `mode = "d1" if depth == 1 else "fold"`. A coin-chain key (`b0.95 CH33 N128 P16 prob`) therefore failed the match and was SILENTLY skipped -- so the only arms this tool could ever seed were arms of the RETIRED estimator, while the flagship column it exists to fill is chain-only.
It is deliberately NOT ported here: `launch_e1_grid.py --cells` takes "model,beta,L,mode,n,rule,seed", which has no field for the chain's PARTICLE COUNT or its prob/logit read-out. Emitting a chain cell through it would top up an arm with different particles from the one the table reports -- a top-up of a different arm under the same name, which is the exact failure this file's own docstring was written about. Chain top-ups go through scripts/launch_rsm_on_actor.py, which carries those fields. """ print(f"### {task}: the reported arm {arm_str!r} is a COIN-CHAIN arm and this launcher only emits " f"fold cells (its --cells grammar has no particle/read-out field, so it would seed a " f"DIFFERENT arm under the same name). Use scripts/launch_rsm_on_actor.py for chain top-ups. " f"Set RSM_TOPUP_READOUT=fold to work on the retired ablation arms instead.")
def reported_arm(task): """The arm the TABLE reports: the plain maximum, with the deterministic (score, episodes) tie-break.
Kept separate from topup_target() on purpose. Conflating the two made the watcher print "mug 9/9" while the table showed mug at one seed -- both true, about different arms, and impossible to read. """ from verdict_table import cells as _c, pool as _p, rate as _r c = _c(task) out = None for (arm, prop) in sorted({(a, p) for (a, p, _, _) in c if a[0] == "rsm:membership"}): if not _readout_ok(arm[1]): continue g = _p(c, lambda x, q, A=arm, P=prop: x == A and q == P) sr, n_ = _r(g) ns = len({ps for (_, ps, _) in g}) if out is None or (sr, n_) > (out[0], out[1]): out = (sr, n_, ns, arm[1], prop) return out
def top_arms(task, k): """The k best membership arms, as (rsm_ckpt, beta, depth, n, fam, label, arm_str, prop).
Topping up only the current maximum does not converge on a task whose arms are within noise of each other: verifying the leader knocks it down, a different one-seed arm becomes the leader, and the top-up starts over. Mug and threading cycled through four arms each this way. Bringing the top k arms to three seeds each ends the cycle, because the eventual maximum is then taken over arms that are all properly verified rather than over one-seed noise. """ from verdict_table import cells as _c, pool as _p, rate as _r c = _c(task) scored = [] for (arm, prop) in sorted({(a, p) for (a, p, _, _) in c if a[0] == "rsm:membership"}): if not _readout_ok(arm[1]): continue g = _p(c, lambda x, q, A=arm, P=prop: x == A and q == P) sr, n_ = _r(g) scored.append((sr, n_, arm[1], prop)) scored.sort(key=lambda x: (-x[0], -x[1])) out = [] for sr, n_, arm_str, prop in scored[:k]: m = re.match(r"([A-Za-z0-9_]+)@(\S+) b([\d.]+) L(\d+) N(\d+)", arm_str) if not m: _refuse(task, arm_str) continue model, ck, beta, depth, nn = m.group(1), m.group(2), float(m.group(3)), int(m.group(4)), int(m.group(5)) out.append((f"runs/{task}/rsm/{model}/ckpt_{ck}.pt", beta, depth, nn, POLF_INV[prop], BASE_LABEL.get(model, model) + _ck_suffix(ck), arm_str, prop)) return out
def topup_target(task): """The arm to top up: exactly the arm the TABLE reports.
An earlier version invested instead in whichever statistically-tied arm was nearest verification. That converged, but it verified the WRONG arm: mug's table row (12.0%, one seed) and its top-up target became different arms, so the number the paper would print had no path to three seeds while compute went to an arm nobody would quote. The standing rule is the opposite -- admit the best number and top IT up -- so the target is the reported arm, full stop.
The churn that motivated the sticky rule had a different cause and is fixed at its root: three mug arms sat at exactly 12.0% and the argmax flipped on set-iteration order. reported_arm() iterates sorted and breaks ties by (score, episodes), so identical data now always yields the same arm and the target stops moving on its own.
-> (rsm_ckpt, beta, depth, n, proposer family, model label) or None """ rep = reported_arm(task) if not rep: return None m = re.match(r"([A-Za-z0-9_]+)@(\S+) b([\d.]+) L(\d+) N(\d+)", rep[3]) if not m: _refuse(task, rep[3]) return None model, ck, beta, depth, n_ = m.group(1), m.group(2), float(m.group(3)), int(m.group(4)), int(m.group(5)) ckpt = f"runs/{task}/rsm/{model}/ckpt_{ck}.pt" label = BASE_LABEL.get(model, model) + _ck_suffix(ck) return ckpt, beta, depth, n_, POLF_INV[rep[4]], label, rep[3], rep[4]
def have(task, arm_str, prop): """{(policy seed, eval seed)} the TABLE accepts for this arm.
This used to glob runs/<task>/eval_*/*.json and match on the planner overrides directly, which counted cells that verdict_table.cells() DISCARDS -- wrong evaluation region, wrong horizon, wrong policy epoch, no episodes. Threading had nine such cells (run with SquareNut init bounds on a threading task), so the driver reported 9/9 and launched nothing while the table, seeing only the one valid cell, went on reporting a single-seed number that could never be topped up.
Counting through cells() makes the two agree by construction: "9/9" can only mean nine cells the table actually reads. """ from verdict_table import cells as _c got = set() for (arm, pol, ps, es), v in _c(task).items(): if arm[0] != "rsm:membership" or arm[1] != arm_str or pol != prop or not v: continue got.add((ps, es)) return got
def ckpt(task, fam, seed, epoch=5000): """The saved checkpoint of family `fam`, seed `seed` at `epoch` (every family saves 500..5000 in steps of 500). Epoch became a proposer axis on 2026-09-21: the IDQL recipe on threading is a 28 % proposer at epoch 500 and a 13.8 % one at 5000, so a proposer is now (family, epoch), not family alone.""" g = sorted(glob.glob(str(ROOT / "runs" / task / "policy" / f"{fam}_seed{seed}" / "*" / "*" / "models" / f"model_epoch_{epoch}.pth"))) if g: return g[0] # ROLLING FALLBACK (2026-09-21). A sweep arm whose training stopped early keeps only # rolling/model_epoch_<E>.pth (the last one written). Admit it so the arm can be screened at that # epoch; the eval JSON records the exact path, and verdict_table reads the epoch from it, so a later # overwrite of the rolling file can never be confused with this cell. r = ROOT / "runs" / task / "policy" / f"{fam}_seed{seed}" / "rolling" / f"model_epoch_{epoch}.pth" return str(r) if r.is_file() else None
def main(): ap = argparse.ArgumentParser() ap.add_argument("tasks", nargs="*", default=[]) ap.add_argument("--print-only", action="store_true") ap.add_argument("--queue", default="preemptable") ap.add_argument("--rollouts", type=int, default=50) ap.add_argument("--top-k", type=int, default=1, help="top up the k best arms per task, not just the reported one. Use this on tasks " "whose arms are within noise of each other, where verifying only the leader " "never converges (see top_arms).") ap.add_argument("--status", action="store_true", help="print '<task>:<have>/9' for the CURRENT flagship arms and exit (submits nothing). " "Progress must be reported against the arm the table is reporting NOW; a watcher " "with its own copy of the arm list silently tracks a stale one once a recipe " "sweep moves the flagship.") a = ap.parse_args()
if a.status: for task in (a.tasks or list(ENVS)): rep = reported_arm(task) arm = topup_target(task) if not arm or not rep: print(f"{task}: no membership arm yet") continue rsm, beta, depth, n_, fam, mlabel, arm_str, prop = arm got = have(task, arm_str, prop) same = rep[3] == f"{mlabel}" # cosmetic only; the two are compared by value below print(f"{task}: TABLE {rep[0]:.1f}% ({rep[2]} seed(s), {rep[3]}) | " f"TOPUP {len(got)}/9 cells on {mlabel} b{beta} L{depth} N{n_}" + ("" if rep[3].startswith(mlabel[:2]) else "")) return for task in (a.tasks or list(ENVS)): env = ENVS[task] if a.top_k > 1: targets = top_arms(task, a.top_k) else: t0 = topup_target(task) targets = [t0] if t0 else [] if not targets: print(f"\n### {task}: no membership arm yet -- nothing to top up") continue for rsm, beta, depth, n_, fam, mlabel, arm_str, prop in targets: if not (ROOT / rsm).is_file(): print(f"\n### {task}: arm references {rsm}, which is missing -- skipped") continue got = have(task, arm_str, prop) want = {(pp, ee) for pp in (0, 1, 2) for ee in (0, 1, 2)} miss = sorted(want - got) print(f"\n### {task} {mlabel} b{beta} L{depth} N{n_} / {fam}") print(f" have {len(got)}/9 missing {len(miss)}: {miss}") if not miss: continue mode = "d1" if depth == 1 else "fold" for es in sorted({e for _, e in miss}): ps = sorted({pp for pp, ee in miss if ee == es}) pol, cells_ = [], [] for pp in ps: ck_ = ckpt(task, fam, pp) if not ck_: print(f" SKIP pseed {pp}: no model_epoch_5000.pth") continue lab = f"{fam}s{pp}" pol += ["--policy", f"{lab}={ck_}"] cells_ += ["--cells", f"{mlabel},{beta},{depth},{mode},{n_},argmax,{lab}"] if not cells_: continue cmd = [sys.executable, str(ROOT / "scripts" / "launch_e1_grid.py"), "--task", task, "--env", env, "--model", f"{mlabel}={ROOT/rsm}:mlp", "--hop", str(ROOT / "runs" / task / "hop" / "gauss" / "policy_r1.pt"), *pol, *cells_, "--num-rollouts", str(a.rollouts), "--horizon", "400", "--eval-seed", str(es), "--tag", f"FLAGTOPUP-es{es}", "--out-dir", str(ROOT / "runs" / task / "eval_flagtopup"), "--pack", "3", "--queue", a.queue] if a.print_only: cmd.append("--print-only") subprocess.run(cmd, check=False)
if __name__ == "__main__": main()12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667#!/usr/bin/env python3"""Hop-head FAMILY control for the sim flagship arms that use depth > 1.
MOTIVATION CORRECTED (2026-09-21). This was launched on a reported ~56x fit gap between the `flow` and`gauss` hop heads on the real cooking cache (sampled-action MSE 0.00042 vs 0.02352). That figure was astep-3000 artefact -- gauss had simply not converged; by ~22.5k steps the two are within 1.3x (gauss 0.00028,flow 0.00021), so gauss is NOT broken and the "a mis-sampling hop head degrades every multi-hop score"argument does not apply to a converged gauss head. The control is still worth running, for the oppositereason: the `fold` read-out chains the hop policy and every sim flagship arm with depth > 1 (piece Cov at 8hops, piece Sub at 3, square Cov at 2, piece-tip at 8) has only ever been evaluated with `gauss`, a family wenever swept. If the two families agree, the depth curve reads as a property of the successor rather than ofhop-sample quality -- which is what we want to be able to say. 36 cells is cheap for turning an unswept axisinto a measured one.
usage: launch_hopfam_on_actor.py [--print-only]"""import subprocessimport sysfrom pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent))from launch_flagship_topup import ENVS, BASE_LABEL, _ck_suffix, ckpt # noqa: E402
ROOT = Path("/proj/dmfexp/zwhong/rsm_rise")# only the flagship arms whose read-out actually uses the hop head (depth > 1), and only where a flow head# exists. square_sub_20100 has no flow head; mug and threading are depth 1, so their rows cannot move.ARMS = { "square_expert_play": ("L40", "best", 0.9, 2), "two_piece_expert_suboptimal": ("M", "s100000", 0.9, 3), "two_piece_expert_play": ("L40", "best", 0.95, 8), "two_piece_expert_play_tipping": ("M", "best", 0.95, 8),}
def main(): dry = "--print-only" in sys.argv for task, (model, ck, b, L) in ARMS.items(): hop = ROOT / f"runs/{task}/hop/flow/policy_r1.pt" rsm = ROOT / f"runs/{task}/rsm/{model}/ckpt_{ck}.pt" if not hop.is_file() or not rsm.is_file(): print(f"{task}: missing {'flow hop head' if not hop.is_file() else 'successor ckpt'}") continue lab = BASE_LABEL.get(model, model) + _ck_suffix(ck) pol, cells = [], [] for p in (0, 1, 2): c = ckpt(task, "S0A", p) if not c: continue pol += ["--policy", f"S0As{p}={c}"] cells += ["--cells", f"{lab},{b},{L},{'d1' if L == 1 else 'fold'},128,argmax,S0As{p}"] if not cells: print(f"{task}: no epoch-5000 S0A"); continue for es in (0, 1, 2): cmd = [sys.executable, str(ROOT / "scripts/launch_e1_grid.py"), "--task", task, "--env", ENVS[task], "--model", f"{lab}={rsm}:mlp", "--hop", str(hop), *pol, *cells, "--num-rollouts", "50", "--horizon", "400", "--eval-seed", str(es), "--tag", f"HOPFLOW-es{es}", "--out-dir", str(ROOT / f"runs/{task}/eval_hopfam"), "--pack", "3", "--queue", "preemptable"] 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 "missing" in l] print(f" {task} b{b} L{L} flow-hop es{es}:", tail[-1:] or r.stderr.strip()[-160:])
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238#!/usr/bin/env python3"""Launch the IFQL baseline of the flagship table -- training and both eval columns (gen_q#264).
IFQL = implicit flow Q-learning, the flow variant of IDQL: an unweighted flow-matching BC actor plus anIQL expectile critic with an HL-Gauss two-hot value head, which at action time draws `num_samples` noises,integrates the flow and takes the arg-max Q. The agent is the verbatim ogbench implementation, vendoredunder code/ifql/impls; code/ifql/train_ifql.py supplies the rsm_rise loader and the fairness constants.
THE TWO COLUMNS, which never pool (verdict_table keys the arm by scorer AND proposer):
(a) `--eval-policy` IFQL AS PUBLISHED. Its own flow actor proposes 128 candidates and its own critic picks one, one action per env step. Policy family `S0Aifql` -> verdict_table's "IFQL policy". Runs through eval_cell.sh with exp.ifql_policy=True (eval.get_policy's IFQL branch).
(b) `--eval-critic` IFQL's CRITIC ON THE RISE ACTOR. The same critic ranks the 128 chunks the S0A actor emits -- the single-actor comparison the flagship table is built on (compare scripts/launch_rsm_on_actor.py, which is the same protocol with the RSM scorer). Policy family `S0A` -> "RISE policy", scorer arm ("critic:ifql", "N=128"). Plain planner cells: training.rsm_backend=ifql with the IFQL bundle as training.rsm_ckpt.
(b-controls) `--eval-controls` the same two controls every scorer column gets: `random` (ignore the scores, pick a candidate at random) and `permuted` (identical scores, shuffled over candidates). Both are attributed to the IFQL scorer, so the column is tested against ITS OWN controls.
FAIRNESS CONSTANTS, identical to every other column: N = 128 candidates per decision step, 3 policyseeds x 3 eval seeds x 50 episodes, horizon 400, the task's canonical eval env (ENVS, imported fromlaunch_flagship_topup so the two can never drift), the binary data-provenance reward, andexp.eval_seed driving both the env's initial conditions and the action draws. The critic seed is pairedwith the actor seed (IFQL seed p ranks S0A seed p), matching how RISE's own critic is co-trained with itsactor, so the column carries three independent (actor, critic) pairs rather than one critic reused.
usage: launch_ifql.py --train [task ...] # 7 x 3 GPU jobs, skips what exists launch_ifql.py --eval-critic [task ...] # column (b) launch_ifql.py --eval-policy [task ...] # column (a) launch_ifql.py --eval-controls [task ...] # column (b)'s random / permuted controls launch_ifql.py --status [task ...]add --print-only to see the cells / commands without submitting anything."""from __future__ import annotations
import argparseimport globimport osimport subprocessimport sysfrom pathlib import Path
ROOT = Path("/proj/dmfexp/zwhong/rsm_rise")sys.path.insert(0, str(ROOT / "scripts"))from launch_flagship_topup import ENVS, ckpt as policy_ckpt # noqa: E402
# Priority order (owner's instruction on gen_q#264).TASKS = ["two_piece_expert_suboptimal", "two_piece_expert_play", "threading_expert_play", "mug_expert_suboptimal", "square_expert_play", "two_piece_expert_play_tipping", "square_sub_20100"]SHORT = {"two_piece_expert_suboptimal": "piecesub", "two_piece_expert_play": "pieceplay", "threading_expert_play": "threading", "mug_expert_suboptimal": "mug", "square_expert_play": "squareplay", "two_piece_expert_play_tipping": "piecetip", "square_sub_20100": "sq20100"}SEEDS = (0, 1, 2)ESEEDS = (0, 1, 2)N = 128# The IFQL critic is a single-step Q over (state, first action): the successor-model knobs below are# carried by launch_e1_grid for every cell and are never read by the ifql backend (exactly as for the# `iql` backend). They are pinned to one value so that two IFQL cells can never look like two# different arms to launch_e1_grid's duplicate check.BETA, DEPTH, MODE = 0.95, 1, "d1"
def bundle(task, seed): return ROOT / "runs" / task / "ifql" / f"s{seed}" / "ifql_bundle.pt"
def published(task, seed): """The IFQL bundle where eval_cell.sh / verdict_table expect a policy checkpoint (rr_ifql.sh).""" return ROOT / "runs" / task / "policy" / f"S0Aifql_seed{seed}" / "ifql" / "ifql" / "models" / "model_epoch_5000.pth"
def live_jobs(): try: r = subprocess.run(["bjobs", "-o", "stat job_name", "-noheader"], capture_output=True, text=True, timeout=120) except Exception: return set() out = set() for line in r.stdout.splitlines(): f = line.split() if len(f) >= 2 and f[0] in ("PEND", "RUN", "PSUSP", "USUSP", "SSUSP"): out.add(f[1]) return out
def train(tasks, dry): busy = live_jobs() n = 0 for task in tasks: if not (ROOT / "cache" / task / "z.f16.npy").is_file(): print(f" {task}: no DINO cache (cache/{task}/z.f16.npy) -- skipped") continue for s in SEEDS: jname = f"rr_ifql_{SHORT.get(task, task)}_s{s}" if bundle(task, s).is_file(): print(f" {task} s{s}: bundle exists, skip") continue if jname in busy: print(f" {task} s{s}: {jname} already PEND/RUN, skip") continue cmd = [str(ROOT / "scripts" / "bsub_gpu.sh"), jname, str(ROOT / "scripts" / "rr_ifql.sh"), task, str(s)] print(" " + " ".join(cmd)) if not dry: bad = ROOT / "status" / "bad_eval_hosts.txt" env = dict(os.environ, RR_QUEUE="preemptable", RR_GROUP="grp_preemptable", RR_MEM=os.environ.get("RR_MEM", "96G")) if "RR_EXCL_HOSTS" not in env and bad.is_file(): env["RR_EXCL_HOSTS"] = " ".join(bad.read_text().split()) subprocess.run(cmd, env=env, check=False) n += 1 print(f"[launch_ifql] {n} training jobs {'would be ' if dry else ''}submitted")
def _e1(task, args, dry, label): cmd = [sys.executable, str(ROOT / "scripts" / "launch_e1_grid.py"), "--task", task, "--env", ENVS[task], "--num-rollouts", "50", "--horizon", "400", "--out-dir", str(ROOT / "runs" / task / "eval_ifql"), "--pack", "3", "--queue", "preemptable", *args] 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 "missing" in l or "WARNING" in l] print(f" {task} {label}: " + (" | ".join(tail) if tail else (r.stderr.strip()[-300:] or "ok"))) if dry: print(" " + "\n ".join(r.stdout.splitlines()[:8]))
def eval_critic(tasks, dry, controls=False, prop="S0A", epoch=5000): """Column (b): the IFQL critic ranking the proposer's 128 chunks (default: the RISE actor, S0A, epoch 5000). --proposer/--epoch (2026-09-21) point it at the row's pinned proposer; label and tag carry both.""" plab = prop + (f"E{epoch}" if epoch != 5000 else "") for task in tasks: fs = str(ROOT / "cache" / task / "feat_stats.npz") for es in ESEEDS: models, pol, cells = [], [], [] for p in SEEDS: b, ck = bundle(task, p), policy_ckpt(task, prop, p, epoch) if not b.is_file(): print(f" {task} s{p}: no IFQL bundle yet -- skipped"); continue if not ck: print(f" {task} s{p}: no epoch-{epoch} {prop} checkpoint -- skipped"); continue lab = f"IFQLs{p}" models += ["--model", f"{lab}={b}:ifql"] pol += ["--policy", f"{plab}s{p}={ck}"] rules = ("random", "permuted") if controls else ("argmax",) for rule in rules: cells += ["--cells", f"{lab},{BETA},{DEPTH},{MODE},{N},{rule},{plab}s{p}"] if not cells: continue sfx = "" if plab == "S0A" else plab tag = f"IFQLCTL{sfx}-es{es}" if controls else f"IFQLCRIT{sfx}-es{es}" _e1(task, [*models, *pol, *cells, "--eval-seed", str(es), "--tag", tag], dry, f"critic{'-controls' if controls else ''} es{es} ({len(cells) // 2} cells)")
def eval_policy(tasks, dry): """Column (a): IFQL as published -- its own flow actor and its own critic.""" for task in tasks: fs = str(ROOT / "cache" / task / "feat_stats.npz") for es in ESEEDS: models, pol, cells = [], [], [] for p in SEEDS: b, pub = bundle(task, p), published(task, p) if not (b.is_file() and pub.is_file()): print(f" {task} s{p}: no published IFQL policy checkpoint yet -- skipped"); continue lab = f"IFQLs{p}" models += ["--model", f"{lab}={b}:ifql"] pol += ["--policy", f"IFQLp{p}={pub}"] cells += ["--cells", f"{lab},{BETA},{DEPTH},{MODE},{N},argmax,IFQLp{p}"] if not cells: continue _e1(task, [*models, *pol, *cells, "--eval-seed", str(es), "--tag", f"IFQLPOL-es{es}", "--extra", "exp.ifql_policy=True", f"exp.ifql_num_samples={N}", f"exp.ifql_feat_stats={fs}"], dry, f"policy es{es} ({len(cells) // 2} cells)")
def status(tasks): from verdict_table import cells as _c, pool as _p, rate as _r, ifql_spread_str mark = ROOT / "runs" / "_ifql_watcher" print(f"{'task':32s} {'bundles':8s} {'gate b/a':10s} {'(a) IFQL published':26s} {'(b) IFQL critic / RISE actor':30s}") for task in tasks: nb = sum(1 for s in SEEDS if bundle(task, s).is_file()) try: c = _c(task) except Exception as e: print(f"{task:32s} {nb}/3 (cells unreadable: {e!r})"); continue def cell(pol): g = _p(c, lambda a, p, P=pol: a[0] == "critic:ifql" and p == P) if not g: return "--" sr, n_ = _r(g) return f"{sr:.1f}% n={n_} cells={len(g)}/9 seeds={len({ps for (_, ps, _) in g})}" gb = "ok" if (mark / f"{task}.smoke_ok_colb").is_file() else "LOCKED" ga = "ok" if (mark / f"{task}.smoke_ok_cola").is_file() else "LOCKED" print(f"{task:32s} {nb}/3 {gb + '/' + ga:10s} {cell('IFQL policy'):26s} {cell('RISE policy'):30s}") print(f"{'':32s} value resolution: {ifql_spread_str(task)}")
def main(): ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) ap.add_argument("tasks", nargs="*", default=[]) ap.add_argument("--train", action="store_true") ap.add_argument("--eval-critic", action="store_true") ap.add_argument("--eval-policy", action="store_true") ap.add_argument("--eval-controls", action="store_true") ap.add_argument("--status", action="store_true") ap.add_argument("--print-only", action="store_true") ap.add_argument("--proposer", default="S0A", help="POL key of the proposer family (default S0A)") ap.add_argument("--epoch", type=int, default=5000, help="proposer checkpoint epoch") a = ap.parse_args() tasks = a.tasks or TASKS for t in tasks: if t not in ENVS: raise SystemExit(f"unknown task {t}; known: {sorted(ENVS)}") if a.train: print("### training"); train(tasks, a.print_only) if a.eval_critic: print("### column (b): IFQL critic on the RISE actor"); eval_critic(tasks, a.print_only, prop=a.proposer, epoch=a.epoch) if a.eval_controls: print("### column (b) controls: random / permuted"); eval_critic(tasks, a.print_only, controls=True, prop=a.proposer, epoch=a.epoch) if a.eval_policy: print("### column (a): IFQL as published"); eval_policy(tasks, a.print_only) if a.status or not any([a.train, a.eval_critic, a.eval_policy, a.eval_controls]): status(tasks)
if __name__ == "__main__": main()1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889#!/usr/bin/env python3"""LeWM scorer sweep on the RISE actor (S0A) -- the pixel world-model comparator of gen_q#268.
Identical protocol to scripts/launch_dinowm_on_actor.py (see that file andlaunch_rsm_on_actor.py): the RISE actor at epoch 5000 proposes 128 chunks per decision step, thescorer ranks, argmax executes; horizon 400, 50 episodes, 3 policy seeds x 3 eval seeds, the task'scanonical env, the provenance/membership label as the reward.
The grid is L in {1,2,4,8} only: LeWM has no discount to sweep, and one hop is one action chunk.`plan_beta` is inert on this backend but every planner cell carries one, so a single value is usedthroughout and verdict_table's arm label ("L<depth> N128") correctly omits it. LeWM's roll-out isdeterministic, so the read-out forces one particle.
usage: launch_lewm_on_actor.py <task> [<task> ...] [--hops 1,2,4,8] [--control-depth 4] [--print-only]"""import subprocess, sys# --proposer FAM (gen_q#268 / #267): the flagship is moving to a best-proposer-per-task table, and every# value-estimation method -- these three included -- must be measured on THAT proposer. The policy# family is therefore a parameter, not the S0A constant it was. The family is carried into the cell# label (S0Aidqls0, S0Ansns1, ...) and into --tag, so a cell on one proposer can never be confused# with, skipped for, or pooled with the same read-out on another: launch_e1_grid's busy/exists checks# key on the cell NAME. Default S0A keeps every existing cell name byte-identical.
from pathlib import Pathsys.path.insert(0, str(Path(__file__).resolve().parent))from launch_flagship_topup import ENVS, ckptROOT = Path("/proj/dmfexp/zwhong/rsm_rise")HOPS = (1, 2, 4, 8)BETA = 0.95 # inert on this backend
def run(task, model, extra, es, label, dry, prop="S0A"): cmd = [sys.executable, str(ROOT / "scripts/launch_e1_grid.py"), "--task", task, "--env", ENVS[task], "--model", f"LEWM={model}:lewm", "--hop", str(ROOT / f"runs/{task}/hop/gauss/policy_r1.pt"), "--num-rollouts", "50", "--horizon", "400", "--eval-seed", str(es), "--tag", (f"LEWMACTOR-es{es}" if prop == "S0A" else f"LEWM{prop}-es{es}"), "--out-dir", str(ROOT / f"runs/{task}/eval_onactor"), "--pack", "4", "--queue", "preemptable", "--primary-beta", str(BETA), *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 "missing" in l] print(f" {task} es{es} {label}:", tail[-1:] or r.stderr.strip()[-300:]) if dry: print("\n".join(r.stdout.splitlines()[:3]))
def main(): dry = "--print-only" in sys.argv hops, cdepth = HOPS, 4 for i, a in enumerate(sys.argv): if a == "--hops": hops = tuple(int(x) for x in sys.argv[i + 1].split(",")) if a == "--control-depth": cdepth = int(sys.argv[i + 1]) prop = "S0A" for i, a in enumerate(sys.argv): if a == "--proposer": prop = sys.argv[i + 1] epoch = 5000 for i, a in enumerate(sys.argv): if a == "--epoch": epoch = int(sys.argv[i + 1]) plab = prop + (f"E{epoch}" if epoch != 5000 else "") # label/tag carry the epoch: 500 and 5000 cells never share a name tasks = [a for a in sys.argv[1:] if not a.startswith("--") and a in ENVS] for task in tasks: model = ROOT / f"runs/{task}/wm/lewm/ckpt_best.pt" if not model.exists(): print(f" {task}: MISSING {model}") continue pol, cells = [], [] for p in (0, 1, 2): c = ckpt(task, prop, p, epoch) if not c: print(f" {task}: no epoch-{epoch} {prop} seed {p}") continue pol += ["--policy", f"{plab}s{p}={c}"] for L in hops: cells.append(f"LEWM,{BETA},{L},{'d1' if L == 1 else 'fold'},128,argmax,{plab}s{p}") if not pol: continue for es in (0, 1, 2): run(task, model, [*pol, *[x for c in cells for x in ("--cells", c)], "--primary-depth", str(cdepth)], es, f"lewm grid ({len(cells)} cells)", dry, plab) run(task, model, [*pol, "--grid", "controls", "--controls-subset", "permuted", "--primary-depth", str(cdepth)], es, "lewm permuted control", dry, plab)
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171#!/usr/bin/env python3"""gen_q#266: sweep `plan_score=prob_log` on the RISE actor (S0A), against the read-out sweep's grid.
WHY. The 443-cell read-out sweep (scripts/launch_readout_on_actor.py) found `prob` far better than`logit` -- threading median 9.9 vs 2.0, mug 9.7 vs 6.4 -- but `prob` gets there while TYING 51-65 of the128 candidates at exactly 1.0, so its arg-max is a uniform draw inside the tied set. `logit` orders all128 and is much worse, but it also throws the fold away: `_q_fold_logit` returns `lg_out.mean(1)`, thereward logit at the LAST hop only, discarding hops 0..L-2.
`prob_log` separates those two confounded changes. It is the SAME quantity as `prob` -- the whole productfold, averaged over particles -- computed as log(1 - Q) so it never rounds to 1.0 (threading records rewardlogits near +121, where sigma is exactly 1.0 even in float64). It is a strictly monotone transform ofprob's infinite-precision value, so it keeps the fold AND totally orders the candidates.
PREDICTION, COMMITTED BEFORE THE RESULT (issue #266). The two readings of the read-out table makeopposite predictions, and both are publishable: * if `prob` beats `logit` because THE FOLD MATTERS, prob_log keeps the fold and adds the ordering, so it should match or beat prob (threading median ~9.9 or better) with ties of 1; * if `prob` beats `logit` because A COARSE FILTER PLUS A NEAR-UNIFORM DRAW over ~60 survivors is doing the work, then sharpening the order will HURT and prob_log falls toward logit (threading ~2.0).The second outcome is the surprising one and must be reported exactly as plainly as the first.
PRIOR SUPPORT FOR BRANCH 2, and the corpus it was measured on (orchestrator, 2026-09-21). The separate108-cell `training.plan_temperature` grid is fully seeded on both open rows (3 policy x 3 eval, 50 eps) andde-saturating the read-out MAKES SELECTION WORSE IN SIMULATION:
mug (Sub.) T=1 12.22 (ties 70.2, sat 0.310) -> T=10 3.56 (ties 1.2, sat 0.031) -> T=25 5.78 (ties 1.0) threading T=1 14.22 (ties 67.7, sat 0.253) -> T=25 3.78 (ties 1.2, sat 0.131)
T=1 reproduces the archived arms within seed noise, so that positive control passes. At T=25, where theread-out is effectively a total order, the rows read 5.78 / 3.78 -- next to the LOGIT read-out's 6.4 / 2.0.
This is NOT a direct prediction for prob_log, and the distinction matters: raising T changes the FUNCTIONbeing folded, while prob_log changes only the PRECISION -- it resolves the tied candidates in the directionthe infinitely-precise mean-sigmoid at T=1 would have ordered them. What the T grid does establish is thatsharpening the order on this reward head, by any means measured so far, has only hurt. Combined with themeasured scale of what prob_log resolves -- prob_log_std ~9.3 on threading, i.e. the tied candidates'(1 - Q) values differ by factors of e^9 at Q values within 1e-50 of 1.0 -- the ordering prob_log recoversINSIDE the tied set is reward-head noise. So branch 2 is the outcome with prior support and a cleannegative is the honest reading: the head is informative about membership while its logit magnitude carrieswithin-group ordering that is no better than random.
CORPUS. The claim "de-saturating improves selection" comes from the REAL corpus (gen_q#261) and it doesNOT transfer to sim -- the T grid above is the measurement. State the corpus with any read-out claim.
Grid: the read-out sweep's, so the cells are directly comparable -- single proposer S0A, N=128,plan_particles=16, beta in {0.90, 0.95, 0.98}, hops in {1, 2, 4}, 3 policy seeds x 3 eval seeds,50 episodes, horizon 400. Tasks: the two open rows plus two_piece_expert_play as a winning-row control.
HEALTH NUMBERS. Every cell records `prob_log_ties_at_max_mean` (must be ~1) beside the unchanged`ties_at_max_mean` / `frac_saturated_mean` of the probability array, so the ordering claim is checkablefrom the eval JSON with no re-scoring. Quote no arm that is not a full 3x3.
MATCHED BASELINE (--baseline). The read-out sweep (launch_readout_on_actor.FLAG) never coveredtwo_piece_expert_play -- it has two_piece_expert_play_TIPPING -- so the winning-row control has no `prob`arm at these betas and hops to be compared against, and a control without a comparator is not a control.`--baseline` submits the SAME grid with `training.plan_score=prob`, tag PROBBASE16, into the sameout-dir: same model, same checkpoint, same seeds, same episodes, same horizon, one field different. Donot use the archived flagship cells for this -- that archive is selection-confounded (the default plannercell ran on every arm), so a `prob` number lifted from it is not paired with anything here.
usage: launch_problog_on_actor.py [<task> ...] [--print-only] [--preflight] [--baseline] no task -> all three --preflight submit ONE cell only and print how to verify the knob landed. Do this FIRST: on 2026-09-21 a 61-cell temperature sweep was spent on `training.plan_temp` where `training.plan_temperature` was meant, and it was only caught because two settings produced bit-identical health numbers. A knob that does not reach the fingerprint is not a measurement of that knob.
IMPORT SAFETY. A launcher must do NOTHING on import. `launch_rsm_on_actor.py` had its submission loopat module level, so `from launch_rsm_on_actor import FLAG` read the IMPORTER's sys.argv as its task listand queued 36 jobs / 144 eval cells before it was caught. Everything here is inside main()."""import subprocessimport sysfrom pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent))from launch_flagship_topup import ENVS, BASE_LABEL, _ck_suffix, ckpt # noqa: E402
ROOT = Path("/proj/dmfexp/zwhong/rsm_rise")OUT_NAME = "eval_problog"TAG_PREFIX = "PROBLOG"
# (successor model, checkpoint) per task -- the SAME arms the read-out sweep used, so prob_log is# comparable cell for cell. two_piece_expert_play is the winning-row control (L40@best, as in# launch_temp_on_actor.ARMS).FLAG = { "threading_expert_play": ("M", "best"), "mug_expert_suboptimal": ("M_s1", "best"), "two_piece_expert_play": ("L40", "best"),}BETAS, HOPS = (0.90, 0.95, 0.98), (1, 2, 4)PARTICLES, N_CAND = 16, 128TASKS = tuple(FLAG)
def _cells(task, lab, policy_seeds, betas=BETAS, hops=HOPS): out = [] for p in policy_seeds: for b in betas: for L in hops: out += ["--cells", f"{lab},{b},{L},{'d1' if L == 1 else 'fold'},{N_CAND},argmax,S0As{p}"] return out
def main(): argv = sys.argv[1:] dry = "--print-only" in argv preflight = "--preflight" in argv baseline = "--baseline" in argv score, tag_pfx = ("prob", "PROBBASE") if baseline else ("prob_log", TAG_PREFIX) tasks = [a for a in argv if not a.startswith("--")] or list(TASKS) bad = [t for t in tasks if t not in FLAG] if bad: print(f"unknown task(s) {bad}; known: {sorted(FLAG)}") return 2 n_sub = 0 for task in tasks: model, ck = FLAG[task] rsm = ROOT / f"runs/{task}/rsm/{model}/ckpt_{ck}.pt" if not rsm.is_file(): print(f"{task}: no {rsm}") continue lab = BASE_LABEL.get(model, model) + _ck_suffix(ck) pol, seeds = [], [] for p in (0, 1, 2): c = ckpt(task, "S0A", p) if c: pol += ["--policy", f"S0As{p}={c}"] seeds.append(p) if not seeds: print(f"{task}: no epoch-5000 S0A") continue out_dir = ROOT / f"runs/{task}/{OUT_NAME}" # --preflight: ONE cell (first policy seed, beta 0.95, 1 hop, eval seed 0), so the knob can be # checked against the recorded fingerprint before the rest of the grid is spent. if preflight: grids = [(seeds[:1], (0.95,), (1,), 0)] else: grids = [(seeds, BETAS, HOPS, es) for es in (0, 1, 2)] for (sds, betas, hops, es) in grids: cells = _cells(task, lab, sds, betas, hops) cmd = [sys.executable, str(ROOT / "scripts/launch_e1_grid.py"), "--task", task, "--env", ENVS[task], "--model", f"{lab}={rsm}:mlp", "--hop", str(ROOT / f"runs/{task}/hop/gauss/policy_r1.pt"), *pol, *cells, "--num-rollouts", "50", "--horizon", "400", "--eval-seed", str(es), "--extra", f"training.plan_particles={PARTICLES}", f"training.plan_score={score}", # the tag carries the read-out AND the particle count, so a prob_log cell can never be # pooled with the `prob` / `logit` cells of the read-out sweep under one arm key. "--tag", f"{tag_pfx}{PARTICLES}-es{es}", "--out-dir", str(out_dir), "--pack", "4", "--queue", "preemptable"] 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 "missing" in l] print(f" {task} {tag_pfx}{PARTICLES} es{es}:", tail[-1:] or r.stderr.strip()[-200:]) n_sub += 1 if preflight: print("\n[preflight] when the first cell lands, verify the knob reached the fingerprint:") print(f" python3 {ROOT}/scripts/check_problog_knob.py") print(" planner.plan_score and scorer.score_kind must read 'prob_log', " "prob_log_ties_at_max_mean ~1.0,") print(" and prob_ties_at_max_mean must still be LARGE -- `prob` would have tied on these very") print(" states, so the ordering is what changed and nothing else. (`ties_at_max_mean` is the") print(" RANKING array's tie count, which under prob_log IS prob_log's, so it must be ~1 too.)") return 0 if n_sub else 1
if __name__ == "__main__": sys.exit(main())12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576#!/usr/bin/env python3"""Sweep the RSM READ-OUT (particle count x score) on the RISE actor for the two open rows.
gen_q#265's CKISO experiment showed the read-out is a first-order lever that the arm key had been poolingover: on threading, the same (model, beta, hops) recipe scores 9.1-12.0 % at `plan_particles=16,plan_score=prob` and 1.0-3.4 % at `256, logit`, while on piece-suboptimal the two agree to 0.6 pt. Theread-out is part of the scorer, so it belongs in the disclosed search -- and the controls (greedy,random-of-128) do not depend on it, so sweeping it cannot inflate a margin without the controls moving.
Health caveat (2026-09-21): `prob` is not simply the better read-out. On square-peg (Cov.) the `P16/prob`arms tie across 18-63 of the 128 candidates, so the arg-max there is a uniform draw inside the tied set --a coarse filter plus resampling rather than a ranking. Report the tie count (`scripts/scorer_health.py`)beside every arm this launcher produces.
usage: launch_readout_on_actor.py <task> [<task> ...] [--print-only]"""import subprocessimport sysfrom pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent))from launch_flagship_topup import ENVS, BASE_LABEL, _ck_suffix, ckpt # noqa: E402
ROOT = Path("/proj/dmfexp/zwhong/rsm_rise")FLAG = {"mug_expert_suboptimal": ("M_s1", "best"), "threading_expert_play": ("M", "best"), "square_expert_play": ("L40", "best"), "two_piece_expert_play_tipping": ("M", "best")}# (particles, score) read-outs to try beside the canonical (256, logit) the flagship already has.READOUTS = [(16, "prob"), (16, "logit"), (256, "prob")]BETAS, HOPS = (0.90, 0.95, 0.98), (1, 2, 4)
# 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(): dry = "--print-only" in sys.argv for task in [a for a in sys.argv[1:] if not a.startswith("--")]: model, ck = FLAG[task] rsm = ROOT / f"runs/{task}/rsm/{model}/ckpt_{ck}.pt" lab = BASE_LABEL.get(model, model) + _ck_suffix(ck) pol = [] for p in (0, 1, 2): c = ckpt(task, "S0A", p) if c: pol += ["--policy", f"S0As{p}={c}"] if not pol: print(f"{task}: no epoch-5000 S0A") continue for (P, sc) in READOUTS: cells = [] for p in (0, 1, 2): if not ckpt(task, "S0A", p): continue for b in BETAS: for L in HOPS: cells += ["--cells", f"{lab},{b},{L},{'d1' if L == 1 else 'fold'},128,argmax,S0As{p}"] for es in (0, 1, 2): cmd = [sys.executable, str(ROOT / "scripts/launch_e1_grid.py"), "--task", task, "--env", ENVS[task], "--model", f"{lab}={rsm}:mlp", "--hop", str(ROOT / f"runs/{task}/hop/gauss/policy_r1.pt"), *pol, *cells, "--num-rollouts", "50", "--horizon", "400", "--eval-seed", str(es), "--extra", f"training.plan_particles={P}", f"training.plan_score={sc}", "--tag", f"RO{P}{sc}-es{es}", "--out-dir", str(ROOT / f"runs/{task}/eval_readout"), "--pack", "4", "--queue", "preemptable"] 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 "missing" in l] print(f" {task} P{P}/{sc} es{es}:", tail[-1:] or r.stderr.strip()[-160:])
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186#!/usr/bin/env python3"""RSM scorer sweep on the RISE actor (S0A) as the single proposer -- the comparison where RISE and RSM differONLY in the scorer (owner, 2026-09-21: "if the only difference between RISE and RSM is the CRITIC, that ismuch better signal").
Per task: the flagship successor model, beta {0.90,0.95,0.98} x hops {1,2,4,8}, N=128 argmax, 3 policy seedsx 3 eval seeds x 50 episodes, plus the S0A controls (greedy, random-candidate, permuted, IQL critic) at theflagship recipe. launch_e1_grid refuses cells that duplicate an existing (policy ckpt, eval seed, rule)elsewhere, so re-running on a task that already has S0A cells only adds the missing ones.
usage: launch_rsm_on_actor.py <task> [<task> ...] [--family <POL key>] [--epoch <E>] [--arms grid|flagship] [--eval-seeds 0,1,2] [--controls bc,random,...] [--critic-from <POL key>] [--print-only]"""import re, subprocess, sysfrom pathlib import Pathsys.path.insert(0, str(Path(__file__).resolve().parent))from launch_flagship_topup import ENVS, BASE_LABEL, _ck_suffix, ckptROOT = Path("/proj/dmfexp/zwhong/rsm_rise")# task -> (successor model, checkpoint, flagship beta, flagship hops), from the 2026-09-21 master tableFLAG = { "square_sub_20100": ("M", "best", 0.9, 3), "square_expert_play": ("L40", "best", 0.9, 2), "two_piece_expert_suboptimal": ("M", "s100000", 0.9, 3), "two_piece_expert_play": ("L40", "best", 0.95, 8), "mug_expert_suboptimal": ("M_s1", "best", 0.95, 1), "threading_expert_play": ("M", "best", 0.9, 1), "two_piece_expert_play_tipping": ("M", "best", 0.95, 8), # REGENERATED-DATA TASKS (2026-09-21): the successor model trained on the mgen data (rsm/M), the parent # task's flagship beta/depth. Same eval envs as the parent rows (robomimic_mug, robomimic_threading_coverage). "mug_mgen": ("M", "best", 0.95, 1), "threading_mgen": ("M", "best", 0.9, 1),}BETAS, HOPS = (0.90, 0.95, 0.98), (1, 2, 4, 8)GAMMA = 0.99 # the planner's plan_gamma; the chain's cap depends on it# --readout chain (gen_q#267, owner 2026-09-22): the coin-terminated beta chain replaces the deterministic# truncated fold. Per particle the walk hops a Bernoulli(p) number of times with# p = (gamma-beta)/(gamma*(1-beta)) [ogbench_genq/rsm.py:113] and reads membership ONCE at the frozen node,# so the composed frame offset is EXACTLY Geom(1-gamma). The chain's only length parameter is the# TRUNCATION CAP, computed here from the 1e-3 tail -- never hard-coded, never swept for success.CHAIN_PARTICLES = (16, 64) # the chain is stochastic, so the particle count is a variance axisCHAIN_BETAS = (0.90, 0.95, 0.98) # all inside the successor's trained band [0.90, 0.995] (train_rsm.py:162)
def chain_cap_for(beta, gamma=GAMMA, tail_eps=1e-3): """The cap as a truncation guard: smallest L with P(walk > L) = p**L <= tail_eps. Imported from the SHIPPED scorer when that import is possible (submit hosts have no torch), else recomputed from the same closed form -- the two are asserted equal in scripts/chain_horizon_test.py, which runs on a node.""" import math p = (gamma - beta) / (gamma * (1.0 - beta)) return int(math.ceil(math.log(tail_eps) / math.log(p)))
def run(task, extra, es, label, dry=False, fam="S0A", tsuf=""): model, ck, b0, L0 = FLAG[task] rsm = ROOT / f"runs/{task}/rsm/{model}/ckpt_{ck}.pt" lab = BASE_LABEL.get(model, model) + _ck_suffix(ck) cmd = [sys.executable, str(ROOT / "scripts/launch_e1_grid.py"), "--task", task, "--env", ENVS[task], "--model", f"{lab}={rsm}:mlp", "--hop", str(ROOT / f"runs/{task}/hop/gauss/policy_r1.pt"), "--num-rollouts", "50", "--horizon", "400", "--eval-seed", str(es), # tsuf (gen_q#267) separates otherwise-identical chain cells that differ only in an --extra # (the particle count), so two particle counts can never write the same JSON. "--tag", ((f"ONACTOR{tsuf}-es{es}" if fam == "S0A" else f"ON{fam}{tsuf}-es{es}")), "--out-dir", str(ROOT / f"runs/{task}/eval_onactor"), "--pack", "4", "--queue", "preemptable", "--primary-beta", str(b0), "--primary-depth", str(L0), *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 "missing" in l] print(f" {task} es{es} {label}:", tail[-1:] or r.stderr.strip()[-200:])
def main(): # --family <POL key> (2026-09-21): the proposer family. Default S0A (the RISE actor). The owner's # restructure compares every value-estimation method on the BEST PROPOSER PER TASK, which may be a # special case of the RISE recipe; the planning screen selected S0Aidql and S0Ansn on threading. The # policy label embeds the family (e.g. S0Aidqls0) and verdict_table recovers the family from the # checkpoint PATH via POL, so cells on different proposers can never pool. fam = "S0A" if "--family" in sys.argv: fam = sys.argv[sys.argv.index("--family") + 1] # --epoch <E> (2026-09-21): the proposer's checkpoint epoch. Label and tag carry it (S0AidqlE500s0, # ONS0AidqlE500-es0) so epoch-500 and epoch-5000 cells of one family can never share a name, and # verdict_table labels the proposer "IDQL policy@500". --arms flagship runs only the pinned recipe # (the epoch/family sweep); --eval-seeds 0 restricts the eval seeds for a screen. epoch = int(sys.argv[sys.argv.index("--epoch") + 1]) if "--epoch" in sys.argv else 5000 arms = sys.argv[sys.argv.index("--arms") + 1] if "--arms" in sys.argv else "grid" # --readout fold|chain (gen_q#267). DEFAULT fold, so every existing invocation of this launcher is # byte-for-byte the command it was; chain is additive and lands in its own eval JSONs (cell names carry # the -ch tag), so the loader can hold both columns at once. readout = sys.argv[sys.argv.index("--readout") + 1] if "--readout" in sys.argv else "fold" if readout not in ("fold", "chain"): raise SystemExit(f"--readout must be fold|chain (got {readout})") # --chain-arms <P>:<score>[,...] (gen_q#267 re-sweep, owner 2026-09-22 06:40/07:05). At the flagship # beta and the COMPUTED cap the chain's only knobs are the particle count (it is a stochastic # estimator, so variance matters) and the read-out, so THAT is the sweep -- 4 arms per row, no cap # sweep and no beta sweep "to be safe". Each arm is submitted SEPARATELY under its own --tag because # plan_particles / plan_score are --extra overrides that apply to a whole submission: mixing them in # one submission would silently run every cell at the last value under a single name (the plan_temp # lesson). Default "16:prob" = the flagship arm alone. # --chain-betas <b>[,<b>] (gen_q#267). The chain runs at the row's flagship beta by default. The # RETIRED fold column of tab:flagship_fold is a maximum over a 12-arm (beta, L) grid, so on the rows # whose winning fold arm sat at a DIFFERENT beta than the pinned flagship recipe, a single-beta chain # cell would be compared against a fold maximum taken at another beta. This adds the published # winner's beta as a second chain arm on exactly those rows; the cap is recomputed for it. chain_betas = ([float(x) for x in sys.argv[sys.argv.index("--chain-betas") + 1].split(",")] if "--chain-betas" in sys.argv else None) chain_arms = [(int(x.split(":")[0]), x.split(":")[1]) for x in (sys.argv[sys.argv.index("--chain-arms") + 1] if "--chain-arms" in sys.argv else "16:prob").split(",")] for _np, _sc in chain_arms: if _np not in CHAIN_PARTICLES or _sc not in ("prob", "logit"): raise SystemExit(f"--chain-arms: {_np}:{_sc} outside the sanctioned grid " f"{CHAIN_PARTICLES} x (prob, logit)") eseeds = tuple(int(x) for x in sys.argv[sys.argv.index("--eval-seeds") + 1].split(",")) if "--eval-seeds" in sys.argv else (0, 1, 2) ctl = sys.argv[sys.argv.index("--controls") + 1] if "--controls" in sys.argv else ("bc,random,permuted,s3h4" if fam.startswith("S0A") else "bc,random,permuted") # every S0A* family has a co-trained critic # --critic-from <FAM> (2026-09-21): where the s3h4 IQL-critic control takes its VALUE FUNCTION, when # that is not the proposer's own family. A BC actor has no co-trained critic, so on a row pinned to a # BC proposer the fair RISE/IDQL-family baseline is "the IQL value function ranking THIS proposer's 128 # candidates" -- stronger than RISE on the actor we already reported as a failed proposer for that task. # The critic must be at the same epoch as the proposer: verdict_table refuses a critic-epoch mismatch. cfrom = sys.argv[sys.argv.index("--critic-from") + 1] if "--critic-from" in sys.argv else fam if cfrom != fam and "s3h4" not in ctl: ctl += ",s3h4" plab = fam + (f"E{epoch}" if epoch != 5000 else "") # MODULE-LEVEL SUBMISSION REMOVED (2026-09-21). This loop used to run at import time, so # `from launch_rsm_on_actor import FLAG` -- which scripts/scorer_rank_check.py does, to read the # flagship recipe -- submitted the entire ONACTOR grid, reading the IMPORTER's sys.argv as the task # list. It queued 36 jobs / 144 eval cells before anyone noticed. A launcher must not do anything # on import; launch_flagship_topup.py already guarded itself this way. dry = "--print-only" in sys.argv tasks = [a for a in sys.argv[1:] if not a.startswith("--") and a in FLAG] for task in tasks: model, ck, b0, L0 = FLAG[task] lab = BASE_LABEL.get(model, model) + _ck_suffix(ck) pol, s0a, cells = [], [], [] for p in (0, 1, 2): c = ckpt(task, fam, p, epoch) if not c: print(f" {task}: no epoch-{epoch} {fam} seed {p}"); continue pol += ["--policy", f"{plab}s{p}={c}"] # the s0a map is keyed by the POLICY label, so the critic can come from another family while # the candidates keep coming from this proposer cc = c if cfrom == fam else ckpt(task, cfrom, p, epoch) if cc: s0a += ["--s0a", f"{plab}s{p}={cc}"] else: print(f" {task}: no epoch-{epoch} {cfrom} seed {p} for the critic -- s3h4 skipped for that seed") if readout == "chain": # CHAIN cells. `arms flagship` = the flagship beta at the computed cap; `arms grid` = the # eval-time re-sweep (beta axis), cap ALWAYS the computed one. There is no depth axis -- # see readout_overrides() in launch_e1_grid.py. The PARTICLE axis is NOT built here: a # particle count is a `training.plan_particles` --extra, which applies to a whole # submission, so each particle count is submitted separately below under its own --tag # (otherwise one --extra would silently re-run every cell of the submission at 64 and the # cell names could not tell the two apart -- the plan_temp lesson). for b in (chain_betas or (CHAIN_BETAS if arms == "grid" else (b0,))): cells += ["--cells", f"{lab},{b},{chain_cap_for(b)},chain,128,argmax,{plab}s{p}"] else: for b in (BETAS if arms == "grid" else (b0,)): for L in (HOPS if arms == "grid" else (L0,)): cells += ["--cells", f"{lab},{b},{L},{'d1' if L == 1 else 'fold'},128,argmax,{plab}s{p}"] if not pol: continue for es in eseeds: if readout == "chain": # no controls re-run: the chain changes only the RSM read-out, and the control arms # (bc / random / permuted / s3h4 IQL critic) do not use it. Re-running them would be # duplicate episodes, not new evidence. for np_, sc in chain_arms: # "16:prob" is the flagship default (plan_particles=16, plan_score=prob from # idql_config.py:126), so it submits with NO --extra and an EMPTY tag -- byte-identical # to the first wave's cell names, which is what stops a re-run duplicating them. dflt = (np_ == 16 and sc == "prob") ptag = "" if dflt else f"P{np_}{sc[:2]}" ex = [] if dflt else ["--extra", f"training.plan_particles={np_}", f"training.plan_score={sc}"] run(task, [*pol, *cells, *ex], es, f"rsm CHAIN {arms} P{np_}/{sc} ({len(cells)//2} cells)", dry, plab, tsuf=ptag) continue run(task, [*pol, *s0a, "--grid", "controls", "--controls-subset", ctl], es, "controls", dry, plab) run(task, [*pol, *cells], es, f"rsm {arms} ({len(cells)//2} cells)", dry, plab)
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168#!/usr/bin/env python3"""TD-FLOW scorer sweep on the RISE actor (S0A), the MC-vs-TD occupancy ablation (gen_q#268).
Identical in every respect to scripts/launch_rsm_on_actor.py -- same proposer (the RISE actor at epoch5000, 128 chunks per decision step, argmax), same 12-arm read-out grid (beta {0.90,0.95,0.98} x hops{1,2,4,8}), same 3 policy seeds x 3 eval seeds x 50 episodes, same horizon 400, same evaluation env --except that the value estimator is a TD-Flow successor model (runs/<task>/rsm/TDF_*) instead of theMonte-Carlo one (runs/<task>/rsm/*). The TD model is the same width/depth/seed/beta-band/reward-headas the flagship MC model of that task, so a TDF cell and its MC twin differ in the occupancy TARGETand in nothing else.
Controls: the scorer-independent ones (greedy, RISE's own IQL critic, random-of-N) are already on diskfrom launch_rsm_on_actor.py and are shared; what is NOT shared is the PERMUTED control, because it mustbe paired with THIS scorer's checkpoint (verdict_table keys the control by the checkpoint that producedthe scores). `--wave flagship` submits only the task's flagship (beta, hops) arm plus that control --the headline MC-vs-TD number -- and `--wave grid` submits the remaining 11 arms.
usage: launch_tdflow_on_actor.py <task> [<task> ...] [--wave flagship|grid|all] [--print-only]"""import subprocess, sys# --proposer FAM (gen_q#268 / #267): the flagship is moving to a best-proposer-per-task table, and every# value-estimation method -- these three included -- must be measured on THAT proposer. The policy# family is therefore a parameter, not the S0A constant it was. The family is carried into the cell# label (S0Aidqls0, S0Ansns1, ...) and into --tag, so a cell on one proposer can never be confused# with, skipped for, or pooled with the same read-out on another: launch_e1_grid's busy/exists checks# key on the cell NAME. Default S0A keeps every existing cell name byte-identical.
from pathlib import Pathsys.path.insert(0, str(Path(__file__).resolve().parent))from launch_flagship_topup import ENVS, _ck_suffix, ckptROOT = Path("/proj/dmfexp/zwhong/rsm_rise")# task -> (TD-Flow cell, checkpoint, flagship beta, flagship hops). The cell mirrors the MC model the# flagship row uses (M -> TDF_M, L40 -> TDF_L40, M_s1 -> TDF_M_s1) and the (beta, hops) are the same# read-out the MC flagship row reports, so the flagship wave is a like-for-like swap of the scorer.FLAG = { "square_sub_20100": ("TDF_M", "best", 0.9, 3), "square_expert_play": ("TDF_L40", "best", 0.9, 2), "two_piece_expert_suboptimal": ("TDF_M", "s100000", 0.9, 3), "two_piece_expert_play": ("TDF_L40", "best", 0.95, 8), "mug_expert_suboptimal": ("TDF_M_s1", "best", 0.95, 1), "threading_expert_play": ("TDF_M", "best", 0.9, 1), "two_piece_expert_play_tipping": ("TDF_M", "best", 0.95, 8), # regenerated-data tasks (2026-09-21): TD-Flow model TDF_M, parent beta/depth "mug_mgen": ("TDF_M", "best", 0.95, 1), "threading_mgen": ("TDF_M", "best", 0.9, 1),}# Cell-name label. verdict_table.py reads the successor model out of the rsm_ckpt PATH, not out of the# cell name, so this label only has to be unique against the MC labels (Mb / L40b / Ms1b / Ms100k) --# otherwise a TD cell and its MC twin would collide on one JSON filename.LABEL = {"TDF_M": "TDFM", "TDF_L40": "TDFL40", "TDF_M_s1": "TDFMs1", "TDF_M_td": "TDFMtd", "TDF_M_td2": "TDFMtd2"}BETAS, HOPS = (0.90, 0.95, 0.98), (1, 2, 4, 8)GAMMA = 0.99 # the planner's plan_gamma; the chain's cap depends on itCHAIN_PARTICLES = (16, 64)
def chain_cap_for(beta, gamma=GAMMA, tail_eps=1e-3): """The chain's truncation cap: smallest L with P(walk > L) = p**L <= tail_eps, p the reference's continuation coin (gamma-beta)/(gamma(1-beta)) [ogbench_genq/rsm.py:113]. Same closed form and same tail as scripts/launch_rsm_on_actor.chain_cap_for -- TD-Flow MUST use the identical cap rule or the comparison measures the read-out instead of the value estimator (owner, 2026-09-22 06:45).""" import math p = (gamma - beta) / (gamma * (1.0 - beta)) return int(math.ceil(math.log(tail_eps) / math.log(p)))
def run(task, extra, es, label, dry, prop="S0A", tsuf=""): model, ck, b0, L0 = FLAG[task] rsm = ROOT / f"runs/{task}/rsm/{model}/ckpt_{ck}.pt" if not rsm.exists(): print(f" {task} es{es} {label}: MISSING {rsm}"); return lab = LABEL[model] + _ck_suffix(ck) cmd = [sys.executable, str(ROOT / "scripts/launch_e1_grid.py"), "--task", task, "--env", ENVS[task], "--model", f"{lab}={rsm}:mlp", "--hop", str(ROOT / f"runs/{task}/hop/gauss/policy_r1.pt"), "--num-rollouts", "50", "--horizon", "400", "--eval-seed", str(es), "--tag", ((f"TDFACTOR{tsuf}-es{es}" if prop == "S0A" else f"TDF{prop}{tsuf}-es{es}")), "--out-dir", str(ROOT / f"runs/{task}/eval_onactor"), "--pack", "4", "--queue", "preemptable", "--primary-beta", str(b0), "--primary-depth", str(L0), *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 "missing" in l] print(f" {task} es{es} {label}:", tail[-1:] or r.stderr.strip()[-300:]) if dry: print("\n".join(r.stdout.splitlines()[:4]))
def main(): dry = "--print-only" in sys.argv wave = "all" prop = "S0A" # --readout fold|chain (gen_q#267, owner 2026-09-22 06:45): TD-Flow shares RSM's eval read-out, so # comparing RSM-chain against TD-Flow-fold would measure the read-out and not the value estimator. # DEFAULT fold, so every existing invocation is unchanged; chain cells carry the -ch name tag and land # in their own JSONs. Settings are TRANSFERRED from the RSM sweep, not swept here (owner 06:50). readout = sys.argv[sys.argv.index("--readout") + 1] if "--readout" in sys.argv else "fold" if readout not in ("fold", "chain"): raise SystemExit(f"--readout must be fold|chain (got {readout})") chain_betas = ([float(x) for x in sys.argv[sys.argv.index("--chain-betas") + 1].split(",")] if "--chain-betas" in sys.argv else None) chain_arms = [(int(x.split(":")[0]), x.split(":")[1]) for x in (sys.argv[sys.argv.index("--chain-arms") + 1] if "--chain-arms" in sys.argv else "16:prob").split(",")] for i, a in enumerate(sys.argv): if a == "--wave": wave = sys.argv[i + 1] if a == "--proposer": prop = sys.argv[i + 1] epoch = 5000 for i, a in enumerate(sys.argv): if a == "--epoch": epoch = int(sys.argv[i + 1]) plab = prop + (f"E{epoch}" if epoch != 5000 else "") # label/tag carry the epoch: 500 and 5000 cells never share a name tasks = [a for a in sys.argv[1:] if not a.startswith("--") and a in FLAG] for task in tasks: model, ck, b0, L0 = FLAG[task] lab = LABEL[model] + _ck_suffix(ck) # MOVING CHECKPOINT GUARD (2026-09-21): ckpt_best.pt is rewritten while the TD-Flow model trains, so # cells launched before the final checkpoint exists load different weights and pool as one arm. # Refuse unless ckpt_s100000.pt sits beside it or --allow-partial is given explicitly. _final = ROOT / f"runs/{task}/rsm/{model}/ckpt_s100000.pt" if ck == "best" and not _final.exists() and "--allow-partial" not in sys.argv: print(f" {task}: TD-Flow {model} still training ({_final.name} absent); refusing to evaluate a moving ckpt_best.pt -- pass --allow-partial to override") continue pol, flag_cells, grid_cells, chain_cells = [], [], [], [] for p in (0, 1, 2): c = ckpt(task, prop, p, epoch) if not c: print(f" {task}: no epoch-{epoch} {prop} seed {p}"); continue pol += ["--policy", f"{plab}s{p}={c}"] # the chain runs at the SAME beta as the matching RSM cell (the row's flagship beta) and at the # cap computed from the 1e-3 tail; there is no depth axis. for _cb in (chain_betas or (b0,)): chain_cells.append(f"{lab},{_cb},{chain_cap_for(_cb)},chain,128,argmax,{plab}s{p}") for b in BETAS: for L in HOPS: spec = f"{lab},{b},{L},{'d1' if L == 1 else 'fold'},128,argmax,{plab}s{p}" (flag_cells if (abs(b - b0) < 1e-9 and L == L0) else grid_cells).append(spec) # The flagship read-out is not always inside the 12-arm grid (square_sub_20100 and # two_piece_expert_suboptimal report hops=3), so add it explicitly when it is not. if L0 not in HOPS or all(abs(b - b0) > 1e-9 for b in BETAS): flag_cells.append(f"{lab},{b0},{L0},{'d1' if L0 == 1 else 'fold'},128,argmax,{plab}s{p}") if not pol: continue flag_cells = sorted(set(flag_cells)) for es in (0, 1, 2): if readout == "chain": cells = [x for c in chain_cells for x in ("--cells", c)] for np_, sc in chain_arms: dflt = (np_ == 16 and sc == "prob") ptag = "" if dflt else f"P{np_}{sc[:2]}" ex = [] if dflt else ["--extra", f"training.plan_particles={np_}", f"training.plan_score={sc}"] run(task, [*pol, *cells, *ex], es, f"tdflow CHAIN P{np_}/{sc} ({len(chain_cells)} cells)", dry, plab, tsuf=ptag) continue if wave in ("flagship", "all"): cells = [x for c in flag_cells for x in ("--cells", c)] run(task, [*pol, *cells], es, f"tdflow flagship ({len(flag_cells)} cells)", dry, plab) # PERMUTED control, paired with THIS scorer: identical scores, candidate order shuffled. run(task, [*pol, "--grid", "controls", "--controls-subset", "permuted"], es, "tdflow permuted control", dry, plab) if wave in ("grid", "all"): cells = [x for c in grid_cells for x in ("--cells", c)] run(task, [*pol, *cells], es, f"tdflow grid ({len(grid_cells)} cells)", dry, plab)
if __name__ == "__main__": main()12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394#!/usr/bin/env python3"""Temperature sweep for the RSM read-out on the RISE actor.
WHY. gen_q#261 traced the real corpus's flat `prob` score to reward-head saturation: mean |logit| ~= 25with ~99.8 % of sampled successors beyond |logit| > 15, so sigma(R/T) underflows or ties at 1 and themean-sigmoid array loses its ordering (ties at the top: ~37 of 128 real, 45-71 in sim, exactly 1 for thelogit array). On the real corpus switching to the logit array fixes it; in sim the sigmoid still WINS(threading 9.4 % vs 2.0 %), even at depth 1, so neither array is simply correct.
`plan_temp` is the knob that attacks the cause rather than the symptom: the fold uses c_k = sigma(R(z_k)/T),so a LARGER T pulls the argument toward 0, de-saturates the sigmoid, and should collapse the tie count whilekeeping the product fold's aggregation over hops -- the property the logit array throws away by reading onlythe terminal hop. It has never been swept: 2954 + 2777 archived cells all sit at T = 0.2 and exactly one at0.05. If a larger T reduces ties without losing the fold, that is strictly better than either array.
WRONG KNOB, FIRST ATTEMPT (2026-09-21). The first run of this launcher passed `training.plan_temp`. Thatis the SOFTMAX-RULE temperature on Qbar (`select(s, rule, temp=cfg["plan_temp"], ...)` in rsm_planner.py) andis read ONLY when `plan_rule=softmax`; every cell here uses `argmax`, so it was inert. The sigmoid read-out Tis `plan_temperature` (rsm_planner.py passes it as `temperature=`; 0 means "the checkpoint's calib.json T,else 1.0"). All 42 cells of that sweep therefore ran at the checkpoint default and are duplicates of thearchived flagship arm -- caught because mug T=10 and T=25 agreed to the third decimal on BOTH`frac_saturated_mean` (0.296) and `ties_at_max_mean` (72.3), and two_piece T=1 and T=5 agreed exactly. Theyare quarantined (`verdict_table.SKIP`) rather than pooled, because the arm key did not contain thetemperature; it now does. A knob that produces bit-identical health numbers at two settings is not ameasurement of that knob -- verify the fingerprint records it before believing any grid built on it.
usage: launch_temp_on_actor.py [--print-only] [--preflight] --preflight submits ONE cell and prints the recorded plan_temperature and tie count, so the knob is checked against the fingerprint before 54 cells are spent on it."""import subprocessimport sysfrom pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent))from launch_flagship_topup import ENVS, BASE_LABEL, _ck_suffix, ckpt # noqa: E402
ROOT = Path("/proj/dmfexp/zwhong/rsm_rise")# the two open rows plus one winning row as a control: if a larger T helps only where the row is weak, that# is a different story from it helping everywhere.ARMS = { "threading_expert_play": ("M", "best", 0.98, 1), "mug_expert_suboptimal": ("M_s1", "best", 0.95, 1), "two_piece_expert_play": ("L40", "best", 0.95, 8),}# gen_q#261 measured on the real cache that ties at the top collapse from 35.5/128 to exactly 1.0 at every# T >= 5, that the depth-4 ANTI-selection is cured by it (sign flips from +0.085 to -0.23..-0.35), and that# T-corrected `prob` then BEATS the logit array (d4 -0.266 +- 0.059, i.e. 4.5 sem) because it keeps the# product fold as well as the ordering. T in [5,70] is a plateau there, so the supported claim is "any T# large enough to leave saturation", not a sharp optimum. Their checkpoints run at T=1 (no calib.json);# MEASURED, not assumed: sim's archived cells record `scorer.temperature = 1.0` with# `temperature_override = 0.0`, so sim ALSO runs at T=1 (there is no calib.json anywhere). The# earlier claim here -- that sim's default is 0.2, five times more saturating -- was wrong: 0.2 is the# dataclass default of `plan_temp`, the inert field. Sim and real start level, and T=1.0 below is# therefore a POSITIVE CONTROL that must reproduce the archived flagship number within seed noise.TEMPS = (1.0, 5.0, 10.0, 25.0) # T=1.0 == the archived effective T, so it is the positive control
def main(): dry = "--print-only" in sys.argv for task, (model, ck, b, L) in ARMS.items(): rsm = ROOT / f"runs/{task}/rsm/{model}/ckpt_{ck}.pt" if not rsm.is_file(): print(f"{task}: no {rsm.name}"); continue lab = BASE_LABEL.get(model, model) + _ck_suffix(ck) pol, cells = [], [] for p in (0, 1, 2): c = ckpt(task, "S0A", p) if not c: continue pol += ["--policy", f"S0As{p}={c}"] cells += ["--cells", f"{lab},{b},{L},{'d1' if L == 1 else 'fold'},128,argmax,S0As{p}"] if not cells: print(f"{task}: no epoch-5000 S0A"); continue for T in TEMPS: for es in (0, 1, 2): cmd = [sys.executable, str(ROOT / "scripts/launch_e1_grid.py"), "--task", task, "--env", ENVS[task], "--model", f"{lab}={rsm}:mlp", "--hop", str(ROOT / f"runs/{task}/hop/gauss/policy_r1.pt"), *pol, *cells, "--num-rollouts", "50", "--horizon", "400", "--eval-seed", str(es), # `plan_temperature`, NOT `plan_temp` -- see WRONG KNOB above. "--extra", f"training.plan_temperature={T}", "--tag", f"TEMPERATURE{str(T).replace('.', 'p')}-es{es}", "--out-dir", str(ROOT / f"runs/{task}/eval_temp2"), "--pack", "3", "--queue", "preemptable"] 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 "missing" in l] print(f" {task} T={T} es{es}:", tail[-1:] or r.stderr.strip()[-160:])
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354#!/usr/bin/env bash# Gate the LeWM trainings on the LeWM smoke (gen_q#268). LSF CPU job -- never the login node.## The LeWM port is already unit-tested on CPU (test_lewm_port.py, 6/6: SIGReg against an independent# numpy implementation, AdaLN-zero identity at init, target-not-detached, read-out round trip). What# those cannot cover is StreamingFrameData against a REAL HDF5 -- the cache-row -> demo-frame mapping# and the episode-resident buffer -- so the trainings wait on scripts/lewm_smoke.sh rather than on a# human. The cluster had 166 jobs pending when this was written, so that wait is hours, not minutes.## Launches ONLY on a clean pass (both "LEWM SMOKE DONE" and "READOUT OK" present, and no traceback).# On a failure it says so and exits without submitting anything: a silent launch of an unvalidated# streaming loader across seven tasks is the failure mode this gate exists to prevent.# Idempotent: status/lewm/launched is the marker, so a restart never double-submits.# usage: lewm_gate.sh [max_iterations] [sleep_seconds]set -uo pipefailROOT=/proj/dmfexp/zwhong/rsm_riseS=$ROOT/status/lewm; mkdir -p "$S"ITERS=${1:-240}; NAP=${2:-300}TASKS="square_expert_play two_piece_expert_suboptimal two_piece_expert_play mug_expert_suboptimalthreading_expert_play two_piece_expert_play_tipping square_sub_20100"
for i in $(seq 1 "$ITERS"); do if [ -f "$S/launched" ]; then echo "[lewm_gate] already launched: $(cat "$S/launched")"; break; fi if [ -f "$S/failed" ]; then echo "[lewm_gate] smoke previously FAILED; not launching"; break; fi ok=0; bad=0 for f in $ROOT/logs/lsf/rr_lewm_smoke.*.out; do [ -f "$f" ] || continue if grep -q "LEWM SMOKE DONE" "$f" && grep -q "READOUT OK" "$f"; then ok=1; fi if grep -qE "Traceback|AssertionError|LEWM SMOKE ERROR" "$f"; then bad=1; fi done for f in $ROOT/logs/lsf/rr_lewm_smoke.*.err; do [ -f "$f" ] && grep -qE "Traceback|AssertionError" "$f" && bad=1 done if [ "$bad" = 1 ] && [ "$ok" = 0 ]; then echo "[lewm_gate] the LeWM smoke FAILED -- not launching. Evidence:" grep -hE -A6 "Traceback|AssertionError" $ROOT/logs/lsf/rr_lewm_smoke.*.out \ $ROOT/logs/lsf/rr_lewm_smoke.*.err 2>/dev/null | head -25 date -u +%FT%TZ > "$S/failed"; break fi if [ "$ok" = 1 ]; then echo "[lewm_gate] smoke PASSED at $(date -u +%FT%TZ) -> launching trainings" for T in $TASKS; do EXHOSTS="p2-r03-n1" "$ROOT/scripts/submit_lewm.sh" "$T" 2>&1 | tail -1 | sed 's/^/ /' done bsub -G grp_preemptable -q preemptable -n 1 -M 16G -r -J rr_lewm_babysit \ -o "$ROOT/logs/lsf/rr_lewm_babysit.%J.out" -e "$ROOT/logs/lsf/rr_lewm_babysit.%J.err" \ "$ROOT/scripts/wm_babysit.sh" lewm 2>&1 | tail -1 | sed 's/^/ /' date -u +%FT%TZ > "$S/launched" break fi echo "[lewm_gate] iteration $i/$ITERS $(date -u +%FT%TZ): smoke not finished yet" sleep "$NAP"doneecho "[lewm_gate] DONE $(date -u +%FT%TZ)"1234567891011121314151617181920212223242526272829303132333435363738394041424344454647#!/usr/bin/env bash# LeWM end-to-end smoke (gen_q#268). GPU LSF job -- never the login node.# test_lewm_port.py already pins the MODEL (SIGReg vs numpy, AdaLN-zero identity, no-detach,# read-out round trip) on CPU. What it cannot cover is the part that touches real data:# A. StreamingFrameData opens the task's source HDF5, maps cache rows to demo frames and asserts# the per-episode frame counts agree -- the alignment that makes LeWM read the same actions and# the same provenance label as every other scorer;# B. a short training runs, the SIGReg term is finite and the embedding does not collapse;# C. the checkpoint it writes loads through lewm_readout and scores candidates at L=1/2/4.set -uo pipefailROOT=/proj/dmfexp/zwhong/rsm_riseCODE=$ROOT/code/gen_q/rsm_liberoSC=$ROOT/runs/_lewm_smoke; rm -rf "$SC"; mkdir -p "$SC"PY=$ROOT/venv_rsm/bin/pythonTASK=${TASK:-two_piece_expert_suboptimal}export OMP_NUM_THREADS=8 PYTHONUNBUFFERED=1 PYTHONPATH=$CODEcd "$CODE"echo "===== A/B. train 120 steps on $TASK ====="$PY train_lewm.py --cache "$ROOT/cache/$TASK" --out "$SC/lewm" --size s --steps 120 \ --batch 16 --resident 12 --refresh-every 4 --eval-every 60 --save-every 0 --eval-rows 64 \ --num-proj 128 --wandb-mode disabled --resume 0 --seed 0 2>&1 \ | grep -E "^\[lewm_data\]|^\[lewm\]" | tee "$SC/train.txt"echo "===== C. read-out ====="$PY - "$SC" <<'PYX'import sys, torchsys.path.insert(0, "/proj/dmfexp/zwhong/rsm_rise/code/gen_q/rsm_libero")import lewm_readoutp = f"{sys.argv[1]}/lewm/ckpt.pt"ck = torch.load(p, map_location="cpu", weights_only=False)print("blob: model=", ck["model"], "| size=", ck["arch"]["size"], "| emb=", ck["arch"]["emb_dim"], "| d_act=", ck["d_act"], "| step=", ck["step"], "| win=", round(float(ck["q_action_winrate"]), 3))dev = "cuda" if torch.cuda.is_available() else "cpu"crit = lewm_readout.load_critic_lewm(p, device=dev)torch.manual_seed(0)B = 8img = torch.randint(0, 255, (B, 6, crit.res, crit.res), dtype=torch.uint8)a = torch.randn(B, crit.d_act).clamp(-1, 1)for mode, L in (("d1", 1), ("fold", 2), ("fold", 4)): q, ql = crit.q((img, None), a, mode=mode, depth=L, gamma=0.99, return_logit=True) q = q.float().cpu() print(f" q[{mode},L={L}] finite={bool(torch.isfinite(q).all())} " f"in[0,1]={bool((q>=0).all() and (q<=1).all())} spread={float(q.max()-q.min()):.5f} " f"mean={float(q.mean()):.4f}")print(" describe:", crit.describe())print("READOUT OK")PYXecho "===== LEWM SMOKE DONE ====="1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189"""THE master results table: every arm per task plus the RSM recipe (reward head, beta, hops, N).Writes docs/MASTER_TABLE.md. All cells: policy epoch 5000, horizon 400, our data."""import syssys.path.insert(0, "/proj/dmfexp/zwhong/rsm_rise/scripts")from verdict_table import cells as _cells_raw, pool, rate, mcnemar, ztest, TASKS, canon_region_key, region_area
_CELL_CACHE = {}
def cells(task): """One snapshot of runs/<task>/eval_*/ per run, shared by every section.
Sections 0, 1 and 5 each re-read the eval tree independently. With ~100 top-up jobs writing JSONs, a cell landing between two of those reads made the sections disagree about the same arm -- the cross-section guard caught exactly that (section 0 ceiling 49.43 vs section 1 headline 51.33 on piece-assembly (Suboptimal)). A results document must be a consistent snapshot of one moment, not a series of reads of a moving directory, or two of its tables will quietly describe different data.
The key carries the task's CANON entry because the alternate-region section deliberately rebinds verdict_table.CANON and re-reads the same task expecting DIFFERENT cells; keying on task alone would hand it the canonical-region snapshot instead. """ import verdict_table as _vtm k = (task, repr(_vtm.CANON.get(task))) if k not in _CELL_CACHE: _CELL_CACHE[k] = _cells_raw(task) return _CELL_CACHE[k]import glob, json as _jsonfrom collections import defaultdict
# trajectory counts, read from the file each policy actually trains on (expert = reward-1 episodes)def _horizon(task): """the rollout horizon every cell of this task is evaluated at, read back from a result file""" for f in glob.glob(f"{ROOT}/runs/{task}/eval_*/*.json"): try: j = _json.load(open(f)) except Exception: continue h = j.get("rollout_horizon") if h: return str(h) return "400"
def _demo_len(task): """median demonstration length, for comparison with the horizon""" import h5py, numpy as _np task = VARIANT_OF.get(task, task) # a flagship variant is a SLICE of the parent's hdf5 src = {"square_expert_play": "data/raw/square_expert_play.hdf5", "square_expert_suboptimal": "data/raw/square_expert_suboptimal.hdf5", "two_piece_expert_play": "data/raw/two_piece_expert_play.hdf5", "two_piece_expert_suboptimal": "data/raw/two_piece_expert_suboptimal.hdf5", "two_piece_expert_play_tipping": "data/raw/two_piece_expert_play_tipping.hdf5", "mug_expert_suboptimal": "data/raw/mug_expert_suboptimal.hdf5", "threading_expert_play": "data/raw/threading_expert_play.hdf5"}.get(task) if not src: return "--" try: with h5py.File(f"{ROOT}/{src}", "r") as h: d = h["data"] L = [d[k]["actions"].shape[0] for k in d if d[k]["rewards"][:].max() > 0] return str(int(_np.median(L))) if L else "--" except Exception: return "--"
_HZ, _DL = {}, {}
def _traj(task): import h5py # A flagship variant has no hdf5 of its own -- it is a cache slice -- so its trajectory # counts are declared in FLAGSHIP_VARIANT rather than counted off disk. if task in VARIANT_TRAJ: return VARIANT_TRAJ[task] src = {"square_expert_play": "data/raw/square_expert_play.hdf5", "square_expert_suboptimal": "data/raw/square_expert_suboptimal.hdf5", "two_piece_expert_play": "data/raw/two_piece_expert_play.hdf5", "two_piece_expert_suboptimal": "data/raw/two_piece_expert_suboptimal.hdf5", "two_piece_expert_play_tipping": "data/raw/two_piece_expert_play_tipping.hdf5", "mug_expert_suboptimal": "data/raw/mug_expert_suboptimal.hdf5", "threading_expert_play": "data/raw/threading_expert_play.hdf5"}.get(task) if not src: return "--" try: with h5py.File(f"{ROOT}/{src}", "r") as h: d = h["data"]; e = sum(1 for k in d if d[k]["rewards"][:].max() > 0) return f"{e} / {len(d)-e}" except Exception: return "--"
_TRAJ = {}
ALT = { # (label, task, pinned region) rows measured in a NON-canonical region, shown separately, never pooled "square-peg (Coverage) — full-table region": ("square_expert_play", {"SquareNut": [[-0.16, 0.16], [-0.2, 0.2]]}),}ALT_IS_FLAGSHIP = set() # alternate rows that belong in section 1 insteadPAPER_REGIME = { "square_sub_paper2": ("square-peg (Suboptimal) — Table IV data regime", "20 / 80", "nut [0,0.12],[-0.225,0]"),}# tasks whose FLAGSHIP row is a data variant; the released-file task drops to secondary with a note.FLAGSHIP_VARIANT = { "square_expert_suboptimal": ("square_sub_20100", "square-peg (Suboptimal)", "20 / 100"),}DEMOTED_NOTE = {"square_expert_suboptimal": "released file, 5x the expert data of the flagship variant"}VARIANT_OF = {v[0]: k for k, v in FLAGSHIP_VARIANT.items()} # square_sub_20100 -> square_expert_suboptimalVARIANT_TRAJ = {v[0]: v[2] for v in FLAGSHIP_VARIANT.values()} # square_sub_20100 -> "20 / 100"NAME = {"square_expert_suboptimal": "square-peg (Suboptimal)", "square_expert_play": "square-peg (Coverage)", "two_piece_expert_suboptimal": "piece-assembly (Suboptimal)", "two_piece_expert_play": "piece-assembly (Coverage)", "mug_expert_suboptimal": "mug-cleanup (Suboptimal)", "threading_expert_play": "threading (Coverage)", "two_piece_expert_play_tipping": "piece-assembly tip (Coverage)"}NAME.update({v[0]: v[1] for v in FLAGSHIP_VARIANT.values()})# ROW LOOP ORDER. The flagship VARIANT is not in TASKS (it has no hdf5 of its own), so before this# fix only sections 0 and 5 -- which remap through _row_identity -- ever read it, and section 1 built# its square-peg (Suboptimal) row from the released 100/100 file and then demoted that row to# secondary. Net effect: the flagship had no square-peg (Suboptimal) row at all once the variant# started producing evaluations and the "still training" placeholder stopped firing. The variant is# emitted as its own row, immediately before its parent, which keeps the released file visible in# secondary without letting it stand in for the corrected split.ROW_TASKS = []for _t, _ in TASKS: _v = FLAGSHIP_VARIANT.get(_t) if _v: ROW_TASKS.append(_v[0]) ROW_TASKS.append(_t)PAPER = {"square_expert_suboptimal": (8.0, 34.0, 41.3, 56.0), "square_expert_play": (18.7, 0.0, 19.6, 50.7), "two_piece_expert_suboptimal": (20.0, 23.3, 35.7, 36.0), "two_piece_expert_play": (14.7, 2.0, 16.3, 70.7), "mug_expert_suboptimal": (31.3, 32.7, 36.7, 40.7), "threading_expert_play": (17.3, 0.0, 9.8, 22.7), "two_piece_expert_play_tipping": (0.0, 0.0, 8.0, 51.3)}
def flat(d): o = defaultdict(list) for (P, ps, es), v in d.items(): o[(ps, es)] += v return o
def parse(recipe): """'M@best b0.95 L1 N128' -> (model@ckpt, beta, hops, N).
BOTH GRAMMARS (gen_q#267, 2026-09-23). This matched only the fold key `b<beta> L<depth> N<n>`, so every COIN-CHAIN arm printed `? ? ?` in the beta/hops/N columns -- visible in the 11:52Z build on square-peg (Coverage), the one row whose flagship arm was already a chain arm. With section 1 now chain-only that would have blanked the configuration columns of the whole table. A chain key is `b<beta> CH<cap> N<n> P<particles> <prob|logit>`, whose length parameter is the CAP, not a depth -- it is reported as `cap <L>` with the particle count and read-out beside it, because for a chain those two are part of the estimator and a top-up that changed them would be a different arm. """ import re m = re.match(r"(\S+) b([0-9.]+) L(\d+) N(\d+)", recipe or "") if m: return m.groups() m = re.match(r"(\S+) b([0-9.]+) CH(\d+) N(\d+)(?: P(\d+))?(?: (prob|logit))?(?: F(\d+))?", recipe or "") if m: # FLOW STEPS travel with the arm too (gen_q#275 via BETA_PATTERNS): the number of Euler steps # per successor draw changes what a SAMPLE is, so a cell at F4 is a different estimator from # one at the default F8 and must be named as such wherever the configuration is printed. _extra = "".join([" P%s" % m.group(5) if m.group(5) else "", " %s" % m.group(6) if m.group(6) else "", " F%s" % m.group(7) if m.group(7) else ""]) return (m.group(1), m.group(2), "cap %s%s" % (m.group(3), _extra), m.group(4)) return ("?", "?", "?", "?")
FLAG, SEC, ALTREW, ORCROW, VERLOW = [], [], [], [], []# ---- SECTION 0 (owner 2026-09-21): the SINGLE-ACTOR flagship first. "the flagship must use a single# actor for RSM for fair comparisons against IDQL and RISE ... we must make sure the reason RSM is winning# is not because it is allowed to argmax actors over tasks depending on who is winning." RSM proposes# from the RISE actor on every task; built by flagship_latex.build with RSM_PROPOSER pinned.def _missing_note(rows): """Which flagship tasks have no RISE-actor RSM arm, named from the data.
This sentence used to be hardcoded and went stale: it said "mug: relaxed-criterion re-evaluation running" after mug had a full 3x3 and was printing 12.7 in the table right above it. A caption that states which rows are missing must be computed from the rows, or it becomes a false claim the moment a row lands. """ from verdict_table import TASKS as _T have = {r["label"] for r in rows} import flagship_latex as _F absent = [_F.NICE.get(nm, nm) for _, nm in _T if _F.NICE.get(nm, nm) not in have] if not absent: return "Every flagship task has RISE-actor RSM cells." return ("No RISE-actor RSM cells yet for: " + ", ".join(absent) + " (its actor is still training at the time of generation).")
def _single_actor_section(): import re as _re, os as _os _os.environ["RSM_PROPOSER"] = "RISE policy" import flagship_latex as _FL _FL.RSM_PROPOSER = "RISE policy" rows, counts = _FL.build(cells) def strip(x): x = x.replace("{\\pm}", "±").replace("^{\\dagger}", "†").replace("^{*}", "*").replace("_{(", "₍").replace(")}", "₎").replace("$", "") x = _re.sub(r"\\mathrm\{([^}]*)\}", r"\1", x) # \mathrm{n/a} must not leak into markdown # \textit{...} reaches here now that the RSM column is CHAIN-ONLY and an incomplete row prints # its launch state (`pend k/9` / `launched` / `queued`) instead of a superseded fold number. x = _re.sub(r"\\textit\{([^}]*)\}", r"*\1*", x) return _re.sub(r"\\mathbf\{([^}]*)\}", r"**\1**", x) out = ["## 0. Single-actor flagship — RSM proposes from the RISE actor on every task", "", "RISE and RSM differ only in the scorer (same S0A candidates, N=128); IDQL uses its own co-trained actor. " "No per-task proposer choice. mean ± SE across seeds (subscript = seed count); Δ = margin over the strongest " "baseline (* p<0.05). RISE-g = the RISE actor sampled once. " + _missing_note(rows) + " " # READ-OUT SPLIT (gen_q#267; the threading three-way disagreement, 2026-09-23). The RSM # column used to be r["rsm"], the maximum over BOTH read-outs -- on threading the retired # deterministic fold (33.4) -- printed directly above a margins table whose RSM column was # the coin-chain arm (21.6), with nothing saying the two were different estimators. The # headline column is now CHAIN-ONLY and carries its own Δ and its own bolding; the fold # maximum is kept, but only in a column that says so. "**RSM is the coin-terminated β-chain read-out** (gen_q#267), the same column the paper's " "`tab:flagship` prints; a row whose chain cells have not all landed prints its launch state " "rather than a fold number. The last column is the RETIRED deterministic truncated fold, the " "maximum over that read-out's arms, shown only so the change is visible -- it is not a " "flagship number and its per-row (β, L) and retained mass are in `tab:flagship_fold`. The two " "columns are different estimators on the same checkpoints, so they are not comparable as " "seeds of one method.", "", "| Task | BC | BC-u | RISE-g | IDQL | RISE | IFQL | RSM (ours, RISE actor) | Δ | RSM-fold (retired) |", "|---|---|---|---|---|---|---|---|---|---|"] for r in rows: out.append("| " + " | ".join([r["label"], *map(strip, r["base_chain"]), strip(r["rsm_chain_disp"]), strip(r["db_chain"]), # FOLD-ONLY, and never bolded. This used to print `rsm`, the # maximum over BOTH read-outs, so a column headed "RSM-fold # (retired)" showed a CHAIN number wherever the chain arm won the # row -- it did on Square (Cov.): 20.9 (chain) where the fold's own # best arm is 17.6. `rsm_fold_disp` is selected by the same rule # restricted to fold recipes. De-bolding stays: the retired number # is context, never a winner, and bolding it put two winners in the # threading row under two different estimators. _re.sub(r"\*\*([^*]*)\*\*", r"\1", strip(r["rsm_fold_disp"]))]) + " |") # COMPUTED, NOT HARDCODED. The first draft of this sentence named threading's two numbers # (21.6 paired vs 22.8 pooled); the very next build made both 24.4 as more chain cells landed, so a # hardcoded pair would already have been a false claim -- the same failure _missing_note exists to # stop. Name only the rows where the two columns actually differ, from the rows. def _lead(x): """first number in a rendered cell, or None -- the two columns print different decorations (the margins cell has no +-SE), so compare the VALUE, not the string.""" m = _re.search(r"-?\d+\.\d+", strip(x or "")) return None if not m else round(float(m.group(0)), 1) _dif = [r["label"] for r in rows if _lead(r.get("ar")) is not None and _lead(r.get("rsm_chain_disp")) is not None and _lead(r["ar"]) != _lead(r["rsm_chain_disp"])] _difnote = ("" if not _dif else " It differs from the headline column on: " + ", ".join(_dif) + ".") out += ["", "**Same-actor margins** (paired cells, RISE-actor proposer): greedy / RISE critic / RSM / vs greedy / vs RISE. " "RSM here is the SAME chain read-out as the column above, but recomputed on the cells the three " "columns share, so it can differ from the headline number wherever greedy or the RISE critic is " "missing a seed." + _difnote, "", "| Task | RISE-g | RISE | RSM (chain) | vs. RISE-g | vs. RISE |", "|---|---|---|---|---|---|"] for r in rows: if r["ar"] != "--": out.append("| " + " | ".join([r["label"], strip(r["ag"]), strip(r["aq"]), strip(r["ar"]), strip(r["adg"]), strip(r["adq"])]) + " |") _os.environ.pop("RSM_PROPOSER", None); _FL.RSM_PROPOSER = None return out + [""]
L = ["# Master results table", "", *_single_actor_section(), "*horizon* is the rollout budget in environment steps, with the median expert demonstration length in " "parentheses: a policy slower than its demonstrator times out. " "**Column meanings.** *vs same policy, no selection* is the paired difference against that very policy rolled out " "greedily, i.e. what best-of-N selection adds. *vs random-candidate control* draws the same N candidates from the " "same proposer and picks one at random (permuted scores); it separates a real value ranking from the benefit of " "merely drawing N candidates. NOTE (audit 2026-09-21): on 6/7 flagship rows the permuted run used a different " "successor configuration from the reported arm, so it is a random-candidate control, not a shuffle of the " "reported arm's own scores. " "*IDQL critic, same proposer* is IDQL's own critic scoring candidates drawn from the SAME policy the RSM arm " "selects from, so only the scorer differs -- RISE by contrast keeps its own policy, because its proposer is part " "of that method. *vs BEST baseline* compares against the strongest of BC, BCU, IDQL and RISE on that task. " "Every row states the **evaluation region**: the box the object is randomly placed in at reset. Success rates are " "only comparable within a region -- square-peg BC-expert is 2.6 % over the coverage box and 10.9 % over the much " "smaller `square_image_ood` box -- so the loaders never pool two regions and `docs/REGIONS.md` lists every region " "any number was measured in. All cells are policy epoch 5000, horizon 400, on our data, 3 training seeds x 3 eval seeds unless the n says " "otherwise. **BC** = diffusion policy on the expert demonstrations; **BCU** = on expert + non-expert; " "**RISE** = RISE's policy + its IQL critic choosing among 128 candidates; **IDQL** = RISE without augmentation " "or the Lipschitz penalty. **RSM** = our successor-model value choosing among N candidates from the named " "proposer. *head* is the reward the successor model scores: `membership` is RISE's own 0/1 expert label (what " "every baseline also trains on), `progress` is our shaped label from privileged sim state. *beta* is the " "geometric horizon parameter of the successor flow and *hops* the number of composed flow steps in the " "read-out. Deltas are exact paired McNemar tests against the same proposer's greedy rollouts and against the " "random-candidate control; a **win** needs both below p = 0.05.", "", "| task | expert / non-expert traj | horizon (median expert demo) | eval region (object start box) | BC | BCU | IDQL | RISE | **RSM** | throughput | mean steps | seeds (train x eval) | per seed | episodes/cell | n total | proposer | head | beta | hops | N | IDQL critic, same proposer | vs same policy, no selection | vs shuffled-score control | vs BEST baseline | verdict |", "|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|"]import subprocess as _spdef _idql_status(task): """empty IDQL cell -> say what is happening instead of a bare dash""" try: live = _sp.run(["bjobs", "-noheader", "-o", "job_name"], capture_output=True, text=True, timeout=25).stdout except Exception: live = "" n = sum(1 for l in live.splitlines() if l.strip() == f"rr_idql_{task}_s0" or l.strip().startswith(f"rr_idql_{task}_s")) eps = [] for d in glob.glob(f"{ROOT}/runs/{task}/policy/S0Aidql_seed*/rolling"): e = sorted(int(re.search(r"epoch_(\d+)", x).group(1)) for x in glob.glob(d + "/*.pth")) if glob.glob(d + "/*.pth") else [] if e: eps.append(e[-1]) if not eps and not n: return "not launched" return f"*training, ep {min(eps) if eps else 0}-{max(eps) if eps else 0}/5000, {n} running*"
def _idql_interim(task): """best IDQL number we have at ANY epoch < 5000, so the column is not just a dash""" best = None for f in glob.glob(f"{ROOT}/runs/{task}/eval_*/*.json"): try: j = _json.load(open(f)) except Exception: continue m = re.search(r"/policy/S0Aidql_seed(\d)/.*epoch_(\d+)", j.get("eval_ckpt", "") or "") if not m or not j.get("num_episodes"): continue o = j.get("planner_overrides") or {} if (o.get("plan_n") or 1) > 1: continue # greedy IDQL policy only ep = int(m.group(2)) if best is None or ep > best[0]: best = (ep, 100 * j["success_rate"], j["num_episodes"]) return None if not best else f"{best[1]:.1f} @ep{best[0]}"
import re, globimport json as _jsonROOT = "/proj/dmfexp/zwhong/rsm_rise"import verdict_table as _vt0_vt0.CANON["square_expert_play"] = ("small", {"SquareNut": [[-0.115, -0.09], [-0.12, 0.11]]})_vt0._AUTO.pop("square_expert_play", None)REG = {}for task in ROW_TASKS: k = canon_region_key(task) or "env default" for part in k.split(";"): if part.startswith(("SquareNut=", "Piece1=", "Needle=")) or "=" not in part: REG[task] = part.replace("SquareNut=", "nut ").replace("Piece1=", "piece1 ").replace("Needle=", "needle ") break REG.setdefault(task, k[:40])IDQL_NOTE = {}# READ-OUT PREDICATE, imported once and shared by every section of this file (gen_q#267). The arm-key# grammar ("CH<cap>" = coin chain, "L<d>" = retired fold) is defined by the table generator, so the# classifier is imported rather than re-derived: the markdown and the LaTeX must never disagree about# which arm is which estimator. Imported HERE, above the row loop, because section 1's selection needs# it and the later import at the upper-bound section was too late for that.from flagship_latex import _recipe_is_chain as _F_is_chain_selfrom flagship_latex import _readout_of as _F_readout# GRID COMPLETENESS TIER (gen_q#267, 2026-09-23 19:2xZ). Run 10 fixed this in the LaTeX generator# (`flagship_latex._seed_tier_key`) after a 7-of-9-cell arm displaced a complete 9-of-9 one in the# flagship maximum. THIS file was not fixed, and it is the file that writes docs/MASTER_TABLE.md --# the document the orchestrator and the issue threads read. Measured on the 18:39Z build: section 1# printed two_piece_expert_suboptimal at **50.0** from an arm with **3 of 9 cells**# (E1-Ms100k-R0.98-11-ch-N128-argmax-ONACTORP8pr; 3 policy seeds x 1 eval seed) against the complete# 9/9 arm's 45.1, and mug_expert_suboptimal at **23.6** from a **5 of 9** arm (ONS3H1P16lo) against# the complete 19.8 -- and both printed with the same `(3 seeds)` annotation as a full grid, because# `ns >= 2` counts POLICY seeds and says nothing about how many of the 9 cells landed. Worse, `rate()`# pools EPISODES, so on an unbalanced grid the seed with more cells is weighted more: the same five mug# cells read 23.6 pooled and 21.1 as a mean over policy seeds. So: completeness outranks rate here too.from flagship_latex import _seed_tier_key as _F_tierFOLD_EXCLUDED = {} # task -> (n fold arms excluded from the section-1 flagship, their best score)CHAIN_EXCLUDED = {} # task -> (n chain arms excluded for gamma/degeneracy, their best score) -- NOT fold_ub_chain_excl = {} # display label -> n chain arms excluded from section 0's retired fold columnsSEARCH = {} # task -> (n_arms_searched, best, runner_up)ALT_ROW = {} # task -> best completion-reward (env success) armORACLE_ROW = {} # task -> best progress-head arm (DISQUALIFIED, dense privileged reward)NAME_SUFFIX = {}_TCACHE = {} # task -> (episodes by arm, horizon by arm) for the throughput column_FLAG_VAL = {} # display label -> the RSM value section 1 prints, for the section-0 cross-check_FLAG_MAX = {}_CAND_MAX = {}_FLAG_CTRL = [] # the selection verdict of each flagship row, for the section-1 headline countagg = []for task in ROW_TASKS: c = cells(task) b = {} for lab, pred in (("BC", lambda a, p: a[0] == "greedy" and p == "BC-expert"), ("BCU", lambda a, p: a[0] == "greedy" and p == "BC-unified"), # RISE actor sampled once, no critic (audit 2026-09-21 C2): a baseline the delta and # the routing rule must see, printed in the paper table as RISE-g. ("RISEg", lambda a, p: a[0] == "greedy" and p == "RISE policy"), ("IDQL", lambda a, p: a[0] == "critic" and p == "IDQL policy"), ("RISE", lambda a, p: a[0] == "critic" and p == "RISE policy")): g = pool(c, pred); b[lab] = rate(g)[0] if g else None _ro = [(_json.load(open(_f))) for _f in glob.glob(f"{ROOT}/runs/{task}/eval_riseonline/*.json")] _ro = [(j["success_rate"] * j["num_episodes"], j["num_episodes"]) for j in _ro if j.get("num_episodes")] if _ro: _v = 100 * sum(a for a, _ in _ro) / sum(n for _, n in _ro) if b.get("RISE") is None or _v > b["RISE"]: b["RISE"] = _v if b.get("IDQL") is None: itr = _idql_interim(task) b["IDQL"] = None IDQL_NOTE[task] = (itr + " *(interim)*") if itr else _idql_status(task) # REWARD-MATCHING RULING 2026-09-20. RISE's reward is PROVENANCE, not outcome: their # relabel_rewards.py writes a constant over every frame of an episode (1 for the expert file, # 0 for the non-expert file) and robomimic/algo/iql_diffusion.py consumes that field unchanged # (`q_target = rewards + (1-dones)*discount*target_vf_pred`). So: # membership -- the SAME provenance label the RISE and IDQL critics see. Reward-matched. FLAGSHIP. # completion -- per-frame env success. A DIFFERENT reward from the paper's, not a correction to # it; a legitimate alternative, reported as its own table. # progress -- dense hand-designed potential over privileged sim state. Not matched to anything. # DISQUALIFIED (see scripts/train_progress_head.py banner). HEAD_SECTION = {"membership": "flagship", "completion": "altreward", "progress": "oracle"} best = prov = None _uncapped_max = None # max over EVERY chain membership arm, ignoring both the seed split and the # grid-completeness tier. Section 0's CEILING is exactly that quantity (the # owner's definition: "the best mean across the seeds done for a config"), and # the cross-section guard below compares the two. Before the completeness tier # this was recoverable as max(best, prov); now that the headline refuses partial # arms it is not, and computing it here keeps the guard comparing like with like # instead of firing on a difference the tier creates on purpose (it fired on # square-peg (Sub.): ceiling 55.33 vs headline 51.56, job 1885157). _verified = [] # every arm that qualifies for the flagship, for the search-size disclosure _fold_seen = [] # (score, seeds) of the membership arms EXCLUDED for being the retired fold _chain_excluded_seen = [] # (score, seeds) EXCLUDED for being a chain arm at the wrong gamma / cap 0 alt = orc = None # SORTED, not a set: three mug arms sit at exactly 12.0% (6/50 each), and iterating a set made the # argmax -- and so the recipe printed in the paper table -- depend on hash order. Regenerating with # unchanged data could name a different arm. Sorted iteration plus the (score, episodes) comparison # below makes the choice a function of the data alone: higher score wins, an exact tie goes to the # arm with more episodes behind it, and a full tie resolves by name. for (a, p) in sorted({(a, p) for (a, p, _, _) in c if a[0].startswith("rsm:")}): g = pool(c, lambda x, q, A=a, P=p: x == A and q == P) sr, n = rate(g); ns = len({ps for (_, ps, _) in g}) sect = HEAD_SECTION.get(a[0].split(":")[1], "oracle") if sect == "altreward": if ns >= 2 and (alt is None or sr > alt[0]): alt = (sr, n, a, p, g) continue if sect == "oracle": if ns >= 2 and (orc is None or sr > orc[0]): orc = (sr, n, a, p, g) continue # READ-OUT SPLIT, section 1 (gen_q#267; found 2026-09-23 11:55Z by reading the generated # markdown rather than the generator). `sect == "flagship"` admitted EVERY membership arm at # ANY read-out, so this section -- the master table's headline comparison, the one pasted into # issues -- printed the RETIRED deterministic fold under a bare "**RSM**" heading with its own # `verdict` column. Measured on the 11:52Z build: threading printed **33.0** with `hops 1`, # i.e. the L=1 fold arm, four hours after the 33.4 fold number was publicly RETRACTED on #267 # (the chain reads 25.8, delta -0.6, NO DECISION) -- and it was marked **win**. Mug printed # 22.2 (chain 19.1), piece (Cov.) 50.3 (46.0), piece-tip 6.9 (5.3). Sections 0 and 5 and every # LaTeX table were already read-out scoped; this one was missed because its arm loop is a # different piece of code from the one those share. # The flagship section now ranges over CHAIN arms only, so a fold number can never take the # row; the fold maxima stay in section 0's columns that name them retired and in # tab:ablation_betarec. A task with no chain arm falls through to the existing "no best and no # prov" branch, which prints dashes -- never a fold number standing in for a chain number. # AND "NOT CHAIN" IS NOT THE SAME AS "FOLD" (2026-09-24, run 20). Since run 19 the chain # predicate also EXCLUDES a chain arm at the wrong gamma or with a degenerate cap 0, so # `not _F_is_chain_sel(...)` is true for three different things: a genuine fold arm, an # off-gamma chain arm and a zero-recursion chain arm. Bucketing all three as "fold" is the # mirror of the #267 defect this section exists to prevent -- a CHAIN number standing in as a # FOLD number -- and it was live in the retired columns (Square (Cov.)'s fold ceiling read 20.0 # from `L40@best b0.95 CH0`, a chain key). So the retired bucket is now the POSITIVE test # `_readout_of(...) == "fold"`; an excluded chain arm is counted separately and belongs to # NEITHER column, which is what "excluded" has to mean if the exclusion is to be believed. if not _F_is_chain_sel(a[1]): if _F_readout(a[1]) == "fold": _fold_seen.append((sr, ns)) else: _chain_excluded_seen.append((sr, ns)) continue if _uncapped_max is None or sr > _uncapped_max: _uncapped_max = sr if ns >= 2: _verified.append(sr) if best is None or _F_tier(sr, n, ns, len(g)) > _F_tier(best[0], best[1], len({ps for (_, ps, _) in best[4]}), len(best[4])): best = (sr, n, a, p, g) else: # single-seed: only surfaced if it beats the qualifying row if prov is None or _F_tier(sr, n, ns, len(g)) > _F_tier(prov[0], prov[1], len({ps for (_, ps, _) in prov[4]}), len(prov[4])): prov = (sr, n, a, p, g) ALT_ROW[task] = alt; ORACLE_ROW[task] = orc FOLD_EXCLUDED[task] = (len(_fold_seen), max([x[0] for x in _fold_seen], default=None)) CHAIN_EXCLUDED[task] = (len(_chain_excluded_seen), max([x[0] for x in _chain_excluded_seen], default=None)) # The flagship is a MAXIMUM over arms, where an arm is # (successor model, head, beta, hops, read-out, candidate count, proposer). Record how many arms that # maximum ranged over and what the runner-up scored, so the row is never read as a default configuration. # See docs/PROPOSER_SELECTION.md: best-to-second gaps are 0.0-5.7 pts (a plateau, which is what a real # effect looks like) while best-to-median gaps reach 16 pts (which is why the search size must be stated). _verified.sort(reverse=True) SEARCH[task] = (len(_verified), _verified[0] if _verified else None, _verified[1] if len(_verified) > 1 else None) f = lambda v, _t=task: (IDQL_NOTE.get(_t, "--") if v is None else f"{v:.1f}") def emit(rec, status, tmp=False, dest=None): sr_, n_, a_, p_, g_ = rec head_ = a_[0].split(":")[1] # ORACLE REWARD (ruling 2026-09-20). The `progress` head regresses a DENSE hand-designed # potential over privileged simulator state (distance to object, distance to target), while # BC/BCU use no reward and RISE/IDQL critics use the dataset's 0/1 expert-membership label. # A progress row is therefore NOT reward-matched to anything it is printed beside and may not # be quoted as a result. See docs/WHY_TASKS_DIFFER.md and the banner in # scripts/train_progress_head.py. Marked here so the disqualification travels with the number. _m, beta_, hops_, N_ = parse(a_[1]) if head_ == "progress": head_ = "progress **[ORACLE: dense privileged reward, NOT reward-matched, do not quote]**" # THROUGHPUT (user 2026-09-20): success_rate * horizon / mean policy timesteps -- successes per # horizon-worth of environment steps, so a policy that finishes sooner scores higher than one # with the same success rate that only just makes it. Computed from `first_success_step`, NOT # from `length`: every eval sets end_on_success but the rollout loop runs to the horizon anyway, # so `length` is the constant 400 on successes and failures alike. See scripts/throughput.py. _thr = _thr_steps = None try: from throughput import collect as _tcol, arm_throughput as _tarm _td, _th = _TCACHE.setdefault(task, _tcol(task)) _tk = (a_[1], p_) if _tk in _td: _tr = _tarm(_td[_tk], _th[_tk]) if _tr: _thr, _thr_steps = _tr[2], _tr[1] except Exception: pass gg_ = flat(pool(c, lambda x, q, P=p_: x[0] == "greedy" and q == P)) gp_ = flat(pool(c, lambda x, q, P=p_, H=head_: x == ("permuted", H) and q == P)) mg_, mp_ = mcnemar(flat(g_), gg_), mcnemar(flat(g_), gp_) dd = lambda m: "--" if not m else f"{m['a']-m['b']:+.1f} (p={m['p']:.3f})" _sp_rows = [] for _f in glob.glob(f"{ROOT}/runs/{task}/eval_sameprop/*.json"): try: _j = _json.load(open(_f)) except Exception: continue _o = _j.get("planner_overrides") or {} if (_o.get("rsm_backend") != "iql") or not _j.get("num_episodes"): continue _m = re.search(r"/policy/(S0A|S0B|S3H1)_seed(\d)/", _j.get("eval_ckpt", "") or "") if not _m or _m.group(1) != p_.replace("BC-expert", "S3H1").replace("BC-unified", "S0B").replace("RISE policy", "S0A"): continue _sp_rows.append((_j["success_rate"] * _j["num_episodes"], _j["num_episodes"])) idql_sp = (f"{100*sum(a for a,_ in _sp_rows)/sum(bn for _,bn in _sp_rows):.1f}" if _sp_rows else "--") _bb = [v for v in b.values() if isinstance(v, (int, float))] _bl = [k for k, v in b.items() if isinstance(v, (int, float)) and v == max(_bb)] if _bb else [] vsb = "--" if not _bb else f"{sr_-max(_bb):+.1f} vs {_bl[0]}" ps2 = defaultdict(lambda: [0, 0]) for (P, s2, e2), v in g_.items(): ps2[s2][0] += sum(v); ps2[s2][1] += len(v) per = "/".join(f"{100*x/y:.0f}" for _, (x, y) in sorted(ps2.items())) ne_ = len({e2 for (_, _, e2) in g_}) # THE VERDICT IS ABOUT SELECTION, NOT ABOUT THE BASELINE. The question a reviewer asks first is # "is the gain from your scorer or from the policy you sampled from?", and the two controls answer # it: `no selection` re-runs the SAME policy greedily, `shuffled` picks one of N candidates at random (a # permuted order. Beating BC while losing to your own greedy control is not evidence for the # method. This used to read `elif status: v_ = status`, so the seed caveat REPLACED the verdict and # four of seven flagship rows stated their seed count and nothing about whether selection helped -- # including piece-assembly (Coverage), which is -0.5 against its own no-selection control. The # control verdict is now always stated and the caveat is appended to it. okk = mg_ and mp_ and mg_["p"] < .05 and mp_["p"] < .05 and mg_["a"] > mg_["b"] and mp_["a"] > mp_["b"] if mg_ and mg_["a"] < mg_["b"]: _ctrl = "**below its own no-selection control**" elif okk: _ctrl = "**win**" elif mg_ and mg_["p"] < .05 and mg_["a"] > mg_["b"]: _ctrl = "control undecided" else: _ctrl = "no gain" if tmp: v_ = f"{_ctrl}; **TEMPORARY** -- only {len(ps2)} training seed(s), 3-seed verification running" elif status: v_ = f"{_ctrl}; {status}" else: v_ = _ctrl # FAIRNESS RULE (user, 2026-09-20): every method printed in one table must see the SAME reward, # except BC/BCU which have none by construction. The RISE and IDQL critic columns are trained on # the provenance label, so they may ONLY be printed beside a membership-head RSM arm. In the # env-success and oracle sections their numbers would be a different-reward comparison, so they # are suppressed rather than shown, and the cell says why. # Suppress the critic columns only where the REWARD differs (sections 2 and 3). Section 1b is # the same provenance reward as section 1 -- a weaker configuration, not a different reward -- # so its critic numbers are matched and must be shown. _offreward = dest is not None and dest is not VERLOW _unmatched = "*n/a: critic not retrained on this reward*" _bIDQL = _unmatched if _offreward else f(b['IDQL']) _bRISE = _unmatched if _offreward else f(b['RISE']) # FLAGSHIP ADMISSION (user 2026-09-20): "for flagship we can admit the best numbers and config # if seed needs to be refilled -- we top up". The best matched-reward arm belongs in the # flagship WITH its seed count stated, not buried in secondary; the seeds get topped up. # Previously any row carrying a `status` string was routed to SEC, which sent every # single-seed maximum to secondary -- e.g. piece-assembly suboptimal's 58.0 sat in section 4 # while the flagship showed the 29.4 arm that merely happened to have three seeds. # Match the CURRENT best-arm status text. This used to key on "single-seed maximum"; when the # status was reworded to "BEST ARM at n/3 training seeds" the check silently stopped matching # and every under-seeded WINNING arm was routed to secondary, leaving the flagship with one row. _underseeded = bool(status) and "BEST ARM at" in str(status) _dest = dest if dest is not None else ( FLAG if (_underseeded or not status) and task not in NAME_SUFFIX else (SEC if (status and not tmp) or task in NAME_SUFFIX else FLAG)) if _dest is FLAG: _FLAG_VAL[f"{NAME[task]}{NAME_SUFFIX.get(task,'')}"] = sr_ _FLAG_MAX[f"{NAME[task]}{NAME_SUFFIX.get(task,'')}"] = _CAND_MAX.get(task, sr_) _FLAG_CTRL.append(_ctrl) _dest.append(f"| {NAME[task]}{NAME_SUFFIX.get(task,'')} | {_TRAJ.setdefault(task, _traj(task))} | {_HZ.setdefault(task, _horizon(task))} ({_DL.setdefault(task, _demo_len(task))}) | {REG.get(task,'?')} | {f(b['BC'])} | {f(b['BCU'])} | {_bIDQL} | {_bRISE} | **{sr_:.1f}** | {'--' if _thr is None else f'{_thr:.3f}'} | {'--' if _thr_steps is None else f'{_thr_steps:.0f}'} | " f"{len(ps2)}x{ne_} | {per} | {n_//max(len(ps2)*ne_,1)} | {n_} | {p_} | {head_} | {beta_} | {hops_} | {N_} | {idql_sp} | {dd(mg_)} | {dd(mp_)} | {vsb} | {v_} |") # DEMOTION BEFORE THE EARLY RETURN (2026-09-23). The suffix was set ten lines BELOW this branch, # so a task with a FLAGSHIP_VARIANT that has no qualifying arm of its own left through here # UNRELABELLED and its 100/100 released-file row landed in section 4 under the bare flagship label, # while the 20/100 variant held the same label in section 1 -- which is exactly what the # label/dataset guard below exists to catch, and it duly fired ("square-peg (Suboptimal)" carrying # 20/100 and 100/100). Harmless while every task had an arm at ANY read-out; the chain-only # selection above is what made the branch reachable. _fv0 = FLAGSHIP_VARIANT.get(task) if _fv0: _dn00 = DEMOTED_NOTE.get(task, "") NAME_SUFFIX[task] = f" — {_dn00}" if _dn00 else " — released file" if not best and not prov: if task in VARIANT_OF: continue # parent emits a "still training" placeholder for it # COLUMN COUNT (ORCH run 57, 2026-09-23 12:20Z): this dashes-only placeholder printed 22 fields # against a 25-field header, so the column guard below rejected the whole document the moment # the 12:09 demotion fix made this branch emit a row. Dashes only -- no number changes. SEC.append(f"| {NAME[task]}{NAME_SUFFIX.get(task,'')} | {_TRAJ.setdefault(task, _traj(task))} | {_HZ.setdefault(task, _horizon(task))} ({_DL.setdefault(task, _demo_len(task))}) | {REG.get(task,'?')} | {f(b['BC'])} | {f(b['BCU'])} | {f(b['IDQL'])} | {f(b['RISE'])} | -- | -- | -- | -- | -- | -- | -- | -- | -- | -- | -- | -- | -- | -- | -- | -- | -- |") continue _fv = FLAGSHIP_VARIANT.get(task) # DEMOTION IS UNCONDITIONAL (bug found 2026-09-20). This used to fire only while the variant had # NO evaluations, so the moment square_sub_20100 produced its first cell the released 100/100 file # stopped being relabelled and reappeared in the FLAGSHIP section under the flagship label -- while # section 0, which reads the variant, showed the 20/100 numbers for the same row name. Two datasets, # one label, three sections disagreeing. The suffix must be set whenever a variant exists. if _fv: _dn0 = DEMOTED_NOTE.get(task, "") NAME_SUFFIX[task] = f" — {_dn0}" if _dn0 else " — released file" if _fv and not glob.glob(f"{ROOT}/runs/{_fv[0]}/eval_*/*.json"): try: live = _sp.run(["bjobs", "-noheader", "-o", "job_name"], capture_output=True, text=True, timeout=25).stdout except Exception: live = "" nj = sum(1 for l in live.splitlines() if _fv[0].replace("square_sub_", "sq") in l or _fv[0] in l) eps = [max([int(re.search(r"epoch_(\d+)", x).group(1)) for x in glob.glob(d + "/*.pth")] or [0]) for d in glob.glob(f"{ROOT}/runs/{_fv[0]}/policy/*/rolling")] note = (f"*training, ep {min(eps)}-{max(eps)}/5000, {nj} jobs*" if eps else (f"*launched, {nj} jobs, no checkpoint yet*" if nj else "*not launched*")) FLAG.append(f"| {_fv[1]} | {_fv[2]} | {_HZ.setdefault(task, _horizon(task))} ({_DL.setdefault(task, _demo_len(task))}) | {REG.get(task,'?')} | {note} | {note} | {note} | {note} | " f"-- | -- | -- | -- | -- | -- | -- | -- | -- | -- | -- | -- | -- | -- | -- | -- | -- |") # a verified arm (>=2 training seeds) always wins the flagship row; an unverified arm is promoted only when # the task has no verified arm at all. Single-seed maxima are systematically optimistic: on 2026-09-20 the # 3-seed verification moved square subopt 77.0 -> 69.8, threading 22.0 -> 14.4 and mug 18.0 -> 7.8. # FLAGSHIP = THE VICTORY CASE (user 2026-09-20: "flagship is attempting to show rsm victory under # fair conditions"). One row per task: the BEST matched-reward arm, whatever its seed count, with # that count stated. A verified arm that is NOT the best is evidence about a weaker # configuration, not about the method's ceiling, so it moves to its own section rather than # sitting beside the headline and dragging the reader's eye to the lower number. _cands = [x for x in (best, prov) if x] if _cands: # ROUTING RULE (user 2026-09-20): "prefer winning but seed-deficient over clearly losing". The # converse also holds: a VERIFIED (>=2-seed) arm that beats every baseline is never displaced by # a newer single-seed maximum a few tenths higher -- on 2026-09-21 fresh 1-seed cells pushed # square coverage 12.4(3) -> 12.7(1) and threading 18.6(3) -> 20.0(1) out of the flagship, which # is the winner's curse the seed count exists to prevent. The single-seed arm takes the row # only when no verified arm wins. _blmax = max([v for v in b.values() if v is not None] or [float("-inf")]) # the max-over-arms, which section 0 calls the ceiling -- unrestricted on purpose, see _uncapped_max _CAND_MAX[task] = _uncapped_max if _uncapped_max is not None else max(x[0] for x in _cands) if best and best[0] > _blmax: _top = best else: _top = max(_cands, key=lambda x: x[0]) _other = next((x for x in _cands if x is not _top), None) _nseed = len({ps for (_, ps, _) in _top[4]}) # CELLS, NOT ONLY SEEDS (gen_q#267, 2026-09-23 run 13). This caveat counted POLICY SEEDS only, so # an arm with all three policy seeds but one eval seed each -- 3 of the 9 (policy seed x eval seed) # cells, 150 of 450 episodes -- printed with NO caveat at all, indistinguishable from a full grid. # That is exactly how the 18:39Z build presented piece-assembly (Sub.) at 50.0 (3/9 cells) and # mug-cleanup (Sub.) at 23.6 (5/9 cells) as finished results. The completeness TIER above now # keeps such an arm out of the row whenever a complete one exists; when every candidate is partial # (or the routing rule below promotes a seed-deficient winner on purpose), the row must at least # say so, and say it in cells. _ncell = len(_top[4]) _demoted = task in NAME_SUFFIX # a DIFFERENT dataset from the flagship variant of this task emit(_top, None if (_nseed >= 3 and _ncell >= 9) else f"*BEST ARM at {_nseed}/3 training seeds and {_ncell}/9 grid cells; top-up running. " f"An arm is selected on a COMPLETE 3x3 grid whenever one exists (`flagship_latex._seed_tier_key`); " f"this row had none. Historical regression on this " f"project when single-seed maxima were verified: -7.2, -7.6, -10.2 pts.*") # Section 1b holds ONE thing: an arm that scores WORSE than the flagship row but carries MORE # training seeds -- the "inferior but 3-seed" row the flagship is not allowed to hide behind. # It is emitted only when that is actually true. Previously every runner-up was sent here, so a # SINGLE-seed loser (piece-assembly suboptimal 46.0 at 1x1, beside a 52.0 flagship row at 2x3) # appeared under a heading that calls its rows verified. A runner-up with no seed advantage is # neither a stronger result nor a stronger verification, so it is dropped rather than printed. # Demoted rows are a different dataset entirely and belong wholly in secondary, not split # across two sections as they were when only `_top` honoured NAME_SUFFIX. if _other is not None and not _demoted: _on = len({ps for (_, ps, _) in _other[4]}) if _on > _nseed: emit(_other, f"*{_on}/3 training seeds vs the flagship arm's {_nseed}/3, but scores " f"lower ({_other[0]:.1f} vs {_top[0]:.1f})*", dest=VERLOW) # Sections 2 and 3: the same row builder, different reward, different destination. if ALT_ROW.get(task): emit(ALT_ROW[task], "*env-success reward; RISE/IDQL critics NOT retrained on it; label is the " "pre-settle `goal.npz` (overcounts 1.85-2.86x)*", dest=ALTREW) if ORACLE_ROW.get(task): emit(ORACLE_ROW[task], "**DISQUALIFIED: dense privileged reward, not matched to any baseline**", dest=ORCROW) if best: sr, n, a, p, g = best else: sr, n, a, p, g = prov bb = max([x for x in b.values() if x is not None], default=None) if bb is not None and task not in FLAGSHIP_VARIANT: agg.append((sr, bb))# ---- rows measured in an alternate evaluation region -------------------------------------------------------import verdict_table as _vtfor label, (task, spec) in ALT.items(): keep = _vt.CANON.get(task) _vt.CANON[task] = ("alt", spec) try: c = cells(task) b2 = {} for lab, pred in (("BC", lambda a, p: a[0] == "greedy" and p == "BC-expert"), ("BCU", lambda a, p: a[0] == "greedy" and p == "BC-unified"), ("IDQL", lambda a, p: a[0] == "critic" and p == "IDQL policy"), ("RISE", lambda a, p: a[0] == "critic" and p == "RISE policy")): g = pool(c, pred); b2[lab] = rate(g)[0] if g else None bestA = None for (a, p) in {(a, p) for (a, p, _, _) in c if a[0].startswith("rsm:")}: g = pool(c, lambda x, q, A=a, P=p: x == A and q == P) sr, n = rate(g) if bestA is None or sr > bestA[0]: bestA = (sr, n, a, p, g) ff = lambda v: "--" if v is None else f"{v:.1f}" _k, _v = sorted(spec.items())[0] reg = ("nut " if _k == "SquareNut" else ("piece1 " if _k == "Piece1" else _k + " ")) + \ ",".join(f"[{a[0]:g},{a[1]:g}]" for a in _v[:2]) if bestA: sr, n, a, p, g = bestA head = a[0].split(":")[1]; _m, beta, hops, N = parse(a[1]) gg = flat(pool(c, lambda x, q, P=p: x[0] == "greedy" and q == P)) gp = flat(pool(c, lambda x, q, P=p, H=head: x == ("permuted", H) and q == P)) mg, mp = mcnemar(flat(g), gg), mcnemar(flat(g), gp) dd = lambda m: "--" if not m else f"{m['a']-m['b']:+.1f} (p={m['p']:.3f})" ps3 = defaultdict(lambda: [0, 0]) for (P, s3, e3), v in g.items(): ps3[s3][0] += sum(v); ps3[s3][1] += len(v) per3 = "/".join(f"{100*x/y:.0f}" for _, (x, y) in sorted(ps3.items())) okk = mg and mp and mg["p"] < .05 and mp["p"] < .05 and mg["a"] > mg["b"] and mp["a"] > mp["b"] vv = "**win**" if okk else ("control undecided" if mg and mg["p"] < .05 and mg["a"] > mg["b"] else "no gain") # MATCHED-REWARD ROUTING (user 2026-09-20: "every table should have a matched reward"). # This path predates the reward split and used to dump every head into SEC, so a # progress-head row sat beside provenance-reward rows and beside IDQL/RISE numbers. # Route by head, and suppress the critic columns whenever the reward is not the # provenance label the critics were trained on. _sec = {"membership": SEC, "completion": ALTREW}.get(head, ORCROW) _off = _sec is not SEC _na = "*n/a: critic not retrained on this reward*" _hd = head if head != "progress" else \ "progress **[ORACLE: dense privileged reward, NOT reward-matched, do not quote]**" # NOTE the horizon column: it was missing here, so every cell after `reg` shifted one # left and the row printed 21 columns against a 23-column header. _sec.append(f"| {label} | {_TRAJ.setdefault(task, _traj(task))} | {_HZ.setdefault(task, _horizon(task))} ({_DL.setdefault(task, _demo_len(task))}) | {reg} | {ff(b2['BC'])} | {ff(b2['BCU'])} | {_na if _off else ff(b2['IDQL'])} | {_na if _off else ff(b2['RISE'])} | " f"**{sr:.1f}** | -- | -- | {len(ps3)}x{len({e3 for (_,_,e3) in g})} | {per3} | {n//max(len(ps3)*len({e3 for (_,_,e3) in g}),1)} | {n} | {p} | {_hd} | {beta} | " f"{hops} | {N} | -- | {dd(mg)} | {dd(mp)} | " + ("--" if _off or not [v for v in b2.values() if isinstance(v,(int,float))] else f"{sr-max(v for v in b2.values() if isinstance(v,(int,float))):+.1f}") + f" | {vv} |") else: SEC.append(f"| {label} | {_TRAJ.setdefault(task, _traj(task))} | {_HZ.setdefault(task, _horizon(task))} ({_DL.setdefault(task, _demo_len(task))}) | {reg} | {ff(b2['BC'])} | {ff(b2['BCU'])} | {ff(b2['IDQL'])} | {ff(b2['RISE'])} | " f"-- | -- | -- | -- | -- | -- | -- | -- | -- | -- | -- | -- | -- | -- | -- | -- | -- |") finally: if keep is None: _vt.CANON.pop(task, None) else: _vt.CANON[task] = keep _vt._AUTO.pop(task, None)
# ---- paper-data-regime rows (may still be training) --------------------------------------------------------for task, (label, traj, reg) in PAPER_REGIME.items(): c = cells(task) if glob.glob(f"{ROOT}/runs/{task}/eval_*/*.json") else {} b3 = {} for lab, pred in (("BC", lambda a, p: a[0] == "greedy" and p == "BC-expert"), ("BCU", lambda a, p: a[0] == "greedy" and p == "BC-unified"), # RISE actor sampled once, no critic (audit 2026-09-21 C2): a baseline the delta and # the routing rule must see, printed in the paper table as RISE-g. ("RISEg", lambda a, p: a[0] == "greedy" and p == "RISE policy"), ("IDQL", lambda a, p: a[0] == "critic" and p == "IDQL policy"), ("RISE", lambda a, p: a[0] == "critic" and p == "RISE policy")): g = pool(c, pred) if c else None b3[lab] = rate(g)[0] if g else None try: live = _sp.run(["bjobs", "-noheader", "-o", "job_name"], capture_output=True, text=True, timeout=25).stdout except Exception: live = "" nrun = sum(1 for l in live.splitlines() if "sqsub2" in l or f"idql_{task}" in l) eps = [] for d in glob.glob(f"{ROOT}/runs/{task}/policy/*/rolling"): e = [int(re.search(r"epoch_(\d+)", x).group(1)) for x in glob.glob(d + "/*.pth")] if e: eps.append(max(e)) note = (f"*training, ep {min(eps)}-{max(eps)}/5000, {nrun} jobs*" if eps else (f"*launched, {nrun} jobs, no checkpoint yet*" if nrun else "*not launched*")) ff = lambda v: note if v is None else f"{v:.1f}" SEC.append(f"| {label} | {traj} | {_HZ.setdefault(task, _horizon(task))} (--) | {reg} | {ff(b3['BC'])} | {ff(b3['BCU'])} | {ff(b3['IDQL'])} | {ff(b3['RISE'])} | " f"-- | -- | -- | -- | -- | -- | -- | -- | -- | -- | -- | -- | -- | -- | -- | -- | -- |")
HDR = L[-2:] # the header + separator built aboveL = L[:-2]# The flagship ROW for some tasks is a data variant (square-peg suboptimal: the 20/100 subsample,# not the released 100/100 file, which carries 5x the expert data and was demoted by the user).# Sections 0 and 5 iterate over TASKS and so must honour that mapping, otherwise they report the# DEMOTED file under the FLAGSHIP label -- and, worse, aim top-up compute at the demoted row.def _row_identity(task): """-> (task_whose_cells_to_use, display_name, is_demoted_release)""" fv = FLAGSHIP_VARIANT.get(task) if fv: return fv[0], fv[1], False return task, NAME.get(task, task), False
# ---- UPPER-BOUND SUMMARY ------------------------------------------------------------------------# "What is the ceiling if the single-seed winners reproduce across seeds?" One row per task:# the verified number we can quote today, and the number we would quote if the best never-verified# arm held up. The gap between them is exactly what the top-up is buying.# the read-out classifier lives with the table generator that defines the arm-key grammar# ("CH<cap>" = coin chain, "L<d>" = retired fold); it is imported rather than re-derived so the# markdown and the LaTeX can never disagree about which arm is which estimator.import flagship_latex as _FLC_F_is_chain = _FLC._recipe_is_chain
UB = []_CEIL_CHECK = {} # display label -> section 0 ceiling, cross-checked against the section 1 row belowfor task, _lbl in TASKS: _src, _disp, _ = _row_identity(task) try: c = cells(_src) except Exception: continue base = defaultdict(lambda: [0.0, 0]); agg3 = defaultdict(lambda: [0.0, 0]); sd3 = defaultdict(set) # READ-OUT SPLIT (gen_q#267, orchestrator 2026-09-23 07:05Z). This section used to aggregate every # `rsm:membership` arm regardless of read-out, so "today" and the verdict were the maximum over the # RETIRED deterministic fold -- three tables below a headline column that is chain-only. On # threading that made this section say "win" (fold 33.4 vs BC 26.3) while the flagship column two # tables up says no decision (chain 24.4 vs 26.3). The verdicts here are now computed from the # CHAIN arms alone, the same estimator the paper's tab:flagship prints; the fold maximum is kept in # columns that NAME it as retired, never as the row's number. ch3 = defaultdict(lambda: [0.0, 0]); chsd = defaultdict(set); chcl = defaultdict(set) fo3 = defaultdict(lambda: [0.0, 0]); fosd = defaultdict(set); focl = defaultdict(set) # FOLD-ONLY, for the retired columns for (arm, pol, ps, es), e in c.items(): if arm[0] == "greedy": base[pol][0] += sum(e); base[pol][1] += len(e) elif arm[0].startswith("rsm:membership"): k = (arm[1], pol); agg3[k][0] += sum(e); agg3[k][1] += len(e); sd3[k].add(ps) if _F_is_chain(arm[1]): ch3[k][0] += sum(e); ch3[k][1] += len(e); chsd[k].add(ps); chcl[k].add((ps, es)) elif _FLC._readout_of(arm[1]) == "fold": # POSITIVE test, not `else` (2026-09-24, run 20). `_F_is_chain` excludes off-gamma and # cap-0 chain arms as well as fold arms, so an `else` here labelled a CHAIN key as the # row's fold number -- Square (Cov.)'s "ceiling, fold (retired)" read 20.0 from # `L40@best b0.95 CH0`. Excluded chain arms now enter neither column and are counted. fo3[k][0] += sum(e); fo3[k][1] += len(e); fosd[k].add(ps); focl[k].add((ps, es)) else: _ub_chain_excl[_disp] = _ub_chain_excl.get(_disp, 0) + 1 bb = max((x / y * 100 for x, y in base.values() if y >= 150), default=float("nan")) # CEILING (user 2026-09-20): "the best mean across the seeds done for a config, ie mean over # 1, 2 or 3 seeds". So the ceiling ranges over EVERY arm, whatever its seed count, and its value # is that arm's pooled mean over the seeds it actually has. When the winner already has three # seeds the ceiling equals today and nothing is pending -- which is itself the useful signal. # "Verified" MUST mean here exactly what it means in section 1: three training seeds. This also # carried a >=300-episode floor, which the prose never stated, so square-peg (Coverage) -- whose # 3-seed flagship arm has 150 episodes (3 seeds x 1 eval seed x 50) -- was excluded here and the # column fell back to a weaker arm: section 0 said "today 8.7, tie" while section 1 said 9.3 on the # same task at the same three seeds. One document, one definition; the episode count is printed # beside the number so a thin 3-seed result is still visible as thin. # (The maxima over BOTH read-outs used to be computed here and printed in the two "retired" # columns and handed to the cross-section guard. Both were wrong for the same reason -- a mixed # maximum under a single-estimator heading -- and both are now computed per read-out below. The # mixed quantity is not needed anywhere, so it is not computed at all: an unused mixed maximum is # just waiting for someone to print it.) # the same two quantities restricted to the coin-terminated chain read-out # "TODAY" IS A PRINTED HEADLINE, so it takes the same grid-completeness tier section 1 now uses: # a 3-of-9-cell arm reading 50.0 must not displace the complete 9-of-9 arm reading 45.1 (the 18:39Z # defect). The CEILING (`allc`) deliberately does NOT -- the owner's definition is "the best mean # across the seeds done for a config", i.e. over every arm however partial -- but it now carries the # cell count so the column can say how thin the grid behind it is. verc = [(x / y * 100, k, y) for k, (x, y) in ch3.items() if len(chsd[k]) >= 3] allc = [(x / y * 100, k, len(chsd[k]), y) for k, (x, y) in ch3.items() if y >= 50] _vc = max(verc, key=lambda t: _F_tier(t[0], t[2], 3, len(chcl[t[1]])), default=(float("nan"), None, 0)) vbc, vepsc = _vc[0], _vc[2] ubc = max(allc, default=(float("nan"), None, 0, 0)) # ...and restricted to the RETIRED FOLD, for the two columns that NAME it (found 2026-09-23 12:05Z). # These two printed `vb` and `ub[0]`, the maxima over BOTH read-outs, under headings "today, fold # (retired)" and "ceiling, fold (retired)" -- so wherever the chain arm won the row, a column # labelled `fold` printed the CHAIN number. That is byte-for-byte the defect fixed in the LaTeX # single-actor table in run 8 (Square (Cov.) printed 20.9 in an "RSM-fold (retired)" column whose # own best fold arm is 17.6); it survived here because this section computes its own maxima. _verf = [(x / y * 100, k, y) for k, (x, y) in fo3.items() if len(fosd[k]) >= 3] _allf = [(x / y * 100, k, len(fosd[k]), y) for k, (x, y) in fo3.items() if y >= 50] vbf = max(_verf, key=lambda t: _F_tier(t[0], t[2], 3, len(focl[t[1]])), default=(float("nan"), None, 0))[0] ubf = max(_allf, default=(float("nan"), None, 0, 0))[0] # A MISSING baseline is not a loss. bb is nan whenever no greedy arm has >=150 episodes yet (the # 20/100 square split, whose BC/BCU evals are still running). Every comparison against nan is # False, so the verdicts used to fall through to "LOSS" and "still loses" -- the table asserted a # defeat on a task it had never measured a baseline for, and printed "nan" and "+nan" as values. _nob = bb != bb _noch = vbc != vbc # no chain arm verified at three seeds yet now = ("*no baseline yet*" if _nob else ("*chain pending*" if _noch else ("win" if vbc > bb else ("tie" if abs(vbc - bb) < 1.0 else "LOSS")))) _ceilc = ubc[0] ceil = ("*no baseline yet*" if _nob else ("*chain pending*" if _ceilc != _ceilc else ("win" if _ceilc > bb else "still loses"))) _pend = "" if ubc[2] >= 3 else f" *(pending {3-ubc[2]} seed(s))*" # episodes behind the ceiling number, so a 1-seed/50-episode ceiling cannot be mistaken for a # 3-seed/450-episode one at a glance UB.append((_disp, "--" if _nob else f"{bb:.1f}", "--" if _noch else f"{vbc:.1f} ({vepsc} ep)", now, "--" if _ceilc != _ceilc else f"{_ceilc:.1f}", f"{ubc[2]}/3", ubc[3], "--" if (_nob or _ceilc != _ceilc) else f"{_ceilc-bb:+.1f}", ceil + _pend, "--" if vbf != vbf else f"{vbf:.1f}", "--" if ubf != ubf else f"{ubf:.1f}")) # COMPARE LIKE WITH LIKE (2026-09-23). This handed the guard `ub[0]`, the ceiling over BOTH # read-outs, while section 1's max-over-arms is now CHAIN-ONLY -- so the guard fired on square-peg # (Suboptimal) with "ceiling 58.00 != max 50.44", 58.00 being a fold arm. The guard exists to # catch the two sections reading different DATA, not different estimators; it now compares the # chain ceiling, which is the quantity section 1 maximises. _CEIL_CHECK[_disp] = ubc[0]
# CROSS-SECTION GUARD. Section 0's ceiling and section 1's headline are the same quantity by# construction -- the best membership arm over whatever seeds it has -- so if they ever disagree, one# of the two sections is reading a different task, a different reward head or a different region.# That exact failure has happened twice here (the FLAGSHIP_VARIANT remap, and the 300-episode floor# above), and both times the table looked perfectly plausible while saying two things at once.# Since the 2026-09-21 routing rule a verified winner may sit in section 1 BELOW a single-seed# maximum, so the guard compares the ceiling to the max over flagship candidates (_FLAG_MAX), which is# the headline whenever no verified winner was preferred, and requires headline <= ceiling always.for _lbl_, _c_ in _CEIL_CHECK.items(): _f_ = _FLAG_VAL.get(_lbl_); _m_ = _FLAG_MAX.get(_lbl_, _f_) if _f_ is not None and _c_ == _c_ and (abs(_m_ - _c_) > 0.05 or _f_ > _c_ + 0.05): raise AssertionError(f"section 0 ceiling {_c_:.2f} != section 1 max-over-arms {_m_:.2f} " f"(headline {_f_:.2f}) for {_lbl_!r}")
if UB: L += ["", "## 0. Upper bound --- what the table becomes if the single-seed winners reproduce", "", "**Today** is the best arm verified at three policy seeds. **Ceiling** is the best *mean* over any " "arm, pooled across whatever seeds that arm actually has (1, 2 or 3) -- so a ceiling at 3/3 seeds " "is already verified and equals today, while a ceiling at 1/3 is a candidate the top-up is testing. " "The seed and episode counts behind the ceiling are given so a 50-episode single-seed number is " "never mistaken for a 450-episode verified one. **The ceiling also admits arms whose 3x3 cell " "grid is only partly landed**, which `today` does not: since 2026-09-23 the headline prefers a " "COMPLETE 9-cell arm to any partial one however high it scores (`flagship_latex._seed_tier_key`, " "now shared by this file), because an in-flight arm's episode-pooled rate is weighted towards " "whichever policy seed happened to land more cells. `scripts/chain_grid_census.py` prints the " "gap per task; where the ceiling exceeds today, check it there before quoting the ceiling.", "", "This is an UPPER BOUND, not a forecast. Each ceiling rests on 50-100 episodes at one policy seed, " "picked as the maximum over 27-119 arms, so it is upward biased twice over: by selection and by " "small n. Every time a single-seed maximum on this project was actually verified it fell: " "-7.2, -7.6, -10.2 points.", "", "**Every RSM number in the first nine columns is the coin-terminated \u03b2-chain read-out** " "(gen_q#267) \u2014 the same estimator as the flagship column at the top of this file. The last two " "columns are the RETIRED deterministic truncated fold, kept only so the change is visible; they " "are not this section's numbers and no verdict is computed from them.", "", "| task | best baseline | today, chain (3 seeds) | verdict | ceiling, chain | ceiling seeds | ceiling episodes | margin at ceiling | verdict at ceiling | today, fold (retired) | ceiling, fold (retired) |", "|---|---|---|---|---|---|---|---|---|---|---|"] for r in UB: L += ["| " + " | ".join(str(x) for x in r) + " |"] # r[8] now carries a "*(pending N seed(s))*" suffix, so match on the prefix, not equality. _w = sum(1 for r in UB if r[3] == "win"); _cw = sum(1 for r in UB if str(r[8]).startswith("win")) _settled = sum(1 for r in UB if "pending" not in str(r[8])) _nb = sum(1 for r in UB if r[1] == "--") _npend = sum(1 for r in UB if str(r[2]) == "--") L += ["", f"**{_w} of {len(UB)} rows win today on the chain read-out; {_cw} of {len(UB)} would win at " f"the ceiling.** " + (f"{_npend} row(s) have no 3-seed chain arm yet and are counted as neither. " if _npend else "") + f"{_settled} ceiling(s) are already verified at 3 seeds and will not move." + (f" {_nb} row(s) have no baseline measured yet and are counted as neither." if _nb else ""), ""]
def _tbl(rows, empty): """HDR + rows, or a sentence when there are none.
A markdown table whose only lines are the header and the `|---|` separator renders as an empty grid -- section 2 shipped that way, because no `completion`-head arm has reached two seeds yet. An empty section must SAY it is empty, not look like a table that lost its contents. """ return (HDR + rows) if rows else [f"*{empty}*", ""]
def _fold_excl_note(): """How much was excluded, COMPUTED -- a typed count goes stale the moment a cell lands (run 7).""" _n = sum(v[0] for v in FOLD_EXCLUDED.values()) _rows = sum(1 for v in FOLD_EXCLUDED.values() if v[0]) if not _n: return "No fold arm exists in these rows." return (f"{_n} fold arm(s) across {_rows} row(s) were excluded from this maximum for that reason; " "they remain in section 0's columns that name them retired and in the paper's " "`tab:ablation_betarec`." + _chain_excl_note())
def _chain_excl_note(): """Chain arms excluded for NOT being this paper's chain (wrong gamma, or cap 0 = no recursion). Reported separately from the fold count because they are a different defect and, unlike a fold arm, they appear in NO column of this document -- if the count were folded into the fold total, a reader would look for them in the retired columns and not find them (run 20).""" _n = sum(v[0] for v in CHAIN_EXCLUDED.values()) _rows = sum(1 for v in CHAIN_EXCLUDED.values() if v[0]) _ub = sum(_ub_chain_excl.values()) if not _n and not _ub: return "" _best = max([v[1] for v in CHAIN_EXCLUDED.values() if v[1] is not None], default=None) return (f" A FURTHER {_n} arm(s) across {_rows} row(s) carry the chain tag but are NOT this paper's " f"chain -- either at an evaluation-time γ other than {_FLC.FLAGSHIP_GAMMA:g} (the cap does " "not match the 1e-3 truncation tail its β implies) or at cap 0, where β ≥ γ " "makes the continuation probability exactly 0 and the walk is one successor draw with no " f"recursion. They are excluded from EVERY column of this document, not moved to the retired " f"fold ones (best excluded score {'n/a' if _best is None else f'{_best:.1f}'}; " f"{_ub} further such arm(s) were kept out of section 0's retired columns).")
L += ["## 1. Flagship comparison --- RISE-faithful reward (reward-matched)", "", "**Reward structure is matched across every column.** RISE's reward is data PROVENANCE, not outcome: " "`relabel_rewards.py` writes a constant over every frame of an episode (1 for the expert file, 0 for the " "non-expert file) and `iql_diffusion.py` consumes that field unchanged. So BC and BCU use no reward, the " "RISE and IDQL critics use the provenance label, and the RSM arm below uses the *same* provenance label " "(`membership` head). Nothing here sees a signal the others do not.", "", "One row per task: the strongest membership-head RSM arm in that task's canonical evaluation region, against " "every baseline. Where the strongest arm is not yet verified on three training seeds it is shown as a " "**TEMPORARY flagship**; quote such a row only with its seed count.", "", "**The RSM column is the coin-terminated \u03b2-chain read-out only** (gen_q#267), the same estimator " "as section 0 and as the paper's `tab:flagship`. Until 2026-09-23 this section ranged over BOTH " "read-outs, so it printed the retired deterministic fold under this heading with its own `verdict` " "\u2014 on threading it printed 33.0 at `hops 1`, four hours after that number was publicly retracted " "on #267, and marked it **win**. " + _fold_excl_note() + " A task with no chain arm prints dashes; a " "fold number never stands in for a chain number.", "", # The headline a reviewer needs before any per-row number: on how many tasks does the SCORER # actually do something? Beating BC is not that question -- the proposer alone can do it. f"**Selection verdict across the {len(_FLAG_CTRL)} flagship rows: " f"{sum(1 for v in _FLAG_CTRL if v == '**win**')} beat both controls, " f"{sum(1 for v in _FLAG_CTRL if 'below its own' in v)} score BELOW their own no-selection control, " f"{sum(1 for v in _FLAG_CTRL if v in ('no gain', 'control undecided'))} are undecided " f"(mostly 50-episode single-seed cells).** A row can beat every baseline and still be carried by " f"its proposer rather than by the scorer; the two control columns are what separate those cases, " f"and the verdict column now always reports them.", ""] + _tbl(FLAG, "No task has a matched-reward arm yet.")if VERLOW: L += ["", "## 1b. Better verified, lower scoring --- same reward regime, weaker configuration", "", "Every row here is an arm that carries **more training seeds than its task's section-1 row but " "scores lower**. This is the honest counterweight to the flagship's admission of " "seed-deficient winners: if the best arm rests on one seed while a different configuration has " "three, both numbers are on the table and the seed counts are printed beside each. A runner-up " "with no seed advantage over the flagship row is neither a better result nor better evidence, " "so it is not printed at all. Reward regime is identical to section 1; the critic columns are " "shown because the reward is matched.", ""] + _tbl(VERLOW, "No task has a better-verified arm that scores below its flagship row.")
L += ["", "## 2. Alternative reward --- per-frame environment success (backup flagship)", "", "The `completion` head scores per-frame task success recovered by state replay, rather than data provenance. " "This is **not a correction to RISE, it is a different reward**: the paper never uses outcome labels. It is " "reported here as a legitimate alternative and would become the headline only if it beats section 1. " "Reward matching still requires the RISE and IDQL critics to be retrained on the same per-frame label, which " "has NOT been done, so a win here is not yet a matched win.", "", "Known defect: `train_goal_head.py` defaults to the PRE-settle label (`goal.npz`), which overcounts success " "by 1.85x to 2.86x against the corrected `goal_settle.npz`. Every existing completion checkpoint records " "`from goal.npz`, i.e. the uncorrected detector. These rows are provisional until retrained.", ""] + _tbl(ALTREW, "No completion-head arm has reached two training seeds yet, so there is nothing to report here.")L += ["", "## 3. DISQUALIFIED --- dense privileged reward (oracle)", "", "**Do not quote.** The `progress` head regresses a dense hand-designed potential over privileged simulator " "state (end-effector-to-object and object-to-target distances; 4315 distinct values over 13973 grasped " "frames on piece-assembly). No other method sees it, so these rows are not reward-matched to anything " "printed beside them. Retired 2026-09-20; kept only so existing artefacts remain traceable.", ""] + _tbl(ORCROW, "No oracle-head arm remains on record.")L += ["", "## 4. Secondary results --- RISE-faithful reward (same regime as section 1)", "", "**Same reward regime as section 1**, so every column here is matched: BC/BCU use no reward, the RISE and " "IDQL critics and the RSM arm all use the provenance label. Rows land here for reasons of *evidence*, not " "reward: single-seed arms awaiting verification, alternate evaluation regions, and task variants whose " "trainings have not finished. Any row whose reward is not the provenance label is routed to section 2 or 3 " "instead, whichever code path produced it.", ""] + _tbl(SEC, "Nothing is currently held back from the flagship.")
# COLUMN-COUNT GUARD. The alternate-region path used to omit the horizon column, so its rows printed# 21 fields against a 23-field header and every cell after the region silently shifted one to the left# -- the `head` column displayed the beta value. That was invisible in both the markdown and the PDF.# LABEL/DATASET CONSISTENCY GUARD (added after two bugs of this shape on 2026-09-20).# The column guard below catches MALFORMED rows. It cannot catch a well-formed row carrying the wrong# dataset. Twice tonight a row label was attached to two different datasets -- the released# square-peg 100/100 file and its 20/100 subsample -- because one code path honoured# FLAGSHIP_VARIANT and another did not. Symptom: section 0 said 41.3 and section 1 said 73.2 for a# row with the same name. Rule: one display label maps to exactly one (expert/non-expert) trajectory# count across the whole document._label_traj = {}for _sec_name, _rows in (("1 flagship", FLAG), ("1b verified-lower", VERLOW), ("2 alt-reward", ALTREW), ("3 oracle", ORCROW), ("4 secondary", SEC)): for _r in _rows: _f = [x.strip() for x in _r.split("|")] if len(_f) < 4: continue _lab, _tj = _f[1], _f[2] if not _tj or "/" not in _tj: continue if _lab in _label_traj and _label_traj[_lab][0] != _tj: raise AssertionError( f"label '{_lab}' carries two different datasets: {_label_traj[_lab][0]} " f"(section {_label_traj[_lab][1]}) vs {_tj} (section {_sec_name}). " f"A demoted variant is probably not being relabelled.") _label_traj.setdefault(_lab, (_tj, _sec_name))
_ncol = HDR[0].count("|") - 1for _sec_name, _rows in (("1 flagship", FLAG), ("1b verified-lower", VERLOW), ("2 alt-reward", ALTREW), ("3 oracle", ORCROW), ("4 secondary", SEC)): for _r in _rows: _n = _r.count("|") - 1 assert _n == _ncol, (f"section {_sec_name}: row has {_n} columns, header has {_ncol}.\n" f" {_r[:160]}")
# ---- TOP-UP PLAN --------------------------------------------------------------------------------# User ruling 2026-09-20: "if we already had 3 seeds and the average got dropped from seed 0, not a# valid topup candidate". An arm at >=3 policy seeds HAS been tested; its 3-seed mean is the answer# and re-running it only chases noise. A valid candidate is an arm that BEATS the best baseline and# has FEWER than 3 policy seeds, i.e. was never verified at all.TOPUP = []for task, _lbl in TASKS: _src, _disp, _ = _row_identity(task) try: c = cells(_src) except Exception: continue base = defaultdict(lambda: [0.0, 0]); agg2 = defaultdict(lambda: [0.0, 0]); sd = defaultdict(set) cl = defaultdict(set) # arm -> the (policy seed, eval seed) CELLS it has landed, of the 9 for (arm, pol, ps, es), e in c.items(): if arm[0] == "greedy": base[pol][0] += sum(e); base[pol][1] += len(e) elif arm[0].startswith("rsm:membership"): k = (arm[1], pol); agg2[k][0] += sum(e); agg2[k][1] += len(e); sd[k].add(ps); cl[k].add((ps, es)) bb = max((x / y * 100 for x, y in base.values() if y >= 150), default=0.0) cand = [(x / y * 100, k, len(sd[k]), y) for k, (x, y) in agg2.items() if y >= 50 and x / y * 100 > bb and len(sd[k]) < 3] # SECOND CANDIDATE CLASS: THREE POLICY SEEDS, INCOMPLETE 3x3 GRID (gen_q#267, 2026-09-23 run 13). # The rule above nominates on POLICY SEEDS only (`len(sd[k]) < 3`), so an arm with all three policy # seeds but one or two EVAL seeds each -- 3, 4 or 5 of the 9 cells -- could never be nominated. # Those are exactly the four arms the grid census currently reports as EXPOSED (piece-assembly # (Sub.) 4/9 cells reading 50.0 against the complete 45.1, square-peg (Sub.) 7/9 at 55.1 vs 51.6, # piece-tip 8/9 at 6.8 vs 5.6, mug 5/9 at 21.1 vs 19.8): the completeness tier keeps them out of # every printed table, and this plan could not ask for the 1-5 cells that would settle them, so the # question just sat there. This does NOT reopen the owner's 2026-09-20 ruling ("if we already had # 3 seeds and the average got dropped from seed 0, not a valid topup candidate") -- that ruling is # about RE-RUNNING an arm already measured on the full grid, and these arms have never been # measured on it. They are listed separately and labelled, never merged into the class above. fill = [(x / y * 100, k, len(sd[k]), y, len(cl[k])) for k, (x, y) in agg2.items() if y >= 50 and x / y * 100 > bb and len(sd[k]) >= 3 and len(cl[k]) < 9] done = sum(1 for k in agg2 if len(sd[k]) >= 3 and len(cl[k]) >= 9) # READ-OUT IN THE PLAN (gen_q#267, 2026-09-23). This list nominates GPU, and it pooled every # `rsm:membership` arm at ANY read-out, so it kept nominating arms of the RETIRED deterministic # fold -- seeding an estimator no published column prints. Rather than silently dropping them # (the fold rows still populate tab:ablation_betarec, so that is not my call to make here), the # read-out is now PRINTED and chain candidates are ordered first, so nobody spends a node on a # fold arm without seeing that is what they are doing. Predicate imported from flagship_latex so # the plan and the tables cannot disagree about which arm is which estimator. from flagship_latex import _recipe_is_chain as _isch # INADMISSIBLE CHAIN KEYS ARE NOT `fold` ARMS (gen_q#267, 2026-09-24 run 22). The label above is a # BINARY on _recipe_is_chain, so an arm carrying the chain tag that this paper cannot print -- cap 0 # (degenerate: beta >= gamma, the continuation coin never fires) or off-gamma (the cap is not the # 1e-3 tail its beta implies) -- fell into the `fold (retired)` bucket and was NOMINATED FOR GPU # under the name of an estimator it is not. The 2026-09-24 02:41 build printed three of them: # piece-assembly (Cov.) `L40@best b0.95 CH15 ... ` 41.3 and `L40@best b0.9 CH35 ...` 40.7, and # piece-tip `M@best b0.95 CH0 ...` 6.0 asking for 6 cells on a walk with no recursion. They are # DROPPED from the plan (no column can ever print them, so the GPU would buy nothing) and counted in # a note, rather than relabelled -- the same rule section 0 already applies to its columns. from verdict_table import _chain_tag_inadmissible as _inadm _drop_c = [t for t in cand if _inadm(t[1][0])] _drop_f = [t for t in fill if _inadm(t[1][0])] cand = [t for t in cand if not _inadm(t[1][0])] fill = [t for t in fill if not _inadm(t[1][0])] cand.sort(key=lambda t: (not _isch(t[1][0]), -t[0])) for sr, k, ns, n in cand[:3]: TOPUP.append((_disp, f"{bb:.1f}", f"{sr:.1f}", "chain" if _isch(k[0]) else "**fold (retired)**", k[1], k[0], f"{ns}/3", n, (3 - ns) * 3)) if _drop_c or _drop_f: TOPUP.append((_disp, "", "", "", "", f"*{len(_drop_c)+len(_drop_f)} candidate(s) dropped: they " f"carry the chain tag but are not this paper's chain (cap 0, or a cap that is not " f"the 1e-3 tail their beta implies at gamma=0.99), so no column can print them and " f"GPU spent on them buys nothing*", "", "", "")) if cand: _nch = sum(1 for t in cand if _isch(t[1][0])) TOPUP.append((_disp, "", "", "", "", f"*+{max(len(cand)-3,0)} more candidates " f"({_nch} chain / {len(cand)-_nch} fold); " f"{done} arm(s) already at 3 seeds ON THE FULL 3x3 GRID and therefore NOT candidates*", "", "", "")) # the fill class, chain first and highest first, and only the chain ones are worth GPU fill.sort(key=lambda t: (not _isch(t[1][0]), -t[0])) for sr, k, ns, n, nc in fill[:3]: TOPUP.append((_disp, f"{bb:.1f}", f"{sr:.1f}", "chain" if _isch(k[0]) else "**fold (retired)**", k[1], k[0], f"3/3 seeds, **{nc}/9 cells**", n, 9 - nc))
if TOPUP: L += ["", "## 5. Top-up plan --- which under-seeded arms are being verified", "", "A **valid top-up candidate** beats the best baseline AND has fewer than three policy seeds, " "i.e. it was never verified. An arm already at three seeds has been tested: its three-seed mean " "is the answer even if that mean fell below its seed-0 value, and re-running it only chases " "noise. Those are excluded by construction.", "", "Each top-up runs the arm at 3 policy seeds x 3 eval seeds, 50 episodes per cell, so a single " "50-episode cell is replaced by 450 episodes. **Multiplicity warning:** these candidates were " "chosen by taking the maximum over 27-119 arms per row, so the reported maximum is upward " "biased; the top-up measures whether a specific arm holds, it does not remove the selection " "bias in how it was picked.", "", "Candidates are ordered **chain first**: the flagship prints the coin-terminated chain " "read-out, so a `fold (retired)` nomination would spend GPU seeding an estimator that appears " "only in the ablation table. The read-out is a column so that choice is visible.", "", "A **second class** of candidate carries `3/3 seeds, k/9 cells`: all three policy seeds but " "only one or two eval seeds each, so it has never been measured on the full grid. Since " "2026-09-23 the printed tables prefer a complete arm to any partial one, so these arms score " "above the headline and are excluded from it; the missing cells are what would settle them, " "and this class asks for exactly those. It does not reopen the ruling above, which is about " "re-running an arm already measured on the full 3x3 grid.", "", "| task | best baseline | arm's 1-seed score | read-out | proposer | recipe | seeds | eps so far | cells to run |", "|---|---|---|---|---|---|---|---|---|"] for r in TOPUP: L += ["| " + " | ".join(str(x) for x in r) + " |"]
if agg: # Selection disclosure. The flagship cell is a maximum over arms, so the search size belongs next to it. L += ["", "**How the flagship arm was chosen.** Each row reports the best-scoring arm with at least two " "training seeds, where an arm is (successor model, reward head, beta, hops, read-out, candidate " "count, proposer). The table below states how many arms that maximum ranged over and what the " "runner-up scored. Best-to-runner-up gaps are small, i.e. the top of the distribution is a plateau " "rather than a spike, which is what a real effect looks like; but the baselines receive no " "equivalent search, each contributing one fixed configuration. See `docs/PROPOSER_SELECTION.md`, " "which also shows that the proposer choice survives held-out validation on a disjoint eval seed.", "", "| task | arms searched | best | runner-up |", "|---|---|---|---|"] for _t, _lbl in TASKS: _n, _bs, _ru = SEARCH.get(_t, (0, None, None)) if not _n: continue _gap = f" (gap {_bs - _ru:+.1f})" if (_bs is not None and _ru is not None) else "" L += [f"| {_lbl} | {_n} | {('%.1f' % _bs) if _bs is not None else '--'} | " f"{(('%.1f' % _ru) + _gap) if _ru is not None else 'only one qualifying arm'} |"] L += ["", f"Mean over the {len(agg)} tasks with an RSM arm: best baseline {sum(x for _, x in agg)/len(agg):.1f}, " f"RSM **{sum(x for x, _ in agg)/len(agg):.1f}**, margin **{sum(x-y for x, y in agg)/len(agg):+.1f}**.", ""]L += ["", "For orientation only, the paper's Table I on the same task rows (different data mix and, on the piece " "tasks, a different success criterion, so NOT comparable to the columns above):", "", "| task | BC | BCU | IDQL | RISE |", "|---|---|---|---|---|"]for task, _ in TASKS: q = PAPER[task] L.append(f"| {NAME[task]} | {q[0]} | {q[1]} | {q[2]} | {q[3]} |")L.append("")open("/proj/dmfexp/zwhong/rsm_rise/docs/MASTER_TABLE.md", "w").write("\n".join(L))print("\n".join(L[:22]))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869#!/usr/bin/env python3"""The reference scale for train_rsm.py's `td_tgt_mse_vs_mc` diagnostic (gen_q#268).
WHY THIS EXISTS. `td_tgt_mse_vs_mc` is the MSE between the TD-Flow occupancy target and theMonte-Carlo target the SAME anchor would have received. It is tempting to read it as a convergencemeasure -- "the bootstrap is learning the MC occupancy" -- and that reading is WRONG, which thisscript demonstrates rather than argues. The occupancy m_beta(.|s,a) is a DISTRIBUTION; the MC targetis one draw from it and a converged bootstrap is an independent draw from the same distribution, sotheir expected squared difference is 2 * Var(m_beta), not zero. A TD run whose diagnostic fell to~0 would be one whose bootstrap had collapsed onto the conditional MEAN.
So the reference is the MC-vs-MC spread: draw TWO independent truncated-geometric futures at the sameanchor and the same beta, and measure the same per-dimension MSE. Any TD value near that number isconsistent with a correctly-spread bootstrap; a value far above it is a mismatched target, and avalue far below it is over-smoothing.
usage: mc_target_spread.py <task> [<task> ...] [--rows 8192] [--json status/tdflow/mc_spread.json]"""import argparseimport jsonimport sysfrom pathlib import Path
import numpy as np
ROOT = Path("/proj/dmfexp/zwhong/rsm_rise")sys.path.insert(0, str(ROOT / "code/gen_q/rsm_libero"))
def main(): ap = argparse.ArgumentParser() ap.add_argument("tasks", nargs="+") ap.add_argument("--rows", type=int, default=8192) ap.add_argument("--beta-lo", type=float, default=0.90) ap.add_argument("--beta-hi", type=float, default=0.995) ap.add_argument("--beta-trunc-eps", type=float, default=0.02) ap.add_argument("--seed", type=int, default=0) ap.add_argument("--json", default=str(ROOT / "status/tdflow/mc_spread.json")) a = ap.parse_args() from data import LiberoRSMData, truncated_geometric_future out = {} for task in a.tasks: d = LiberoRSMData(str(ROOT / "cache" / task), chunk=8, in_ram=False, reward_mode="dense") rng = np.random.default_rng(a.seed) eps_pool = d.train_eps w = d.ep_len[eps_pool].astype(np.float64); w /= w.sum() e = rng.choice(eps_pool, size=a.rows, p=w) lo, hi = d.ep_from[e], d.ep_to[e] t = lo + (rng.random(a.rows) * (hi - lo)).astype(np.int64) # the SAME per-anchor beta cap the trainer applies (gen_q#262) L = np.maximum(hi - t, 1).astype(np.float64) beta_hi_eff = np.clip(np.power(a.beta_trunc_eps, 1.0 / L), a.beta_lo, a.beta_hi) beta = a.beta_lo + rng.random(a.rows) * (beta_hi_eff - a.beta_lo) f1 = truncated_geometric_future(t, hi, beta, rng.random(a.rows)) f2 = truncated_geometric_future(t, hi, beta, rng.random(a.rows)) x1, x2, x0 = d._feat(f1), d._feat(f2), d._feat(t) mc_mc = float(((x1 - x2) ** 2).mean()) stay = float(((x0 - x1) ** 2).mean()) out[task] = {"mc_vs_mc": mc_mc, "stay_vs_mc": stay, "rows": int(a.rows), "beta_mean": float(beta.mean()), "beta_max": float(beta.max())} print(f"[mc_spread] {task}: MC-vs-MC {mc_mc:.3f} | now-vs-MC {stay:.3f} | " f"mean beta {beta.mean():.4f} (capped, max {beta.max():.4f})", flush=True) Path(a.json).parent.mkdir(parents=True, exist_ok=True) Path(a.json).write_text(json.dumps(out, indent=1)) print(f"[mc_spread] wrote {a.json}")
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106#!/usr/bin/env python3"""Run, under the MEMBERSHIP reward, the recipes that only the DISQUALIFIED progress head ever saw.
The progress head (dense privileged shaping) was swept before it was ruled out, and its sweeps did notcover the same ground as the membership sweeps that replaced it. Two consequences, both of which makethe membership numbers look worse than they may be:
* beta 0.95 is heavily represented under progress and thin under membership, which matters because the progress head's best arm sits at b0.95 on five of six tasks; * the RISE-policy proposer at one hop is the progress winner on both two-piece tasks and was never tried there under membership. Piece-tip is the extreme case: 9 progress recipes against 4 membership ones, progress 29.5 % vs membership 1.6 %.
Comparing a 4-arm search against a 9-arm search and concluding the reward is worse is a search-budgetartefact, not a result. This submits the missing recipes at eval seed 0 so the comparison is like forlike; winners then go through launch_flagship_topup.py as usual.
usage: parity_sweep.py [--top 3] [--print-only] [task ...]"""from __future__ import annotations
import argparseimport globimport reimport subprocessimport sysfrom pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent))from verdict_table import cells, pool, rate # noqa: E402from launch_flagship_topup import ENVS, POLF, BASE_LABEL, _ck_suffix, ckpt # noqa: E402
ROOT = Path("/proj/dmfexp/zwhong/rsm_rise")
def recipes(c, head): out = {} for (a, p) in {(a, p) for (a, p, _, _) in c if a[0] == f"rsm:{head}"}: m = re.match(r"(\S+)@(\S+) b([\d.]+) L(\d+) N(\d+)", a[1]) if not m: continue sr, n = rate(pool(c, lambda x, q, A=a, P=p: x == A and q == P)) key = (p, float(m.group(3)), int(m.group(4)), int(m.group(5))) if key not in out or sr > out[key][0]: out[key] = (sr, n, m.group(1), m.group(2)) return out
def main(): ap = argparse.ArgumentParser() ap.add_argument("tasks", nargs="*") ap.add_argument("--top", type=int, default=3, help="untested recipes per task, best-first by progress score") ap.add_argument("--print-only", action="store_true") ap.add_argument("--queue", default="preemptable") a = ap.parse_args() for task in (a.tasks or list(ENVS)): if task not in ENVS: continue c = cells(task) pr, me = recipes(c, "progress"), recipes(c, "membership") if not pr: continue gap = sorted(set(pr) - set(me), key=lambda k: -pr[k][0])[:a.top] if not gap: print(f"### {task}: membership already covers every progress recipe") continue # a membership successor checkpoint to score with: prefer the one the task's own arms use mem_ck = None for (p_, b_, l_, n_) in sorted(me, key=lambda k: -me[k][0]): mem_ck = (me[(p_, b_, l_, n_)][2], me[(p_, b_, l_, n_)][3]) break if not mem_ck: print(f"### {task}: no membership arm to take a successor checkpoint from -- skipped") continue model, ck = mem_ck ckpt_path = ROOT / f"runs/{task}/rsm/{model}/ckpt_{ck}.pt" if not ckpt_path.is_file(): print(f"### {task}: {ckpt_path} missing -- skipped") continue label = BASE_LABEL.get(model, model) + _ck_suffix(ck) print(f"\n### {task} scoring with {label} ({model}@{ck})") for (prop, beta, hops, N) in gap: fam = POLF.get(prop) pol = ckpt(task, fam, 0) if fam else None if not pol: print(f" SKIP {prop} b{beta} L{hops} N{N}: no {fam}_seed0 checkpoint") continue mode = "d1" if hops == 1 else "fold" print(f" launch {prop:<12} b{beta} L{hops} N{N} (progress scored {pr[(prop,beta,hops,N)][0]:.1f}%)") cmd = [sys.executable, str(ROOT / "scripts" / "launch_e1_grid.py"), "--task", task, "--env", ENVS[task], "--model", f"{label}={ckpt_path}:mlp", "--hop", str(ROOT / "runs" / task / "hop" / "gauss" / "policy_r1.pt"), "--policy", f"{fam}s0={pol}", "--cells", f"{label},{beta},{hops},{mode},{N},argmax,{fam}s0", "--num-rollouts", "50", "--horizon", "400", "--eval-seed", "0", "--tag", "PARITY-es0", "--out-dir", str(ROOT / "runs" / task / "eval_parity"), "--pack", "3", "--queue", a.queue] if a.print_only: cmd.append("--print-only") subprocess.run(cmd, check=False, stdout=subprocess.DEVNULL)
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195#!/usr/bin/env python3"""gen_q#266: the read-out table — `prob` vs `logit` vs `prob_log` on the RISE actor (S0A).
One arm = (task, read-out, beta, hops). One cell = (policy seed, eval seed), so a full arm is 3x3 = 9cells. ONLY fully-seeded arms are quoted; the rest are counted and excluded, never averaged over whathappens to have finished.
Every score is printed with its health numbers, per the standing rule that a self-implemented scorer isnot reportable without something a reader can check:
ties mean over decision steps of how many of the 128 candidates tie at the arg-max of the RANKING array, at the 1e-6 absolute tolerance the other read-outs use. For prob_log this tolerance is not meaningful (the quantity spans 40+ orders of magnitude: ~124 where every candidate succeeds, ~1e-44 in a hopeless state), so `dist` below is the one to read. dist mean number of DISTINCT values in the array -- tolerance-free. 128 = a total order. p_ties ties of the PROBABILITY array on the same states, whatever ranks. This is the within-cell control: it says what `prob` would have tied on exactly these states. sat frac_saturated_mean, the share of candidates with Q >= 0.999.
usage: problog_table.py [--md] [task ...]"""import argparseimport globimport jsonimport osimport reimport statistics as stfrom collections import defaultdict
ROOT = "/proj/dmfexp/zwhong/rsm_rise"TASKS = ("threading_expert_play", "mug_expert_suboptimal", "two_piece_expert_play")# out-dir -> how to name the read-out of a cell found thereDIRS = {"eval_readout": None, "eval_problog": "P16 prob_log"}CELL = re.compile(r"^E1-(?P<model>[A-Za-z0-9_]+)-R(?P<beta>[0-9.]+)-(?P<L>\d+)-N(?P<n>\d+)-" r"(?P<rule>[a-z]+)-(?P<tag>[A-Za-z0-9]+)-es(?P<es>\d+)-s(?P<pol>S0As\d+)$")# eval_readout tags: RO16prob / RO16logit / RO256probRO = re.compile(r"^RO(?P<p>\d+)(?P<kind>prob|logit)$")PROBLOG = re.compile(r"^PROBLOG(?P<p>\d+)$")# the matched `prob` baseline this launcher submits itself, for the tasks the read-out sweep never covered.# Kept a SEPARATE row from the archived eval_readout "P16 prob" so the two are never silently merged.PROBBASE = re.compile(r"^PROBBASE(?P<p>\d+)$")
def readout_of(tag): m = RO.match(tag) if m: return f"P{m.group('p')} {m.group('kind')}" m = PROBLOG.match(tag) if m: return f"P{m.group('p')} prob_log" m = PROBBASE.match(tag) if m: return f"P{m.group('p')} prob-matched" return None
def load(task): """-> {(readout, beta, L): {(pol, es): (success, health dict)}}""" arms = defaultdict(dict) for d in DIRS: for f in glob.glob(os.path.join(ROOT, "runs", task, d, "*.json")): base = os.path.basename(f)[:-5] m = CELL.match(base) if not m: continue ro = readout_of(m.group("tag")) if ro is None or m.group("n") != "128" or m.group("rule") != "argmax": continue try: j = json.load(open(f)) except Exception: continue if j.get("partial") or j.get("num_episodes", 0) < 50: continue pl = j.get("planner") or {} # guard against a mislabelled directory: the cell's own recorded plan_score must match the # read-out the NAME claims. A tag that does not match the fingerprint is dropped, loudly. want = ro.split()[1].replace("prob-matched", "prob") got = pl.get("plan_score") if got != want: print(f" !! {task}/{d}/{base}: name says {want}, JSON says {got} -- dropped") continue pt = j.get("planner_time") or {} eps = [e.get("plan") for e in (j.get("episodes") or []) if e.get("plan")]
def avg(k): # nan is how eval.py's cell-level roll-up spells "this diagnostic did not exist when the # cell ran"; treat it as absent rather than letting it poison a mean. v = [e[k] for e in eps if isinstance(e, dict) and e.get(k) is not None and e[k] == e[k]] if v: return sum(v) / len(v) w = pt.get(k) return w if (w is not None and w == w) else None h = {k: avg(k) for k in ("ties_at_max_mean", "frac_saturated_mean", "prob_ties_at_max_mean", "prob_log_distinct_mean", "prob_distinct_mean", "score_std_mean")} key = (ro, float(m.group("beta")), int(m.group("L"))) arms[key][(m.group("pol"), int(m.group("es")))] = (100.0 * j["success_rate"], h) return arms
def fmt(v, nd=1): return "--" if v is None else f"{v:.{nd}f}"
def main(): ap = argparse.ArgumentParser() ap.add_argument("tasks", nargs="*", default=[]) ap.add_argument("--md", action="store_true", help="markdown table for the issue") a = ap.parse_args() tasks = a.tasks or list(TASKS) rows = [] for task in tasks: arms = load(task) by_ro = defaultdict(list) incomplete = defaultdict(int) for (ro, beta, L), cells in sorted(arms.items()): if len(cells) < 9: incomplete[ro] += 1 continue sc = [v[0] for v in cells.values()] med = st.median(sc) hs = [v[1] for v in cells.values()]
def hm(k): v = [h[k] for h in hs if h.get(k) is not None] return sum(v) / len(v) if v else None by_ro[ro].append((med, max(sc), hm("ties_at_max_mean"), hm("prob_log_distinct_mean"), hm("prob_ties_at_max_mean"), hm("frac_saturated_mean"))) for ro in sorted(by_ro): v = by_ro[ro] meds = [x[0] for x in v]
def col(i): w = [x[i] for x in v if x[i] is not None] return sum(w) / len(w) if w else None rows.append(dict(task=task, readout=ro, arms=len(v), median=st.median(meds), best=max(x[1] for x in v), ties=col(2), dist=col(3), p_ties=col(4), sat=col(5), excluded=incomplete.get(ro, 0))) for ro in sorted(set(incomplete) - set(by_ro)): rows.append(dict(task=task, readout=ro, arms=0, median=None, best=None, ties=None, dist=None, p_ties=None, sat=None, excluded=incomplete[ro])) hdr = ["task", "read-out", "arms", "median", "max", "ties", "dist", "p_ties", "sat", "excl"] if a.md: print("| " + " | ".join(hdr) + " |") print("|" + "|".join("---" for _ in hdr) + "|") else: print(("{:<24} {:<14} {:>4} {:>7} {:>6} {:>7} {:>6} {:>7} {:>6} {:>5}").format(*hdr)) for r in rows: cells = [r["task"], r["readout"], str(r["arms"]), fmt(r["median"]), fmt(r["best"]), fmt(r["ties"]), fmt(r["dist"]), fmt(r["p_ties"]), fmt(r["sat"], 3), str(r["excluded"])] if a.md: print("| " + " | ".join(cells) + " |") else: print(("{:<24} {:<14} {:>4} {:>7} {:>6} {:>7} {:>6} {:>7} {:>6} {:>5}").format(*cells)) tot_excl = sum(r["excluded"] for r in rows) print(f"\n{sum(r['arms'] for r in rows)} fully-seeded arm(s) quoted; " f"{tot_excl} arm(s) excluded for not having a full 3x3.")
if __name__ == "__main__": main()
# --------------------------------------------------------------------------- ## paired comparison: the same (beta, hops, policy seed, eval seed) under two read-outs# --------------------------------------------------------------------------- #def paired(task, ro_a, ro_b): """[(cell key, score_a, score_b)] over every cell present under BOTH read-outs.
This is the comparison that matters. Medians over arms mix 9 arms x 9 cells and hide the pairing; here each pair differs in ONE field (plan_score) with the same successor model, checkpoint, beta, hops, policy seed, eval seed, episode count and horizon, so the difference is attributable. """ arms = load(task) a = {(k[1], k[2]) + c: v[0] for k, cells in arms.items() if k[0] == ro_a for c, v in cells.items()} b = {(k[1], k[2]) + c: v[0] for k, cells in arms.items() if k[0] == ro_b for c, v in cells.items()} keys = sorted(set(a) & set(b), key=str) return [(k, a[k], b[k]) for k in keys]
def sign_test(pairs): """two-sided exact binomial sign test on the non-tied pairs -> (n, n_a_wins, n_ties, p).""" from math import comb wins = sum(1 for _, x, y in pairs if x > y) loss = sum(1 for _, x, y in pairs if x < y) ties = sum(1 for _, x, y in pairs if x == y) n = wins + loss if n == 0: return len(pairs), wins, ties, 1.0 k = min(wins, loss) p = min(1.0, 2.0 * sum(comb(n, i) for i in range(k + 1)) / 2.0 ** n) return len(pairs), wins, ties, p12345678910111213141516171819202122232425262728293031323334#!/usr/bin/env bash# gen_q#266: babysit the prob_log grid AND its matched `prob` baseline.## launch_problog_on_actor.py is idempotent -- launch_e1_grid skips cells whose JSON already exists and# cells that are already PEND/RUN -- so re-running it whenever nothing of ours is in flight is exactly# "resubmit whatever was preempted or vanished", with no risk of piling duplicates onto a busy queue.## Note for whoever restarts this: do NOT `pkill -f problog_watcher.sh`. The pattern matches the shell# that is running the kill (the script body appears in its command line), so it kills the caller too --# exit 144, and any file rewrite in the same command silently never happens. Kill it by PID:# kill $(pgrep -f "bash scripts/problog_watcher.sh")ROOT=/proj/dmfexp/zwhong/rsm_riseLOG=$ROOT/status/problog_watch.logTOTAL=${TOTAL:-324} # 243 prob_log cells + 81 matched-prob cells on two_piece_expert_playmkdir -p "$ROOT/status"# One instance only. Two watchers can both see a cell as "missing" in the same window and both# submit it, which wastes a GPU slot on a duplicate. flock makes a second start a no-op.exec 9>"$ROOT/status/.problog_watch.lock"flock -n 9 || { echo "$(date -u +%H:%M:%S) another watcher holds the lock; exiting" >> "$LOG"; exit 0; }for pass in $(seq 1 "${PASSES:-72}"); do done_n=$(ls $ROOT/runs/*/eval_problog/*.json 2>/dev/null | wc -l) inflight=$(bjobs -w 2>/dev/null | grep -E "PROBLOG16|PROBBASE16" | grep -cE "PEND|RUN") echo "$(date -u +%H:%M:%S) pass=$pass done=$done_n/$TOTAL inflight=$inflight" >> "$LOG" if [ "$done_n" -ge "$TOTAL" ]; then echo "$(date -u +%H:%M:%S) GRID COMPLETE" >> "$LOG" break fi if [ "$inflight" -eq 0 ]; then echo " nothing in flight; resubmitting missing cells" >> "$LOG" python3 $ROOT/scripts/launch_problog_on_actor.py >> "$LOG" 2>&1 python3 $ROOT/scripts/launch_problog_on_actor.py two_piece_expert_play --baseline >> "$LOG" 2>&1 fi sleep 600done123456789101112131415161718192021222324252627282930313233343536373839404142434445#!/usr/bin/env python3"""Collect the D3 (stitch-feasibility) numbers for the crossed v5 2x2 and its references into onemarkdown + LaTeX table. Reads only json written by stitch_feasibility.py; no compute."""import json, os, sysROOT = "/proj/dmfexp/zwhong/rsm_rise"S = f"{ROOT}/status/real"DRAWS = [("12345", f"{S}/STITCH_FEASIBILITY_2x2_seed12345.json"), ("777", f"{S}/STITCH_FEASIBILITY_2x2_seed777.json"), ("999", f"{S}/STITCH_FEASIBILITY_2x2_seed999.json")]ORDER = ["ft_v5", "ft_v5_x10", "ft_v5_x01", "ft_v5_s1", "shipped_R_M", "shipped_R_M_s1", "scratch_v0"]LABEL = {"ft_v5": "ft_v5 (trunk s0 x rng s0)", "ft_v5_x10": "ft_v5_x10 (trunk s0 x rng s1)", "ft_v5_x01": "ft_v5_x01 (trunk s1 x rng s0)", "ft_v5_s1": "ft_v5_s1 (trunk s1 x rng s1)", "shipped_R_M": "R_M shipped (provenance, no ft)", "shipped_R_M_s1": "R_M_s1 shipped", "scratch_v0": "R_RW_v0 from scratch (dataset rule)"}rows = {}for name, path in DRAWS: if not os.path.exists(path): print(f"[2x2] MISSING {path}", file=sys.stderr); continue d = json.load(open(path)) for h, v in d["heads"].items(): rows.setdefault(h, {})[name] = vpresent = [h for h in ORDER if h in rows] + [h for h in rows if h not in ORDER]def fmt(v, k): return "--" if v is None else f"{v[k]:.3f}"md = ["| head | draw | top1-rewarded | per-anchor AUC | frac anchors >0.5 | pooled AUC |", "|---|---|---|---|---|---|"]for h in present: for name, _ in DRAWS: v = rows[h].get(name) if v is None: continue md.append(f"| {LABEL.get(h,h)} | {name} | {fmt(v,'top1_rewarded_frac')} | " f"{fmt(v,'auc_per_anchor_mean')} | {fmt(v,'auc_per_anchor_frac_above_0.5')} | " f"{fmt(v,'auc_pooled')} |")open(f"{S}/D3_2x2_table.md", "w").write("\n".join(md) + "\n")tex = [r"\begin{tabular}{lrrrrr}\hline", r"head & draw & top1-rew. & per-anchor AUC & frac$>$0.5 & pooled AUC\\\hline"]for h in present: for name, _ in DRAWS: v = rows[h].get(name) if v is None: continue tex.append(f"{LABEL.get(h,h).replace('_',r'\_')} & {name} & {fmt(v,'top1_rewarded_frac')} & " f"{fmt(v,'auc_per_anchor_mean')} & {fmt(v,'auc_per_anchor_frac_above_0.5')} & " f"{fmt(v,'auc_pooled')}\\\\")tex.append(r"\hline\end{tabular}")open(f"{ROOT}/docs/tex/_d3_2x2.tex", "w").write("\n".join(tex) + "\n")print("\n".join(md))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244#!/usr/bin/env python"""Emit the LaTeX fragments the reward study inputs:
docs/tex/_stitch_and_cal.tex reward-head calibration + stitch control per fine-tuned variant (status/real/REWARD_FT_NUMBERS.json) docs/tex/_decisive.tex THE DECISIVE TEST -- D1 terminal separability, D2 junction ambiguity, D3 stitching feasibility, the v5 "RISE reward as shipped" correction, and the open-loop screen re-cut by episode provenance (status/real/DECISIVE_REWARD.json, STITCH_FEASIBILITY.json, V5_REWARD.json, OPENLOOP_BY_PROVENANCE.json)
Every table caption names the json it came from. Missing inputs degrade to a one-line "not landed"note so the PDF always builds."""import jsonfrom pathlib import Path
ROOT = Path("/proj/dmfexp/zwhong/rsm_rise")ST = ROOT / "status/real"TEX = ROOT / "docs/tex"
NICE = {"v0": "v0 provenance", "v1": "v1 goal transition", "v2": "v2 arrival", "v3": "v3 final segment", "v4": "v4 success tail", "v5": "v5 RISE provenance"}
def load(p): try: return json.loads((ST / p).read_text()) except Exception as e: print(f"[tex] missing {p}: {e}") return None
def esc(s): return str(s).replace("_", r"\_").replace("&", r"\&").replace("%", r"\%")
def f(x, n=3, dash="--"): try: if x is None: return dash v = float(x) return dash if v != v else f"{v:.{n}f}" except Exception: return dash
# ----------------------------------------------------------------- _stitch_and_cal.texft = load("REWARD_FT_NUMBERS.json")L = []if ft and "calibration" in ft: cal, st = ft["calibration"], ft.get("stitch", {}) L += [r"\begin{table}[htbp]\centering\small", r"\caption{\textbf{Health of every fine-tuned reward head}, from " r"\texttt{status/real/REWARD\_FT\_NUMBERS.json}. \emph{R-head AUC} separates that variant's own " r"positive frames from its negatives on the held-out episodes --- it says the head learned the " r"labels it was given, nothing more. \emph{CFM} is the flow-matching loss and \emph{nnl1 vs stay} " r"the chained-sample distance divided by the hold-still control ($>1$ = worse than standing " r"still). The stitch columns are the cross-trajectory control of " r"\texttt{scripts/real/stitch\_multihop.py} (\texttt{status/real/stitch\_multihop\_R\_M\_ft\_*.json}): " r"\emph{ratio} is the route-2 $\to$ route-3 splice distance over the within-route reference and " r"\emph{control} the same quantity for the route-1 splice, which must be worse.}" r"\label{tab:rheadcal}", r"\begin{tabular}{lrrrrrrr}\toprule", r"variant & step & R-head AUC & CFM & nnl1 vs stay & stitch ratio & control & $R$ logit \\\midrule"] for k in sorted(cal): c = cal[k]; s = st.get(k, {}) L.append(f"{esc(k)} & {c.get('step','--')} & {f(c.get('rhead_auc_val'),4)} & {f(c.get('cfm_val'))} & " f"{f(c.get('nnl1_ratio_vs_stay_val'))} & {f(s.get('ratio_median'))} & " f"{f(s.get('route1_control_median'))} & {f(s.get('rhead_logit_mean'),1)} \\\\") L += [r"\bottomrule\end{tabular}\end{table}"] L += [r"", r"\noindent\textbf{Read the AUC column with care.} An AUC of 1.000 means the head reproduces " r"\emph{its own} labels perfectly; for v0 those labels are ``this episode succeeded'', which is " r"decidable from provenance alone. v2's AUC is \texttt{NaN} because its 50 positive frames all fall " r"in the training split (2 in validation, both in one episode). What the head can actually " r"\emph{discriminate} is the subject of the next section.", r""]else: L = [r"\noindent\emph{(Health table not yet landed: status/real/REWARD\_FT\_NUMBERS.json missing.)}"](TEX / "_stitch_and_cal.tex").write_text("\n".join(L) + "\n")print("[tex] wrote _stitch_and_cal.tex")
# ----------------------------------------------------------------- _decisive.texD = load("DECISIVE_REWARD.json")S3 = load("STITCH_FEASIBILITY.json")V5 = load("V5_REWARD.json")PR = load("OPENLOOP_BY_PROVENANCE.json")L = [r"\clearpage", r"\section{The decisive test: can stitching be shown under this reward?}" r"\label{sec:decisive}", r"""The corpus has exactly the structure a stitching demonstration needs. State 2 (\emph{pan on stove,tomato at its initial position}) is visited by three different routes: route 2 (\texttt{0->2->3}), route 3(\texttt{2->3->4}, the \emph{only} rewarded route) and route 4 (\texttt{0->2->6}, a failure). So from onejunction state the data contains both a rewarded continuation and a failure continuation, and the twoterminals differ only in where the pan ends up (Fig.~\ref{fig:success} vs Fig.~\ref{fig:stage6}). What wasnever established is whether the \emph{trained reward head} can tell those apart --- and if it cannot, everygreen/red marking in a stitching figure is decoration. Three diagnostics answer that, all on cached featureswith no new training.""", r""]
if D: L += [r"\subsection{D1 --- can the head separate the two terminals?}", r"""$R(z)$ evaluated on every frame whose \texttt{annot.edge\_to} is 4 (rewarded: pan on grate,tomato in bowl) versus 6 (failure: pan on the stove, tomato in bowl), and on the last 30 frames of each suchepisode. 0.5 is chance. \texttt{scripts/real/decisive\_reward.py} $\to$\texttt{status/real/DECISIVE\_REWARD.json}.""", r"\begin{table}[htbp]\centering\small", r"\caption{\textbf{D1/D2 --- what each reward head can actually discriminate.} AUC of $R(z)$; " r"0.5 is chance. \emph{4 vs 6} is the decisive column: those two states differ only in where the " r"pan ends. \emph{4 vs 3} asks whether the head can tell the finished state from the mid-task " r"cooking state. \emph{junction} is D2: frames in the first 30 after leaving state 2, rewarded " r"continuation (route 3) versus failure continuation (route 4) --- physically the same situation, " r"so a provenance head should sit near chance or, worse, be confidently wrong." r"}\label{tab:decisive}", r"\begin{tabular}{lrrrrr}\toprule", r"head & 4 vs 6 (all) & 4 vs 6 (tail 30) & 4 vs 3 (tail) & 4 vs 5 (tail) & junction r3 vs r4 \\\midrule"] for k, h in D["heads"].items(): a = h["auc"] L.append(f"{esc(k)} & {f(a['D1_term4_vs_term6_allframes'],4)} & {f(a['D1_term4_vs_term6_tail'],4)} & " f"{f(a['D1_term4_vs_term3_tail'],4)} & {f(a['D1_term4_vs_term5_tail'],4)} & " f"{f(a['D2_junction_leave_r3_vs_r4'],4)} \\\\") L += [r"\bottomrule\end{tabular}\end{table}", r""]else: L += [r"\noindent\emph{(D1/D2 not yet landed: status/real/DECISIVE\_REWARD.json missing; LSF rr\_decisive.)}", r""]
if S3: L += [r"\subsection{D3 --- the demonstration number}", r"""Standing at a junction state \emph{as it is actually visited on the failure route} (the last 40frames before route-4 episodes leave state 2), 128 candidate action chunks are scored: 64 drawn from therewarded continuation (route 3, segment $2\to3$) and 64 from the failure continuation (route 4, segment$2\to6$). Logged chunks are used rather than proposer samples precisely so that the label ``this candidatecontinues toward the goal'' is ground truth. The read-out is the flagship one --- \texttt{d1}, $\beta=0.99$,16 particles, probability, $T=25$, argmax over 128 --- identical to\texttt{status/real/openloop\_*/scorer\_openloop.json}. Chance is 0.5 for both columns.\texttt{scripts/real/stitch\_feasibility.py} $\to$ \texttt{status/real/STITCH\_FEASIBILITY.json}.""", r"\begin{table}[htbp]\centering\small", r"\caption{\textbf{D3 --- does $Q$ separate the rewarded continuation from the failure " r"continuation at the shared junction state?} \emph{AUC} pooled over all anchors and averaged " r"per anchor; \emph{top-1} is how often the argmax of 128 is a rewarded-continuation chunk " r"(chance $0.5$); \emph{spread} is the mean max$-$min of the 128 scores, i.e.\ how much dynamic " r"range the ranking has at all.}\label{tab:d3}", r"\begin{tabular}{lrrrrr}\toprule", r"head & AUC (pooled) & AUC (per anchor) & frac anchors $>0.5$ & top-1 rewarded & score spread \\\midrule"] for k, h in S3["heads"].items(): L.append(f"{esc(k)} & {f(h['auc_pooled'],4)} & {f(h['auc_per_anchor_mean'],4)} & " f"{f(h['auc_per_anchor_frac_above_0.5'],3)} & {f(h['top1_rewarded_frac'],3)} & " f"{h['score_spread_mean']:.2e} \\\\") L += [r"\bottomrule\end{tabular}\end{table}", r""]else: L += [r"\noindent\emph{(D3 not yet landed: status/real/STITCH\_FEASIBILITY.json missing; LSF rr\_d3stitch.)}", r""]
if V5: L += [r"\subsection{A correction: the reward RISE trains on is not the reward the dataset defines}", r"""The robomimic conversion labels an episode \emph{expert} when its final state is in $\{3,4\}$(\texttt{scripts/real/convert\_cooking\_hdf5.py:100}) and writes $+1$ on every frame of those episodes(\texttt{:150}), also storing that flag as the hdf5 attribute \texttt{success} (\texttt{:158}). The datasetcard is narrower: \textbf{``Reward state IDs: [4]''}, with\texttt{reward = float(goal\_reached == 1 and reached\_state\_id in reward\_states)}, and its state tablemarks state 3 as \emph{``[Cooking state] Pan on stove, Tomato in the pan --- Terminal in task: False ---Rewarded arrival: False''}. State 3 is therefore not a second success terminal; it is the mid-task statewith the tomato still in the pan, where routes 1 and 2 simply stop.""", r"\begin{center}\small\begin{tabular}{rrrcc}\toprule", r"terminal & episodes & frames & RISE calls it expert & dataset rewards it \\\midrule"] for t, v in sorted(V5["by_terminal_state"].items()): L.append(f"{t} & {v['n_eps']} & {v['frames']} & {'yes' if v['rise_expert'] else 'no'} & " f"{'yes' if v['dataset_rewarded'] else 'no'} \\\\") L += [r"\bottomrule\end{tabular}\end{center}", r"\noindent So RISE's critic is trained with $+1$ on every frame of " + str(V5["n_episodes_positive"]) + r" of 248 episodes (" + str(V5["pos_frames"]) + r" frames, " + f"{100*V5['frac_frames']:.1f}" + r"\% of the corpus), and " + str(V5["episodes_rise_says_expert_but_dataset_does_not_reward"]) + r" of those episodes never put the tomato in the bowl. The successor's own \texttt{v0} uses the " r"dataset rule instead (" + str(V5["n_episodes_positive_dataset_rule"]) + r" episodes). No successor cell had ever been trained on RISE's labels, so they were added as " r"\texttt{v5} (\texttt{scripts/real/make\_v5\_reward.py} $\to$ " r"\texttt{cache/real\_cooking\_v5/reward\_v5\_riseprov.f32.npy}, counts in " r"\texttt{status/real/V5\_REWARD.json}).", r""]
if PR: key = next((k for k in PR if PR[k].get("n_decisions", 0) > 100), None) if key: v = PR[key] L += [r"\subsection{The open-loop screen re-cut by episode provenance}", r"A natural defence of the open-loop numbers is that only " + str(v["n_rewarded_episodes"]) + r" of the " + str(len(v["episodes"])) + r" held-out episodes reach the goal, so on the rest ``agreeing with the logged chunk'' is " r"agreeing with a failure. That defence is testable and it fails: every learned scorer " r"ranks \emph{below} chance on the rewarded episodes too. " r"\texttt{scripts/real/openloop\_by\_provenance.py} $\to$ " r"\texttt{status/real/OPENLOOP\_BY\_PROVENANCE.json}, cell \texttt{" + esc(v.get("tag", key)) + r"}, " + str(v["n_decisions"]) + r" paired decisions, nothing re-scored.", r"\begin{table}[htbp]\centering\small", r"\caption{\textbf{Oracle rank percentile split by whether the episode reaches the goal.} " r"$1.0$ = the oracle's own pick, $0.0$ = the worst of 128; a plain sample (\texttt{greedy}) " r"and the permutation controls sit at $0.5$ by construction. Lower than $0.5$ means the " r"scorer systematically prefers candidates the oracle ranks badly." r"}\label{tab:provsplit}", r"\begin{tabular}{lrrrr}\toprule", r"scorer & all & rewarded eps & failure eps & route 3 only \\\midrule"] for k, r in v["scorers"].items(): L.append(f"{esc(k.replace('score_',''))} & {f(r['all']['rank_pct'],4)} & " f"{f(r['rewarded_eps']['rank_pct'],4)} & {f(r['failure_eps']['rank_pct'],4)} & " f"{f(r.get('route3',{}).get('rank_pct'),4)} \\\\") L += [r"\bottomrule\end{tabular}\end{table}", r""]
# ----------------------------------------------------------------- the verdictL += [r"\subsection{Verdict, and the smallest fix}", r"""\textbf{No head passes.} D1 looks perfect for v0/v1 --- AUC $1.000$ separating state 4 from state 6--- but D2 shows what that AUC is made of: the \emph{same} head separates the \emph{junction} frames ofroute 3 from those of route 4 with AUC $1.000$ as well, and route 3's junction frames are its \emph{first}frames, before the pan has been touched. The shipped head reads $R(z)=+24.4$ there and $-24.8$ on route 4,the same $\pm25$ it reads at the terminals (Table~\ref{tab:decisive}, logit means in\texttt{status/real/DECISIVE\_REWARD.json}). Sharper still: routes 2 and 3 both contain the physical edge$2\to3$, labelled $0$ in one recording and $+1$ in the other, and the head separates those two copies of thesame transition with AUC $1.000$. The head has learned \emph{which recording a frame belongs to}.And D3, which is the demonstration itself, comes out below chance for every head: the top-ranked of 128candidates is a rewarded-continuation chunk $3$--$28\%$ of the time (chance $50\%$), and for the shippedhead the chain from the \emph{top} candidate retrieves a state-6 failure frame ($0\%$ of particles in thegoal region) while the chain from the \emph{bottom} candidate retrieves a state-4 goal frame ($100\%$).""", r"", r"""\textbf{Why this is structural, not a training failure.} Only route 3 is rewarded, and route 3 isalso the only route that \emph{starts} at state 2 (\texttt{cache/real\_cooking\_v5/SEGMENTS.json}: route 3 is\texttt{2->3->4}, two segments, no \texttt{0->2} prefix). So within this corpus ``this state is on the way tothe goal'' and ``this frame was recorded in a route-3 session'' are the same predicate, and a per-frame labelthat is constant over the recording cannot distinguish them. No amount of relabelling inside the existingepisodes fixes that; v1, v2 and v3 are three different ways of slicing the same 50 recordings.""", r"", r"""\textbf{The smallest fix}, in increasing cost:\begin{enumerate}\itemsep1pt\item \textbf{Record route 5.} The dataset card already declares route 5 $=$ \texttt{1->3->4} with a target of 50 episodes and none collected. Route 5 and route 1 (\texttt{0->1->3}) share state 1, and route 5 reaches the goal --- a second junction with a success and a non-success continuation, recorded in the \emph{same} session style. Two junctions instead of one also breaks the ``route 3 is special'' cue.\item \textbf{Record a failure continuation out of state 3 in a route-3 session} (pour, then leave the pan on the stove $=$ state 6). That puts both terminals inside the \emph{same} recording family, which is the only thing that makes the reward a function of the scene rather than of the session.\item \textbf{Replace the provenance label with a state-based one:} the dataset's own rule \texttt{reward = float(goal\_reached == 1 and reached\_state\_id in [4])} is exactly v2 and is already state-based --- but it fires on 50 frames in 181{,}530, and the v2 heads measured here are the worst of the set (D1 AUC $0.11$--$0.33$). A detector-style label (``pan on grate'' from the scene, applied to every frame of every recording) is the version of v2 that would have enough positives to train on.\end{enumerate}""", r""]
(TEX / "_decisive.tex").write_text("\n".join(L) + "\n")print("[tex] wrote _decisive.tex")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270"""Emit the LaTeX table fragments for docs/tex/real_proposal_report.tex (owner request 2026-09-22, gen_q #263).
Every number is read from a file on disk; nothing is typed in by hand except the hold-still baseline, which isquoted from logs/lsf/rr_cpu_actnorm.1836483.out (scripts/tmp/action_norms_real.py, validation split).
Sources pi0.5 : the `EVAL step N:` lines of logs/lsf/rr_openpi_<run>.*.out (same parser as plot_proposal_curves.py) robomimic: <policy>/replay_e<E>/replay_eval.json and runs/real/replay/<tag>/replay_eval.json -> pooled_episode_mean.{xyz_l2_first_cm,xyz_l2_chunk_cm,...} (rise_replay_eval.py, stride 10, 25 eps) open-loop: status/real/openloop_S0Aidql_*/scorer_openloop.json (scorer_openloop.py, fixed harness) W&B : status/real/wandb_runs.json (scripts/tmp/wandb_public_and_list.py) + the per-run wandb_id.txt filesWrites docs/tex/_real_tables.tex and status/real/report_numbers.json."""import glob, json, os, re, collections
ROOT = "/proj/dmfexp/zwhong/rsm_rise"HOLD_FIRST, HOLD_CHUNK, HOLD_STEP = 0.81, 1.53, 0.22 # rr_cpu_actnorm.1836483.out, validation splitENT_PROJ = "richardrl/rsm_rise"
def tex(s): return s.replace("_", r"\_")
def path_tex(p): """A long absolute path typeset so it can break after every separator (\path{} never breaks).""" return r"\texttt{%s}" % (tex(p).replace("/", r"/\allowbreak ") .replace(r"\_", r"\_\allowbreak "))
# ----------------------------------------------------------------- pi0.5 EVAL linesPAT = re.compile(r"EVAL step (\d+): val: xyz_first=([0-9.]+)cm xyz_chunk=([0-9.]+)cm loss=([0-9.e-]+) " r"grip_acc=([0-9.]+), train_eval: xyz_first=([0-9.]+)cm xyz_chunk=([0-9.]+)cm")openpi = {}for run in ("stock_s0", "stock_s1", "rise_s0", "rise_s1", "riseadv_s0", "riseadv_s1"): pts = {} for f in glob.glob(f"{ROOT}/logs/lsf/rr_openpi_{run}.*.out"): for m in PAT.finditer(open(f, errors="ignore").read()): s = int(m.group(1)); s -= s % 500 pts[s] = tuple(float(x) for x in m.groups()[1:]) if pts: openpi[run] = sorted(pts.items())
# Display names + HF mirror file names. Every checkpoint here is trained on rsm_cooking_v5, this# project's own FR3 data; "robomimic" is only the framework RISE ships in (the .pth file format), so the# register names the checkpoint by ROLE and DATA, not by library (owner, 2026-09-22).HF_REPO = "https://huggingface.co/rli14/rsm_cooking_v5_checkpoints"DISPLAY = {"S0Aidql_seed0": r"RISE actor (rsm\_real)", "S0Aidql_seed1": r"RISE actor (rsm\_real)", "S0B_seed0": r"BC-union (rsm\_real)", "S0B_seed1": r"BC-union (rsm\_real)"}PLAIN = {k: v.replace(r"\_", "_") for k, v in DISPLAY.items()} # for rows that pass through tex()HF_NAME = {"S0Aidql_seed0": "rise_actor_rsm_real_s0_e3000.pth", "S0Aidql_seed1": "rise_actor_rsm_real_s1_e3000.pth", "S0B_seed0": "bc_union_rsm_real_s0_e5000.pth", "S0B_seed1": None, # second BC-union seed is not in the mirror "stock_s1": "pi05_bc_rsm_real_stock_s1_29999/"}
# ----------------------------------------------------------------- robomimic replay evalsdef load_replay(p): d = json.load(open(p)) m = d["pooled_episode_mean"] return dict(path=p, ckpt=d["ckpt"], stride=d["stride"], n_episodes=d["n_episodes"], first=m["xyz_l2_first_cm"], chunk=m["xyz_l2_chunk_cm"], first_max=m.get("xyz_l2_first_max_cm"), grip=m.get("grip_bin_acc"))
robo = collections.defaultdict(dict) # robo["S0Aidql_seed1"][3000] = {...}for p in glob.glob(f"{ROOT}/runs/cooking_v5_expert_suboptimal/policy/*/replay_e*/replay_eval.json"): fam = p.split("/policy/")[1].split("/")[0] e = int(re.search(r"replay_e(\d+)/", p).group(1)) robo[fam][e] = load_replay(p)for p in glob.glob(f"{ROOT}/runs/real/replay/*/replay_eval.json"): tag = p.split("/replay/")[1].split("/")[0] # e.g. S0Aidql_s1_e2500 m = re.match(r"(S0Aidql|S0B)_s(\d)_e(\d+)$", tag) if not m: continue fam, e = f"{m.group(1)}_seed{m.group(2)}", int(m.group(3)) robo[fam].setdefault(e, load_replay(p)) # the replay_e<E> copy wins if both exist
# ----------------------------------------------------------------- W&B urlswb = {} # display name -> url (the surviving run, see below)wb_rows = []wbjson = f"{ROOT}/status/real/wandb_runs.json"wb_meta = {}if os.path.exists(wbjson): blob = json.load(open(wbjson)) wb_meta = {k: v for k, v in blob.items() if k != "runs"} wb_rows = blob["runs"] # a cell that was preempted and resumed leaves several W&B runs under one display name; the one to link is the # newest that is not `crashed`/`failed` (that is the run the current job is still writing to). Sorted so the # preferred run is assigned LAST and therefore wins the dict slot. for r in sorted(wb_rows, key=lambda d: (d["state"] not in ("crashed", "failed"), d["created"])): wb[r["name"]] = r["url"]def wb_url_for(sub): for n, u in wb.items(): if sub in n: return u return Noneopenpi_ids = {}for f in glob.glob(f"{ROOT}/runs/openpi/checkpoints/*/*/wandb_id.txt"): openpi_ids[f.split("/")[-2]] = open(f).read().strip()
# ----------------------------------------------------------------- the policy / checkpoint tabledef latest_dir(fam): """Absolute path of the models/ dir holding the highest-epoch checkpoint of a robomimic family.""" best = (None, -1) for p in glob.glob(f"{ROOT}/runs/cooking_v5_expert_suboptimal/policy/{fam}/*/*/models/model_epoch_*.pth"): e = int(re.search(r"model_epoch_(\d+)\.pth", p).group(1)) if e > best[1]: best = (p, e) return best
POLICIES = [] # (role, policy, recipe, seed, steps, abspath, wandb url)for run, cfg in (("stock_s0", "pi05_cooking_stock"), ("stock_s1", "pi05_cooking_stock"), ("rise_s0", "pi05_cooking_rise"), ("rise_s1", "pi05_cooking_rise"), ("riseadv_s0", "pi05_cooking_riseadv")): d = f"{ROOT}/runs/openpi/checkpoints/{cfg}/{run}" steps = sorted(int(x) for x in os.listdir(d) if x.isdigit()) if os.path.isdir(d) else [] last = steps[-1] if steps else None rid = openpi_ids.get(run) url = f"https://wandb.ai/{ENT_PROJ}/runs/{rid}" if rid else None role = "BC" if run.startswith("stock") else "RISE actor" POLICIES.append((role, "pi0.5 " + run.rsplit("_s", 1)[0], cfg, run[-1], f"{last} steps", f"{d}/{last}", url, HF_NAME.get(run)))for fam, role in (("S0B_seed0", "BC"), ("S0B_seed1", "BC"), ("S0Aidql_seed0", "RISE actor"), ("S0Aidql_seed1", "RISE actor")): p, e = latest_dir(fam) POLICIES.append((role, DISPLAY[fam], "cooking_v5_expert_suboptimal", fam[-1], f"epoch {e}", p, wb_url_for(f"{fam}"), HF_NAME.get(fam)))
L = []A = L.appendA(r"% generated by scripts/real/build_real_report_tables.py -- do not edit by hand")A(r"\newcommand{\holdfirst}{%.2f}" % HOLD_FIRST)A(r"\newcommand{\holdchunk}{%.2f}" % HOLD_CHUNK)A(r"\newcommand{\holdstep}{%.2f}" % HOLD_STEP)
A(r"\begin{table}[htbp]\centering\small")A(r"\caption{Real-world (\texttt{rsm\_cooking\_v5}) proposal policies: role, recipe, seed, training length, " r"absolute checkpoint path, W\&B run and the file name in the Hugging Face mirror. Every row is fine-tuned " r"on \texttt{rsm\_cooking\_v5}, this project's own FR3 cooking data (\emph{robomimic}, where it appears " r"elsewhere, is the training framework RISE ships in --- a file format, not a data source). \emph{BC} rows are plain " r"behaviour cloning; \emph{RISE actor} rows carry the RISE/IDQL actor recipe and ship their co-trained IQL " r"critic in the same file. Epochs are the latest on disk at the time of writing. The \emph{HF mirror} column " r"gives the file name in the public Hugging Face repo (Sec.~\ref{sec:hf}); \emph{--} means that seed was not " r"mirrored.}")A(r"\label{tab:ckpt}")A(r"\begin{tabular}{@{}lllp{13mm}p{46mm}lp{30mm}@{}}\toprule")A(r"role & policy & seed & length & checkpoint (absolute) & W\&B & HF mirror name \\ \midrule")for role, pol, recipe, seed, steps, p, url, hfn in POLICIES: link = r"\href{%s}{run}" % url if url else "--" hf = (r"{\tiny \texttt{%s}}" % tex(hfn)) if hfn else "--" A(r"%s & %s & %s & %s & {\tiny %s} & %s & %s \\[2pt]" % (role, pol, seed, tex(steps), path_tex(p or "--"), link, hf))A(r"\bottomrule\end{tabular}\end{table}")
# ----------------------------------------------------------------- the fit table (ratios to hold-still)A(r"\begin{table}[htbp]\centering\small")A(r"\caption{Held-out fit on the 25 validation episodes, quoted as a ratio to the hold-still predictor " r"(copy the current end-effector xyz: \holdfirst~cm first action, \holdchunk~cm 8-step chunk mean; per-step " r"motion \holdstep~cm). Ratio $>1$ means better than hold-still. pi0.5 rows are the run's own " r"\texttt{EVAL step} lines at the last step; RISE-stack rows are " r"\texttt{replay\_eval.json:pooled\_episode\_mean} (stride 10, 25 episodes).}")A(r"\label{tab:fit}")A(r"\begin{tabular}{@{}llrrrrp{38mm}@{}}\toprule")A(r"policy & at & first (cm) & chunk (cm) & first ratio & chunk ratio & source \\ \midrule")A(r"hold-still & -- & %.2f & %.2f & 1.00 & 1.00 & \texttt{action\_norms\_real.py} \\ \midrule" % (HOLD_FIRST, HOLD_CHUNK))fitrows = []for run, pts in sorted(openpi.items()): s, v = pts[-1] fitrows.append((f"pi0.5 {run}", f"{s} steps", v[0], v[1], f"logs/lsf/rr_openpi_{run}.*.out"))for fam in ("S0Aidql_seed0", "S0Aidql_seed1", "S0B_seed0", "S0B_seed1"): if not robo[fam]: continue e = max(robo[fam]) r = robo[fam][e] fitrows.append((f"{PLAIN[fam]} s{fam[-1]}", f"epoch {e}", r["first"], r["chunk"], r["path"].replace(ROOT + "/", "")))for nm, at, f0, c0, src in fitrows: A(r"%s & %s & %.2f & %.2f & %.2f$\times$ & %.2f$\times$ & {\tiny %s} \\" % (tex(nm), tex(at), f0, c0, HOLD_FIRST / f0, HOLD_CHUNK / c0, path_tex(src)))A(r"\bottomrule\end{tabular}\end{table}")
# ----------------------------------------------------------------- per-epoch RISE-stack tableA(r"\begin{table}[htbp]\centering\small")A(r"\caption{Per-epoch held-out fit of the RISE-stack actors (\texttt{replay\_eval.json}, stride 10, 25 " r"validation episodes). Empty cells have no replay eval on disk.}")A(r"\label{tab:perepoch}")eps = sorted({e for fam in robo for e in robo[fam] if e >= 500})A(r"\begin{tabular}{@{}l" + "r" * len(eps) + r"@{}}\toprule")A(r"policy (first / chunk cm) & " + " & ".join(str(e) for e in eps) + r" \\ \midrule")for fam in ("S0Aidql_seed0", "S0Aidql_seed1", "S0B_seed0", "S0B_seed1"): cells = [] for e in eps: r = robo[fam].get(e) cells.append(r"\tiny %.2f/%.2f" % (r["first"], r["chunk"]) if r else "--") A(tex(f"{PLAIN[fam]} s{fam[-1]}") + " & " + " & ".join(cells) + r" \\")A(r"\bottomrule\end{tabular}\end{table}")
# ----------------------------------------------------------------- open-loop scorer comparisonol = []for d in sorted(glob.glob(f"{ROOT}/status/real/openloop_S0Aidql_*")): p = f"{d}/scorer_openloop.json" if os.path.exists(p): ol.append(json.load(open(p)))A(r"\begin{table}[htbp]\centering\small")if ol: A(r"\caption{Open-loop selection on the \texttt{S0Aidql} proposers' 128 candidates (fixed harness, " r"\texttt{scorer\_openloop.py}; stride 25, 25 episodes). \emph{greedy} is the proposer's own first " r"sample; \emph{permuted} rows are the score-shuffling controls. Lower is better.}") A(r"\label{tab:openloop}") A(r"\begin{tabular}{@{}llrrrr@{}}\toprule") A(r"cell & scorer & first (cm) & chunk (cm) & $\Delta$ vs greedy & win rate \\ \midrule") for d in ol: first = True for k in ("greedy", "idql", "rsm", "permuted:idql", "permuted:rsm", "random"): s = d["scorers"].get(k) if not s: continue A(r"%s & %s & %.3f & %.3f & %+.3f & %.3f \\" % (tex(d["tag"]) if first else "", tex(k), s["first_mean_cm"], s["chunk_mean_cm"], s["delta_vs_greedy_cm"], s["win_rate_vs_greedy"])) first = False A(r"\midrule") A(r"\bottomrule\end{tabular}")else: A(r"\caption{Open-loop selection comparison: pending.}\label{tab:openloop}") A(r"\begin{tabular}{@{}l@{}}\toprule pending \\ \bottomrule\end{tabular}")A(r"\end{table}")
# ----------------------------------------------------------------- the W&B sectionW = []if wb_meta: W.append(r"The project is \href{%s}{\texttt{%s}}." % (wb_meta["project_url"], tex(wb_meta["project"]))) ab, aa = wb_meta["access_before"], wb_meta["access_after"] W.append(r"The project's \texttt{access} field read back \texttt{%s} \emph{before} this run and \texttt{%s} " r"\emph{after}. \texttt{USER\_READ} is W\&B's \emph{public: anyone with the link can view}, so the " r"project %s. The reader/mutation script is \texttt{scripts/tmp/wandb\_public\_and\_list.py} " r"(run on a CPU node; it issues \texttt{upsertModel(access: USER\_READ)} only when the project is not " r"already public, and it was, so no mutation was sent)." % (tex(ab), tex(aa), r"was \textbf{already public} and needed no change" if ab == "USER_READ" else r"was made public by this run")) if wb_meta.get("upsert_error"): W.append(r"\textbf{The mutation was refused.} The exact API error was:") W.append(r"\begin{quote}\ttfamily\small %s \end{quote}" % tex(wb_meta["upsert_error"][:600])) W.append(r"The owner can flip it by hand in the project settings " r"(\emph{Settings} $\to$ \emph{Privacy} $\to$ \emph{Public}).") W.append(r"All %d cooking runs and their URLs are listed in \path{status/real/wandb_runs.json}; the " r"per-policy links are in Table~\ref{tab:ckpt}." % len(wb_rows)) if wb: W.append(r"\begin{table}[htbp]\centering\small\caption{Every \texttt{cooking} run in the project.}" r"\label{tab:wandb}\begin{tabular}{@{}llll@{}}\toprule") W.append(r"run & state & created & URL \\ \midrule") for r in sorted(wb_rows, key=lambda d: (d["name"], d["created"])): W.append(r"{\tiny %s} & %s & %s & {\tiny \href{%s}{%s}} \\" % (tex(r["name"]), tex(r["state"]), tex(r["created"]), r["url"], tex(r["url"].split("/runs/")[-1]))) W.append(r"\bottomrule\end{tabular}\end{table}")else: W.append(r"\textbf{Pending:} \texttt{scripts/tmp/wandb\_public\_and\_list.py} had not written " r"\path{status/real/wandb_runs.json} when this PDF was built.")open(f"{ROOT}/docs/tex/_real_wandb.tex", "w").write("\n".join(W) + "\n")
open(f"{ROOT}/docs/tex/_real_tables.tex", "w").write("\n".join(L) + "\n")json.dump(dict(hold=dict(first=HOLD_FIRST, chunk=HOLD_CHUNK, step=HOLD_STEP), openpi={k: v[-1] for k, v in openpi.items()}, robomimic={f: {str(e): r for e, r in v.items()} for f, v in robo.items()}, policies=[dict(zip(("role", "policy", "recipe", "seed", "length", "ckpt", "wandb"), p)) for p in POLICIES], openloop=[d["tag"] for d in ol], wandb=wb_meta), open(f"{ROOT}/status/real/report_numbers.json", "w"), indent=1)print("wrote docs/tex/_real_tables.tex and status/real/report_numbers.json")print("openpi runs:", sorted(openpi)); print("robomimic epochs:", {f: sorted(v) for f, v in robo.items()})print("open-loop cells:", [d["tag"] for d in ol]); print("wandb runs indexed:", len(wb))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199#!/usr/bin/env python"""LaTeX tables + JSON for the FINE-TUNED reward-head study (gen_q #261).
Sources, all named in the PDF: status/real/GOAL_REWARD.json label counts v0..v3 (make_goal_reward.py) status/real/SUCCESS_TAIL.json label counts v4 (make_v4_reward.py) runs/real_cooking_v5/rsm/R_M_ft_v*/history.json reward-head calibration at step 110000 status/real/stitch_multihop_R_M_ft_v*.json stitch control + reward head on rolled-out states status/real/openloop_FT_*/scorer_openloop.json+.npz open-loop screen on identical candidatesWrites docs/tex/_reward_tables2.tex and status/real/REWARD_FT_NUMBERS.json."""import json, glob, osfrom pathlib import Pathimport numpy as np
ROOT = Path("/proj/dmfexp/zwhong/rsm_rise")RUNS = ROOT / "runs/real_cooking_v5/rsm"ST = ROOT / "status/real"VERS = ["v0", "v1", "v2", "v3"]SEEDS = ["", "_s1"]LBL = {"v0": "v0 provenance", "v1": "v1 goal transition", "v2": "v2 arrival", "v3": "v3 final segment"}RULE = { "v0": "+1 on EVERY frame of a successful episode, 0 on every frame of a failed one", "v1": "+1 on every frame of the last run heading into state 4 (the whole 3->4 segment: approach, pour, pan return)", "v2": "+1 only on the single frame where the operator declares state 4 (the last frame of the episode)", "v3": "+1 on the final segment of EVERY episode, successful or not",}NPY = {"v0": "reward_v0_provenance.f32.npy", "v1": "reward_v1_goaltrans.f32.npy", "v2": "reward_v2_arrival.f32.npy", "v3": "reward_v3_finalseg.f32.npy"}KEY = {"v0": "v0_provenance_dense", "v1": "v1_goal_transition", "v2": "v2_arrival_only", "v3": "v3_final_segment_all_episodes"}OUT = {}
def esc(s): return str(s).replace("_", r"\_").replace("%", r"\%").replace("->", r"$\to$")
G = json.load(open(ST / "GOAL_REWARD.json")); by = {v["name"]: v for v in G["versions"]}T4 = json.load(open(ST / "SUCCESS_TAIL.json"))OUT["labels"] = {v: by[KEY[v]] for v in VERS}; OUT["v4_success_tail"] = T4L = []
# ---------- 1. the reward table: one row per variant, plain words + counts --------------------L.append(r"\begin{table}[htbp]\centering\footnotesize")L.append(r"\caption{\textbf{The reward rule, in one sentence per variant.} Counts over the whole cache " r"(181{,}530 frames / 248 episodes, of which 50 succeed). \texttt{status/real/GOAL\_REWARD.json}; " r"v4 in \texttt{status/real/SUCCESS\_TAIL.json}.}\label{tab:rewardrule}")L.append(r"\begin{tabular}{p{0.10\linewidth}p{0.52\linewidth}rrr}\toprule")L.append(r"variant & which frames are $+1$ & $+1$ frames & \% & eps.\ with a $+1$ \\\midrule")for v in VERS: d = by[KEY[v]] L.append(f"{esc(LBL[v])} & {esc(RULE[v])} & {d['pos_frames']} & {100*d['frac_frames']:.3f} & " f"{d['episodes_with_any_positive']}/248 \\\\")L.append(r"v4 success tail & $+1$ from the success marker to the end of a successful episode " r"--- \emph{identically equal to v2 here}: the marker IS the last frame in all 50 " r"(\texttt{SUCCESS\_TAIL.json}, tail $=1$ frame for every episode) & " f"{T4['v4']['pos_frames']} & {100*T4['v4']['frac_frames']:.3f} & " f"{T4['v4']['episodes_with_any_positive']}/248 \\\\")L.append(r"\bottomrule\end{tabular}\end{table}")
# ---------- 2. reward-head calibration after the fine-tune ------------------------------------cal = {}for v in VERS: for s in SEEDS: p = RUNS / f"R_M_ft_{v}{s}/history.json" if p.exists(): h = json.load(open(p))[-1] cal[v + s] = {k: h.get(k) for k in ("step", "rhead_auc_val", "rhead_auc_train", "rhead_mae_val", "rhead_pred_mean_pos_val", "rhead_pred_mean_neg_val", "rhead_pos_rate_val", "cfm_val", "nnl1_ratio_val", "nnl1_ratio_vs_stay_val", "q_success_auc")} cal[v + s]["success_auc"] = h["per_task"]["0"]["success_auc"]OUT["calibration"] = calL.append(r"\begin{table}[htbp]\centering\footnotesize")L.append(r"\caption{\textbf{Reward head after the 10k-step warm-start fine-tune} (step 110000; " r"\texttt{runs/real\_cooking\_v5/rsm/R\_M\_ft\_<v>[\_s1]/history.json}, last entry). " r"\emph{AUC} = held-out separation of $+1$ from $0$ frames by $R(z)$; \emph{pos}/\emph{neg} are its " r"mean predictions on those two sets; \emph{succ AUC} is the value's separation of successful from " r"failed episodes --- 1.000 for v0 only because v0's label IS episode success.}\label{tab:rheadcal}")L.append(r"\begin{tabular}{lrrrrrr}\toprule")L.append(r"cell & $R$ AUC (val) & $R$ MAE & mean $R$ on $+1$ & mean $R$ on $0$ & succ AUC & CFM val \\\midrule")for v in VERS: for s in SEEDS: k = v + s if k not in cal: continue c = cal[k] L.append(f"R\\_M\\_ft\\_{esc(v+s)} & {c['rhead_auc_val']:.4f} & {c['rhead_mae_val']:.4f} & " f"{c['rhead_pred_mean_pos_val']:.4f} & {c['rhead_pred_mean_neg_val']:.4f} & " f"{c['success_auc']:.4f} & {c['cfm_val']:.4f} \\\\")L.append(r"\bottomrule\end{tabular}\end{table}")
# ---------- 3. stitch control + reward head on rolled-out states ------------------------------sti = {}for v in VERS: for s in SEEDS: p = ST / f"stitch_multihop_R_M_ft_{v}{s}.json" if p.exists(): d = json.load(open(p)) h1 = d["multihop"][0] sti[v + s] = {"ratio_median": d["splice"]["ratio_median"], "route1_control_median": d["splice"]["route1_control_median"], "jump_median": d["splice"]["jump_median"], "own_future": h1["own_future"], "goal_region": h1["goal_region"], "random_pool": h1["random_pool"], "rhead_mean": h1["rhead_mean"], "rhead_logit_mean": h1["rhead_logit_mean"], "rhead_logit_sat_frac": h1["rhead_logit_sat_frac"]}OUT["stitch"] = stiif sti: L.append(r"\begin{table}[htbp]\centering\footnotesize") L.append(r"\caption{\textbf{Stitch control and the reward head on rolled-out states} " r"(\texttt{scripts/real/stitch\_multihop.py} $\to$ " r"\texttt{status/real/stitch\_multihop\_R\_M\_ft\_<v>.json}). \emph{ratio} = splice jump / one-hop " r"motion at the cross-trajectory splice; its control is the same measurement inside a single " r"route (\texttt{route1\_control\_median}, $\approx 1$ means the splice is not special. " r"Columns 4--6 are one 100-frame hop from held-out states: distance to the model's own future, " r"to the goal region, and to a random pool. \emph{sat} = fraction of rolled-out states on which " r"the reward logit is saturated.}\label{tab:stitchft}") L.append(r"\begin{tabular}{lrrrrrrr}\toprule") L.append(r"cell & ratio & control & own fut. & goal reg. & rand.\ pool & mean $R$ & sat \\\midrule") for k, c in sti.items(): L.append(f"R\\_M\\_ft\\_{esc(k)} & {c['ratio_median']:.4f} & {c['route1_control_median']:.4f} & " f"{c['own_future']:.3f} & {c['goal_region']:.3f} & {c['random_pool']:.3f} & " f"{c['rhead_mean']:.2e} & {c['rhead_logit_sat_frac']:.2f} \\\\") L.append(r"\bottomrule\end{tabular}\end{table}")
# ---------- 4. the open-loop screen (RISE recipe) ---------------------------------------------OL = []for tag, pretty in [("FT_S0Aidql_s0_e2000_d1_T25", "S0Aidql seed 0 @ epoch 2000"), ("FT_S0Aidql_s1_e2500_d1_T25", "S0Aidql seed 1 @ epoch 2500")]: p = ST / f"openloop_{tag}/scorer_openloop.json" if p.exists(): OL.append((tag, pretty, json.load(open(p)), ST / f"openloop_{tag}/scores.npz"))OUT["openloop"] = {}ORDER = ["greedy", "idql", "permuted:idql", "rsm", "permuted:rsm"] + \ [f"rsm@ft_{v}{s}" for v in VERS for s in SEEDS] + ["oracle"]PRETTY = {"greedy": "greedy (plain sample)", "idql": "IDQL critic", "permuted:idql": "\\quad permuted control", "rsm": "RSM flagship R\\_M (100k, v0 labels)", "permuted:rsm": "\\quad permuted control", "oracle": "oracle (best of the 128)"}for v in VERS: for s in SEEDS: PRETTY[f"rsm@ft_{v}{s}"] = f"RSM ft {esc(v+s)}"for tag, pretty, d, npz in OL: sc = d["scorers"] # paired per-decision comparison against the v0 fine-tune control paired = {} if npz.exists(): z = np.load(npz, allow_pickle=True) err = z["err_first"] # (n_dec, n_cand) cm def pick(name): key = "score_" + name.replace(":", "_") return err[np.arange(err.shape[0]), z[key].argmax(1)] if key in z.files else None base = pick("rsm@ft_v0") for k in sc: if k == "oracle": continue e = pick(k) if k != "greedy" else err[:, 0] if e is None or base is None: continue dd = e - base paired[k] = {"mean_cm": float(e.mean()), "delta_vs_ftv0_cm": float(dd.mean()), "se_cm": float(dd.std(ddof=1) / np.sqrt(len(dd))), "win_vs_ftv0": float((e < base).mean()), "n": int(len(dd))} OUT["openloop"][tag] = {"n_episodes": d["n_episodes"], "n_decisions": d["n_decisions"], "valid_for_results": d["valid_for_results"], "scorers": sc, "paired": paired} L.append(r"\begin{table}[htbp]\centering\footnotesize") L.append(r"\caption{\textbf{Open-loop best-of-128 screen, " + esc(pretty) + r"} " r"(\texttt{scripts/real/scorer\_openloop.py}, N=128 diffusion candidates, argmax, prob read-out, " r"$T{=}25$, d1, $\beta{=}0.99$; " + f"{d['n_episodes']} held-out episodes, {d['n_decisions']} decisions" r"). Every scorer ranks the SAME 128 candidates at the SAME state, so the comparison is paired. " r"\emph{first} = cm between the chosen first action and the logged expert action (lower is closer " r"to the demonstrator); \emph{$\Delta$ vs ft\_v0} is the paired mean difference $\pm$ s.e.; " r"\emph{rank} is the chosen candidate's percentile in the oracle ordering (0.5 = chance). Source: " r"\texttt{status/real/openloop\_" + esc(tag) + r"/}.}\label{tab:ol" + tag.replace("_", "") + "}") L.append(r"\begin{tabular}{lrrrrr}\toprule") L.append(r"scorer & first (cm) & $\Delta$ vs ft\_v0 (cm) & win vs ft\_v0 & win vs greedy & rank pct \\\midrule") for k in ORDER: if k not in sc: continue v_ = sc[k]; p_ = paired.get(k) dcol = f"{p_['delta_vs_ftv0_cm']:+.4f} $\\pm$ {p_['se_cm']:.4f}" if p_ else "---" wcol = f"{p_['win_vs_ftv0']:.3f}" if p_ else "---" L.append(f"{PRETTY.get(k, esc(k))} & {v_['first_mean_cm']:.4f} & {dcol} & {wcol} & " f"{v_['win_rate_vs_greedy']:.3f} & {v_['oracle_rank_pct_mean']:.4f} \\\\") if k == "permuted:rsm": L.append(r"\midrule") L.append(r"\bottomrule\end{tabular}\end{table}")
Path(ROOT / "docs/tex/_reward_tables2.tex").write_text("\n".join(L) + "\n")(ST / "REWARD_FT_NUMBERS.json").write_text(json.dumps(OUT, indent=2, default=float))print("[rw2] wrote docs/tex/_reward_tables2.tex", len(L), "lines; open-loop tags:", [t for t, _, _, _ in OL])for tag in OUT["openloop"]: pr = OUT["openloop"][tag]["paired"] for k in ORDER: if k in pr: print(f" {tag} {k:20s} mean={pr[k]['mean_cm']:.4f} d_vs_ftv0={pr[k]['delta_vs_ftv0_cm']:+.4f}" f" +-{pr[k]['se_cm']:.4f} win={pr[k]['win_vs_ftv0']:.3f}")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276#!/usr/bin/env python"""LaTeX fragments for the reward-head study (gen_q #261): docs/tex/_reward_tables.tex.
Sources: status/real/GOAL_REWARD.json (label counts, written by scripts/real/make_goal_reward.py),runs/real_cooking_v5/rsm/R_RW_v*/{ckpt.pt,history.json} (training + health),status/real/stitch_multihop_R_RW_v*.json (chaining control),status/real/openloop_RW_*/scorer_openloop.json (open-loop selection on identical candidates)."""import json, globfrom pathlib import Pathimport numpy as np
ROOT = Path("/proj/dmfexp/zwhong/rsm_rise")RUNS = ROOT / "runs/real_cooking_v5/rsm"TEX = ROOT / "docs/tex/_reward_tables.tex"VERS = [("R_RW_v0", "v0 provenance (dense)", "reward_v0_provenance.f32.npy"), ("R_RW_v1", "v1 goal transition", "reward_v1_goaltrans.f32.npy"), ("R_RW_v2", "v2 arrival only", "reward_v2_arrival.f32.npy"), ("R_RW_v3", "v3 final segment (all eps)", "reward_v3_finalseg.f32.npy")]NAME2KEY = {"R_RW_v0": "v0_provenance_dense", "R_RW_v1": "v1_goal_transition", "R_RW_v2": "v2_arrival_only", "R_RW_v3": "v3_final_segment_all_episodes"}
def esc(s): return str(s).replace("_", "\\_").replace("%", "\\%")
G = json.load(open(ROOT / "status/real/GOAL_REWARD.json"))by = {v["name"]: v for v in G["versions"]}L = []
# ---- label counts -------------------------------------------------------------------------L.append(r"\begin{table}[htbp]\centering\small")L.append(r"\caption{The four reward labels, counted on \texttt{cache/real\_cooking\_v5} " r"(181{,}530 frames, 248 episodes). \emph{train}/\emph{val} use the SAME split every cell " r"trains on (\texttt{LiberoRSMData} seed 0, \texttt{val\_frac} 0.1, unstratified: 24 validation " r"episodes, of which %d are rewarded). Source: \texttt{status/real/GOAL\_REWARD.json}, produced by " r"\texttt{scripts/real/make\_goal\_reward.py}.}" % by["v0_provenance_dense"]["val_episodes_expert"])L.append(r"\label{tab:labels}")L.append(r"\begin{tabular}{lrrrrrr}\toprule")L.append(r"label & pos.\ frames & \% of frames & train & val & eps.\ with a pos. & of which suboptimal \\\midrule")for cell, lbl, _ in VERS: v = by[NAME2KEY[cell]] L.append(f"{esc(lbl)} & {v['pos_frames']} & {100*v['frac_frames']:.3f} & {v['pos_frames_train']} & " f"{v['pos_frames_val']} & {v['episodes_with_any_positive']}/248 & " f"{v['episodes_with_any_positive_suboptimal']} \\\\")L.append(r"\bottomrule\end{tabular}\end{table}")
# ---- per-route breakdown -----------------------------------------------------------------L.append(r"\begin{table}[htbp]\centering\small")L.append(r"\caption{Positive frames by route. Route 3 (\texttt{2->3->4}) is the ONLY route that reaches the " r"goal state 4, and it is exactly the set of 50 episodes the cache marks \texttt{ep\_success}. " r"Source: \texttt{status/real/GOAL\_REWARD.json}, \texttt{by\_route}.}")L.append(r"\label{tab:byroute}")routes = sorted(by["v0_provenance_dense"]["by_route"], key=int)L.append(r"\begin{tabular}{lll" + "r" * len(VERS) + r"}\toprule")L.append(r"route & path & eps & " + " & ".join(esc(l) for _, l, _ in VERS) + r" \\\midrule")for rt in routes: row = by["v0_provenance_dense"]["by_route"][rt] cells = [] for cell, _, _ in VERS: b = by[NAME2KEY[cell]]["by_route"][rt] cells.append(f"{b['pos_frames']}") L.append(f"{rt} & \\texttt{{{esc(row['path'])}}} & {row['n_eps']} & " + " & ".join(cells) + r" \\")L.append(r"\bottomrule\end{tabular}\end{table}")
# ---- FINE-TUNED cells (run 2: the owner's correction -- finetune, do not retrain) ---------# Every ft cell starts from the flagship successor's own step-100000 checkpoint (R_M for seed 0,# R_M_s1 for seed 1), swaps in the new per-frame reward labels and runs 10k further steps at the# checkpoint's final learning rate (3e-4; train_rsm.py has no LR schedule). Mechanics and the# guard that stops a preempted cell rewinding: scripts/rr_rsm.sh, cells R_M_ft_v*.FT = [("R_M_ft_v0", "v0 provenance (control)"), ("R_M_ft_v1", "v1 goal transition"), ("R_M_ft_v2", "v2 arrival only"), ("R_M_ft_v3", "v3 final segment (all eps)"), ("R_M_ft_v0_s1", "v0 provenance (control), seed 1"), ("R_M_ft_v1_s1", "v1 goal transition, seed 1"), ("R_M_ft_v2_s1", "v2 arrival only, seed 1"), ("R_M_ft_v3_s1", "v3 final segment, seed 1")]BASE = [("R_M", "flagship, provenance label (not fine-tuned)"), ("R_M_s1", "flagship seed 1 (not fine-tuned)")]
def read_cell(cell, label, stitch_prefix="stitch_multihop_"): d = RUNS / cell rec = {"cell": cell, "label": label, "step": None, "hist": {}, "ckpt": None} ck = sorted(glob.glob(str(d / "ckpt_s*.pt")), key=lambda f: int(f.split("_s")[-1].split(".")[0])) rec["ckpt"] = ck[-1] if ck else (str(d / "ckpt.pt") if (d / "ckpt.pt").exists() else None) if (d / "history.json").exists(): h = json.load(open(d / "history.json")) if h: rec["hist"] = h[-1]; rec["step"] = h[-1].get("step") sm = ROOT / f"status/real/{stitch_prefix}{cell}.json" rec["stitch"] = json.load(open(sm)) if sm.exists() else None return rec
def health_table(rows, caption, label): out = [r"\begin{table}[htbp]\centering\small", r"\caption{%s}" % caption, r"\label{%s}" % label, r"\begin{tabular}{llrrrrrr}\toprule", r"cell & label & step & r-auc val & r-mae val & pos rate & nnl1 ratio & vs stay \\\midrule"] for r_ in rows: h = r_["hist"] def g(k, f="{:.4f}"): v = h.get(k) return f.format(v) if isinstance(v, (int, float)) and np.isfinite(v) else "---" out.append(f"\\texttt{{{esc(r_['cell'])}}} & {esc(r_['label'])} & " f"{r_['step'] if r_['step'] is not None else '---'} & {g('rhead_auc_val')} & " f"{g('rhead_mae_val','{:.2e}')} & {g('rhead_pos_rate_val')} & {g('nnl1_ratio_val')} & " f"{g('nnl1_ratio_vs_stay_val')} \\\\") out.append(r"\bottomrule\end{tabular}\end{table}") return out
def chain_table(rows, caption, label): if not any(r_["stitch"] for r_ in rows): return [] out = [r"\begin{table}[htbp]\centering\small", r"\caption{%s}" % caption, r"\label{%s}" % label, r"\begin{tabular}{lrrrrr}\toprule", r"cell & splice ratio & rhead @1 hop & @2 & @4 & @8 \\\midrule"] for r_ in rows: s_ = r_["stitch"] if not s_: continue mh = {int(x["hops"]): x for x in s_["multihop"]} def rh(k): return f"{mh[k]['rhead_mean']:.2e}" if k in mh else "---" out.append(f"\\texttt{{{esc(r_['cell'])}}} & {s_['splice']['ratio_median']:.4f} & {rh(1)} & " f"{rh(2)} & {rh(4)} & {rh(8)} \\\\") out.append(r"\bottomrule\end{tabular}\end{table}") return out
ft_rows = [read_cell(c, l) for c, l in FT if (RUNS / c).exists()]base_rows = [read_cell(c, l) for c, l in BASE if (RUNS / c).exists()]L += health_table(base_rows + ft_rows, r"FINE-TUNED reward heads (the run-2 recipe) and the two un-fine-tuned flagship successors " r"they start from. Each \texttt{R\_M\_ft\_v*} cell loads \texttt{R\_M}'s (resp.\ " r"\texttt{R\_M\_s1}'s) step-100000 checkpoint -- weights, EMA target and optimiser state -- " r"swaps in the new per-frame label and runs 10{,}000 further steps at the same learning rate " r"($3\times10^{-4}$; \texttt{train\_rsm.py} has no LR schedule, so `the checkpoint's final " r"learning rate' and `the training learning rate' are the same number). Seed is matched to the " r"source cell, so the validation split is the source's. Numbers read from each cell's own " r"\texttt{runs/real\_cooking\_v5/rsm/<cell>/history.json}.", "tab:fthealth")L += chain_table(ft_rows, r"Chained-hop / stitch control re-measured on every fine-tuned checkpoint " r"(\texttt{scripts/real/stitch\_multihop.py}, $\beta_{hi}{=}0.99$, hop $=100$ frames, 256 " r"anchors). The reward changed, so this control cannot be inherited from \texttt{R\_M}. " r"Sources: \texttt{status/real/stitch\_multihop\_R\_M\_ft\_*.json}.", "tab:ftchain")
# ---- FINE-TUNED open-loop: all variants scored on ONE candidate set ------------------------olft = sorted(glob.glob(str(ROOT / "status/real/openloop_FT_*/scorer_openloop.json")))if olft: L.append(r"\begin{table}[htbp]\centering\small") L.append(r"\caption{Open-loop best-of-128 selection with the RISE recipe, fine-tuned reward heads. " r"Every column in a block ranks the SAME 128 candidate chunks at the SAME state (one proposal " r"pass per proposer; \texttt{scorer\_openloop.py --rsm-ckpt-extra}), so the comparison is paired " r"decision by decision. Settings are exactly the flagship read-out of " r"\texttt{status/real/openloop\_S0Aidql\_*}: $N{=}128$, argmax, prob read-out, $T{=}25$, mode d1 " r"depth 1, $\beta{=}0.99$, 16 particles, stride 25, horizon 8, the 25 held-out episodes. " r"\texttt{rsm} is the un-fine-tuned flagship \texttt{R\_M}, i.e. the tie-back control. Errors are " r"the first-action xyz error in cm (lower is better); $\Delta$ is against greedy; \emph{rank pct} " r"is where the pick lands in the oracle's ordering (0.5 = the sampling null). Sources: " r"\texttt{status/real/openloop\_FT\_*/scorer\_openloop.json}.}") L.append(r"\label{tab:ftopenloop}") L.append(r"\begin{tabular}{llrrrr}\toprule") L.append(r"proposer & scorer & first (cm) & $\Delta$ (cm) & win vs greedy & rank pct \\\midrule") for f in olft: d = json.load(open(f)) order = ["greedy", "idql", "permuted:idql", "rsm", "permuted:rsm"] + \ sorted(k for k in d["scorers"] if k.startswith("rsm@")) + ["oracle"] first = True for s_ in order: v = d["scorers"].get(s_) if not v: continue L.append(f"{esc(d['tag']) if first else ''} & {esc(s_)} & {v['first_mean_cm']:.4f} & " f"{v['delta_vs_greedy_cm']:+.4f} & {v['win_rate_vs_greedy']:.3f} & " f"{v['oracle_rank_pct_mean']:.3f} \\\\") first = False L.append(r"\midrule") L[-1] = r"\bottomrule\end{tabular}\end{table}"else: L.append(r"\emph{The fine-tuned open-loop cells had not landed when this PDF was built; their job ids are " r"in Sec.~\ref{sec:rwstatus}.}")
# ---- training / health -------------------------------------------------------------------rows = []for cell, lbl, _ in VERS: d = RUNS / cell rec = {"cell": cell, "label": lbl, "step": None, "hist": {}, "ckpt": None} ck = sorted(glob.glob(str(d / "ckpt_s*.pt")), key=lambda f: int(f.split("_s")[-1].split(".")[0])) rec["ckpt"] = ck[-1] if ck else (str(d / "ckpt.pt") if (d / "ckpt.pt").exists() else None) if (d / "history.json").exists(): h = json.load(open(d / "history.json")) if h: rec["hist"] = h[-1]; rec["step"] = h[-1].get("step") sm = ROOT / f"status/real/stitch_multihop_{cell}.json" rec["stitch"] = json.load(open(sm)) if sm.exists() else None rows.append(rec)
L.append(r"\begin{table}[htbp]\centering\small")L.append(r"\caption{FROM-SCRATCH control runs (\texttt{R\_RW\_v*}, 100k steps from random init). Health of each reward version at its last evaluated step, read from that cell's own " r"\texttt{runs/real\_cooking\_v5/rsm/R\_RW\_v*/history.json}. Architecture, cache, optimiser, " r"$\beta$ band, chunk, seed and step budget are identical to \texttt{R\_M}; ONLY the per-frame " r"reward label differs. \texttt{pos rate} is the fraction of validation anchors the label marks " r"positive, and is the denominator the AUC has to be read against.}")L.append(r"\label{tab:rwhealth}")L.append(r"\begin{tabular}{llrrrrrr}\toprule")L.append(r"cell & label & step & r-auc val & r-mae val & pos rate & nnl1 ratio & vs stay \\\midrule")for r_ in rows: h = r_["hist"] def g(k, f="{:.4f}"): v = h.get(k) return f.format(v) if isinstance(v, (int, float)) and np.isfinite(v) else "---" L.append(f"\\texttt{{{esc(r_['cell'])}}} & {esc(r_['label'])} & " f"{r_['step'] if r_['step'] is not None else '---'} & {g('rhead_auc_val')} & " f"{g('rhead_mae_val','{:.2e}')} & {g('rhead_pos_rate_val')} & {g('nnl1_ratio_val')} & " f"{g('nnl1_ratio_vs_stay_val')} \\\\")L.append(r"\bottomrule\end{tabular}\end{table}")
# ---- chaining control --------------------------------------------------------------------if any(r_["stitch"] for r_ in rows): L.append(r"\begin{table}[htbp]\centering\small") L.append(r"\caption{Chained-hop control per reward version (\texttt{scripts/real/stitch\_multihop.py}, " r"$\beta_{hi}{=}0.99$, hop $=100$ frames, 256 anchors). \texttt{rhead} is the mean reward-head " r"read-out at the end of the chain: under the provenance label it underflows within a few hops, " r"which is what leaves a planner with no gradient. Sources: " r"\texttt{status/real/stitch\_multihop\_R\_RW\_v*.json}.}") L.append(r"\label{tab:rwchain}") L.append(r"\begin{tabular}{lrrrrr}\toprule") L.append(r"cell & splice ratio & rhead @1 hop & @2 & @4 & @8 \\\midrule") for r_ in rows: s = r_["stitch"] if not s: continue mh = {int(x["hops"]): x for x in s["multihop"]} def rh(k): return f"{mh[k]['rhead_mean']:.2e}" if k in mh else "---" L.append(f"\\texttt{{{esc(r_['cell'])}}} & {s['splice']['ratio_median']:.4f} & {rh(1)} & " f"{rh(2)} & {rh(4)} & {rh(8)} \\\\") L.append(r"\bottomrule\end{tabular}\end{table}")
# ---- open loop ---------------------------------------------------------------------------ol = sorted(glob.glob(str(ROOT / "status/real/openloop_RW_*/scorer_openloop.json")))if ol: L.append(r"\begin{table}[htbp]\centering\small") L.append(r"\caption{Open-loop selection, one row block per reward version, run with " r"\texttt{scripts/real/scorer\_openloop.py} at the SAME proposer checkpoints, seed, stride, " r"candidate count and read-out settings as the \texttt{R\_M} cells of the successor report, so " r"the versions are compared on identical candidate sets. Errors in cm; $\Delta$ against greedy " r"(negative = better). Sources: \texttt{status/real/openloop\_RW\_*/scorer\_openloop.json}.}") L.append(r"\label{tab:rwopenloop}") L.append(r"\begin{tabular}{llrrrr}\toprule") L.append(r"cell & scorer & first (cm) & $\Delta$ (cm) & win vs greedy & rank pct \\\midrule") for f in ol: d = json.load(open(f)) first = True for s in ["greedy", "rsm", "permuted:rsm", "oracle"]: v = d["scorers"].get(s) if not v: continue L.append(f"{esc(d['tag']) if first else ''} & {esc(s)} & {v['first_mean_cm']:.4f} & " f"{v['delta_vs_greedy_cm']:+.4f} & {v['win_rate_vs_greedy']:.3f} & " f"{v['oracle_rank_pct_mean']:.3f} \\\\") first = False L.append(r"\midrule") L[-1] = r"\bottomrule\end{tabular}\end{table}"else: L.append(r"\emph{The open-loop selection comparison had not landed when this PDF was built; the cells " r"are listed in Sec.~\ref{sec:rwstatus}.}")
TEX.write_text("\n".join(L) + "\n")print("wrote", TEX)json.dump({"rows": [{k: v for k, v in r_.items() if k != "stitch"} for r_ in rows], "ft_rows": [{k: v for k, v in r_.items() if k != "stitch"} for r_ in ft_rows], "base_rows": [{k: v for k, v in r_.items() if k != "stitch"} for r_ in base_rows], "ft_openloop": {Path(f).parent.name: json.load(open(f))["scorers"] for f in olft}, "labels": G["versions"]}, open(ROOT / "status/real/REWARD_STUDY_NUMBERS.json", "w"), indent=2, default=str)print("wrote", ROOT / "status/real/REWARD_STUDY_NUMBERS.json")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232#!/usr/bin/env python"""Collect every number the successor report (gen_q #261) quotes, from files on disk, and emitLaTeX fragments + a machine-readable status/real/SUCCESSOR_NUMBERS.json.
Sources, all named in the PDF next to the number they produce: runs/real_cooking_v5/rsm/<cell>/ckpt.pt ["config"], ["step"] -- the knobs and the final step runs/real_cooking_v5/rsm/<cell>/history.json -- the training/eval curve the trainer wrote status/real/wandb_runs.json -- W&B ids/urls (written by the REAL_REPORT stream) status/real_cooking_stitch_arrivals.json -- cross-trajectory stitch control (feature space) status/real_cooking_stitch_multihop.json -- chained-hop control on R_M status/real_cooking_beta.json -- the beta band derivation status/real/GOAL_REWARD.json -- reward-version label counts status/real/openloop_S0Aidql_*/scorer_openloop.json + scores.npz -- open-loop selection + ties"""import json, glob, os, sysfrom pathlib import Pathimport numpy as np
ROOT = Path("/proj/dmfexp/zwhong/rsm_rise")RUNS = ROOT / "runs/real_cooking_v5/rsm"OUT = ROOT / "status/real/SUCCESSOR_NUMBERS.json"TEX = ROOT / "docs/tex"
ORDER = ["R_M", "R_M_s1", "R_M_notrunc", "R_M_notrunc_s1", "R_M_chunk20", "R_M_rterm40", "R_M_rterm40st", "R_M_rterm120", "R_L40", "R_L40_notrunc", "R_XL", "R_XL_notrunc", "R_RW_v0", "R_RW_v1", "R_RW_v2", "R_RW_v3"]KNOB = { "R_M": "flagship: width 1024, depth 4, seed 0, beta [0.95,0.99], trunc eps 0.02, chunk 8, dense reward", "R_M_s1": "R\\_M at training seed 1 (also reseeds the episode split)", "R_M_notrunc": "R\\_M with --beta-trunc-eps 0.99: the per-anchor beta cap never binds (pre-fix behaviour)", "R_M_notrunc_s1": "R\\_M\\_notrunc at seed 1", "R_M_chunk20": "R\\_M with --chunk 20 (0.40\\,s of motion at 50\\,Hz instead of 0.16\\,s)", "R_M_rterm40": "reward-mode terminal, k=40 frames (0.8\\,s, 2000 positives)", "R_M_rterm40st": "rterm40 with --stratify-success 1 (different val split; new baseline, not a drop-in)", "R_M_rterm120": "reward-mode terminal, k=120 frames (2.4\\,s, 6000 positives)", "R_L40": "width 1536, R\\_M otherwise", "R_L40_notrunc": "width 1536, cap disabled", "R_XL": "width 2048, R\\_M otherwise", "R_XL_notrunc": "width 2048, cap disabled", "R_RW_v0": "reward study v0: provenance label supplied as an array (must reproduce R\\_M)", "R_RW_v1": "reward study v1: goal-transition label (last contiguous edge\\_to==4 run)", "R_RW_v2": "reward study v2: arrival frames only (50 positives)", "R_RW_v3": "reward study v3: final segment of EVERY episode (provenance-free)",}
def esc(s): return str(s).replace("_", "\\_").replace("%", "\\%")
wb = {}p = ROOT / "status/real/wandb_runs.json"if p.exists(): for r in json.load(open(p))["runs"]: wb[r["name"]] = r
cells = []for name in ORDER: d = RUNS / name if not (d / "history.json").exists() and not (d / "ckpt.pt").exists(): continue rec = {"cell": name, "dir": str(d), "knob": KNOB.get(name, "")} try: import torch c = torch.load(d / "ckpt.pt", map_location="cpu", weights_only=False) rec["step"] = int(c["step"]); rec["config"] = c["config"] except Exception as e: rec["step"] = None; rec["config"] = {}; rec["ckpt_error"] = str(e) ck = sorted(glob.glob(str(d / "ckpt_s*.pt")), key=lambda f: int(f.split("_s")[-1].split(".")[0])) rec["ckpt_final"] = ck[-1] if ck else str(d / "ckpt.pt") rec["ckpt_all"] = ck h = [] if (d / "history.json").exists(): h = json.load(open(d / "history.json")) rec["n_evals"] = len(h) rec["history_last"] = h[-1] if h else {} rec["curve"] = [{k: e.get(k) for k in ["step", "cfm_val", "reward_auc", "rhead_auc_val", "rhead_mae_val", "q_action_winrate", "nnl1_ratio_val", "nnl1_ratio_vs_stay_val", "minmse_val", "q_mean"]} for e in h] r = wb.get(f"real_cooking_v5/rsm/{name}") rec["wandb"] = {"id": r["id"], "url": r["url"], "state": r["state"]} if r else None cells.append(rec)
# ---- open-loop selection cells ------------------------------------------------------------ol = []# report A quotes ONLY the flagship S0Aidql re-runs (the harness-fixed cells of #263 comment 5769487243).# openloop_FT_* belongs to the reward-head study (report B) and openloop_SMOKE_* is a 1-episode patch test.for f in sorted(glob.glob(str(ROOT / "status/real/openloop_S0Aidql_*/scorer_openloop.json"))): d = json.load(open(f)) rec = {k: d[k] for k in ("tag", "policy", "rsm_ckpt", "rsm_hop_ckpt", "rsm_mode", "rsm_depth", "rsm_beta", "rsm_score_kind", "rsm_temperature", "n_cand", "stride", "n_episodes", "n_decisions", "candidate_spread_xyz_cm", "valid_for_results") if k in d} rec["file"] = f rec["scorers"] = {k: {kk: vv for kk, vv in v.items()} for k, v in d["scorers"].items()} sp = Path(f).with_name("scores.npz") if sp.exists(): z = np.load(sp) for key, lbl in (("score_rsm", "rsm"), ("score_idql", "idql")): if key not in z.files: continue s = z[key] # TIE COUNT of the read-out: how often the argmax is not unique, and how much of the # 128-candidate array collapses to one value (float32 equality on the ranking array). mx = s.max(1, keepdims=True) n_at_max = (s == mx).sum(1) uniq = np.array([len(np.unique(row)) for row in s]) rec.setdefault("ties", {})[lbl] = { "decisions": int(s.shape[0]), "n_cand": int(s.shape[1]), "frac_decisions_with_tied_argmax": float((n_at_max > 1).mean()), "mean_n_at_max": float(n_at_max.mean()), "max_n_at_max": int(n_at_max.max()), "mean_unique_scores": float(uniq.mean()), "frac_decisions_all_identical": float((uniq == 1).mean()), "score_range_mean": float((s.max(1) - s.min(1)).mean()), } ol.append(rec)
rep = { "generated_by": "scripts/real/build_successor_tables.py", "cache": "cache/real_cooking_v5", "cells": cells, "openloop": ol, "stitch_arrivals": json.load(open(ROOT / "status/real_cooking_stitch_arrivals.json")), "stitch_multihop": json.load(open(ROOT / "status/real_cooking_stitch_multihop.json")), "beta_band": {k: v for k, v in json.load(open(ROOT / "status/real_cooking_beta.json")).items() if k != "lens"}, "goal_reward": (json.load(open(ROOT / "status/real/GOAL_REWARD.json")) if (ROOT / "status/real/GOAL_REWARD.json").exists() else None),}# per-variant stitch/chaining re-runs, if they existrep["stitch_per_cell"] = {}for f in sorted(glob.glob(str(ROOT / "status/real/stitch_multihop_*.json"))): rep["stitch_per_cell"][Path(f).stem.replace("stitch_multihop_", "")] = json.load(open(f))OUT.write_text(json.dumps(rep, indent=2, default=str))print("wrote", OUT)
# ---------------- LaTeX: register table ----------------------------------------------------L = []L.append(r"\begin{table}[htbp]\centering\small")L.append(r"\caption{Successor-model register on \texttt{cache/real\_cooking\_v5}. Every cell is " r"\texttt{rsm\_libero/train\_rsm.py} launched through \texttt{scripts/rr\_rsm.sh}; the knobs are read " r"back from each checkpoint's own \texttt{config} blob, not from the launcher. " r"Checkpoint paths are absolute. Source: \texttt{status/real/SUCCESSOR\_NUMBERS.json}.}")L.append(r"\label{tab:cells}")L.append(r"\begin{tabular}{llrrrrrl}\toprule")L.append(r"cell & reward & width & chunk & trunc & seed & step & W\&B \\\midrule")for c in cells: cf = c["config"] or {} rw = cf.get("reward_mode", "?") if cf.get("reward_npy"): rw = Path(cf["reward_npy"]).stem.replace("reward_", "").replace(".f32", "") elif rw == "terminal": rw = f"terminal k={cf.get('k_success')}" wbs = (r"\href{%s}{%s}" % (c["wandb"]["url"], c["wandb"]["id"][:8])) if c["wandb"] else "---" L.append(f"\\texttt{{{esc(c['cell'])}}} & {esc(rw)} & {cf.get('flow_width','?')} & " f"{cf.get('chunk','?')} & {cf.get('beta_trunc_eps','?')} & {cf.get('seed','?')} & " f"{c['step'] if c['step'] is not None else '---'} & {wbs} \\\\")L.append(r"\bottomrule\end{tabular}\end{table}")
# ---------------- LaTeX: health table ------------------------------------------------------L.append(r"\begin{table}[htbp]\centering\small")L.append(r"\caption{Health numbers at the final step of each cell, all read from that cell's own " r"\texttt{history.json} (the trainer's held-out evaluation). \texttt{cfm} is the flow " r"matching validation loss; \texttt{r-auc}/\texttt{r-mae} the reward head on the validation " r"episodes; \texttt{nnl1 ratio} the successor sample's nearest-neighbour $L_1$ to the episode's " r"own future divided by the same distance to a random pool (lower is better, $1.0$ = no better " r"than random); \texttt{vs stay} the same ratio against the hold-still predictor (>1 means the " r"sample is FARTHER from the future than simply staying put); \texttt{win} the fraction of " r"validation anchors where the logged action outranks a random one.}")L.append(r"\label{tab:health}")L.append(r"\begin{tabular}{lrrrrrrr}\toprule")L.append(r"cell & cfm val & r-auc val & r-mae val & nnl1 ratio & vs stay & minmse & win \\\midrule")for c in cells: h = c["history_last"] or {} def g(k, f="{:.4f}"): v = h.get(k) return f.format(v) if isinstance(v, (int, float)) else "---" L.append(f"\\texttt{{{esc(c['cell'])}}} & {g('cfm_val')} & {g('rhead_auc_val')} & " f"{g('rhead_mae_val','{:.2e}')} & {g('nnl1_ratio_val')} & {g('nnl1_ratio_vs_stay_val')} & " f"{g('minmse_val')} & {g('q_action_winrate')} \\\\")L.append(r"\bottomrule\end{tabular}\end{table}")
# ---------------- LaTeX: open-loop table ---------------------------------------------------L.append(r"\begin{table}[htbp]\centering\small")L.append(r"\caption{Open-loop selection on the \texttt{S0Aidql} proposers, 128 candidates per decision, " r"705 decisions over the 25 validation episodes, \emph{after} the frame-history fix " r"(\#263 comment 5769487243). Errors are the xyz $L_2$ of the chosen first action against the " r"logged one, in cm. $\Delta$ is against greedy (negative = better). " r"\texttt{rank} is the mean oracle-rank percentile of the chosen candidate (0.5 = blind). " r"Source files: \texttt{status/real/openloop\_*/scorer\_openloop.json}.}")L.append(r"\label{tab:openloop}")L.append(r"\begin{tabular}{llrrrr}\toprule")L.append(r"cell & scorer & first (cm) & $\Delta$ (cm) & win vs greedy & rank pct \\\midrule")for r_ in ol: if not r_.get("valid_for_results"): continue first = True for s in ["greedy", "idql", "permuted:idql", "rsm", "permuted:rsm", "oracle"]: v = r_["scorers"].get(s) if not v: continue L.append(f"{esc(r_['tag']) if first else ''} & {esc(s)} & {v['first_mean_cm']:.4f} & " f"{v['delta_vs_greedy_cm']:+.4f} & {v['win_rate_vs_greedy']:.3f} & " f"{v['oracle_rank_pct_mean']:.3f} \\\\") first = False L.append(r"\midrule")L[-1] = r"\bottomrule\end{tabular}\end{table}"
# ---------------- LaTeX: tie table ---------------------------------------------------------L.append(r"\begin{table}[htbp]\centering\small")L.append(r"\caption{Ties in the ranking array, computed here from the per-decision score matrices " r"\texttt{status/real/openloop\_*/scores.npz} ($705\times128$ float32). " r"\emph{tied argmax} is the fraction of decisions where more than one candidate attains the " r"maximum; \emph{unique} the mean number of distinct score values among the 128 candidates; " r"\emph{range} the mean max$-$min of the score array. A saturated \texttt{prob} read-out shows " r"itself as a small unique count and a near-zero range.}")L.append(r"\label{tab:ties}")L.append(r"\begin{tabular}{llrrrr}\toprule")L.append(r"cell & scorer & tied argmax & mean at max & unique / 128 & range \\\midrule")for r_ in ol: for s, t in (r_.get("ties") or {}).items(): L.append(f"{esc(r_['tag'])} & {esc(s)} & {t['frac_decisions_with_tied_argmax']:.3f} & " f"{t['mean_n_at_max']:.2f} & {t['mean_unique_scores']:.1f} & " f"{t['score_range_mean']:.3e} \\\\")L.append(r"\bottomrule\end{tabular}\end{table}")
(TEX / "_succ_tables.tex").write_text("\n".join(L) + "\n")print("wrote", TEX / "_succ_tables.tex")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307#!/usr/bin/env python3"""gen_q#278 FIGURE B step 1 -- solve the global camera from the data, and report its error.
Owner, 2026-09-23 12:30Z: "we have the robot urdf and the training images. we can counterfactually doforward kinematics and render directions of the actions" -- and the camera pose does NOT have to come fromreal/config/calibration.yaml (which holds only resolution / serial / exposure, no intrinsics or extrinsics).Solve it from thousands of logged correspondences instead.
CORRESPONDENCES 3D data/raw/cooking_v5_expert_suboptimal.hdf5 obs/robot0_eef_pos -- absolute EE xyz, robot base frame. (obs/ee_state[:3] is the same array; eef_pos is used because it is unambiguously the position block.) 2D data/real/rsm_cooking_v5/videos/chunk-000/observation.images.global/episode_%06d.mp4 at 640x480. NOTE the owner's note pointed at data/real/lerobot_home -- that tree is EMPTY on this filesystem; the full-res LeRobot frames live under data/real/rsm_cooking_v5. hdf5 demo_N.attrs['episode_index'] == N and annot/frame_index is 0..T-1, so the pairing is by index with no interpolation.
PIXEL DETECTOR (the arm is the only thing that moves) background = per-episode median over the sampled frames; diff = |frame - background| in grayscale; threshold = max(--abs-thresh, Otsu); morphological open/close; connected components. REJECT a frame when: no blob above --min-area; the second largest blob exceeds --split-frac of the largest (a split silhouette); the blob exceeds --max-area-frac of the image; or the blob spans --frame-span-frac of BOTH image dimensions (a lighting change rather than the arm). There is deliberately NO "touches the border" rule: the FR3 is anchored off-frame so its silhouette reaches the image edge in almost every frame -- the first smoke run (LSF 1886290) rejected 172 of 200 frames on exactly that rule, which is why it is not used. Two pixel estimators are reported side by side, because the centroid of the whole arm silhouette is NOT a fixed 3D point and that bias is the main thing that can wreck this fit: centroid -- centroid of the largest moving blob (the owner's recipe); tipmotion -- centroid of the top --tip-pct percentile of |frame[t]-frame[t-k]| inside that blob, i.e. the fastest-moving pixels; distaltip -- mean of the blob pixels in the top --distal-pct percentile of distance from the blob's own border-touching pixels (the arm's off-frame base), i.e. the distal end of the arm. Smoke LSF 1886310 (8 eps, 194 correspondences): centroid held-out 65.4 px, tipmotion 102.5 px -- the whole-silhouette centroid is NOT a fixed 3D point and the fastest-moving pixels track the elbow as often as the gripper, which is why distaltip was added.
FIT Hartley-normalised DLT for the full 3x4 P (11 dof) inside a RANSAC loop, then a least-squares refit on the inliers. Episodes are split by EPISODE (never by frame) into fit / held-out, so the reported residual is on frames from episodes the fit never saw. Median and p90 reprojection error in pixels at 640x480.
The gate the owner set: median held-out residual < ~10 px -> the overlay is trustworthy for arrowdirections. Worse than that and we publish the base-frame panels only and say so."""import argparse, json, os, sysimport numpy as np
ROOT = "/proj/dmfexp/zwhong/rsm_rise"VID = ROOT + "/data/real/rsm_cooking_v5/videos/chunk-000/observation.images.global/episode_%06d.mp4"H5 = ROOT + "/data/raw/cooking_v5_expert_suboptimal.hdf5"
def decode(path, idxs): """Return {frame_index: HxWx3 uint8} for the requested indices, decoding the file once.""" import av want = set(int(i) for i in idxs) out = {} with av.open(path) as c: st = c.streams.video[0] st.thread_type = "AUTO" for n, fr in enumerate(c.decode(st)): if n in want: out[n] = fr.to_ndarray(format="rgb24") if len(out) == len(want): break return out
def detect(frames, idxs, a): """frames: {i: rgb}. Returns list of (frame_index, px_centroid, px_tipmotion) for accepted frames.""" import cv2 ks = sorted(frames) if len(ks) < 5: return [], {"too_few_frames": len(ks)} stack = np.stack([cv2.cvtColor(frames[k], cv2.COLOR_RGB2GRAY) for k in ks]) bg = np.median(stack, axis=0).astype(np.uint8) Himg, Wimg = bg.shape area_img = float(Himg * Wimg) kern = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5)) acc, rej = [], {"no_blob": 0, "frame_spanning": 0, "split": 0, "too_big": 0} for pos, k in enumerate(ks): g = stack[pos] d = cv2.absdiff(g, bg) thr_otsu, _ = cv2.threshold(d, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU) thr = max(a.abs_thresh, float(thr_otsu)) m = (d >= thr).astype(np.uint8) m = cv2.morphologyEx(m, cv2.MORPH_OPEN, kern) m = cv2.morphologyEx(m, cv2.MORPH_CLOSE, kern) n, lab, stats, cent = cv2.connectedComponentsWithStats(m, 8) if n <= 1: rej["no_blob"] += 1 continue areas = stats[1:, cv2.CC_STAT_AREA] order = np.argsort(areas)[::-1] big = order[0] + 1 if areas[order[0]] < a.min_area: rej["no_blob"] += 1 continue if areas[order[0]] > a.max_area_frac * area_img: rej["too_big"] += 1 continue if len(order) > 1 and areas[order[1]] > a.split_frac * areas[order[0]]: rej["split"] += 1 continue x, y, w, h = (stats[big, cv2.CC_STAT_LEFT], stats[big, cv2.CC_STAT_TOP], stats[big, cv2.CC_STAT_WIDTH], stats[big, cv2.CC_STAT_HEIGHT]) # NOT a border rejection: the FR3 arm is anchored off-frame, so its silhouette touches the image # edge in ~86% of frames (smoke LSF 1886290: 172/200 rejected on that rule). What must be rejected # is a blob that fills the frame -- a lighting change, not the arm. if w >= a.frame_span_frac * Wimg and h >= a.frame_span_frac * Himg: rej["frame_spanning"] += 1 continue blob = (lab == big) c_cent = np.array([cent[big][0], cent[big][1]], float) ys_b, xs_b = np.nonzero(blob) # distaltip: the arm is anchored off-frame, so the blob pixels ON the image border are its base. # The gripper is the distal end -- the blob pixels farthest from that base. Taking the mean of the # top --distal-pct percentile (not the single extreme pixel) keeps it robust to speckle. onb = (xs_b <= 1) | (ys_b <= 1) | (xs_b >= Wimg - 2) | (ys_b >= Himg - 2) c_dist = c_cent if onb.sum() >= 5: base = np.array([xs_b[onb].mean(), ys_b[onb].mean()], float) dd_ = np.hypot(xs_b - base[0], ys_b - base[1]) q = np.percentile(dd_, a.distal_pct) sel = dd_ >= q if sel.sum() >= 5: c_dist = np.array([xs_b[sel].mean(), ys_b[sel].mean()], float) # tip estimator: fastest-moving pixels inside the blob, vs a frame --tip-lag back in the sample ref = stack[max(0, pos - a.tip_lag)] mot = cv2.absdiff(g, ref).astype(np.float32) * blob v = mot[blob] c_tip = c_cent if v.size > 20: q = np.percentile(v, a.tip_pct) sel = blob & (mot >= max(q, 1.0)) if sel.sum() >= 10: ys, xs = np.nonzero(sel) c_tip = np.array([xs.mean(), ys.mean()], float) acc.append((k, c_cent, c_tip, c_dist)) return acc, rej
def dlt(X, x): """Hartley-normalised DLT. X (n,3) world, x (n,2) pixels -> P (3,4).""" n = len(X) cX, cx = X.mean(0), x.mean(0) sX = np.sqrt(3) / max(np.linalg.norm(X - cX, axis=1).mean(), 1e-9) sx = np.sqrt(2) / max(np.linalg.norm(x - cx, axis=1).mean(), 1e-9) T = np.array([[sx, 0, -sx * cx[0]], [0, sx, -sx * cx[1]], [0, 0, 1]]) U = np.eye(4) * sX U[:3, 3] = -sX * cX U[3, 3] = 1 Xn = (X - cX) * sX xn = (x - cx) * sx A = np.zeros((2 * n, 12)) for i in range(n): Xi = np.append(Xn[i], 1.0) A[2 * i, 4:8] = -Xi A[2 * i, 8:12] = xn[i, 1] * Xi A[2 * i + 1, 0:4] = Xi A[2 * i + 1, 8:12] = -xn[i, 0] * Xi _, _, Vt = np.linalg.svd(A) Pn = Vt[-1].reshape(3, 4) return np.linalg.inv(T) @ Pn @ U
def project(P, X): Xh = np.concatenate([X, np.ones((len(X), 1))], 1) p = Xh @ P.T z = p[:, 2:3] z = np.where(np.abs(z) < 1e-9, 1e-9, z) return p[:, :2] / z
def ransac_dlt(X, x, rng, iters=400, thr=12.0, minset=8): n = len(X) best = (None, -1, None) for _ in range(iters): idx = rng.choice(n, size=minset, replace=False) try: P = dlt(X[idx], x[idx]) except np.linalg.LinAlgError: continue e = np.linalg.norm(project(P, X) - x, axis=1) inl = e < thr if inl.sum() > best[1]: best = (P, int(inl.sum()), inl) P, ninl, inl = best if P is None or ninl < 12: return None, None for _ in range(3): # least-squares refit on the inliers, twice re-thresholded P = dlt(X[inl], x[inl]) e = np.linalg.norm(project(P, X) - x, axis=1) inl = e < thr if inl.sum() < 12: break return P, inl
def main(): ap = argparse.ArgumentParser() ap.add_argument("--n-episodes", type=int, default=60) ap.add_argument("--frame-stride", type=int, default=10) ap.add_argument("--max-frames-per-ep", type=int, default=40) ap.add_argument("--abs-thresh", type=float, default=18.0) ap.add_argument("--min-area", type=int, default=400) ap.add_argument("--max-area-frac", type=float, default=0.35) ap.add_argument("--split-frac", type=float, default=0.55) ap.add_argument("--frame-span-frac", type=float, default=0.92) ap.add_argument("--tip-pct", type=float, default=95.0) ap.add_argument("--tip-lag", type=int, default=2) ap.add_argument("--distal-pct", type=float, default=99.0) ap.add_argument("--ransac-thr", type=float, default=12.0) ap.add_argument("--holdout-frac", type=float, default=0.20) ap.add_argument("--seed", type=int, default=0) ap.add_argument("--out", default=ROOT + "/status/real/CAM_DLT.json") a = ap.parse_args() import h5py rng = np.random.default_rng(a.seed)
f = h5py.File(H5, "r") dd = f["data"] eps = sorted(int(k.split("_")[1]) for k in dd.keys()) rng.shuffle(eps) eps = sorted(eps[: a.n_episodes]) print(f"[cam_dlt] {len(eps)} episodes: {eps[:8]}...", flush=True)
rows = [] # (ep, frame, X(3), px_cent(2), px_tip(2)) rej_tot, n_seen = {}, 0 for e in eps: vp = VID % e if not os.path.exists(vp): print(f"[cam_dlt] ep {e}: no video", flush=True) continue pos = dd[f"demo_{e}"]["obs/robot0_eef_pos"][:] idxs = list(range(0, len(pos), a.frame_stride))[: a.max_frames_per_ep] try: frames = decode(vp, idxs) except Exception as ex: print(f"[cam_dlt] ep {e}: decode failed {type(ex).__name__}: {ex}", flush=True) continue acc, rej = detect(frames, idxs, a) n_seen += len(frames) for k, v in rej.items(): rej_tot[k] = rej_tot.get(k, 0) + v for k, c, t, dtip in acc: if k < len(pos): rows.append((e, k, pos[k].astype(float), c, t, dtip)) print(f"[cam_dlt] ep {e}: {len(frames)} decoded, {len(acc)} accepted", flush=True)
if len(rows) < 100: json.dump({"error": "too few correspondences", "n": len(rows), "rejected": rej_tot}, open(a.out, "w"), indent=1) raise SystemExit(f"only {len(rows)} correspondences")
ep_arr = np.array([r[0] for r in rows]) fr_arr = np.array([r[1] for r in rows]) X = np.stack([r[2] for r in rows]) PX = {"centroid": np.stack([r[3] for r in rows]), "tipmotion": np.stack([r[4] for r in rows]), "distaltip": np.stack([r[5] for r in rows])}
uep = np.unique(ep_arr) rng2 = np.random.default_rng(a.seed + 1) ho = set(rng2.choice(uep, size=max(2, int(round(a.holdout_frac * len(uep)))), replace=False).tolist()) is_ho = np.array([e in ho for e in ep_arr]) print(f"[cam_dlt] {len(rows)} correspondences, {len(uep)} episodes, " f"{is_ho.sum()} held-out rows from {len(ho)} episodes", flush=True)
out = {"n_correspondences": int(len(rows)), "n_frames_decoded": int(n_seen), "n_episodes": int(len(uep)), "rejected": rej_tot, "holdout_episodes": sorted(int(e) for e in ho), "image_size": [640, 480], "video_root": VID % 0, "note_lerobot_home_empty": "data/real/lerobot_home is EMPTY; full-res frames come from " "data/real/rsm_cooking_v5/videos/chunk-000/observation.images.global", "estimators": {}} for name, x in PX.items(): P, inl = ransac_dlt(X[~is_ho], x[~is_ho], np.random.default_rng(a.seed + 2), thr=a.ransac_thr) if P is None: out["estimators"][name] = {"error": "RANSAC found no consensus"} continue e_fit = np.linalg.norm(project(P, X[~is_ho]) - x[~is_ho], axis=1) e_ho = np.linalg.norm(project(P, X[is_ho]) - x[is_ho], axis=1) out["estimators"][name] = { "P": P.tolist(), "n_fit_rows": int((~is_ho).sum()), "n_inliers": int(inl.sum()), "inlier_frac": float(inl.mean()), "fit_median_px": float(np.median(e_fit)), "fit_p90_px": float(np.percentile(e_fit, 90)), "heldout_n": int(is_ho.sum()), "heldout_median_px": float(np.median(e_ho)), "heldout_p90_px": float(np.percentile(e_ho, 90)), "heldout_mean_px": float(e_ho.mean()), "gate_lt_10px": bool(np.median(e_ho) < 10.0), } print(f"[cam_dlt] {name}: held-out median {np.median(e_ho):.2f} px, " f"p90 {np.percentile(e_ho,90):.2f} px, inliers {inl.mean():.2f}", flush=True)
np.savez(a.out.replace(".json", "_corr.npz"), ep=ep_arr, frame=fr_arr, X=X, px_centroid=PX["centroid"], px_tipmotion=PX["tipmotion"], px_distaltip=PX["distaltip"], is_heldout=is_ho) json.dump(out, open(a.out, "w"), indent=1) print("[cam_dlt] wrote", a.out, flush=True)
if __name__ == "__main__": main()1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677#!/usr/bin/env python3"""gen_q#278 FIGURE B -- dump global-camera frames with a pixel grid, for hand-labelling the gripper.
The motion-blob detectors all failed the camera fit (smoke LSF 1886310/1886313: centroid 65 px,tipmotion 102 px, distaltip 211 px held-out, against a ~10 px gate) because the moving mask contains thewhole arm AND the manipulated objects. A DLT needs only >=6 good correspondences, so the standard fallbackis a small hand-labelled set. This dumps frames chosen to SPREAD the EE in 3D (greedy farthest-point overobs/robot0_eef_pos) with a 40-px grid burned in so a pixel can be read off the picture."""import argparse, json, osimport numpy as np
ROOT = "/proj/dmfexp/zwhong/rsm_rise"VID = ROOT + "/data/real/rsm_cooking_v5/videos/chunk-000/observation.images.global/episode_%06d.mp4"H5 = ROOT + "/data/raw/cooking_v5_expert_suboptimal.hdf5"
def main(): ap = argparse.ArgumentParser() ap.add_argument("--n", type=int, default=12) ap.add_argument("--pool-episodes", type=int, default=40) ap.add_argument("--stride", type=int, default=25) ap.add_argument("--grid", type=int, default=40) ap.add_argument("--out", default=ROOT + "/status/real/cam_label") a = ap.parse_args() import cv2, h5py, av os.makedirs(a.out, exist_ok=True) f = h5py.File(H5, "r") dd = f["data"] eps = sorted(int(k.split("_")[1]) for k in dd.keys()) rng = np.random.default_rng(0) rng.shuffle(eps) eps = sorted(eps[: a.pool_episodes]) cand = [] for e in eps: if not os.path.exists(VID % e): continue pos = dd[f"demo_{e}"]["obs/robot0_eef_pos"][:] for k in range(0, len(pos), a.stride): cand.append((e, k, pos[k].astype(float))) P = np.stack([c[2] for c in cand]) # greedy farthest-point sampling so the labels span the workspace sel = [int(np.argmax(np.linalg.norm(P - P.mean(0), axis=1)))] for _ in range(a.n - 1): d = np.min(np.linalg.norm(P[:, None] - P[sel][None], axis=2), axis=1) sel.append(int(np.argmax(d))) meta = [] for j, i in enumerate(sel): e, k, xyz = cand[i] with av.open(VID % e) as c: st = c.streams.video[0] st.thread_type = "AUTO" img = None for n, fr in enumerate(c.decode(st)): if n == k: img = fr.to_ndarray(format="bgr24") break if img is None: continue g = img.copy() for x in range(0, g.shape[1], a.grid): cv2.line(g, (x, 0), (x, g.shape[0]), (0, 255, 0), 1) cv2.putText(g, str(x), (x + 2, 12), cv2.FONT_HERSHEY_PLAIN, 0.7, (0, 255, 255), 1) for y in range(0, g.shape[0], a.grid): cv2.line(g, (0, y), (g.shape[1], y), (0, 255, 0), 1) cv2.putText(g, str(y), (2, y + 12), cv2.FONT_HERSHEY_PLAIN, 0.7, (0, 255, 255), 1) name = f"{j:02d}_ep{e}_f{k}.png" cv2.imwrite(os.path.join(a.out, name), g) cv2.imwrite(os.path.join(a.out, "raw_" + name), img) meta.append({"file": name, "episode": int(e), "frame": int(k), "xyz_m": xyz.tolist()}) print("[dump]", name, xyz, flush=True) json.dump(meta, open(os.path.join(a.out, "frames.json"), "w"), indent=1) print("[dump] wrote", len(meta), "frames to", a.out, flush=True)
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197#!/usr/bin/env python"""DECISIVE TEST for the successor's reward head (gen_q #261 / #270, owner ask 2026-09-22 05:40 UTC).
"How can we show STITCHING across trajectories? Under the reward given, can it be shown?"
The corpus structure that would make a stitching demo possible (cache/real_cooking_v5/meta.npz,SEGMENTS.json, and the dataset card data/real/rsm_cooking_v5/README.md):
route 0 0->5 50 eps terminal 5 = FAILURE (pan at start, tomato on stove) route 1 0->1->3 50 eps terminal 3 = "cooking state", pan on stove + tomato IN THE PAN -- NOT a success route 2 0->2->3 48 eps terminal 3 = same non-terminal cooking state route 3 2->3->4 50 eps terminal 4 = THE ONLY REWARDED STATE (pan on grate, tomato in the bowl) route 4 0->2->6 50 eps terminal 6 = FAILURE (pan on the STOVE, tomato in bowl)
State 2 ("pan on stove, tomato at initial state") is shared by routes 2, 3 and 4, so from ONE junctionstate the data holds a rewarded continuation (route 3) and a failure continuation (route 4). That isthe stitch. What is NOT established is whether the trained reward head can support it. Threediagnostics, all on cached features, no training:
D1 SEPARABILITY OF THE TWO TERMINALS. State 4 (rewarded) and state 6 (failure) differ ONLY in where the pan ends (dataset card, states table). R(z) is evaluated on every frame whose edge_to is 4 vs 6, and on the last --tail frames of each such episode. AUC + score histograms. A head that cannot separate 4 from 6 cannot colour a stitching figure.
D2 JUNCTION AMBIGUITY. Frames at/near state 2, split by the route the episode continued on (2, 3, 4). Under the provenance reward the SAME physical state carries label 1 (route 3) and 0 (routes 2, 4), so the head must be ~chance there. Measured, not assumed.
D3 lives in scripts/real/stitch_feasibility.py (it needs the flow).
Outputs status/real/DECISIVE_REWARD.json + raw logits in DECISIVE_REWARD_scores.npz."""from __future__ import annotationsimport argparse, json, sysfrom pathlib import Pathimport numpy as npimport torch
sys.path.insert(0, "/proj/dmfexp/zwhong/projs/issue_resolver_richardrl/gen_q_rsm/rsm_libero")from data import LiberoRSMData # noqa: E402from model import RewardHead, IdentityEncoder # noqa: E402
ROOT = "/proj/dmfexp/zwhong/rsm_rise"CACHE = f"{ROOT}/cache/real_cooking_v5"
def auc(pos, neg): """Mann-Whitney AUC of pos over neg (ties count 0.5). No sklearn dependency.""" pos = np.asarray(pos, np.float64); neg = np.asarray(neg, np.float64) if len(pos) == 0 or len(neg) == 0: return float("nan") x = np.concatenate([pos, neg]) r = np.empty(len(x), np.float64) o = np.argsort(x, kind="mergesort") xs = x[o] i = 0 while i < len(xs): # average ranks within ties j = i while j + 1 < len(xs) and xs[j + 1] == xs[i]: j += 1 r[o[i:j + 1]] = 0.5 * (i + j) + 1.0 i = j + 1 n1 = len(pos) return float((r[:n1].sum() - n1 * (n1 + 1) / 2.0) / (n1 * len(neg)))
def stats(v): v = np.asarray(v, np.float64) if len(v) == 0: return {"n": 0} return {"n": int(len(v)), "mean": float(v.mean()), "std": float(v.std()), "p05": float(np.percentile(v, 5)), "median": float(np.median(v)), "p95": float(np.percentile(v, 95)), "min": float(v.min()), "max": float(v.max())}
def main(): ap = argparse.ArgumentParser() ap.add_argument("--ckpt", action="append", default=[], metavar="NAME=PATH", help="repeatable; every head is scored on the identical frame sets") ap.add_argument("--cache", default=CACHE) ap.add_argument("--tail", type=int, default=30, help="last-N-frames subset of each episode (D1)") ap.add_argument("--junction", type=int, default=30, help="D2 window: the last J frames BEFORE leaving state 2 and the first J after") ap.add_argument("--out", default=f"{ROOT}/status/real/DECISIVE_REWARD.json") a = ap.parse_args() dev = "cuda" if torch.cuda.is_available() else "cpu" heads = dict(kv.split("=", 1) for kv in a.ckpt) print(f"[dec] dev={dev} heads={list(heads)}", flush=True)
C = Path(a.cache) m = np.load(C / "meta.npz", allow_pickle=True) ep_from, ep_to = m["ep_from"].astype(int), m["ep_to"].astype(int) route = np.asarray(m["ep_route"], int) succ = np.asarray(m["ep_success"], bool) et = np.load(C / "edge_to.i16.npy").astype(int) ef = np.load(C / "edge_from.i16.npy").astype(int) seg = np.load(C / "seg.i16.npy").astype(int) n_ep = len(ep_from)
# ------------------------------------------------------------------ frame sets sets: dict[str, np.ndarray] = {} # D1: every frame heading into each terminal, and the last --tail frames of those episodes for s in (3, 4, 5, 6): sets[f"edge_to_{s}"] = np.nonzero(et == s)[0] for s, rts in [(4, [3]), (6, [4]), (5, [0]), (3, [1, 2])]: rows = np.concatenate([np.arange(ep_to[e] - a.tail, ep_to[e]) for e in np.nonzero(np.isin(route, rts))[0]]) sets[f"tail{a.tail}_term{s}"] = rows # D2: the junction at state 2. "arriving" = last J frames of the segment whose edge_to == 2 # (routes 2 and 4 only -- route 3 episodes START at state 2, frame 0). # "leaving" = first J frames of the segment whose edge_from == 2 (routes 2, 3, 4). for rt in (2, 3, 4): arr, lea = [], [] for e in np.nonzero(route == rt)[0]: lo, hi = ep_from[e], ep_to[e] i_arr = np.nonzero(et[lo:hi] == 2)[0] if len(i_arr): arr.append(np.arange(lo + max(0, i_arr[-1] + 1 - a.junction), lo + i_arr[-1] + 1)) i_lea = np.nonzero(ef[lo:hi] == 2)[0] if len(i_lea): lea.append(np.arange(lo + i_lea[0], lo + min(i_lea[0] + a.junction, hi - lo))) if arr: sets[f"junction_arrive_route{rt}"] = np.concatenate(arr) if lea: sets[f"junction_leave_route{rt}"] = np.concatenate(lea) # whole-route reference pools for rt in range(5): rows = np.concatenate([np.arange(ep_from[e], ep_to[e]) for e in np.nonzero(route == rt)[0]]) sets[f"route{rt}_all"] = rows[::7] # subsample: these are 30-60k rows each
for k, v in sets.items(): print(f"[dec] set {k:28s} n={len(v)}", flush=True)
# ------------------------------------------------------------------ score every head out = {"cache": str(C), "tail": a.tail, "junction": a.junction, "set_sizes": {k: int(len(v)) for k, v in sets.items()}, "route_table": {str(rt): {"n_eps": int((route == rt).sum()), "cache_success": bool(succ[route == rt][0])} for rt in range(5)}, "heads": {}} raw = {} # the feature table is identical for every head (same cache, same chunk/seed) -- build it once c0 = torch.load(list(heads.values())[0], map_location="cpu", weights_only=False)["config"] d = LiberoRSMData(a.cache, chunk=int(c0["chunk"]), k_success=int(c0["k_success"]), seed=int(c0["seed"]), in_ram=True, val_frac=0.1, reward_mode=c0["reward_mode"]) F = lambda idx: d._feat(np.asarray(idx, np.int64)) for name, path in heads.items(): c = torch.load(path, map_location=dev, weights_only=False) cfg = c["config"] rew = RewardHead(int(c["d_lat"]), len(c["tasks"])).to(dev).eval() rew.load_state_dict(c["rew"]) L = {} with torch.no_grad(): for k, rows in sets.items(): lg = [] for i in range(0, len(rows), 8192): z = torch.from_numpy(F(rows[i:i + 8192])).to(dev) t = torch.zeros(len(z), dtype=torch.long, device=dev) lg.append(rew(z, t).float().cpu().numpy()) L[k] = np.concatenate(lg) if lg else np.zeros(0, np.float32) h = {"ckpt": path, "step": int(c.get("step", -1)), "reward_mode": cfg["reward_mode"], "reward_npy": cfg.get("reward_npy", ""), "logit": {k: stats(v) for k, v in L.items()}, "prob": {k: stats(1.0 / (1.0 + np.exp(-np.clip(v, -60, 60)))) for k, v in L.items()}, "sat_frac": {k: float((np.abs(v) > 15).mean()) for k, v in L.items()}} # the decisive AUCs h["auc"] = { "D1_term4_vs_term6_allframes": auc(L["edge_to_4"], L["edge_to_6"]), "D1_term4_vs_term6_tail": auc(L[f"tail{a.tail}_term4"], L[f"tail{a.tail}_term6"]), "D1_term4_vs_term3_tail": auc(L[f"tail{a.tail}_term4"], L[f"tail{a.tail}_term3"]), "D1_term4_vs_term5_tail": auc(L[f"tail{a.tail}_term4"], L[f"tail{a.tail}_term5"]), "D2_junction_leave_r3_vs_r4": auc(L["junction_leave_route3"], L["junction_leave_route4"]), "D2_junction_leave_r3_vs_r2": auc(L["junction_leave_route3"], L["junction_leave_route2"]), "D2_junction_arrive_r2_vs_r4": auc(L["junction_arrive_route2"], L["junction_arrive_route4"]), "route3_vs_route4_allframes": auc(L["route3_all"], L["route4_all"]), } # 12-bin histogram of the logit on the two terminals, for the PDF lo = float(min(L["edge_to_4"].min(), L["edge_to_6"].min())) hi = float(max(L["edge_to_4"].max(), L["edge_to_6"].max())) edges = np.linspace(lo, hi, 13) h["hist"] = {"edges": edges.tolist(), "term4": np.histogram(L["edge_to_4"], edges)[0].tolist(), "term6": np.histogram(L["edge_to_6"], edges)[0].tolist()} out["heads"][name] = h for k, v in L.items(): raw[f"{name}|{k}"] = v.astype(np.float32) print(f"[dec] {name:12s} step={h['step']:>7} " f"AUC(4vs6)={h['auc']['D1_term4_vs_term6_allframes']:.4f} " f"tail={h['auc']['D1_term4_vs_term6_tail']:.4f} " f"AUC(4vs3)={h['auc']['D1_term4_vs_term3_tail']:.4f} " f"junction(r3vsr4)={h['auc']['D2_junction_leave_r3_vs_r4']:.4f}", flush=True)
Path(a.out).write_text(json.dumps(out, indent=1)) np.savez_compressed(a.out.replace(".json", "_scores.npz"), **raw) print(f"[dec] wrote {a.out}", flush=True)
if __name__ == "__main__": main()1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465#!/usr/bin/env python3"""Split a DESTINY_*.json/_scores.npz result by the EPISODE ROUTE of each arm.
Motivation (gen_q#277): the pooled S0 contrast mixes a SHARED-PREFIX pair(0->2->3 goal vs 0->2->6 failure -- identical 0->2 prefix, so appearance and theimmediate action cannot separate them) with a DISJOINT pair (0->1->3 vs 0->5,which differ from the first edge and are therefore confoundable by episodeappearance). Reporting them separately says whether a separating read-out ispredicting the future or recognising the trajectory.
Reads only the artifacts the destiny run already wrote; no model calls."""import argparse, json, sysimport numpy as npsys.path.insert(0, __file__.rsplit("/", 1)[0])from destiny_test import cluster_boot # same estimator, same bootstrap
def main(): ap = argparse.ArgumentParser() ap.add_argument("--json", required=True) ap.add_argument("--cache", default="/proj/dmfexp/zwhong/rsm_rise/cache/real_cooking_v5") ap.add_argument("--n-boot", type=int, default=2000) ap.add_argument("--seed", type=int, default=0) ap.add_argument("--out", required=True) a = ap.parse_args()
d = json.load(open(a.json)) z = np.load(a.json.replace(".json", "_scores.npz"), allow_pickle=True) ep = np.asarray(d["anchor_ep"], np.int64) lab = np.asarray(d["anchor_is_goal"], bool) path = np.load(a.cache + "/meta.npz", allow_pickle=True)["ep_path"] route = np.array([str(path[e]) for e in ep])
goal_routes = sorted(set(route[lab])) fail_routes = sorted(set(route[~lab])) pairs = {"POOLED": (goal_routes, fail_routes)} for g in goal_routes: for f in fail_routes: # shared prefix = same first edge tag = "shared-prefix" if g.split("->")[1] == f.split("->")[1] else "disjoint" pairs["%s vs %s [%s]" % (g, f, tag)] = ([g], [f])
out = {"source": a.json, "contrast": d["contrast"], "routes_goal": {r: int((route[lab] == r).sum()) for r in goal_routes}, "routes_failure": {r: int((route[~lab] == r).sum()) for r in fail_routes}, "n_ep_per_route": {r: int(len(np.unique(ep[route == r]))) for r in goal_routes + fail_routes}, "pairs": {}} for name, (gs, fs) in pairs.items(): sel = np.isin(route, gs + fs) cells = {} for key in z.files: head, ro = key.split("|", 1) S = np.asarray(z[key], np.float64) if len(S) != len(ep): continue cells.setdefault(head, {})[ro] = cluster_boot(S[sel], lab[sel], ep[sel], a.n_boot, a.seed) out["pairs"][name] = {"n_pos": int((lab & sel).sum()), "n_neg": int((~lab & sel).sum()), "n_ep": int(len(np.unique(ep[sel]))), "heads": cells} json.dump(out, open(a.out, "w"), indent=1) print("wrote", a.out)
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324#!/usr/bin/env python"""DESTINY TEST -- gen_q#276 (owner 2026-09-23 11:45Z, corrected 11:55Z and 12:05Z).
Same state, different future. Does the VALUE at an anchor predict where the episode ends up, or is it astate classifier? Eval-only on the cached DINOv2 features; no proposer, no roll-out.
CONTRASTS (--contrast) S2 HEADLINE. Anchors in the 2->3 segment of route 3 (2->3->4, GOAL) vs anchors in the 2->6 segment of route 4 (0->2->6, FAILURE). Both are "pan on stove, tomato at initial state"; only the future differs. S3 SCHEME-DISCRIMINATING. Anchors just after arrival at S3 that go on to pour (route 3, first W frames of the 3->4 segment) vs anchors just after arrival at S3 in an episode that STOPS at cooking (routes 1/2, last W frames). Under EXPERT_EPISODE both arms are positive, so that head should be unable to separate them; under GOAL_SEGMENT only the first is. S0 THE STITCHING TEST. Anchors in the segment leaving S0, by eventual destiny: routes 1/2 (0->1->3, 0->2->3, reach cooking) vs routes 0/4 (0->5, 0->2->6, fail). NOTE, and it is the point of the test: NO logged episode contains both S0 and S4, so no S0 anchor's own episode holds a GOAL_SEGMENT or GOAL_EPISODE positive at all -- the value can only separate these by composing across episodes.
READ-OUTS, on the SAME anchors (--readout, repeatable) rew the reward head alone, sigma(R(z)/T). Under GOAL_SEGMENT an S2 anchor is labelled 0 on BOTH arms by construction, so a null here is EXPECTED; separation would mean the head is leaking trajectory identity, which is a defect (owner 11:55Z). d1 one beta-occupancy read (the read-out the twin shipped). No composition. chain:B:G the coin-terminated beta chain at beta B, gamma G. Needs B < G; the cap comes from the 1e-3 tail. beta must be inside the checkpoint's trained [beta_lo, beta_hi] (R_M: 0.95..0.99). perm:<r> the permuted null for read-out r: the same score vector shuffled across anchors, so the contrast label carries no information. Reported beside every cell.The action handed to the value is the anchor's own LOGGED chunk, so this is V^behaviour(s), not a max overproposals -- the destiny question is about the state's value, not about ranking draws.
REACHABILITY (owner 11:55Z). Every cell is bucketed by the anchor's distance in frames to the first frame ofthe 3->4 segment of ITS OWN episode (inf when that episode has none, which is every failure anchor and everyS0 anchor). The horizon is 1/(1-gamma) frames, so the reachable fraction per bucket is printed beside thecell; a pooled number would hide the horizon limit as a model failure. The distance to the episode's ownTERMINAL is reported too, because route 0->2->6's segments are much shorter than route 2->3->4's and a pooledcomparison would favour the failure arm on distance alone.
Reported per (head, read-out, contrast, bucket): AUC, median value gap, and a CLUSTER bootstrap overEPISODES (n=50 goal episodes is the cluster count on the goal arm, never the frame count).Output: <out>.json (+ <out>_scores.npz with every raw score vector)."""from __future__ import annotationsimport argparse, json, sysfrom pathlib import Pathimport numpy as npimport torch
sys.path.insert(0, "/proj/dmfexp/zwhong/projs/issue_resolver_richardrl/gen_q_rsm/rsm_libero")from data import LiberoRSMData # noqa: E402
ROOT = "/proj/dmfexp/zwhong/rsm_rise"CACHE = f"{ROOT}/cache/real_cooking_v5"# route id -> the planned sequence it was collected for (real/config/task/tabletop.yaml edge_combinations)ROUTE_TXT = {0: "0->5", 1: "0->1->3", 2: "0->2->3", 3: "2->3->4", 4: "0->2->6"}
def auc(pos, neg): pos = np.asarray(pos, np.float64); neg = np.asarray(neg, np.float64) if len(pos) == 0 or len(neg) == 0: return float("nan") x = np.concatenate([pos, neg]); o = np.argsort(x, kind="mergesort"); xs = x[o] r = np.empty(len(x), np.float64); i = 0 while i < len(xs): j = i while j + 1 < len(xs) and xs[j + 1] == xs[i]: j += 1 r[o[i:j + 1]] = 0.5 * (i + j) + 1.0; i = j + 1 n1 = len(pos) return float((r[:n1].sum() - n1 * (n1 + 1) / 2.0) / (n1 * len(neg)))
def cluster_boot(score, lab, ep, n_boot=2000, seed=0): """AUC + median gap with a bootstrap over EPISODES (the cluster), not frames.""" rng = np.random.default_rng(seed) eps = np.unique(ep) a0 = auc(score[lab], score[~lab]); g0 = float(np.median(score[lab]) - np.median(score[~lab])) \ if lab.any() and (~lab).any() else float("nan") out = [] for _ in range(n_boot): take = rng.choice(eps, size=len(eps), replace=True) idx = np.concatenate([np.nonzero(ep == e)[0] for e in take]) l = lab[idx] if not l.any() or l.all(): continue out.append(auc(score[idx][l], score[idx][~l])) out = np.array(out) if out else np.array([np.nan]) return dict(auc=a0, auc_lo=float(np.nanpercentile(out, 2.5)), auc_hi=float(np.nanpercentile(out, 97.5)), median_gap=g0, n_pos=int(lab.sum()), n_neg=int((~lab).sum()), n_ep_pos=int(len(np.unique(ep[lab]))), n_ep_neg=int(len(np.unique(ep[~lab]))))
BUCKETS = [(0, 50), (50, 100), (100, 200), (200, 400), (400, 10 ** 9)]
def main(): ap = argparse.ArgumentParser() ap.add_argument("--ckpt", action="append", default=[], metavar="NAME=PATH", required=True) ap.add_argument("--cache", default=CACHE) ap.add_argument("--contrast", default="S2", choices=["S0", "S2", "S3"]) ap.add_argument("--readout", action="append", default=[], help="rew | d1 | chain:<beta>:<gamma> (the permuted null of each is added automatically)") ap.add_argument("--anchors-per-ep", type=int, default=8, help="uniformly spaced inside the anchor segment") ap.add_argument("--s3-win", type=int, default=100, help="S3 contrast: frames either side of the arrival at S3") ap.add_argument("--hop-ckpt", default=f"{ROOT}/runs/real_cooking_v5/hop/flow/policy_r1.pt", help="Stage-2 hop head. The coin chain re-decides the action at every hop, so at cap>1 " "it is REQUIRED (rsm_scorer.py:622). Unused by rew / d1.") ap.add_argument("--particles", type=int, default=16) ap.add_argument("--temperature", type=float, default=25.0) ap.add_argument("--score-kind", default="prob") ap.add_argument("--held-out-only", type=int, default=1) ap.add_argument("--split", default=f"{ROOT}/data/derived/cooking_v5_split.json") ap.add_argument("--n-boot", type=int, default=2000) ap.add_argument("--seed", type=int, default=0) ap.add_argument("--out", required=True) a = ap.parse_args() readouts = a.readout or ["rew", "d1", "chain:0.99:0.999"] dev = "cuda" if torch.cuda.is_available() else "cpu" heads = dict(kv.split("=", 1) for kv in a.ckpt) rng = np.random.default_rng(a.seed)
C = Path(a.cache) m = np.load(C / "meta.npz", allow_pickle=True) ep_from, ep_to = m["ep_from"].astype(int), m["ep_to"].astype(int) route = np.asarray(m["ep_route"], int) et = np.load(C / "edge_to.i16.npy").astype(int) ef = np.load(C / "edge_from.i16.npy").astype(int) n_ep = len(ep_from)
held = None if a.held_out_only: # same held-out list the edge harness uses (scorer_openloop.py:278) sp = json.loads(Path(a.split).read_text()) held = {int(k) for k, v in sp["episodes"].items() if v["split"] == "valid"}
# ---- the first frame of the 3->4 segment of each episode (inf when it has none): the GOAL_SEGMENT # positive the value has to reach. Reachability is measured against THIS. goal_seg_start = np.full(n_ep, np.inf) for e in range(n_ep): lo, hi = ep_from[e], ep_to[e] i = np.nonzero((ef[lo:hi] == 3) & (et[lo:hi] == 4))[0] if len(i): goal_seg_start[e] = lo + i[0]
def seg_rows(e, a_from, a_to): lo, hi = ep_from[e], ep_to[e] i = np.nonzero((ef[lo:hi] == a_from) & (et[lo:hi] == a_to))[0] return (lo + i) if len(i) else np.array([], int)
# ---- anchors per contrast: (rows, is_goal_arm, episode) rows, lab, aep, note = [], [], [], {} def add(e, r, is_goal): if len(r) == 0: return k = min(a.anchors_per_ep, len(r)) sel = r[np.linspace(0, len(r) - 1, k).astype(int)] rows.append(sel); lab.append(np.full(k, is_goal, bool)); aep.append(np.full(k, e, int))
for e in range(n_ep): if held is not None and e not in held: continue rt = int(route[e]) if a.contrast == "S2": if rt == 3: add(e, seg_rows(e, 2, 3), True) # 2->3->4, the goal continuation elif rt == 4: add(e, seg_rows(e, 2, 6), False) # 0->2->6, the failure continuation elif a.contrast == "S3": if rt == 3: r = seg_rows(e, 3, 4) add(e, r[:a.s3_win], True) # just poured-bound elif rt in (1, 2): lo, hi = ep_from[e], ep_to[e] add(e, np.arange(max(lo, hi - a.s3_win), hi), False) # arrived at S3 and stopped elif a.contrast == "S0": if rt == 1: add(e, seg_rows(e, 0, 1), True) elif rt == 2: add(e, seg_rows(e, 0, 2), True) elif rt == 0: add(e, seg_rows(e, 0, 5), False) elif rt == 4: add(e, seg_rows(e, 0, 2), False) if not rows: raise SystemExit(f"no anchors for contrast {a.contrast}") rows = np.concatenate(rows); lab = np.concatenate(lab); aep = np.concatenate(aep) order = np.argsort(rows); rows, lab, aep = rows[order], lab[order], aep[order]
# distance to the 3->4 boundary of the anchor's OWN episode, and to its own terminal d_goal = np.array([goal_seg_start[e] - r for e, r in zip(aep, rows)], float) d_goal[d_goal < 0] = np.inf d_term = np.array([ep_to[e] - r for e, r in zip(aep, rows)], float) note["anchor_arms"] = { "goal": sorted({ROUTE_TXT[int(route[e])] for e in np.unique(aep[lab])}), "failure": sorted({ROUTE_TXT[int(route[e])] for e in np.unique(aep[~lab])}), } note["frac_anchors_whose_own_episode_has_a_3to4_segment"] = float(np.mean(np.isfinite(d_goal))) note["frac_goal_arm_anchors_needing_a_DIFFERENT_episode_for_the_goal"] = float( np.mean(~np.isfinite(d_goal[lab]))) print(f"[destiny] contrast {a.contrast}: {len(rows)} anchors " f"({lab.sum()} goal from {len(np.unique(aep[lab]))} eps, {(~lab).sum()} failure from " f"{len(np.unique(aep[~lab]))} eps); held-out only={bool(a.held_out_only)}\n" f"[destiny] goal arm routes {note['anchor_arms']['goal']} | failure arm " f"{note['anchor_arms']['failure']}\n" f"[destiny] own episode contains a 3->4 segment for {note['frac_anchors_whose_own_episode_has_a_3to4_segment']:.3f} " f"of anchors; {note['frac_goal_arm_anchors_needing_a_DIFFERENT_episode_for_the_goal']:.3f} of the GOAL arm " f"must compose across episodes", flush=True)
# ---- features + the anchor's own logged chunk c0 = torch.load(list(heads.values())[0], map_location="cpu", weights_only=False) cfg0 = c0["config"]; chunk = int(cfg0["chunk"]) d = LiberoRSMData(a.cache, chunk=chunk, k_success=int(cfg0["k_success"]), seed=int(cfg0["seed"]), in_ram=True, val_frac=0.1, reward_mode=cfg0["reward_mode"]) F = lambda idx: d._feat(np.asarray(idx, np.int64)) epi = np.searchsorted(ep_to, rows, "right") A = np.asarray(d._chunk_at(rows.astype(np.int64), epi.astype(np.int64)), np.float32) A = A.reshape(len(rows), chunk, -1)
from types import SimpleNamespace from robomimic.algo.rsm_scorer import RSMScorer, chain_continuation_p, chain_cap as chain_cap_fn
out = {"contrast": a.contrast, "cache": str(C), "n_anchors": int(len(rows)), "readouts": readouts, "heads": {}, "notes": note, "anchor_rows": rows.tolist(), "anchor_is_goal": lab.tolist(), "anchor_ep": aep.tolist(), "dist_to_3to4_frames": [None if not np.isfinite(x) else float(x) for x in d_goal], "dist_to_own_terminal_frames": d_term.tolist(), "readout_spec": {}} raw = {}
for hname, path in heads.items(): ck = torch.load(path, map_location="cpu", weights_only=False) din = int(ck["d_in"]); bl, bh = ck["config"].get("beta_lo"), ck["config"].get("beta_hi") stub = SimpleNamespace(d=din, sd=torch.ones(din), normalize=None) hres = {"ckpt": path, "beta_lo": bl, "beta_hi": bh, "cells": {}} for ro in readouts: if ro == "rew": sc = RSMScorer(backend="mlp", ckpt=path, hop_ckpt="", state=stub, mode="d1", depth=1, beta=0.99, gamma=0.999, n_particles=1, score_kind=a.score_kind, temperature=a.temperature, device=dev) bk = sc.backend with torch.no_grad(): S = [] for i in range(0, len(rows), 256): x = torch.as_tensor(F(rows[i:i + 256]), dtype=torch.float32, device=dev) z = bk.latent(x) tk = torch.zeros(z.shape[0], dtype=torch.long, device=z.device) r = bk.rew(z, tk) # R(z, task) -> logit (rsm_libero model.py:156) r = r[0] if isinstance(r, (tuple, list)) else r S.append(torch.sigmoid(r.reshape(len(z), -1)[:, 0] / a.temperature).cpu().numpy()) S = np.concatenate(S) spec = {"kind": "reward head alone, sigma(R(z)/T)", "T": a.temperature} else: if ro == "d1": mode, beta, gamma = "d1", 0.99, 0.99 else: _, b, g = ro.split(":"); mode, beta, gamma = "chain", float(b), float(g) if bl is not None and not (float(bl) <= beta <= float(bh)): print(f"[destiny] SKIP {hname} {ro}: beta {beta} OUTSIDE the trained range " f"[{bl},{bh}] -- an out-of-range beta is a defect, not a data point", flush=True) continue sc = RSMScorer(backend="mlp", ckpt=path, hop_ckpt=(a.hop_ckpt if mode in ("chain", "chain_rb") else ""), state=stub, mode=mode, depth=1, beta=beta, gamma=gamma, n_particles=a.particles, score_kind=a.score_kind, temperature=a.temperature, device=dev) p = chain_continuation_p(beta, gamma) if mode == "chain" else 0.0 spec = {"kind": mode, "beta": beta, "gamma": gamma, "p": float(p), "E_extra_hops": float(p / (1 - p)) if p < 1 else None, "E_model_reads": float(1 / (1 - p)) if p < 1 else None, "cap": int(chain_cap_fn(beta, gamma)) if mode == "chain" else 1, "horizon_frames_1_over_1_minus_gamma": float(1 / (1 - gamma)), "particles": a.particles} import time as _t t0 = _t.time() with torch.no_grad(): S = np.empty(len(rows), np.float32) for i in range(len(rows)): x = torch.as_tensor(F([rows[i]]), dtype=torch.float32, device=dev) S[i] = float(sc.score(x, A[i:i + 1, :sc.chunk])[0]) spec["s_per_decision"] = (_t.time() - t0) / max(1, len(rows)) if mode_needs_hop := (ro not in ("rew", "d1")): spec["hop_ckpt"] = a.hop_ckpt out["readout_spec"][ro] = spec raw[f"{hname}|{ro}"] = S perm = S[rng.permutation(len(S))] raw[f"{hname}|perm:{ro}"] = perm cell = {"pooled": cluster_boot(S, lab, aep, a.n_boot, a.seed), "pooled_permuted": cluster_boot(perm, lab, aep, a.n_boot, a.seed), "buckets": {}} H = spec.get("horizon_frames_1_over_1_minus_gamma", float("nan")) for lo_b, hi_b in BUCKETS: sel = (d_goal >= lo_b) & (d_goal < hi_b) key = f"{lo_b}-{'inf' if hi_b > 10 ** 8 else hi_b}" if sel.sum() < 4 or not lab[sel].any() or lab[sel].all(): cell["buckets"][key] = {"n": int(sel.sum()), "skipped": "one arm empty or n<4"} continue c = cluster_boot(S[sel], lab[sel], aep[sel], a.n_boot, a.seed) c["reachable_frac"] = float(np.mean(d_goal[sel] <= H)) if np.isfinite(H) else None cell["buckets"][key] = c sel = ~np.isfinite(d_goal) if sel.sum() >= 4 and lab[sel].any() and not lab[sel].all(): cell["buckets"]["no-3to4-in-own-episode"] = cluster_boot(S[sel], lab[sel], aep[sel], a.n_boot, a.seed) else: cell["buckets"]["no-3to4-in-own-episode"] = { "n": int(sel.sum()), "skipped": "one arm empty -- the goal must come from a DIFFERENT episode"} hres["cells"][ro] = cell pb = cell["pooled"]; pp = cell["pooled_permuted"] print(f"[destiny] {hname:16s} {ro:16s} AUC {pb['auc']:.3f} [{pb['auc_lo']:.3f},{pb['auc_hi']:.3f}] " f"gap {pb['median_gap']:+.4f} | permuted {pp['auc']:.3f} " f"[{pp['auc_lo']:.3f},{pp['auc_hi']:.3f}] | n {pb['n_pos']}+{pb['n_neg']} " f"({pb['n_ep_pos']}+{pb['n_ep_neg']} eps)" + (f" | {spec['s_per_decision']:.3f} s/decision" if "s_per_decision" in spec else ""), flush=True) out["heads"][hname] = hres
Path(a.out).parent.mkdir(parents=True, exist_ok=True) Path(a.out).write_text(json.dumps(out, indent=1)) np.savez_compressed(a.out.replace(".json", "_scores.npz"), **raw) print(f"[destiny] wrote {a.out}", flush=True)
if __name__ == "__main__": main()12345678910111213141516171819202122232425#!/usr/bin/env bash# gen_q#278 -- DIRECTION DUMP for the S0/S2 diversity figure the owner asked for ("visualize all the 3D# directions the end effector goes at the initial state anchors ... I want to see if it is actually diverse").## SAME anchor grid, SAME proposer settings and the SAME edge classification as edge_screen.sh; the ONLY# difference is that NO scorer checkpoint is passed, so scorer_openloop.py builds modes = ["greedy"] alone# (scorer_openloop.py:170) and the run costs proposer sampling only. The per-episode edge_parts/*.npz# therefore carry cand_disp_mm [n_anchor,N,3] / logged_disp_mm / ee_xyz_mm for an actor WITHOUT paying for a# chain, which is what makes the actor-by-actor diversity table affordable.## usage: EDGE_NAME=<tag> EDGE_POLICY=<openpi:cfg:ckpt> dirdump_screen.sh <shard-i> <shard-n>set -uo pipefailROOT=/proj/dmfexp/zwhong/rsm_riseI=${1:-0}; K=${2:-1}NAME=${EDGE_NAME:?set EDGE_NAME}POLICY=${EDGE_POLICY:?set EDGE_POLICY}NCAND=${EDGE_NCAND:-128}OUT=$ROOT/status/real/dir_$NAMEmkdir -p "$OUT"exec $ROOT/scripts/real/run_env_openpi.sh $ROOT/scripts/real/scorer_openloop.py \ --policy "$POLICY" \ --n-cand "$NCAND" --horizon 8 --stride 25 \ --edge-test --edge-horizon 8 --edge-min-sep-deg 20 --edge-anchor-stride 5 \ --edge-anchor-radius-mm 30 --edge-anchor-min-support 20 \ --ep-shard "$I/$K" --tag "dir_$NAME" --out "$OUT"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337r"""#278 RUNG AD -- THE READER FOR THE GOAL-BOUND REPLICATION WAVE (SLURM 42197 ctrl / 42198 aug).
PUSHED BEFORE ANY SHARD OF THE `AD_aug` ARM EXISTED (the aug job was still PENDING on SLURM with anempty output directory when this file was committed), so the statistic, the grouping and the(a)/(b)/(c) reading below are fixed independently of the numbers they will be applied to. The readingitself is NOT new: it is copied verbatim from the payload headersscripts/real/payloads/edgeAD_{ctrl,aug}_s{0..3}.sh, which were pushed at run 36 (gen_q rsm_rise_data7b3d2184) while both jobs were queued and zero shards existed. This file only mechanises it.
THE NUMBER THAT CHOSE THE WAVE (status/real/EDGE_GOALBOUND_AUC.json, LSF 1903087, 114 arms screened atthe common held-out S0 anchor set, leverage-free unweighted per-anchor Mann-Whitney AUC): edge_U_aug AUG_invariant_t0p02_s0/ckpt_s100000.pt gb 0.740 [.676,.843] fail 0.561 edge_T_rise R_XL/ckpt_s100000.pt (CONTROL) gb 0.517 [.464,.578] fail 0.594i.e. the augmented successor INVERTS the control's cell ordering -- but on EIGHT held-out goal-boundepisodes, whose exact paired p-floor 2/2^8 = 0.0078 sits above the screen's Bonferroni 0.05/114 =0.00044. It is a SCREEN HIT. This wave re-measures the same one factor (the successor checkpoint,everything else pinned to edge_T_rise) on 40 goal-bound TRAIN-split clusters, 5x the screen's 8.
CONTRACT: rise_stack/EDGE_TEST.md reserves held-out episodes for headline numbers and train-splitanchors for DEBUGGING. These 60 episodes are all train-split, so WHATEVER THIS PRINTS, the #278verdict stays FAIL / CLOSED and the pre-registered bar is untouched. scorer_openloop.py excludes eachanchor episode from its own direction field (--ep-ids -> ep_excl), so a train episode cannot labelitself.
PRE-REGISTERED READING (from the payload headers, verbatim): (a) REPLICATES: AUG goal-bound AUC_u > 0.5 with its 95 % cluster interval excluding 0.5 AND the paired (rsm - permuted) interval excluding 0, on >= 25 goal-bound episodes. (b) SPECIFIC: additionally (AUG - control) at goal-bound > (AUG - control) at the failure anchors, intervals reported. If AUG beats the control in BOTH cells it is simply a better scorer and the goal-bound framing is wrong; say so. (c) DOES NOT REPLICATE: AUG goal-bound AUC_u falls to ~0.5 or its interval covers chance -> the run-35 hit was multiplicity over 114 arms at 8 clusters and the augmentation option is spent.
CAVEATS THAT TRAVEL WITH EVERY NUMBER HERE: * run 33's candidate gate: the anchors are identical across arms but 45-99 % of the 128 candidates are redrawn per arm, so a BETWEEN-ARM difference contains candidate sampling noise. Each arm's own AUC vs its own greedy / permuted column is within-arm and unaffected. The paired between-arm cells below are printed with that caveat attached and matched anchor-by-anchor (episode, anchor index, verified on ee_xyz_mm) so at least the anchor set is common. * "goal-bound" here means destiny = COOKING (routes 0->1->3, 0->2->3). No S0 episode reaches S4 -- route 2->3->4 does not start at S0 -- which is the owner's stitching point itself."""import sys, os, json, globimport numpy as np
sys.path.insert(0, "/proj/dmfexp/zwhong/rsm_rise/scripts/real")from edge_ceiling2 import arm as ceiling_arm, auc as mw_auc
ROOT = "/proj/dmfexp/zwhong/rsm_rise/status/real"SPLIT = json.load(open("/proj/dmfexp/zwhong/rsm_rise/data/derived/cooking_v5_split.json"))["episodes"]# ---- run 39: the SAME reduction, pointable at a second arm pair by environment only. ----------------# The statistic, the grouping, the bootstrap, the anchor matching and the (a)/(b)/(c) text below are# UNTOUCHED. Only WHICH two arms and WHICH episode list are read can be overridden, so that the# held-out re-read proposed on #278 (comment 5822434834, posted BEFORE this edit) uses byte-identical# code to the train-split read it is compared against. With no environment set, every default is the# rung-AD one and the published train-split verdict reproduces exactly.EPS_FILE = os.environ.get("AD_EPS_FILE", f"{ROOT}/edge_gbrep_eps.txt")EPS = [int(x) for x in open(EPS_FILE).read().replace(",", " ").split()]CTRL = os.environ.get("AD_CTRL", "edge_AD_ctrl")AUG = os.environ.get("AD_AUG", "edge_AD_aug")SPLIT_LABEL = os.environ.get("AD_SPLIT_LABEL", "train (DEBUGGING)")OUT_NAME = os.environ.get("AD_OUT", "EDGE_AD_GBREP.json")NB, SEED = 20000, 0MIN_GB_EPISODES = int(os.environ.get("AD_MIN_GB", "25")) # the rule's power gate, from the payload headers
def sign_test(vals): """Two-sided exact paired sign test over episode-level differences. Pre-registered on #278 comment 5822434834 before this function existed, because a bootstrap percentile interval on ten clusters is not a certification and the exact test's p-floor (2/2**n) must be printed beside it.""" v = np.asarray([x for x in vals if x == x and x != 0.0], float) n = v.size if n == 0: return dict(n=0, n_pos=0, p=float("nan"), p_floor=float("nan")) k = int((v > 0).sum()) from math import comb tail = sum(comb(n, i) for i in range(0, min(k, n - k) + 1)) p = min(1.0, 2.0 * tail / (2.0 ** n)) return dict(n=n, n_pos=k, p=float(p), p_floor=float(2.0 / 2.0 ** n))COLS = {"rsm": "score_rsm", "perm": "score_permuted__rsm", "idql": "score_idql", "permi": "score_permuted__idql"}
def destiny_of(e): return "goalbound" if SPLIT[str(int(e))]["final_state"] in (3, 4) else "failure"
GB = [e for e in EPS if destiny_of(e) == "goalbound"]FA = [e for e in EPS if destiny_of(e) == "failure"]GROUPS = [("DEST_goalbound", GB), ("DEST_failure", FA), ("ALL", EPS)]
# --- rung AG (#278, pushed at zero shards): the S2 anchor set splits the "goalbound" label that S0# forced on us. destiny_of() calls final_state in (3,4) goal-bound, but at S0 that can only ever mean# COOKING -- no S0 episode reaches S4 (see the header). At S2 the two are genuinely different# destinies, so AD_EXTRA_DESTINY=1 adds them as SEPARATE groups. It is a GROUPING, not a statistic:# the AUC, the cluster bootstrap, the pairing and the sign test below are untouched, and with the# variable unset GROUPS is byte-identical to the list that produced every published cell.if os.environ.get("AD_EXTRA_DESTINY", "") not in ("", "0"): G4 = [e for e in EPS if SPLIT[str(int(e))]["final_state"] == 4] C3 = [e for e in EPS if SPLIT[str(int(e))]["final_state"] == 3] GROUPS = ([("DEST_goal4", G4), ("DEST_cook3", C3)] + GROUPS)
# --- per_anchor / boot_matrix / ci are byte-identical to edge_goalbound_auc.py's (run 35, published) --def per_anchor(d, keep): """Per-anchor Mann-Whitney AUC of on-route vs off-route candidates, per scorer. Same loop, same filters, same `auc` as edge_ceiling2.arm -- only the aggregation differs.""" out = {k: [] for k in COLS} out["greedy"] = [] EP, IDX, W, XYZ = [], [], [], [] for f in sorted(glob.glob(f"{d}/edge_parts/*.npz")): e = int(f.split("/")[-1][2:-4]) if e not in keep: continue z = np.load(f, allow_pickle=True) if "onroute" not in z.files: continue onr = np.asarray(z["onroute"], bool) xyz = np.asarray(z["ee_xyz_mm"], np.float64) if "ee_xyz_mm" in z.files else None for i in range(onr.shape[0]): o = onr[i] n = o.size n_on = int(o.sum()) if not (0 < n_on < n): continue EP.append(e) IDX.append(i) XYZ.append(xyz[i] if xyz is not None else np.full(3, np.nan)) W.append((n - n_on) / (n - 1.0)) out["greedy"].append(mw_auc(-np.arange(n, dtype=float), o)) for k, key in COLS.items(): out[k].append(mw_auc(z[key][i].astype(np.float64), o) if key in z.files else np.nan) return ({k: np.asarray(v) for k, v in out.items()}, np.asarray(EP, int), np.asarray(IDX, int), np.asarray(W, float), np.asarray(XYZ, float))
def boot_matrix(EP, nb=NB, seed=SEED): """Cluster (episode) bootstrap as an exact count matrix: B[b,i] = times anchor i's episode drawn.""" u = np.unique(EP) rng = np.random.default_rng(seed) draw = rng.choice(u.size, (nb, u.size), replace=True) cnt = np.zeros((nb, u.size), np.int32) np.add.at(cnt, (np.repeat(np.arange(nb), u.size), draw.ravel()), 1) idx = np.searchsorted(u, EP) return cnt[:, idx].astype(np.float64), u.size
def ci(v, B, alpha=0.05): """Mean of v with a cluster-bootstrap percentile interval at level alpha (two-sided).""" m = float(np.mean(v)) bm = (B @ v) / B.sum(1) return m, float(np.percentile(bm, 100 * alpha / 2)), float(np.percentile(bm, 100 * (1 - alpha / 2)))
def eps_on_disk(a): return {int(f.split("/")[-1][2:-4]) for f in glob.glob(f"{ROOT}/{a}/edge_parts/*.npz")}
# ---------------- what is on disk ----------------have = {a: eps_on_disk(a) & set(EPS) for a in (CTRL, AUG)}both = sorted(have[CTRL] & have[AUG])gb_both = [e for e in both if destiny_of(e) == "goalbound"]fa_both = [e for e in both if destiny_of(e) == "failure"]print(f"RUNG AD reader -- anchor list {EPS_FILE}, {len(EPS)} {SPLIT_LABEL} episodes " f"({len(GB)} goal-bound / {len(FA)} failure)")for a in (CTRL, AUG): g = len([e for e in have[a] if destiny_of(e) == "goalbound"]) print(f" {a:16s} {len(have[a]):3d}/{len(EPS)} episodes on disk ({g} goal-bound)")print(f" common to BOTH arms: {len(both)} episodes ({len(gb_both)} goal-bound, {len(fa_both)} failure)")COMPLETE = len(both) == len(EPS)READABLE = len(gb_both) >= MIN_GB_EPISODESif not COMPLETE: print(f" ** PARTIAL: the wave is not finished. Every cell below is over the {len(both)} common " f"episodes only and is a progress read, not the rung. **")if not READABLE: print(f" ** the rule's power gate (>= {MIN_GB_EPISODES} goal-bound episodes) is NOT met: " f"{len(gb_both)}. NO VERDICT WILL BE PRINTED. **")
# ---------------- SELF-TEST, printed before any new number ----------------print("\nSELF-TEST -- per-anchor AUCs must reproduce edge_ceiling2.arm() exactly (it produced every")print("published ceiling/%ceil number), on the CONTROL arm of this wave, for every group:")ok, ran = True, 0for g, eps in GROUPS: keep = set(eps) & have[CTRL] if not keep: print(f" {g:16s} no episodes on disk yet -- skipped") continue A, EP, IDX, W, XYZ = per_anchor(f"{ROOT}/{CTRL}", keep) r = ceiling_arm(f"{ROOT}/{CTRL}", keep=keep) w_rsm = float((W * A["rsm"]).sum() / W.sum()) d_rsm = float((W * (A["rsm"] - A["greedy"])).mean()) e1 = abs(w_rsm - r["auc_rsm"]["weighted"]) e2 = abs(d_rsm - r["d_vs_greedy_rsm"]) e3 = abs(len(W) - r["n_anchors"]) ok &= (e1 < 1e-12 and e2 < 1e-12 and e3 == 0) ran += 1 print(f" {g:16s} n={len(W):4d} (harness {r['n_anchors']:4d}) AUCw err {e1:.2e} " f"d_vs_greedy err {e2:.2e} [harness d_rsm {r['d_vs_greedy_rsm']:+.4f}]")assert ran and ok, "self-test FAILED -- no number printed"print(" PASS -- the reduction reads the same anchors and the same scores as every published cell.\n")
# ---------------- the table ----------------res = {"_meta": dict(arms=[CTRL, AUG], nb=NB, seed=SEED, episodes=EPS, split=SPLIT_LABEL, goalbound_episodes=GB, failure_episodes=FA, on_disk={a: sorted(have[a]) for a in (CTRL, AUG)}, common_episodes=both, complete=bool(COMPLETE), readable=bool(READABLE), min_gb_episodes=MIN_GB_EPISODES, note="UNWEIGHTED per-anchor Mann-Whitney AUC, on-route vs off-route candidates; " "chance 0.5; TRAIN-split debugging read, NOT the pre-registered bar")}PAIR = {}for g, eps in GROUPS: keep = set(eps) & set(both) print(f"\n### GROUP {g} ({len(keep)} episodes common to both arms)") if not keep: print(" (nothing on disk for both arms yet)") continue hdr = (f"{'arm':16s} {'ep':>2s} {'anc':>4s} {'w_bar':>6s} | {'AUCu_rsm':>8s} {'raw95':>17s} | " f"{'greedy':>6s} {'perm':>6s} {'idql':>6s} | {'rsm-perm':>9s} {'raw95':>17s}") print(hdr) print("-" * len(hdr)) res[g] = {} store = {} for a in (CTRL, AUG): A, EP, IDX, W, XYZ = per_anchor(f"{ROOT}/{a}", keep) store[a] = (A, EP, IDX, W, XYZ) B, nep = boot_matrix(EP) m, lo, hi = ci(A["rsm"], B) dp, dplo, dphi = ci(A["rsm"] - A["perm"], B) dg, dglo, dghi = ci(A["rsm"] - A["greedy"], B) res[g][a] = dict(n_episodes=int(nep), n_anchors=int(len(W)), w_bar=float(W.mean()), auc_rsm=m, auc_rsm_raw95=[lo, hi], auc_greedy=float(A["greedy"].mean()), auc_perm=float(np.nanmean(A["perm"])), auc_idql=float(np.nanmean(A["idql"])), d_rsm_perm=dp, d_rsm_perm_raw95=[dplo, dphi], d_rsm_greedy=dg, d_rsm_greedy_raw95=[dglo, dghi], clears=bool(lo > 0.5 and dplo > 0.0)) star = " *" if res[g][a]["clears"] else " " print(f"{a:16s} {nep:2d} {len(W):4d} {W.mean():6.3f} | {m:8.3f} [{lo:+.3f},{hi:+.3f}] | " f"{A['greedy'].mean():6.3f} {np.nanmean(A['perm']):6.3f} {np.nanmean(A['idql']):6.3f} | " f"{dp:+9.4f} [{dplo:+.3f},{dphi:+.3f}]{star}")
# ---- paired AUG - CTRL at matched anchors (same episode, same anchor index, ee_xyz verified) ---- (Ac, EPc, IXc, Wc, Xc), (Aa, EPa, IXa, Wa, Xa) = store[CTRL], store[AUG] kc = {(e, i): j for j, (e, i) in enumerate(zip(EPc, IXc))} ja, jc = [], [] for j, (e, i) in enumerate(zip(EPa, IXa)): if (e, i) in kc: ja.append(j) jc.append(kc[(e, i)]) ja, jc = np.asarray(ja, int), np.asarray(jc, int) if len(ja): dxyz = float(np.nanmax(np.abs(Xa[ja] - Xc[jc]))) if len(ja) else float("nan") assert not (dxyz > 1e-3), f"matched anchors disagree on ee_xyz_mm by {dxyz:.4g} mm" Bp, nepp = boot_matrix(EPa[ja]) d, dlo, dhi = ci(Aa["rsm"][ja] - Ac["rsm"][jc], Bp) PAIR[g] = dict(n_anchors=int(len(ja)), n_episodes=int(nepp), d=d, raw95=[dlo, dhi], max_ee_xyz_mismatch_mm=dxyz, per_ep=[float(x) for x in [np.mean((Aa["rsm"][ja] - Ac["rsm"][jc])[EPa[ja] == e]) for e in np.unique(EPa[ja])]], eps=[int(e) for e in np.unique(EPa[ja])]) PAIR[g]["sign_test"] = sign_test(PAIR[g]["per_ep"]) res[g]["_paired_aug_minus_ctrl"] = PAIR[g] st = PAIR[g]["sign_test"] print(f" exact paired sign test: {st['n_pos']}/{st['n']} episodes positive, " f"p={st['p']:.2e} (floor 2/2**{st['n']} = {st['p_floor']:.2e})") print(f"{'AUG - CTRL (paired)':16s} {nepp:2d} {len(ja):4d} {'':6s} | {d:+8.4f} " f"[{dlo:+.3f},{dhi:+.3f}] | anchors matched exactly (max ee_xyz gap {dxyz:.1e} mm); " f"CANDIDATES ARE REDRAWN PER ARM (run 33 gate)")
# ---------------- specificity: difference-in-differences ----------------DID = Noneif "DEST_goalbound" in PAIR and "DEST_failure" in PAIR: dg_, dgl, dgh = PAIR["DEST_goalbound"]["d"], *PAIR["DEST_goalbound"]["raw95"] df_, dfl, dfh = PAIR["DEST_failure"]["d"], *PAIR["DEST_failure"]["raw95"] # cluster bootstrap of the contrast itself: resample episodes WITHIN each cell independently pg = np.asarray(PAIR["DEST_goalbound"]["per_ep"]) pf = np.asarray(PAIR["DEST_failure"]["per_ep"]) rng = np.random.default_rng(SEED) bg = pg[rng.integers(0, pg.size, (NB, pg.size))].mean(1) bf = pf[rng.integers(0, pf.size, (NB, pf.size))].mean(1) did = float(pg.mean() - pf.mean()) dlo, dhi = (float(np.percentile(bg - bf, 2.5)), float(np.percentile(bg - bf, 97.5))) DID = dict(did=did, raw95=[dlo, dhi], gb=float(pg.mean()), fail=float(pf.mean()), n_gb_eps=int(pg.size), n_fail_eps=int(pf.size)) res["_specificity_did"] = DID print(f"\nSPECIFICITY (rule (b)): (AUG-CTRL)|goal-bound - (AUG-CTRL)|failure = {did:+.4f} " f"[{dlo:+.3f},{dhi:+.3f}] (gb {pg.mean():+.4f} on {pg.size} eps, " f"fail {pf.mean():+.4f} on {pf.size} eps; episode-level cluster bootstrap)")
# ---------------- the mechanical reading ----------------print("\n" + "=" * 100)if not READABLE: print(f"NO VERDICT: the rule needs >= {MIN_GB_EPISODES} goal-bound episodes common to both arms; " f"{len(gb_both)} are on disk. Re-run when the wave finishes.")else: G = res["DEST_goalbound"] a = G[AUG] rep = bool(a["auc_rsm_raw95"][0] > 0.5 and a["d_rsm_perm_raw95"][0] > 0.0) if rep: spec = bool(DID and DID["raw95"][0] > 0.0) both_cells = bool(res["DEST_failure"][AUG]["auc_rsm_raw95"][0] > 0.5) print(f"READING (a) FIRES -- REPLICATES: AUG goal-bound AUC_u {a['auc_rsm']:.3f} " f"raw95 {['%+.3f' % x for x in a['auc_rsm_raw95']]} (chance 0.5) and paired rsm-permuted " f"{a['d_rsm_perm']:+.4f} {['%+.3f' % x for x in a['d_rsm_perm_raw95']]} on " f"{a['n_episodes']} goal-bound clusters; control {G[CTRL]['auc_rsm']:.3f} " f"{['%+.3f' % x for x in G[CTRL]['auc_rsm_raw95']]}.") if spec and not both_cells: print(" (b) SPECIFIC: the gain is larger at the goal-bound anchors than at the failure " f"anchors, DiD {DID['did']:+.4f} {['%+.3f' % x for x in DID['raw95']]} -- " "augmentation acts exactly where the pooled leverage-weighted metric cannot see it.") elif both_cells: print(" (b) NOT SPECIFIC: AUG also clears chance at the FAILURE anchors " f"({res['DEST_failure'][AUG]['auc_rsm']:.3f}) -- it is simply a better scorer and the " "goal-bound framing is WRONG; say so.") else: print(f" (b) SPECIFICITY NOT ESTABLISHED: DiD {DID['did'] if DID else float('nan'):+.4f} " f"{(['%+.3f' % x for x in DID['raw95']]) if DID else 'n/a'} covers 0.") print(f" SPLIT = {SPLIT_LABEL}. It cannot move the #278 verdict, which is the " "LEVERAGE-WEIGHTED clause-2 number on the S0 held-out set (+0.0135 [-0.0249,+0.0612], " "rung U).") else: print(f"READING (c) FIRES -- DOES NOT REPLICATE: AUG goal-bound AUC_u {a['auc_rsm']:.3f} " f"raw95 {['%+.3f' % x for x in a['auc_rsm_raw95']]}, paired rsm-permuted " f"{a['d_rsm_perm']:+.4f} {['%+.3f' % x for x in a['d_rsm_perm_raw95']]}, on " f"{a['n_episodes']} goal-bound clusters (5x the screen's 8). The run-35 hit " "(0.740 [.676,.843] at 8 clusters) was multiplicity over 114 arms. The closed negative " "is untouched and the augmentation lead is SPENT.")print("=" * 100)print("\nThe pre-registered #278 verdict is UNCHANGED and is not a function of anything above:")print(" clause 1 coverage 0.904 PASS | clause 2 +0.0909 [+0.0373,+0.1480] vs +0.10 FAIL | " "clause 3 flip 0.745 vs greedy 0.519 PASS -> CONJUNCTION FAIL, #278 stays CLOSED.")
out = f"{ROOT}/{OUT_NAME}"json.dump(res, open(out, "w"), indent=1, default=float)print("\nwrote", out)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256r"""#278 RUNG AH -- IS THE S2 RESULT A *CONSTANT* DIRECTION PREFERENCE?
WHY THIS MEASUREMENT, WITH THE NUMBER THAT CHOSE IT (rung AG, SLURM 42623 -> 43081,status/real/EDGE_AG_SEED0.json, logs/slurm/rr_cpu_edgeAG_read.43081.out):
S2 held-out anchors, CONTROL arm (shipped successor R_XL), unweighted per-anchor AUC of the on-route candidates vs the off-route ones: DEST_goal4 (route 2->3->4, on-route edge 2->3) AUC_u 0.246 [+0.159,+0.334] 45 anchors / 5 eps DEST_cook3 (route 0->2->3, on-route edge 2->3) AUC_u 0.319 [+0.260,+0.567] 23 anchors / 4 eps DEST_failure (route 0->2->6, on-route edge 2->6) AUC_u 0.690 [+0.633,+0.754] 65 anchors / 5 eps The four augmented seeds show the same split (goal4 0.194/0.20/0.27/0.29, failure 0.54/../..).
Those two cells are NOT independent claims. At S2 there are exactly two available edges, 2->3 and2->6, and "on-route" is defined relative to the EPISODE'S OWN route: it is 2->3 in the goal-boundgroups and 2->6 in the failure group. So a scorer with a SINGLE FIXED preference for the 2->6direction -- one that ignores the anchor state entirely -- scores AUC ~ 0.25 in the goal-bound cellsand ~ 0.75 in the failure cell BY ARITHMETIC, without conditioning on anything. 0.246 and 0.690 arevery close to exactly that pattern.
If that is what is happening, then the failure-cell positives this project has published (rung AGctrl d_rsm +0.170 at DEST_failure, and the pooled +0.0434 that is positive only because of it) areNOT evidence of planning, and the negative on #278 is localised much more sharply than "the scorerranks at chance": the scorer has NO state-conditional direction preference at the branch at all.
THIS FILE MEASURES THAT DIRECTLY, WITH ONE FIXED EDGE NAME. For every contrastive S2 anchor itcomputes the scorer's preference for the edge literally named "2->6" -- the SAME edge in every group,so the quantity no longer moves when the episode's destiny changes: rp26 = mean rank percentile (edge_field.rank_pct, the published function) of the candidates classified into "2->6", among that anchor's 128 candidates; top1_26 = 1 if the top-scored candidate is classified into "2->6", else 0.Both are aggregated per destiny group with the SAME episode-level cluster bootstrap used byedge_AD_read.py (boot_matrix / ci imported from it, not reimplemented).
PRE-REGISTERED READING (fixed before this file was run; the rule is on rp26 under the `rsm` scorer,the others are reported as nulls and context): (A) CONSTANT DIRECTION PREFERENCE -- rp26 is on the same side of 0.5 in the goal-bound groups and in the failure group, AND the difference rp26(failure) - rp26(goal-bound) has its 95 % cluster interval COVERING 0. Reading: the S2 AUC split is arithmetic, the scorer does not condition on the anchor, and every failure-cell positive published on this test is an artefact of the on-route label tracking the episode's route. Say that plainly. (B) DESTINY-CONDITIONED -- rp26(failure) - rp26(goal-bound) > 0 with its interval EXCLUDING 0. The scorer does condition on the state; the #278 negative is then about the SIZE of the effect, not about the absence of conditioning, and the next rung stays on the scorer's capacity. (C) INVERTED -- the difference is < 0 with its interval excluding 0. That is a sign defect in the labels or the fields and must be hunted before any further scorer work.Ceiling/floor context printed beside every cell: `greedy_idx` (the proposer's own order, an unbiaseddraw -> 0.5) and `random`. A null that is itself off 0.5 means the CANDIDATE POOL is imbalanced andis reported as such.
SCOPE. This is a READ of arrays already on disk (status/real/edge_AG_*/edge_parts/*.npz, written bySLURM 42623). No model runs, no checkpoint is loaded, nothing is retrained and no pre-registeredquantity is altered. The #278 verdict is a function of clause 2 (the leverage-weighted held-out S0d_vs_greedy, +0.0135 [-0.0249,+0.0612] at rung U) and CANNOT be changed by anything printed here --#278 stays CLOSED whichever clause fires.
CAVEATS THAT TRAVEL WITH THESE NUMBERS: * the anchors are the harness's own contrastive anchors (0 < onroute.sum() < n_cand), the same gate behind every published cell, so these rows are the same anchors as rung AG's; * candidates are REDRAWN per arm (run 33), so between-ARM comparisons carry sampling noise; the rule above is a WITHIN-ARM comparison between destiny groups and is not affected by that; * DEST_goal4 has at most 5 held-out clusters and DEST_cook3 at most 5, so intervals are wide by construction; the rule is written to be readable at that power because (A) is the hypothesis that the two cells MOVE TOGETHER, which the pooled goal-bound group (up to 9 clusters) can support."""import os, sys, json, globimport numpy as np
sys.path.insert(0, "/proj/dmfexp/zwhong/rsm_rise/scripts/real")from edge_field import rank_pct # the published rank-percentile, unmodified
# The cluster bootstrap and the interval are NOT reimplemented here: the two functions are LIFTED# VERBATIM out of scripts/real/edge_AD_read.py (the file that produced every published rung# AD/AE/AF/AG cell) by source extraction, so they are byte-identical by construction rather than by# inspection. edge_AD_read.py cannot simply be imported -- it runs its whole analysis at module# level -- so the two function definitions are located with `ast` and exec'd on their own.import ast as _ast_SRC = open("/proj/dmfexp/zwhong/rsm_rise/scripts/real/edge_AD_read.py").read()_TREE = _ast.parse(_SRC)_LIFT = {n.name: _ast.get_source_segment(_SRC, n) for n in _TREE.body if isinstance(n, _ast.FunctionDef) and n.name in ("boot_matrix", "ci")}assert set(_LIFT) == {"boot_matrix", "ci"}, _LIFT.keys()# NB/SEED must exist before the exec: boot_matrix's signature is `def boot_matrix(EP, nb=NB,# seed=SEED)` and Python binds those defaults at definition time. 20000/0 are edge_AD_read.py's own# values, asserted against its source below so a drift there cannot pass silently.assert "NB, SEED = 20000, 0" in _SRC, "edge_AD_read.py changed its bootstrap constants"_NS = {"np": np, "NB": 20000, "SEED": 0}for _n in ("boot_matrix", "ci"): exec(compile(_LIFT[_n], "edge_AD_read.py::" + _n, "exec"), _NS)boot_matrix, ci = _NS["boot_matrix"], _NS["ci"]SPLIT = json.load(open("/proj/dmfexp/zwhong/rsm_rise/data/derived/cooking_v5_split.json"))["episodes"]
ROOT = "/proj/dmfexp/zwhong/rsm_rise/status/real"EPS_FILE = os.environ.get("AH_EPS_FILE", f"{ROOT}/edge_heldout_eps.txt")EPS = [int(x) for x in open(EPS_FILE).read().replace(",", " ").split()]ARMS = os.environ.get("AH_ARMS", "edge_AG_ctrl,edge_AG_aug_s0,edge_AG_aug_s1,edge_AG_aug_s2,edge_AG_aug_s3").split(",")EDGE = os.environ.get("AH_EDGE", "2->6") # the ONE fixed edge name the rule is written onOUT_NAME = os.environ.get("AH_OUT", "EDGE_AH_CONSTPREF.json")NB, SEED = 20000, 0
COLS = {"rsm": "score_rsm", "perm": "score_permuted__rsm", "idql": "score_idql", "permi": "score_permuted__idql"}
def destiny3(e): fs = SPLIT[str(int(e))]["final_state"] return "DEST_goal4" if fs == 4 else ("DEST_cook3" if fs == 3 else "DEST_failure")
def read_arm(d, keep, edge): """per contrastive anchor: rank-pct and top-1 indicator for the FIXED edge name `edge`.""" rp = {k: [] for k in COLS} t1 = {k: [] for k in COLS} rp["greedy_idx"], t1["greedy_idx"], rp["random"], t1["random"] = [], [], [], [] EP, IDX, AVAIL_OK, NSEL = [], [], [], [] rng = np.random.default_rng(SEED) for f in sorted(glob.glob(f"{d}/edge_parts/*.npz")): e = int(f.split("/")[-1][2:-4]) if e not in keep: continue z = np.load(f, allow_pickle=True) if "onroute" not in z.files: continue meta = json.loads(bytes(z["__meta__"]).decode()) onr = np.asarray(z["onroute"], bool) cls = np.asarray(z["cls"], int) for i in range(onr.shape[0]): o, c = onr[i], cls[i] n = o.size if not (0 < int(o.sum()) < n): # the harness's own contrastive gate continue av = meta[i]["avail"] # rung AI (#278): AH_EDGE=__TRUE__ selects the edge THIS EPISODE ACTUALLY TOOK, so the # quantity is "how does the scorer rank the expert's own direction" and is comparable # across destiny groups without the global-ON_ROUTE confusion that rung AH's prose had. e_here = meta[i]["true_edge"] if edge == "__TRUE__" else edge if e_here not in av: AVAIL_OK.append(False) continue sel = (c == av.index(e_here)) if not (0 < int(sel.sum()) < n): # the fixed edge must also be contrastive here continue AVAIL_OK.append(True) EP.append(e); IDX.append(i); NSEL.append(int(sel.sum())) for k, key in COLS.items(): if key not in z.files: rp[k].append(np.nan); t1[k].append(np.nan); continue s = z[key][i].astype(np.float64) rp[k].append(float(rank_pct(s)[sel].mean())) t1[k].append(float(sel[int(np.argmax(s))])) s = -np.arange(n, dtype=float) # greedy_idx: candidate 0 wins -> unbiased draw rp["greedy_idx"].append(float(rank_pct(s)[sel].mean())) t1["greedy_idx"].append(float(sel[int(np.argmax(s))])) s = rng.permutation(n).astype(float) rp["random"].append(float(rank_pct(s)[sel].mean())) t1["random"].append(float(sel[int(np.argmax(s))])) return ({k: np.asarray(v, float) for k, v in rp.items()}, {k: np.asarray(v, float) for k, v in t1.items()}, np.asarray(EP, int), np.asarray(IDX, int), np.asarray(NSEL, float), int(len(AVAIL_OK) - sum(AVAIL_OK)))
def cell(v, EP): B, nclu = boot_matrix(EP, NB, SEED) m, lo, hi = ci(v, B) return dict(mean=m, lo=lo, hi=hi, n=int(v.size), n_clusters=int(nclu))
def diff_cell(v, EP, mask_a, mask_b): """mean(v[a]) - mean(v[b]) with ONE cluster bootstrap over the union of episodes (paired by episode resample, the same construction edge_AD_read.py uses for its DiD).""" EPu = EP B, nclu = boot_matrix(EPu, NB, SEED) wa, wb = mask_a.astype(float), mask_b.astype(float) num_a, den_a = (B * (v * wa)).sum(1), (B * wa).sum(1) num_b, den_b = (B * (v * wb)).sum(1), (B * wb).sum(1) ok = (den_a > 0) & (den_b > 0) d = num_a[ok] / den_a[ok] - num_b[ok] / den_b[ok] m = float(v[mask_a].mean() - v[mask_b].mean()) return dict(mean=m, lo=float(np.percentile(d, 2.5)), hi=float(np.percentile(d, 97.5)), n_a=int(mask_a.sum()), n_b=int(mask_b.sum()), n_boot_ok=int(ok.sum()))
def fmt(c): return f"{c['mean']:+.4f} [{c['lo']:+.4f},{c['hi']:+.4f}]"
def main(): print(__doc__.split("PRE-REGISTERED READING")[0].strip()[:0] or "", end="") print(f"RUNG AH -- constant-direction-preference diagnostic on the FIXED edge '{EDGE}'") print(f" anchors: {EPS_FILE} ({len(EPS)} episodes) arms: {', '.join(ARMS)}") print(f" rp{EDGE} = mean rank percentile of the candidates classified into '{EDGE}';" f" top1 = the top-scored candidate is in '{EDGE}'.") print(" A scorer with a single fixed preference for this edge gives the SAME rp in every" " destiny group.\n") out = {"edge": EDGE, "eps_file": EPS_FILE, "arms": {}} for arm in ARMS: rp, t1, EP, IDX, NSEL, n_skip = read_arm(f"{ROOT}/{arm}", set(EPS), EDGE) if EP.size == 0: print(f"### {arm}: no anchors\n"); continue dst = np.array([destiny3(e) for e in EP]) gb = (dst == "DEST_goal4") | (dst == "DEST_cook3") fa = (dst == "DEST_failure") print(f"### ARM {arm} {EP.size} contrastive anchors / {len(set(EP.tolist()))} episodes " f"(skipped {n_skip} anchors where '{EDGE}' was unavailable); " f"mean candidates in '{EDGE}' {NSEL.mean():.1f} of 128") print(f"{'scorer':<12} {'DEST_goal4':<26} {'DEST_cook3':<26} {'goal-bound pooled':<26} " f"{'DEST_failure':<26} {'fail - goalbound':<26}") arec = {} for k in ["rsm", "perm", "idql", "permi", "greedy_idx", "random"]: v = rp[k] if not np.isfinite(v).any(): continue cells = {g: cell(v[dst == g], EP[dst == g]) for g in ("DEST_goal4", "DEST_cook3", "DEST_failure")} cells["GOALBOUND"] = cell(v[gb], EP[gb]) dif = diff_cell(v, EP, fa, gb) arec[k] = {"rp": {g: cells[g] for g in cells}, "rp_diff_fail_minus_goalbound": dif, "top1": {g: cell(t1[k][dst == g], EP[dst == g]) for g in ("DEST_goal4", "DEST_cook3", "DEST_failure")}} print(f"{k:<12} {fmt(cells['DEST_goal4']):<26} {fmt(cells['DEST_cook3']):<26} " f"{fmt(cells['GOALBOUND']):<26} {fmt(cells['DEST_failure']):<26} {fmt(dif):<26}") print(f"{'top1 rsm':<12} " + " ".join(f"{g.split('_')[1]} {arec['rsm']['top1'][g]['mean']:.3f}" for g in ('DEST_goal4', 'DEST_cook3', 'DEST_failure'))) d = arec["rsm"]["rp_diff_fail_minus_goalbound"] gbm, fam = arec["rsm"]["rp"]["GOALBOUND"]["mean"], arec["rsm"]["rp"]["DEST_failure"]["mean"] same_side = (gbm - 0.5) * (fam - 0.5) > 0 if d["lo"] <= 0.0 <= d["hi"] and same_side: verdict = ("(A) CONSTANT DIRECTION PREFERENCE -- rp is on the same side of 0.5 in both " f"destinies (goal-bound {gbm:.3f}, failure {fam:.3f}) and their difference " f"{fmt(d)} covers 0. The S2 AUC split is arithmetic: the scorer does not " "condition on the anchor, and the failure-cell positives are an artefact of " "the on-route label tracking the episode's route.") elif d["lo"] > 0.0: verdict = ("(B) DESTINY-CONDITIONED -- rp is higher on the failure route " f"{fmt(d)}, interval excludes 0. The scorer DOES condition on the state; " "the #278 negative is about the size of the effect, not its absence.") elif d["hi"] < 0.0: verdict = ("(C) INVERTED -- rp is LOWER on the failure route " + fmt(d) + ", interval excludes 0. A sign defect in the labels or the fields; hunt it " "before any further scorer work.") else: verdict = ("(A-partial) the difference " + fmt(d) + " covers 0 but the two destinies are " f"NOT on the same side of 0.5 (goal-bound {gbm:.3f}, failure {fam:.3f}): " "consistent with a constant preference too weak to place, not with conditioning.") print(" READING " + verdict + "\n") arec["verdict"] = verdict out["arms"][arm] = arec out["note"] = ("#278 stays CLOSED: its clause 2 is the leverage-weighted held-out S0 d_vs_greedy " "(+0.0135 [-0.0249,+0.0612], rung U) and is not a function of anything here.") p = f"{ROOT}/{OUT_NAME}" json.dump(out, open(p, "w"), indent=1, default=float) print("wrote", p)
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222r"""#278 RUNG AJ -- IS THE S2 INVERSION A DIRECTION PREFERENCE OR A MAGNITUDE PREFERENCE?
THE NUMBERS THAT CHOSE IT (all measured this run, all on the held-out S2 anchors):
1. RUNG AI (SLURM 43088, status/real/EDGE_AI_TAKEN_S2.json) -- rp_taken, the mean rank percentile the scorer gives the candidates classified into THE EDGE THE EXPERT ACTUALLY TOOK: arm goal-bound pooled DEST_failure top1_taken (goal4/cook3/fail) AG ctrl (R_XL) 0.4183 [.3951,.4497] 0.4532 [.4157,.4784] 0.222 / 0.348 / 0.415 AG aug s0 0.3949 [.3651,.4354] 0.5112 [.4877,.5321] 0.239 / 0.208 / 0.631 AG aug s1 0.3896 [.3575,.4320] 0.4684 [.4331,.4910] 0.289 / 0.348 / 0.354 AG aug s2 0.4167 [.3902,.4481] 0.5043 [.4732,.5258] 0.244 / 0.417 / 0.523 AG aug s3 0.4311 [.3969,.4599] 0.4607 [.4285,.4857] 0.311 / 0.542 / 0.415 nulls (permuted:rsm, permuted:idql, random, greedy_idx) 0.49-0.52 in every cell All five arms are BELOW 0.5 at the goal-bound anchors with intervals excluding it, and never above it anywhere. The scorer is not at chance at S2: it reliably prefers the direction the expert did NOT take, and the nulls show the candidate pool itself is balanced.
2. THE LABELS ARE NOT THE CAUSE (status/real/EDGE_FIELD_VALIDATE_h16.json, already on disk, the same min-sep 20 deg setting every wave used): at S2 the HELD-OUT LOGGED ACTION is classified into its own true edge with accuracy 0.688 (chance 0.5, n = 1281, 15 episodes; recall 2->3 0.611, 2->6 0.864), the two fields are separated by a median 69.0 deg with none below 20, and 2->6 is the most concentrated field in the graph (leave-one-out median 18.2 deg, R 0.526). An inverted or unusable field would not classify the expert's own action correctly. So the sign lives in the SCORER, and rung AH's option (C) "sign defect in the labels" is answered NO.
3. WHAT IS STILL OPEN, AND IS WHAT THIS FILE MEASURES. The edge classes are not magnitude-neutral: a candidate is assigned to the edge whose field its DISPLACEMENT best matches, and the two S2 edges differ in how far the gripper travels. If the scorer simply prefers BIG (or small) moves, it produces exactly the observed pattern without any directional opinion at all.
THE MEASUREMENT, per arm, on the same contrastive anchors: (a) MAG_RHO -- the per-anchor Spearman correlation between the scorer's score and cand_mag_mm, aggregated with the episode cluster bootstrap. How much of the ordering is magnitude. (b) MAG_GAP -- mean cand_mag_mm of the true-edge candidates minus that of the others (mm), so the size of the confound is visible in physical units. (c) rp_taken_STRAT -- rp_taken recomputed WITHIN magnitude quartiles: each anchor's 128 candidates are split into 4 equal bins by cand_mag_mm, the rank percentile is taken inside each bin, and the true-edge candidates' within-bin percentiles are averaged. If magnitude is the whole story this returns to 0.5; if the preference is directional it survives. rp_taken (unstratified) is reprinted beside it from the same code path so the attenuation is read off one row.
PRE-REGISTERED READING (fixed before the job was submitted; on the `rsm` scorer, goal-bound cell): (J1) MAGNITUDE CONFOUND -- rp_taken_STRAT's interval COVERS 0.5 while rp_taken's excludes it. The S2 inversion is then a preference over how far the arm moves, not over where it goes, and the edge test at S2 has been reading a magnitude preference. The fix is to control magnitude in the candidate set, which is standard practice and already has a harness knob (cand_shrink). (J2) DIRECTIONAL -- rp_taken_STRAT stays below 0.5 with its interval excluding it. The inversion is genuinely about direction; magnitude does not explain it, and the next work is the scorer's own polarity (the value/reward it maximises at these states), not the candidate set. (J3) PARTIAL -- the point estimate moves toward 0.5 by more than half the gap but the interval still excludes it. Both mechanisms are present; report both sizes and say which dominates. MAG_RHO and MAG_GAP are printed for every arm whichever clause fires, because a large rho with an unattenuated rp_taken_STRAT is itself a finding: it means the scorer's ordering is mostly magnitude AND still anti-correlated with the expert's direction.
Reads arrays already on disk (SLURM 42623). No model is loaded, nothing is retrained, and nopre-registered quantity is altered. #278 stays CLOSED: its clause 2 is the leverage-weightedheld-out S0 d_vs_greedy, +0.0135 [-0.0249,+0.0612] at rung U, and is not a function of anything here."""import os, sys, json, globimport numpy as np
sys.path.insert(0, "/proj/dmfexp/zwhong/rsm_rise/scripts/real")from edge_field import rank_pct
# same verbatim lift as rung AH/AI: the bootstrap is edge_AD_read.py's, by source extractionimport ast as _ast_SRC = open("/proj/dmfexp/zwhong/rsm_rise/scripts/real/edge_AD_read.py").read()_TREE = _ast.parse(_SRC)_LIFT = {n.name: _ast.get_source_segment(_SRC, n) for n in _TREE.body if isinstance(n, _ast.FunctionDef) and n.name in ("boot_matrix", "ci")}assert set(_LIFT) == {"boot_matrix", "ci"}assert "NB, SEED = 20000, 0" in _SRC, "edge_AD_read.py changed its bootstrap constants"_NS = {"np": np, "NB": 20000, "SEED": 0}for _n in ("boot_matrix", "ci"): exec(compile(_LIFT[_n], "edge_AD_read.py::" + _n, "exec"), _NS)boot_matrix, ci = _NS["boot_matrix"], _NS["ci"]
ROOT = "/proj/dmfexp/zwhong/rsm_rise/status/real"SPLIT = json.load(open("/proj/dmfexp/zwhong/rsm_rise/data/derived/cooking_v5_split.json"))["episodes"]EPS = [int(x) for x in open(os.environ.get("AJ_EPS_FILE", f"{ROOT}/edge_heldout_eps.txt") ).read().replace(",", " ").split()]ARMS = os.environ.get("AJ_ARMS", "edge_AG_ctrl,edge_AG_aug_s0,edge_AG_aug_s1,edge_AG_aug_s2,edge_AG_aug_s3").split(",")OUT_NAME = os.environ.get("AJ_OUT", "EDGE_AJ_MAGNITUDE.json")NQ = int(os.environ.get("AJ_QUANTILES", "4"))COLS = {"rsm": "score_rsm", "perm": "score_permuted__rsm", "idql": "score_idql"}
def destiny3(e): fs = SPLIT[str(int(e))]["final_state"] return "DEST_goal4" if fs == 4 else ("DEST_cook3" if fs == 3 else "DEST_failure")
def spearman(a, b): ra = np.argsort(np.argsort(np.asarray(a, float))).astype(float) rb = np.argsort(np.argsort(np.asarray(b, float))).astype(float) ra -= ra.mean(); rb -= rb.mean() d = np.sqrt((ra * ra).sum() * (rb * rb).sum()) return float((ra * rb).sum() / d) if d > 0 else np.nan
def strat_rank_pct(s, mag, nq): """rank percentile computed WITHIN magnitude quantile bins (ties in mag broken by order).""" n = len(s) order = np.argsort(np.asarray(mag, float), kind="stable") out = np.full(n, np.nan) bins = np.array_split(order, nq) for b in bins: if b.size < 2: out[b] = 0.5 continue out[b] = rank_pct(np.asarray(s, float)[b]) return out
def read_arm(d, keep): rows = {k: {"rp": [], "rps": [], "rho": []} for k in COLS} EP, GAP, NSEL = [], [], [] for f in sorted(glob.glob(f"{d}/edge_parts/*.npz")): e = int(f.split("/")[-1][2:-4]) if e not in keep: continue z = np.load(f, allow_pickle=True) if "onroute" not in z.files: continue meta = json.loads(bytes(z["__meta__"]).decode()) onr, cls, mag = np.asarray(z["onroute"], bool), np.asarray(z["cls"], int), np.asarray(z["cand_mag_mm"], float) for i in range(onr.shape[0]): o, c, m = onr[i], cls[i], mag[i] n = o.size if not (0 < int(o.sum()) < n): continue av = meta[i]["avail"] te = meta[i]["true_edge"] if te not in av: continue sel = (c == av.index(te)) if not (0 < int(sel.sum()) < n): continue EP.append(e); NSEL.append(int(sel.sum())) GAP.append(float(m[sel].mean() - m[~sel].mean())) for k, key in COLS.items(): if key not in z.files: for q in ("rp", "rps", "rho"): rows[k][q].append(np.nan) continue s = z[key][i].astype(np.float64) rows[k]["rp"].append(float(rank_pct(s)[sel].mean())) rows[k]["rps"].append(float(strat_rank_pct(s, m, NQ)[sel].mean())) rows[k]["rho"].append(spearman(s, m)) return ({k: {q: np.asarray(v, float) for q, v in r.items()} for k, r in rows.items()}, np.asarray(EP, int), np.asarray(GAP, float), np.asarray(NSEL, float))
def cell(v, EP): B, nclu = boot_matrix(EP, 20000, 0) m, lo, hi = ci(v, B) return dict(mean=m, lo=lo, hi=hi, n=int(v.size), n_clusters=int(nclu))
def fmt(c): return f"{c['mean']:+.4f} [{c['lo']:+.4f},{c['hi']:+.4f}]"
def main(): print(f"RUNG AJ -- direction or magnitude? {NQ} magnitude quantile bins per anchor, " f"{len(EPS)} held-out episodes, arms: {', '.join(ARMS)}") print(" rp_taken = rank percentile of the EXPERT'S OWN edge's candidates (rung AI's quantity)") print(" rp_STRAT = the same, ranked WITHIN magnitude quantile bins") print(" MAG_RHO = per-anchor Spearman(score, candidate displacement magnitude)") print(" MAG_GAP = mean magnitude of the expert-edge candidates minus the others, mm\n") out = {"n_quantiles": NQ, "arms": {}} for arm in ARMS: R, EP, GAP, NSEL = read_arm(f"{ROOT}/{arm}", set(EPS)) if EP.size == 0: print(f"### {arm}: no anchors\n"); continue dst = np.array([destiny3(e) for e in EP]) gb = (dst == "DEST_goal4") | (dst == "DEST_cook3") fa = (dst == "DEST_failure") print(f"### ARM {arm} {EP.size} anchors / {len(set(EP.tolist()))} episodes; " f"expert-edge candidates {NSEL.mean():.1f} of 128; " f"MAG_GAP goal-bound {fmt(cell(GAP[gb], EP[gb]))} mm, failure {fmt(cell(GAP[fa], EP[fa]))} mm") print(f"{'scorer':<8} {'group':<12} {'rp_taken':<26} {'rp_STRAT':<26} {'MAG_RHO':<26}") rec = {"mag_gap": {"goalbound": cell(GAP[gb], EP[gb]), "failure": cell(GAP[fa], EP[fa])}} for k in COLS: if not np.isfinite(R[k]["rp"]).any(): continue rec[k] = {} for gname, msk in (("goal-bound", gb), ("failure", fa)): c_rp, c_rs, c_rh = (cell(R[k]["rp"][msk], EP[msk]), cell(R[k]["rps"][msk], EP[msk]), cell(R[k]["rho"][msk], EP[msk])) rec[k][gname] = {"rp_taken": c_rp, "rp_strat": c_rs, "mag_rho": c_rh} print(f"{k:<8} {gname:<12} {fmt(c_rp):<26} {fmt(c_rs):<26} {fmt(c_rh):<26}") g = rec["rsm"]["goal-bound"] rp, rs = g["rp_taken"], g["rp_strat"] below_rp, below_rs = rp["hi"] < 0.5, rs["hi"] < 0.5 moved = (rs["mean"] - rp["mean"]) / max(0.5 - rp["mean"], 1e-9) if below_rp and not below_rs: v = (f"(J1) MAGNITUDE CONFOUND -- rp_taken {fmt(rp)} excludes 0.5 but stratified " f"{fmt(rs)} covers it (closed {100*moved:.0f} % of the gap). The S2 inversion is a " "preference over how far the arm moves, not over where it goes.") elif below_rp and below_rs and moved <= 0.5: v = (f"(J2) DIRECTIONAL -- stratified {fmt(rs)} still excludes 0.5 (only " f"{100*moved:.0f} % of the gap closed). Magnitude does not explain the inversion; " "the scorer's own polarity at these states does.") elif below_rp and below_rs: v = (f"(J3) PARTIAL -- stratified {fmt(rs)} still excludes 0.5 but closed " f"{100*moved:.0f} % of the gap: both mechanisms are present, magnitude the larger.") else: v = (f"NOT INVERTED IN THIS ARM -- rp_taken {fmt(rp)} does not exclude 0.5; the " "(J1)/(J2)/(J3) rule does not apply and the cell is reported as is.") print(" READING " + v + "\n") rec["verdict"] = v out["arms"][arm] = rec p = f"{ROOT}/{OUT_NAME}" json.dump(out, open(p, "w"), indent=1, default=float) print("wrote", p)
if __name__ == "__main__": main()12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788#!/usr/bin/env python"""gen_q#276 STEP 1 (label validation) -- are the per-EPISODE edge labels consistent with where thearm actually ended up?
The rendered stage frames say two things the yaml does not: `end_stage2_global.png` (episode 100, theLAST frame annotated edge_to==2 on route 0->2->3) shows the pan at its STARTING position with thetomato in it -- i.e. state 1 -- while episode 101 on the same route shows the pan on the stove with thetomato untouched, which is state 2 exactly. So at least one episode's segment label does not match itsscene. A mislabelled episode pollutes that edge's direction field, so count them.
Proxy, no vision needed: at the ARRIVAL frame of a segment (its last frame) the gripper has justreleased whatever it carried, so the ee position is a signature of the edge. Per edge we take themedian arrival position over its episodes and report each episode's distance to it; an episode far fromits own edge's centre, and CLOSER to a sibling edge's centre, is flagged. CPU only."""from __future__ import annotationsimport argparse, json, sysfrom collections import defaultdictimport numpy as np
sys.path.insert(0, "/proj/dmfexp/zwhong/rsm_rise/scripts/real")from edge_field import ROOT, HDF5, SPLIT
def main(): ap = argparse.ArgumentParser() ap.add_argument("--hdf5", default=str(HDF5)) ap.add_argument("--split", default=str(SPLIT)) ap.add_argument("--out", required=True) a = ap.parse_args() import h5py meta = json.load(open(a.split))["episodes"] arr = defaultdict(list) # edge -> [(ep, xyz_at_arrival)] with h5py.File(a.hdf5, "r") as f: for ep in sorted(int(k) for k in meta): g = f["data"][f"demo_{ep}"] P = g["obs"]["robot0_eef_pos"][()].astype(np.float64) ef = g["annot"]["edge_from"][()].astype(int) et = g["annot"]["edge_to"][()].astype(int) for e in sorted(set(zip(ef.tolist(), et.tolist()))): m = np.nonzero((ef == e[0]) & (et == e[1]))[0] if len(m): arr[e].append((ep, P[m[-1]])) res = {"hdf5": a.hdf5, "edges": {}, "flagged": []} cen = {e: np.median(np.stack([x for _, x in v]), 0) for e, v in arr.items()} for e, v in sorted(arr.items()): key = f"{e[0]}->{e[1]}" d = np.array([np.linalg.norm(x - cen[e]) for _, x in v]) * 1000.0 sib = [s for s in arr if s[0] == e[0] and s != e] res["edges"][key] = { "n_episodes": len(v), "centre_xyz_m": [float(x) for x in cen[e]], "dist_to_own_centre_mm": {"median": float(np.median(d)), "p90": float(np.percentile(d, 90)), "max": float(d.max())}, "siblings": [f"{s[0]}->{s[1]}" for s in sib], "sibling_centre_sep_mm": {f"{s[0]}->{s[1]}": float(1000 * np.linalg.norm(cen[e] - cen[s])) for s in sib}, } # an episode is FLAGGED when its arrival is closer to a sibling edge's centre than to its own for (ep, x) in v: own = np.linalg.norm(x - cen[e]) for s in sib: if np.linalg.norm(x - cen[s]) < own: res["flagged"].append({"episode": int(ep), "labelled_edge": key, "closer_to": f"{s[0]}->{s[1]}", "dist_own_mm": float(1000 * own), "dist_other_mm": float(1000 * np.linalg.norm(x - cen[s])), "split": meta[str(ep)]["split"], "path": meta[str(ep)]["path"]}) break n_by = defaultdict(int) for r in res["flagged"]: n_by[r["labelled_edge"]] += 1 res["flagged_count_by_edge"] = dict(n_by) res["flagged_total"] = len(res["flagged"]) res["n_episodes"] = len(meta) json.dump(res, open(a.out, "w"), indent=1) print("[arr] wrote", a.out) for k, v in res["edges"].items(): print(f"[arr] {k:<6} n={v['n_episodes']:3d} own-centre dist med {v['dist_to_own_centre_mm']['median']:6.1f} " f"p90 {v['dist_to_own_centre_mm']['p90']:6.1f} mm sibling sep {v['sibling_centre_sep_mm']}") print(f"[arr] FLAGGED {res['flagged_total']} of {sum(len(v) for v in arr.values())} segments: {dict(n_by)}") for r in res["flagged"][:40]: print("[arr] ep %d labelled %s but closer to %s (%.0f vs %.0f mm) path=%s split=%s" % (r["episode"], r["labelled_edge"], r["closer_to"], r["dist_own_mm"], r["dist_other_mm"], r["path"], r["split"]))
if __name__ == "__main__": main()12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879r"""#278 run 33 addendum: HOW DIFFERENT are the candidate sets across arms?
edge_route_decomp.py's GATE A (onroute classification, elementwise) FAILED on 7/7 non-control armswith 27-75 of 291 anchors mismatched. The anchors themselves match (same episode/frame), so whatdiffers is the PROPOSER's 128 draws. Every cross-arm comparison in this ladder -- rungs V, Z, AA,AB, AC -- reads arms through DIFFERENT candidate sets at the same anchors, so the size of thatdifference is a property of the whole study, not of this run. Quantify it from the shards:per anchor, the fraction of the 128 candidate displacement vectors that are not bitwise equal tothe control's, and the fraction of anchors that are fully identical."""import json, sysimport numpy as npfrom pathlib import Path
ROOT = Path("/proj/dmfexp/zwhong/rsm_rise/status/real")CTRL = "edge_T_rise"ARMS = ["edge_V_goalep", "edge_V_goalseg", "edge_V_win400", "edge_V_win100", "edge_AC_rise_flow4", "edge_AC_rise_flow16", "edge_AC_rise_flow32"]COMMON = set(json.load(open(ROOT / "EDGE_ROUTE_DECOMP.json"))["_meta"]["common_episodes"])
def load(arm): out = {} for f in sorted((ROOT / arm / "edge_parts").glob("ep*.npz")): if f.name.endswith(".tmp.npz"): continue z = np.load(f, allow_pickle=False) meta = json.loads(bytes(z["__meta__"]).decode()) if not meta: continue for i, m in enumerate(meta): if int(m["episode"]) not in COMMON: continue out[(int(m["episode"]), int(m["frame"]))] = dict( disp=np.asarray(z["cand_disp_mm"][i], np.float32), logged=np.asarray(z["logged_disp_mm"][i], np.float32), ee=np.asarray(z["ee_xyz_mm"][i], np.float32), onroute=np.asarray(z["onroute"][i], bool), cls=np.asarray(z["cls"][i], np.int8)) return out
C = load(CTRL)print(f"control {CTRL}: {len(C)} anchors on the common episode set\n")hdr = (f"{'arm':22s} {'anchors':>8s} {'ee match':>9s} {'logged match':>13s} " f"{'anchors w/ identical cands':>27s} {'mean frac cands differing':>26s} " f"{'onroute mismatched anchors':>27s}")print(hdr); print("-" * len(hdr))out = {"control": CTRL, "n_anchors": len(C), "arms": {}}for a in ARMS: A = load(a) keys = [k for k in C if k in A] ee = sum(1 for k in keys if np.array_equal(A[k]["ee"], C[k]["ee"])) lg = sum(1 for k in keys if np.array_equal(A[k]["logged"], C[k]["logged"])) frac, ident, onr = [], 0, 0 for k in keys: d1, d2 = A[k]["disp"], C[k]["disp"] if d1.shape != d2.shape: frac.append(1.0); continue same = np.all(np.isclose(d1, d2, rtol=0, atol=1e-6), axis=-1) frac.append(float(1.0 - same.mean())) ident += int(same.all()) onr += int(not np.array_equal(A[k]["onroute"], C[k]["onroute"])) r = dict(n_anchors=len(keys), ee_match=ee, logged_match=lg, anchors_identical_candidates=ident, mean_frac_candidates_differing=float(np.mean(frac)) if frac else float("nan"), median_frac_candidates_differing=float(np.median(frac)) if frac else float("nan"), onroute_mismatched_anchors=onr) out["arms"][a] = r print(f"{a:22s} {len(keys):8d} {ee:4d}/{len(keys):<4d} {lg:6d}/{len(keys):<6d} " f"{ident:12d}/{len(keys):<4d} {r['mean_frac_candidates_differing']:26.4f} " f"{onr:22d}/{len(keys):<4d}")json.dump(out, open(ROOT / "EDGE_CANDIDATE_GATE.json", "w"), indent=1, default=float)print("\n-> status/real/EDGE_CANDIDATE_GATE.json")print("READING: ee_xyz and the logged action match everywhere -> the ANCHORS are the same physical\n" "states (that is the gate RANK_CTRL and every earlier rung checked). What differs is the\n" "PROPOSER DRAW. A between-arm delta is therefore measured through resampled candidates, and\n" "the ordering that survives that resampling (the flow arms reproduce the route decomposition\n" "with freshly drawn candidates) is the stronger claim, not the weaker one.")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128#!/usr/bin/env python3"""gen_q#278 -- what the on-route rank-pct metric can MAXIMALLY show, and what it is really measuring.
Two exact facts about the headline metric, both derived from edge_field.rank_pct and verifiedagainst the shipped edge_test.json to 4 decimal places:
1. IDENTITY (holds per anchor, exactly, no approximation): mean rank_pct over on-route = [ (n_on-1)/2 + n_off * AUC ] / (n-1) where AUC is the Mann-Whitney separation of on-route from off-route candidates at that anchor. The within-on-route term is a complete round robin and is therefore SCORER-INDEPENDENT. So the only thing any scorer can move is n_off*AUC/(n-1), and
2. CEILING: AUC <= 1 gives ceiling = (n_off + (n_on-1)/2)/(n-1) ~= 1 - f_onroute/2. d_vs_greedy therefore has a hard upper bound set by the PROPOSER's on-route fraction, not by the scorer. The pre-registered +0.10 bar is a fraction of THAT, not of 1.0.
3. LEVERAGE: the per-anchor weight is w = n_off/(n-1). It varies from 1/127 to ~30/127 across anchors, so a plain average of per-anchor AUC is NOT what the metric reports; the metric is the LEVERAGE-WEIGHTED AUC. Both are printed, because the gap between them says how concentrated the test's power is."""import sys, json, globimport numpy as np
sys.path.insert(0, __file__.rsplit("/", 1)[0])from edge_field import rank_pct
NB, SEED = 2000, 0
def auc(sc, o): a, b = sc[o], sc[~o] return float(((a[:, None] > b[None, :]).sum() + 0.5 * (a[:, None] == b[None, :]).sum()) / (a.size * b.size))
def arm(d, keep=None): cols = {"rsm": "score_rsm", "idql": "score_idql", "perm": "score_permuted__rsm", "permi": "score_permuted__idql"} W, EP, A = [], [], {k: [] for k in cols} A["greedy"] = [] RP = {k: [] for k in list(cols) + ["greedy"]} CEIL = [] for f in sorted(glob.glob(f"{d}/edge_parts/*.npz")): z = np.load(f, allow_pickle=True) if "onroute" not in z.files: continue e = int(f.split("/")[-1][2:-4]) if keep is not None and e not in keep: continue onr = np.asarray(z["onroute"], bool) for i in range(onr.shape[0]): o = onr[i]; n = o.size; n_on = int(o.sum()); n_off = n - n_on if not (0 < n_on < n): continue w = n_off / (n - 1.0) W.append(w); EP.append(e) CEIL.append((n_off + (n_on - 1) / 2.0) / (n - 1)) g = -np.arange(n, dtype=float) A["greedy"].append(auc(g, o)); RP["greedy"].append(float(rank_pct(g)[o].mean())) for k, key in cols.items(): if key in z.files: sc = z[key][i].astype(np.float64) A[k].append(auc(sc, o)); RP[k].append(float(rank_pct(sc)[o].mean())) W = np.asarray(W); EP = np.asarray(EP) u = np.unique(EP) rng = np.random.default_rng(SEED) boots = [np.concatenate([np.flatnonzero(EP == q) for q in rng.choice(u, u.size, True)]) for _ in range(NB)]
def wm(v, idx=None): v = np.asarray(v) if idx is None: return float((W * v).sum() / W.sum()) return float((W[idx] * v[idx]).sum() / W[idx].sum())
out = {"n_anchors": len(W), "n_episodes": int(u.size), "onroute_frac": float(1 - (W * (len(W) / len(W))).mean() * 0), # filled below "w_mean": float(W.mean()), "w_p50": float(np.median(W)), "w_p90": float(np.percentile(W, 90)), "leverage_top20pct_share": float(np.sort(W)[::-1][:max(1, len(W) // 5)].sum() / W.sum()), "ceiling_rankpct": float(np.mean(CEIL))} for k, v in A.items(): if not v: continue v = np.asarray(v) bw = [wm(v, b) for b in boots] bu = [v[b].mean() for b in boots] out["auc_" + k] = {"weighted": wm(v), "w_lo": float(np.percentile(bw, 2.5)), "w_hi": float(np.percentile(bw, 97.5)), "unweighted": float(v.mean()), "u_lo": float(np.percentile(bu, 2.5)), "u_hi": float(np.percentile(bu, 97.5))} out["rankpct_" + k] = float(np.mean(RP[k])) # exact reconstruction check: d_vs_greedy must equal mean_a[ w_a*(AUC_a - AUCg_a) ] g = np.asarray(A["greedy"]) for k in A: if k == "greedy": continue out["d_vs_greedy_" + k] = float((W * (np.asarray(A[k]) - g)).mean()) out["d_ceiling"] = out["ceiling_rankpct"] - out["rankpct_greedy"] # AUC the +0.10 bar demands, in the SAME leverage-weighted units the metric reports out["auc_needed_for_bar"] = out["auc_greedy"]["weighted"] + 0.10 / float(W.mean()) return out
if __name__ == "__main__": o = {} for d in sys.argv[1:]: t = d.rstrip("/").split("/")[-1] try: o[t] = arm(d) except Exception as e: o[t] = {"error": repr(e)} print(f"{'arm':20s} {'eps':>3s} {'anc':>4s} {'wbar':>5s} {'d_ceil':>7s} {'d_rsm':>7s} {'%ceil':>6s} " f"| {'AUCw_rsm':>22s} {'AUCw_grd':>8s} {'AUCw_prm':>8s} {'AUC_need':>8s} | {'AUCu_rsm':>8s}") for t, r in o.items(): if "error" in r: print(f"{t:20s} {r['error'][:70]}"); continue a = r["auc_rsm"] print(f"{t:20s} {r['n_episodes']:3d} {r['n_anchors']:4d} {r['w_mean']:5.3f} " f"{r['d_ceiling']:+7.4f} {r['d_vs_greedy_rsm']:+7.4f} " f"{100*r['d_vs_greedy_rsm']/r['d_ceiling']:5.1f}% | " f"{a['weighted']:.3f}[{a['w_lo']:.3f},{a['w_hi']:.3f}] " f"{r['auc_greedy']['weighted']:8.3f} {r['auc_perm']['weighted']:8.3f} " f"{r['auc_needed_for_bar']:8.3f} | {a['unweighted']:8.3f}") import os op = os.environ.get("RR_CEIL_OUT", "status/real/EDGE_CEILING.json") json.dump(o, open(op, "w"), indent=1) print("->", op)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118r"""#278 run 34 (second reduction): IS RUN 33'S ROUTE HETEROGENEITY A SCORER DEFICIT OR HEADROOM?
Run 33 measured d_vs_greedy +0.1340 on the 0->5 route against +0.0448 on the on-route-edge routesand +0.0032 at the cooking cell of the same first edge. That was read as "the pooled number iscarried by the failure route". There is an alternative reading with a measurable signature, and theartefacts on disk already contain it: at a failure anchor the LOGGED action heads off-route, so thegreedy/BC baseline is bad by construction and the headroom is large; at an on-route anchor the loggedaction is already on-route and there is little room above it. The metric's own ceiling identity(edge_ceiling2.py, verified to 4 dp against edge_field.rank_pct) gives the headroom per anchor: d_ceiling = ceiling_rankpct - rankpct_greedy, ceiling = (n_off + (n_on-1)/2)/(n-1)so %ceil = d_rsm / d_ceiling is the scorer's share of what was AVAILABLE in that group.
PRE-REGISTERED READING (written before the per-group numbers were computed; the pooled cell%ceil 47.9 % is already published, the per-group split is not): (i) %ceil approximately FLAT across the four routes (spread <= ~10 points) -> the absolute heterogeneity run 33 reported is a HEADROOM effect. The scorer converts the same share of the available signal everywhere, and the correct statement is that the TEST has little power at on-route anchors, not that the scorer fails there. (ii) %ceil MUCH LOWER on the goal-bound routes (0->1->3, 0->2->3) than on 0->5 -> the deficit is the scorer, exactly as run 33 read it, and the goal-bound cell is a genuine failure. (iii) %ceil HIGHER on the goal-bound routes -> the pooled number understates the scorer at the states a planner needs, and the on-route cells are power-limited.Either way the verdict on #278 is untouched: this is a decomposition of a fired rule, not a new arm.
No new model call, no new harness: edge_ceiling2.arm() called per route group via its own `keep`argument, on the SAME edge_parts/*.npz as every published number."""import sys, json, osimport numpy as npsys.path.insert(0, "/proj/dmfexp/zwhong/rsm_rise/scripts/real")from edge_ceiling2 import arm
ROOT = "/proj/dmfexp/zwhong/rsm_rise/status/real"SPLIT = json.load(open("/proj/dmfexp/zwhong/rsm_rise/data/derived/cooking_v5_split.json"))["episodes"]COMMON = [7, 9, 12, 22, 46, 52, 54, 68, 73, 86, 105, 107, 120, 131, 137, 204, 223, 224, 230, 231]ARMS = [("edge_T_rise", "CONTROL, shipped best cell (GOAL_EPISODE, flow 8, p16)"), ("edge_AC_rise_flow32", "replicate at flow 32"), ("edge_V_goalseg", "GOAL_SEGMENT label (pooled-negative arm)")]
def route_of(e): return "->".join(str(x) for x in SPLIT[str(int(e))]["path"])
def destiny_of(e): return "goalbound" if SPLIT[str(int(e))]["final_state"] in (3, 4) else "failure"
by_route = {}for e in COMMON: by_route.setdefault(route_of(e), []).append(e)GROUPS = [("ALL", COMMON)] + [(f"R_{k}", v) for k, v in sorted(by_route.items())]GROUPS += [("ONROUTE_EDGE", [e for e in COMMON if route_of(e) != "0->5"]), ("DEST_goalbound", [e for e in COMMON if destiny_of(e) == "goalbound"]), ("DEST_failure", [e for e in COMMON if destiny_of(e) == "failure"])]
print("route census of the common 20 held-out episodes (printed before any number):")for k, v in sorted(by_route.items()): print(f" {k:10s} {len(v)} episodes {v} destiny={destiny_of(v[0])}")
out = {"_meta": dict(common_episodes=COMMON, groups={k: v for k, v in GROUPS}, note="edge_ceiling2.arm() per group; contrastive anchors only, as the metric")}for a, lab in ARMS: d = f"{ROOT}/{a}" if not os.path.isdir(d + "/edge_parts"): print(f"\n{a}: no parts on disk -- skipped"); continue print(f"\n### {a} -- {lab}") hdr = (f"{'group':16s} {'eps':>3s} {'anc':>4s} {'wbar':>5s} {'d_ceil':>8s} {'d_rsm':>8s} " f"{'%ceil':>7s} | {'AUCw_rsm':>8s} {'AUCw_grd':>8s} {'AUC_need':>8s} {'rp_grd':>7s}") print(hdr); print("-" * len(hdr)) out[a] = {"_label": lab} for g, eps in GROUPS: try: r = arm(d, keep=set(eps)) except Exception as ex: # a group with no contrastive anchor print(f"{g:16s} error {ex!r}"); continue if not r.get("n_anchors"): print(f"{g:16s} no contrastive anchors"); continue pc = 100 * r["d_vs_greedy_rsm"] / r["d_ceiling"] if r["d_ceiling"] else float("nan") r["pct_of_ceiling"] = pc out[a][g] = r print(f"{g:16s} {r['n_episodes']:3d} {r['n_anchors']:4d} {r['w_mean']:5.3f} " f"{r['d_ceiling']:+8.4f} {r['d_vs_greedy_rsm']:+8.4f} {pc:6.1f}% | " f"{r['auc_rsm']['weighted']:8.3f} {r['auc_greedy']['weighted']:8.3f} " f"{r['auc_needed_for_bar']:8.3f} {r['rankpct_greedy']:7.3f}")
# ---- the mechanical reading, on the CONTROL ----c = out.get("edge_T_rise", {})keys = ["R_0->5", "R_0->1->3", "R_0->2->3", "R_0->2->6"]pcs = {k: c[k]["pct_of_ceiling"] for k in keys if k in c}if len(pcs) == 4: spread = max(pcs.values()) - min(pcs.values()) gb = np.mean([pcs["R_0->1->3"], pcs["R_0->2->3"]]) fe = pcs["R_0->5"] if spread <= 10.0: verd = ("(i) %ceil is FLAT across routes -> run 33's absolute heterogeneity is a HEADROOM " "effect; the test has little power at on-route anchors rather than the scorer " "failing there") elif gb < fe - 10.0: verd = ("(ii) %ceil is MUCH LOWER on the goal-bound routes -> the deficit is the scorer at " "exactly the states a planner needs, as run 33 read it") elif gb > fe + 10.0: verd = ("(iii) %ceil is HIGHER on the goal-bound routes -> the pooled number UNDERSTATES " "the scorer where a planner needs it and the on-route cells are power-limited") else: verd = ("between the pre-registered cases: spread > 10 points but the goal-bound mean is " "within 10 points of the failure route -- report the numbers, claim neither") print(f"\n%ceil per route (control): " + " ".join(f"{k}={v:.1f}%" for k, v in pcs.items())) print(f"spread {spread:.1f} points; goal-bound mean {gb:.1f}% vs failure edge {fe:.1f}%") print("READING: " + verd) out["_reading"] = dict(pct_of_ceiling=pcs, spread=spread, goalbound_mean=float(gb), failure_edge=float(fe), verdict=verd) print("\nThe #278 verdict is UNCHANGED either way: the bar is on the pooled clause-2 number " "(+0.0909 < +0.10) and this is a decomposition of it, not a new arm.")
p = f"{ROOT}/EDGE_CEILING_ROUTE.json"json.dump(out, open(p, "w"), indent=1, default=float)print("\nwrote", p)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204#!/usr/bin/env python3"""gen_q#278 -- FIGURE A and the DIVERSITY TABLE for the proposer's first-action directions.
Owner, 2026-09-23: "visualize all the 3D directions the end effector goes at the initial state anchors ...for every anchor give a 3D direction ... I want to see if it is actually diverse, the pi.5".
Reads the RAW 3-vectors the edge writer stores per anchor (scorer_openloop.py: cand_disp_mm [n_anchor,N,3],logged_disp_mm [n_anchor,3], ee_xyz_mm [n_anchor,3], all base-frame mm) -- directions are NEVER inferred fromthe class labels. No camera model is needed for any number or panel here; the image overlay (FIGURE B) is aseparate step that only ships if its held-out reprojection residual is small.
Per anchor, over candidates whose displacement exceeds --min-mag-mm: mean_pair_angle_deg mean pairwise angle between unit directions (spread of the fan) sphere_cov fraction of a 4096-point Fibonacci sphere within --cap-deg of SOME candidate (a solid-angle estimate: 1.0 = the whole sphere is within one cap of a sample) n_clusters greedy leader clustering of the unit directions at --cluster-deg logged_min_angle_deg angle from the LOGGED direction to the nearest candidate -- can this proposer produce the action the demonstrator actually took?Aggregated per branch state with a CLUSTER bootstrap over EPISODES (the anchors within an episode are notindependent), matching the edge test's own convention."""import argparse, glob, json, osimport numpy as np
ROOT = "/proj/dmfexp/zwhong/rsm_rise"
def unit(v): n = np.linalg.norm(v, axis=-1, keepdims=True) return np.where(n > 0, v / np.maximum(n, 1e-9), 0.0)
def fib_sphere(n=4096): i = np.arange(n) + 0.5 phi = np.arccos(1 - 2 * i / n) theta = np.pi * (1 + 5 ** 0.5) * i return np.stack([np.cos(theta) * np.sin(phi), np.sin(theta) * np.sin(phi), np.cos(phi)], 1)
def leader_clusters(u, deg): c = np.cos(np.deg2rad(deg)) heads = [] for d in u: if not heads or max(float(d @ h) for h in heads) < c: heads.append(d) return len(heads)
def boot_ci(vals, groups, n_boot=2000, seed=0): vals, groups = np.asarray(vals, float), np.asarray(groups) if len(vals) == 0: return (float("nan"),) * 3 gs = np.unique(groups) idx = {g: np.where(groups == g)[0] for g in gs} rng = np.random.default_rng(seed) out = np.empty(n_boot) for b in range(n_boot): pick = rng.choice(gs, len(gs), replace=True) out[b] = np.mean(np.concatenate([vals[idx[g]] for g in pick])) return float(vals.mean()), float(np.percentile(out, 2.5)), float(np.percentile(out, 97.5))
def load_arm(d, state, min_mag, cap_deg, cluster_deg, sphere): """-> per-anchor rows + the pooled unit directions for the figures.""" rows, pool = [], [] for f in sorted(glob.glob(os.path.join(d, "edge_parts", "*.npz"))): z = np.load(f) if "cand_disp_mm" not in z.files: continue # written before the raw-vector instrumentation landed meta = json.loads(bytes(z["__meta__"]).decode()) disp, logd, cls = z["cand_disp_mm"], z["logged_disp_mm"], z["cls"] for i, m in enumerate(meta): if int(m["state"]) != state: continue dd = disp[i] keep = np.linalg.norm(dd, axis=-1) >= min_mag if keep.sum() < 2: continue u = unit(dd[keep]) cosm = np.clip(u @ u.T, -1, 1) iu = np.triu_indices(len(u), 1) mean_pair = float(np.degrees(np.arccos(cosm[iu])).mean()) cov = float((np.max(sphere @ u.T, axis=1) >= np.cos(np.deg2rad(cap_deg))).mean()) lu = unit(logd[i]) lmin = float(np.degrees(np.arccos(np.clip((u @ lu).max(), -1, 1)))) if np.linalg.norm(logd[i]) > 0 else float("nan") rows.append(dict(episode=int(m["episode"]), frame=int(m["frame"]), state=state, n_used=int(keep.sum()), mean_pair_angle_deg=mean_pair, sphere_cov=cov, n_clusters=leader_clusters(u, cluster_deg), logged_min_angle_deg=lmin, median_mag_mm=float(np.median(np.linalg.norm(dd, axis=-1))), disp_spread_mm=float(m.get("disp_spread_mm", float("nan"))))) pool.append((int(m["episode"]), int(m["frame"]), u, unit(logd[i]), cls[i][keep], [str(e) for e in m["avail"]])) return rows, pool
def summarise(rows, seed=0): if not rows: return {"n_anchor": 0} g = [r["episode"] for r in rows] out = {"n_anchor": len(rows), "n_episode": len(set(g))} for k in ("mean_pair_angle_deg", "sphere_cov", "n_clusters", "logged_min_angle_deg", "median_mag_mm", "disp_spread_mm"): v = [r[k] for r in rows] v = [x for x in v if np.isfinite(x)] gg = [r["episode"] for r in rows if np.isfinite(r[k])] m, lo, hi = boot_ci(v, gg, seed=seed) out[k] = {"mean": m, "lo": lo, "hi": hi} return out
def figure_a(pool, name, state, png, max_anchors=24): import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt if not pool: return None # panel 1-3: ALL anchors pooled, the three base-frame projections; panel 4+: small multiples planes = [(0, 1, "X (mm, base frame)", "Y"), (0, 2, "X", "Z"), (1, 2, "Y", "Z")] fig = plt.figure(figsize=(16, 5.2)) for p, (a, b, xl, yl) in enumerate(planes): ax = fig.add_subplot(1, 3, p + 1) for ep, fr, u, lu, cls, avail in pool: for c in np.unique(cls): s = cls == c lab = avail[c] if 0 <= c < len(avail) else "undef" ax.scatter(u[s][:, a], u[s][:, b], s=2, alpha=0.25, color=plt.cm.tab10(int(c) % 10), label=lab) ax.arrow(0, 0, lu[a] * 0.9, lu[b] * 0.9, color="k", width=0.004, alpha=0.30, length_includes_head=True) ax.set_xlim(-1.1, 1.1); ax.set_ylim(-1.1, 1.1); ax.set_aspect("equal") ax.set_xlabel(xl); ax.set_ylabel(yl) h, l = ax.get_legend_handles_labels() seen = dict(zip(l, h)) if p == 0: ax.legend(seen.values(), seen.keys(), fontsize=7, loc="upper right", markerscale=4) fig.suptitle(f"FIGURE A -- {name}: unit first-action directions at S{state} anchors, all anchors pooled " f"(black = the LOGGED action, colour = edge class)") fig.tight_layout(); fig.savefig(png, dpi=130); plt.close(fig)
# small multiples, XY view, one panel per anchor -- "is it diverse" at a glance sm = png.replace(".png", "_anchors.png") k = min(max_anchors, len(pool)) cols, rowsn = 6, int(np.ceil(k / 6)) fig, axes = plt.subplots(rowsn, cols, figsize=(2.1 * cols, 2.1 * rowsn), squeeze=False) step = max(1, len(pool) // k) for j in range(rowsn * cols): ax = axes[j // cols][j % cols]; ax.set_xticks([]); ax.set_yticks([]) if j >= k: ax.axis("off"); continue ep, fr, u, lu, cls, avail = pool[j * step] ax.scatter(u[:, 0], u[:, 1], s=4, c=[plt.cm.tab10(int(c) % 10) for c in cls], alpha=0.7) ax.arrow(0, 0, lu[0] * 0.9, lu[1] * 0.9, color="k", width=0.03, length_includes_head=True) ax.set_xlim(-1.15, 1.15); ax.set_ylim(-1.15, 1.15); ax.set_aspect("equal") ax.set_title(f"ep{ep} f{fr}", fontsize=6) fig.suptitle(f"FIGURE A (small multiples) -- {name}, S{state}: XY top view, one panel per anchor") fig.tight_layout(); fig.savefig(sm, dpi=130); plt.close(fig) return sm
def main(): ap = argparse.ArgumentParser() ap.add_argument("--arm", action="append", required=True, metavar="NAME=DIR", help="a run directory containing edge_parts/ with cand_disp_mm") ap.add_argument("--state", type=int, action="append", default=None) ap.add_argument("--min-mag-mm", type=float, default=1.0) ap.add_argument("--cap-deg", type=float, default=20.0) ap.add_argument("--cluster-deg", type=float, default=20.0) ap.add_argument("--figdir", default=f"{ROOT}/docs/figs/real_dirs") ap.add_argument("--out", required=True) a = ap.parse_args() states = a.state or [0, 2] sphere = fib_sphere(4096) os.makedirs(a.figdir, exist_ok=True) res, md = {}, [] md.append("| arm | state | anchors (eps) | mean pairwise angle (deg) [CI] | sphere coverage @20deg [CI] " "| clusters @20deg [CI] | angle to LOGGED (deg) [CI] | median |disp| mm |") md.append("|---|---|---|---|---|---|---|---|") for spec in a.arm: name, d = spec.split("=", 1) for st in states: rows, pool = load_arm(d, st, a.min_mag_mm, a.cap_deg, a.cluster_deg, sphere) s = summarise(rows) res[f"{name}|S{st}"] = {"dir": d, "summary": s, "params": {"min_mag_mm": a.min_mag_mm, "cap_deg": a.cap_deg, "cluster_deg": a.cluster_deg}} if s["n_anchor"]: png = os.path.join(a.figdir, f"figA_{name}_S{st}.png") figure_a(pool, name, st, png) res[f"{name}|S{st}"]["figures"] = [png, png.replace(".png", "_anchors.png")] f = lambda k, p=1: (f"{s[k]['mean']:.{p}f} [{s[k]['lo']:.{p}f},{s[k]['hi']:.{p}f}]") md.append(f"| {name} | S{st} | {s['n_anchor']} ({s['n_episode']}) | {f('mean_pair_angle_deg')} " f"| {f('sphere_cov',3)} | {f('n_clusters')} | {f('logged_min_angle_deg')} " f"| {s['median_mag_mm']['mean']:.1f} |") else: md.append(f"| {name} | S{st} | 0 | -- (no edge_parts with cand_disp_mm) | | | | |") print(f"[dirfig] {name} S{st}: {json.dumps(s)}", flush=True) json.dump(res, open(a.out, "w"), indent=1) open(a.out.replace(".json", ".md"), "w").write("\n".join(md) + "\n") print("wrote", a.out, "and", a.out.replace(".json", ".md"))
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283#!/usr/bin/env python"""gen_q#276 STEP 1 -- the edge-direction field, and its validation.
The rig has no simulator, so a candidate action cannot be rolled out. But `actions_raw` is an ABSOLUTEend-effector target (data attr action_type='absolute'), so a candidate chunk at frame t proposes aDISPLACEMENT d = a[H-1,:3] - p_t from the current ee position p_t. The task graph's edges each have acharacteristic displacement direction at a given place on the table (edge 0->2 = "to the pan handle",0->1/0->5 = "to the tomato", then apart), so `d` classifies which edge a candidate is taking.
Direction is a FIELD, not a constant: "to the tomato" points differently from the left of the table thanfrom the right. So the field of edge e is estimated by k-nearest-neighbours in ee-xyz over the loggedframes that carry annot.edge_from/edge_to == e, on the TRAIN split only.
field_e(p) = normalise( sum_{i in kNN_e(p)} w_i u_i ), u_i = normalise(a_i[H-1,:3] - p_i)
and a candidate with displacement d at p is classified argmax_e cos(d, field_e(p)).
Validation (EDGE_TEST.md step 1, "a mislabelled edge silently inverts the whole test"): * angular spread of each edge's field, globally and after conditioning on position (leave-one-EPISODE-out); * pairwise separation of the fields that are available at the same anchor -- two edges whose fields are parallel at an anchor cannot be told apart there, however clean each one is on its own; * the decisive one: classify the LOGGED action of HELD-OUT episodes at the anchors. If the true expert displacement is not recovered, no candidate's can be.
Everything here reads only annot/, obs/robot0_eef_pos and actions_raw -- no images, no model: CPU only."""from __future__ import annotationsimport jsonfrom pathlib import Pathimport numpy as np
ROOT = Path("/proj/dmfexp/zwhong/rsm_rise")HDF5 = ROOT / "data/raw/cooking_v5_expert_suboptimal.hdf5"SPLIT = ROOT / "data/derived/cooking_v5_split.json"
# real/config/task/tabletop.yaml, transcribed in rise_stack/EDGE_TEST.md. on-route = lies on some route to# the single rewarded state 4; the two terminals 5 and 6 are failures.ON_ROUTE = {(0, 1), (0, 2), (1, 3), (2, 3), (3, 4)}FAILURE = {(0, 5), (2, 6)}BRANCH_STATES = (0, 2) # the shared-prefix states: 3 edges leave 0, 2 leave 2
def unit(v, axis=-1, eps=1e-9): n = np.linalg.norm(v, axis=axis, keepdims=True) return v / np.maximum(n, eps)
def ang_deg(a, b): """angle between unit-ish vectors, degrees, elementwise over the leading axes.""" c = np.clip((unit(a) * unit(b)).sum(-1), -1.0, 1.0) return np.degrees(np.arccos(c))
def load_frames(horizon=8, hdf5=HDF5, split=SPLIT, max_eps=0): """Per-frame table over every episode: ee position, chunk displacement, edge label, split.
Displacement uses the LOGGED ACTION at the end of the chunk (a[t+H-1]) minus the CURRENT ee position, which is exactly the quantity a candidate chunk supplies -- not p[t+H]-p[t], which carries the controller's tracking lag and would bias the field against the candidates. """ import h5py meta = json.load(open(split))["episodes"] eps = sorted(int(k) for k in meta) if max_eps: eps = eps[:max_eps] rec = [] with h5py.File(hdf5, "r") as f: for ep in eps: g = f["data"][f"demo_{ep}"] P = g["obs"]["robot0_eef_pos"][()].astype(np.float64) A = (g["actions_raw"] if "actions_raw" in g else g["actions"])[()].astype(np.float64)[:, :3] ef = g["annot"]["edge_from"][()].astype(int) et = g["annot"]["edge_to"][()].astype(int) T = len(P) t = np.arange(0, T - horizon) d = A[t + horizon - 1] - P[t] rec.append(dict(ep=ep, t=t, p=P[t], d=d, ef=ef[t], et=et[t], split=meta[str(ep)]["split"], path=tuple(meta[str(ep)]["path"]))) return rec
def stack(rec, which=None): sel = [r for r in rec if which is None or r["split"] == which] if not sel: return dict(ep=np.zeros(0, int), t=np.zeros(0, int), p=np.zeros((0, 3)), d=np.zeros((0, 3)), ef=np.zeros(0, int), et=np.zeros(0, int)) return dict(ep=np.concatenate([np.full(len(r["t"]), r["ep"]) for r in sel]), t=np.concatenate([r["t"] for r in sel]), p=np.concatenate([r["p"] for r in sel]), d=np.concatenate([r["d"] for r in sel]), ef=np.concatenate([r["ef"] for r in sel]), et=np.concatenate([r["et"] for r in sel]))
class EdgeField: """kNN direction field of one edge, fitted on the train split."""
def __init__(self, p, u, ep, k=64, min_move_m=2e-3): from scipy.spatial import cKDTree self.k = k self.p, self.u, self.ep = p, u, ep self.tree = cKDTree(p) if len(p) else None self.min_move_m = min_move_m
def __len__(self): return len(self.p)
def __call__(self, q, exclude_ep=None): """field direction(s) at query position(s) q [.,3] -> unit [.,3] (zeros where no support).""" q = np.atleast_2d(np.asarray(q, float)) out = np.zeros((len(q), 3)) if self.tree is None: return out kk = min(self.k if exclude_ep is None else self.k * 4, len(self.p)) dist, idx = self.tree.query(q, k=kk) dist = np.atleast_2d(dist); idx = np.atleast_2d(idx) for i in range(len(q)): j = idx[i] m = np.ones(len(j), bool) if exclude_ep is not None: m &= (self.ep[j] != exclude_ep[i]) j = j[m][: self.k] if len(j) == 0: continue out[i] = unit(self.u[j].mean(0)) return out
def fit_fields(tr, k=64, min_move_m=2e-3): """one EdgeField per (from,to) present in the train split.""" fields, counts = {}, {} mag = np.linalg.norm(tr["d"], axis=1) keys = sorted(set(zip(tr["ef"].tolist(), tr["et"].tolist()))) for e in keys: m = (tr["ef"] == e[0]) & (tr["et"] == e[1]) & (mag >= min_move_m) counts[e] = dict(n_frames=int(m.sum()), n_frames_all=int(((tr["ef"] == e[0]) & (tr["et"] == e[1])).sum()), n_episodes=int(len(set(tr["ep"][m].tolist())))) fields[e] = EdgeField(tr["p"][m], unit(tr["d"][m]), tr["ep"][m], k=k, min_move_m=min_move_m) return fields, counts
def edges_from(fields, s): return [e for e in fields if e[0] == s]
def classify(d, p, fields, avail): """argmax_e cos(d, field_e(p)). d,p are [N,3]; avail is the list of candidate edges. Returns (idx into avail [N], cos matrix [N,len(avail)]).""" F = np.stack([fields[e](p) for e in avail], 1) # [N,E,3] c = (unit(d)[:, None, :] * F).sum(-1) c[np.isnan(c)] = -1.0 return c.argmax(1), c
# ================================================================================================# gen_q#276 STEP 2 -- the five numbers. This is the ONLY place the metric is defined; both# scorer_openloop.py (at the end of a run) and edge_report.py (merging shards) call it, so a# sharded screen and an unsharded one produce the identical summary.# ================================================================================================
def rank_pct(s): """for every candidate, the fraction of the OTHER candidates it strictly beats. 1.0 = top.
Strictly-lower counting (not average-rank) is deliberate: the reward head saturates on this cache and ties at the max are the failure mode we must be able to SEE, so a tied block gets the pessimistic percentile and `ties_at_max` is reported beside every number.""" s = np.asarray(s, np.float64) n = len(s) if n < 2: return np.zeros(n) order = np.argsort(s, kind="stable") ss = s[order] # number of entries strictly below each sorted position lower = np.searchsorted(ss, ss, side="left").astype(np.float64) out = np.empty(n) out[order] = lower / (n - 1) return out
def _boot_ci(vals, groups, n_boot=2000, seed=0, alpha=0.05): """cluster bootstrap over EPISODES (anchors inside one episode are not independent).""" vals = np.asarray(vals, float); groups = np.asarray(groups) m = np.isfinite(vals) vals, groups = vals[m], groups[m] if len(vals) == 0: return dict(mean=float("nan"), lo=float("nan"), hi=float("nan"), n=0, n_episodes=0) g = np.unique(groups) idx = {gg: np.where(groups == gg)[0] for gg in g} rng = np.random.default_rng(seed) bs = np.empty(n_boot) for b in range(n_boot): pick = rng.choice(len(g), len(g), replace=True) take = np.concatenate([idx[g[p]] for p in pick]) bs[b] = vals[take].mean() return dict(mean=float(vals.mean()), lo=float(np.percentile(bs, 100 * alpha / 2)), hi=float(np.percentile(bs, 100 * (1 - alpha / 2))), n=int(len(vals)), n_episodes=int(len(g)))
def summarise_anchors(recs, modes, seed=0, n_boot=2000): """recs: the per-anchor dicts written by scorer_openloop.py --edge-test.
Returns the EDGE_TEST.md numbers per branch state: coverage (gate), on-route rank percentile per scorer with the paired delta vs greedy and a cluster-bootstrap CI, the permuted control, the counterfactual flip rate, and beside them the candidate spread and ties-at-max that say whether the candidate set could carry any signal. """ cols = list(modes) + ["greedy_idx", "random"] res = {"n_anchors_total": len(recs), "states": {}} rng = np.random.default_rng(seed) for s_ in sorted({int(r["state"]) for r in recs}): R = [r for r in recs if int(r["state"]) == s_] eps = np.array([int(r["episode"]) for r in R]) cov = np.array([bool(np.any(r["onroute"])) for r in R]) nN = np.array([int(r["n_cand"]) for r in R]) non = np.array([int(np.sum(r["onroute"])) for r in R]) nundef = np.array([int(np.sum(np.asarray(r["cls"]) < 0)) for r in R]) d = {"n_anchors": len(R), "n_episodes": int(len(set(eps.tolist()))), "avail": R[0]["avail"], "n_cand": int(nN[0]) if len(nN) else 0, "coverage": float(cov.mean()), "coverage_ci": _boot_ci(cov.astype(float), eps, n_boot, seed), "onroute_frac_of_candidates": float((non / np.maximum(nN, 1)).mean()), "undirected_frac_of_candidates": float((nundef / np.maximum(nN, 1)).mean()), "cand_disp_spread_mm": float(np.mean([r["disp_spread_mm"] for r in R])), "cand_disp_mag_mm_mean": float(np.mean([np.mean(r["cand_mag_mm"]) for r in R])), "true_edge_counts": {}, "scorers": {}, "flip": {}} for r in R: d["true_edge_counts"][r["true_edge"]] = d["true_edge_counts"].get(r["true_edge"], 0) + 1
# ---- ranking: only anchors where BOTH classes are present can order anything ---------- contrast = np.array([0 < int(np.sum(r["onroute"])) < int(r["n_cand"]) for r in R]) d["n_anchors_contrastive"] = int(contrast.sum()) fail = np.array([bool(r["true_is_failure"]) for r in R]) d["n_anchors_failure_edge"] = int(fail.sum())
def scores_of(r, m): n = int(r["n_cand"]) if m == "greedy_idx": return -np.arange(n, dtype=float) # candidate 0 wins; an unbiased draw -> null 0.5 if m == "random": return rng.permutation(n).astype(float) sc = r["scores"].get(m) return None if sc is None else np.asarray(sc, np.float64)
per = {} for m in cols: rk, tie, flip_c, flip_all, ok = [], [], [], [], [] for r, c_ in zip(R, contrast): sc = scores_of(r, m) if sc is None: rk.append(np.nan); tie.append(np.nan); ok.append(False); continue ok.append(True) orr = np.asarray(r["onroute"], bool) tie.append(float((sc == sc.max()).sum())) rk.append(float(rank_pct(sc)[orr].mean()) if (c_ and orr.any()) else np.nan) if r["true_is_failure"]: hit = bool(orr[int(np.argmax(sc))]) flip_all.append(float(hit)) if orr.any(): flip_c.append(float(hit)) if not any(ok): continue per[m] = np.array(rk) d["scorers"][m] = {"onroute_rank_pct": _boot_ci(rk, eps, n_boot, seed), "ties_at_max_mean": float(np.nanmean(tie)), "ties_at_max_frac_all_tied": float(np.nanmean(np.asarray(tie) >= np.asarray(nN, float)))} d["flip"][m] = {"rate_covered_anchors": (float(np.mean(flip_c)) if flip_c else float("nan")), "n_covered": len(flip_c), "rate_all_failure_anchors": (float(np.mean(flip_all)) if flip_all else float("nan")), "n_all": len(flip_all)} # ---- paired deltas: same anchors, same candidates, only the ranking rule differs ------ if "greedy_idx" in per: for m in per: if m == "greedy_idx": continue dv = per[m] - per["greedy_idx"] d["scorers"][m]["delta_vs_greedy"] = _boot_ci(dv, eps, n_boot, seed) for m in [x for x in per if not x.startswith("permuted:")]: pm = f"permuted:{m}" if pm in per: d["scorers"][m]["delta_vs_permuted"] = _boot_ci(per[m] - per[pm], eps, n_boot, seed) res["states"][f"S{s_}"] = d return res123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173#!/usr/bin/env python"""gen_q#276 STEP 1 validation of the edge-direction estimator. CPU only (annot + eef_pos + actions_raw).
Writes one JSON with, per edge: the angular spread of its direction field (global and after conditioning onposition, leave-one-EPISODE-out); per branch state: the anchor count under the shared-prefix filter, thepairwise separation of the fields available there, and the accuracy of classifying the HELD-OUT loggedaction. An edge whose directions do not concentrate cannot classify anything and is reported for exclusion."""from __future__ import annotationsimport argparse, json, sys, timefrom pathlib import Pathimport numpy as np
sys.path.insert(0, "/proj/dmfexp/zwhong/rsm_rise/scripts/real")from edge_field import (ROOT, load_frames, stack, fit_fields, unit, ang_deg, edges_from, ON_ROUTE, FAILURE, BRANCH_STATES)
def main(): ap = argparse.ArgumentParser() ap.add_argument("--horizon", type=int, default=8) ap.add_argument("--knn", type=int, default=64) ap.add_argument("--min-move-mm", type=float, default=2.0) ap.add_argument("--anchor-radius-mm", type=float, default=30.0) ap.add_argument("--anchor-min-support", type=int, default=20) ap.add_argument("--min-sep-deg", default="0,20,30,45", help="admissibility sweep: an anchor is kept only if EVERY pair of edges available " "there has fields at least this far apart. 0 = the position-support filter only. " "This is a property of the LABELS and the geometry, not of any scorer: at S0 the " "on-route edge 0->1 and the failure edge 0->5 both start by reaching for the " "tomato, so before the grasp no direction can separate them and an anchor there " "carries no information for ANY ranking rule.") ap.add_argument("--stride", type=int, default=5, help="subsample frames for the spread stats") ap.add_argument("--max-eps", type=int, default=0) ap.add_argument("--out", required=True) a = ap.parse_args() t0 = time.time() mm = a.min_move_mm / 1000.0 rec = load_frames(horizon=a.horizon, max_eps=a.max_eps) print(f"[ef] loaded {len(rec)} episodes {time.time()-t0:.0f}s", flush=True) tr, va = stack(rec, "train"), stack(rec, "valid") fields, counts = fit_fields(tr, k=a.knn, min_move_m=mm) print(f"[ef] fields: {sorted(fields)} {time.time()-t0:.0f}s", flush=True)
res = {"horizon": a.horizon, "knn": a.knn, "min_move_mm": a.min_move_mm, "anchor_radius_mm": a.anchor_radius_mm, "anchor_min_support": a.anchor_min_support, "n_episodes": len(rec), "n_frames_train": int(len(tr["t"])), "n_frames_valid": int(len(va["t"])), "edges": {}, "branch_states": {}}
# ---- per-edge angular spread ------------------------------------------------------------- for e, F in sorted(fields.items()): key = f"{e[0]}->{e[1]}" d = {"n_frames_moving": counts[e]["n_frames"], "n_frames_all": counts[e]["n_frames_all"], "n_episodes": counts[e]["n_episodes"], "on_route": e in ON_ROUTE, "failure": e in FAILURE} if len(F) < 50: d["status"] = "too few frames"; res["edges"][key] = d; continue u = F.u gmean = unit(u.mean(0)) d["global_resultant_R"] = float(np.linalg.norm(u.mean(0))) ga = ang_deg(u, gmean[None, :]) d["global_angle_to_mean_deg"] = {"median": float(np.median(ga)), "p90": float(np.percentile(ga, 90)), "mean": float(ga.mean())} # conditional (the field actually used): predict each train frame from OTHER episodes' neighbours sub = np.arange(0, len(F), max(1, a.stride)) pred = F(F.p[sub], exclude_ep=F.ep[sub]) ok = np.linalg.norm(pred, axis=1) > 0.5 la = ang_deg(u[sub][ok], pred[ok]) d["conditional_loo_angle_deg"] = {"n": int(ok.sum()), "median": float(np.median(la)), "p90": float(np.percentile(la, 90)), "mean": float(la.mean()), "frac_within_45deg": float((la < 45).mean()), "frac_within_90deg": float((la < 90).mean())} # concentration of the conditional residual: R of the residual directions d["conditional_resultant_R"] = float(np.linalg.norm(unit(u[sub][ok]).mean(0))) d["usable"] = bool(d["conditional_loo_angle_deg"]["median"] < 45.0) res["edges"][key] = d print(f"[ef] {key:7s} n={len(F):6d} eps={d['n_episodes']:3d} globalR={d['global_resultant_R']:.3f} " f"medang={d['global_angle_to_mean_deg']['median']:5.1f} loo_med={np.median(la):5.1f} " f"usable={d['usable']}", flush=True)
# ---- anchors, separation, held-out logged-action classification --------------------------- r = a.anchor_radius_mm / 1000.0 for s in BRANCH_STATES: avail = sorted(edges_from(fields, s)) key = f"S{s}" info = {"available_edges": [f"{u}->{v}" for u, v in avail], "n_edges": len(avail)} if len(avail) < 2: info["status"] = "not a branch"; res["branch_states"][key] = info; continue
def anchors(tab): m = tab["ef"] == s idx = np.where(m)[0] if len(idx) == 0: return idx, np.zeros(0, bool) p = tab["p"][idx] sup = np.ones(len(idx), bool) for e in avail: F = fields[e] cnt = np.array([len(x) for x in F.tree.query_ball_point(p, r)]) sup &= cnt >= a.anchor_min_support return idx, sup
thetas = [float(x) for x in a.min_sep_deg.split(",")]
def sep_mask(P, theta): """pairwise field separation at each position >= theta (deg).""" Fv = {e: fields[e](P) for e in avail} m = np.ones(len(P), bool) for i in range(len(avail)): for j in range(i + 1, len(avail)): m &= ang_deg(Fv[avail[i]], Fv[avail[j]]) >= theta return m, Fv
sweep = {} for theta in thetas: ent = {} for name, tab in (("train", tr), ("valid", va)): idx, sup = anchors(tab) keep = idx[sup] if len(keep): ms, Fv = sep_mask(tab["p"][keep], theta) keep = keep[ms] ent[f"n_frames_at_{name}"] = int(len(idx)) ent[f"n_anchors_{name}"] = int(len(keep)) ent[f"anchor_frac_{name}"] = float(len(keep) / max(len(idx), 1)) if name == "valid": vi = keep if len(vi): P = va["p"][vi] Fv = {e: fields[e](P) for e in avail} s_ = {} for i in range(len(avail)): for j in range(i + 1, len(avail)): e1, e2 = avail[i], avail[j] ang = ang_deg(Fv[e1], Fv[e2]) s_[f"{e1[0]}->{e1[1]} vs {e2[0]}->{e2[1]}"] = { "median_deg": float(np.median(ang)), "p10_deg": float(np.percentile(ang, 10)), "frac_below_20deg": float((ang < 20).mean())} ent["field_separation_at_valid_anchors"] = s_ D = va["d"][vi] keepm = np.linalg.norm(D, axis=1) >= mm true_e = list(zip(va["ef"][vi].tolist(), va["et"][vi].tolist())) C = np.stack([Fv[e] for e in avail], 1) cos = (unit(D)[:, None, :] * C).sum(-1) pred = cos.argmax(1) tru = np.array([avail.index(t) for t in true_e]) ent["heldout_logged_action_classification"] = { "n": int(keepm.sum()), "accuracy": float((pred[keepm] == tru[keepm]).mean()) if keepm.any() else None, "chance": 1.0 / len(avail), "n_valid_episodes": int(len(set(va["ep"][vi].tolist()))), "per_true_edge": {f"{avail[i][0]}->{avail[i][1]}": {"n": int(((tru == i) & keepm).sum()), "recall": float((pred[keepm & (tru == i)] == i).mean()) if (keepm & (tru == i)).any() else None} for i in range(len(avail))}, "confusion": [[int(((tru == i) & (pred == j) & keepm).sum()) for j in range(len(avail))] for i in range(len(avail))]} acc = ent.get("heldout_logged_action_classification", {}).get("accuracy") print(f"[ef] {key} theta={theta:5.1f} anchors valid={ent['n_anchors_valid']:6d}" f"/{ent['n_frames_at_valid']} train={ent['n_anchors_train']:6d} " f"acc={acc if acc is None else round(acc,4)} chance={1.0/len(avail):.3f}", flush=True) sweep[f"{theta:g}"] = ent info["min_sep_sweep"] = sweep res["branch_states"][key] = info
Path(a.out).parent.mkdir(parents=True, exist_ok=True) json.dump(res, open(a.out, "w"), indent=1) print(f"[ef] wrote {a.out} {time.time()-t0:.0f}s", flush=True)
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306r"""#278 run 34: THE PRE-REGISTERED BAR HAS THREE CLAUSES AND ONLY ONE OF THEM HAS BEEN REPORTEDAT THE BEST CELL. This applies clause 3 -- the COUNTERFACTUAL FLIP RATE, which rise_stack/EDGE_TEST.md(b89c430, unchanged) calls "the sharpest number" -- to the arms already on disk.
THE HOLE (why this is a reading, not a new rung). EDGE_TEST.md "Pass bar (pre-registered)" is aCONJUNCTION of three clauses: (1) proposer coverage of the on-route cluster >= 0.8 of anchors; (2) RSM on-route rank percentile > greedy by >= 0.10 and > its permuted control, interval excluding 0; (3) counterfactual flip rate at failure anchors >= 0.5 for RSM and STRICTLY GREATER than BC/greedy's.Runs 31/32/33 reported (1) and (2) in every table and CLOSED #278 on (2). Clause (3) has been computedby edge_field.summarise_anchors into every arm's own edge_test.json since the arm ran -- it was simplynever carried into the matched tables, so the closing negative quoted one clause of a three-clause bar.This run carries all three, on the COMMON episode set, with the episode-cluster interval clause (3)never had, and states the OVERLAP: at S0 the only logged failure first edge is 0->5, so clause (3) ismeasured on a SUBSET of the very route that run 33 showed carries the pooled clause-(2) number.
NO NEW RULE IS PRE-REGISTERED HERE, AND NONE COULD BE: the flip numbers were already on disk. Therule applied is the contract's own clause text, quoted verbatim below, pre-registered at b89c430before any arm ran. Nothing is retrained and no model is called: this is a re-read of the existingedge_parts/*.npz through edge_field.summarise_anchors, the one place the metric is defined.
NO SECOND HARNESS: coverage / rank / flip all come from edge_field.summarise_anchors viaedge_report.load_dir; the per-anchor recomputation exists ONLY as a self-test that must agree with itto 0.00e+00 before any number is printed."""import sys, jsonimport numpy as npsys.path.insert(0, "/proj/dmfexp/zwhong/rsm_rise/scripts/real")from pathlib import Pathfrom edge_report import load_dirfrom edge_field import summarise_anchors, rank_pct
ROOT = Path("/proj/dmfexp/zwhong/rsm_rise/status/real")SPLIT = json.load(open("/proj/dmfexp/zwhong/rsm_rise/data/derived/cooking_v5_split.json"))["episodes"]N_BOOT = 2000BAR = 0.10FLIP_BAR = 0.50CTRL = "edge_T_rise"
# the arms that pin the SAME cell (proposer pi05_cooking_rise/rise_s0/29999, R_XL, beta 0.99 /# gamma 0.995) and therefore share an anchor set. T = shipped best cell; AC = flow replicates;# AB = particle replicates; V = the trained reward LABELS at this cell.ARMS = [("edge_T_rise", "GOAL_EPISODE R_XL s100000 flow 8 p16 (CONTROL = shipped best cell)"), ("edge_AC_rise_flow4", "GOAL_EPISODE flow 4 (replicate)"), ("edge_AC_rise_flow16", "GOAL_EPISODE flow 16 (replicate)"), ("edge_AC_rise_flow32", "GOAL_EPISODE flow 32 (replicate)"), ("edge_AB_rise_p16_s202", "GOAL_EPISODE p16 seed 202 (replicate)"), ("edge_AB_rise_p64", "GOAL_EPISODE p64 (replicate)"), ("edge_AB_rise_p256", "GOAL_EPISODE p256 (replicate)"), ("edge_V_goalep", "GOAL_EPISODE R_XL_ft_v0 pos share 0.294"), ("edge_V_goalseg", "GOAL_SEGMENT R_XL_ft_v1 pos share 0.167"), ("edge_V_win400", "GOAL_WINDOW_400 R_XL_ft_B400 pos share 0.111"), ("edge_V_win100", "GOAL_WINDOW_100 R_XL_ft_B pos share 0.028")]
CLAUSES = { 1: 'Proposer coverage of the on-route cluster **>= 0.8** of anchors at both branch states.', 2: ('RSM on-route rank percentile **> greedy by >= 0.10** and **> its permuted control** with a ' 'paired interval that excludes zero, at both S0 and S2, on held-out episodes.'), 3: ('Counterfactual flip rate at failure anchors **>= 0.5** for RSM and **strictly greater than** ' "BC/greedy's."),}
def route_of(ep): return "->".join(str(x) for x in SPLIT[str(int(ep))]["path"])
def boot_ci(vals, eps, seed=0, alpha=0.05): """the harness's episode-cluster bootstrap, applied to a per-anchor vector.""" vals = np.asarray(vals, float); eps = np.asarray(eps) m = np.isfinite(vals); vals, eps = vals[m], eps[m] if not len(vals): return dict(mean=float("nan"), lo=float("nan"), hi=float("nan"), n=0, n_episodes=0) g = np.unique(eps); idx = {x: np.where(eps == x)[0] for x in g} rng = np.random.default_rng(seed); bs = np.empty(N_BOOT) for b in range(N_BOOT): take = np.concatenate([idx[g[p]] for p in rng.choice(len(g), len(g), replace=True)]) bs[b] = vals[take].mean() return dict(mean=float(vals.mean()), lo=float(np.percentile(bs, 100 * alpha / 2)), hi=float(np.percentile(bs, 100 * (1 - alpha / 2))), n=int(len(vals)), n_episodes=int(len(g)))
def f(d, w=24): if not d or not np.isfinite(d.get("mean", float("nan"))): return f"{'--':>{w}s}" return f"{d['mean']:+.4f}[{d['lo']:+.4f},{d['hi']:+.4f}]".rjust(w)
def fr(d, w=22): if not d or not np.isfinite(d.get("mean", float("nan"))): return f"{'--':>{w}s}" return f"{d['mean']:.3f}[{d['lo']:.3f},{d['hi']:.3f}]".rjust(w)
# ---------------------------------------------------------------- per-anchor flip, recomputed ------def flip_vectors(recs, keep, modes): """Per-anchor flip indicator for each scorer, on the CLAUSE-3 anchor set: anchors whose LOGGED edge is a failure edge (true_is_failure) AND where the proposer covered the on-route cluster (otherwise there is nothing for the argmax to flip TO). Exactly edge_field's own definition.""" out = {m: [] for m in modes} eps, rts, i_greedy = [], [], [] rng = np.random.default_rng(0) for r in recs: if int(r["state"]) != 0 or int(r["episode"]) not in keep: continue if not bool(r["true_is_failure"]): continue orr = np.asarray(r["onroute"], bool) if not orr.any(): continue eps.append(int(r["episode"])); rts.append(route_of(r["episode"])) n = int(r["n_cand"]) for m in modes: if m == "greedy_idx": sc = -np.arange(n, dtype=float) elif m == "random": sc = rng.permutation(n).astype(float) else: s = r["scores"].get(m) sc = None if s is None else np.asarray(s, np.float64) out[m].append(float(orr[int(np.argmax(sc))]) if sc is not None else np.nan) i_greedy.append(0) return {m: np.asarray(v, float) for m, v in out.items()}, np.asarray(eps), rts
def rank_delta_vec(recs, keep, m, sel=None): """per-anchor (rank_pct of on-route under m) - (under greedy), on contrastive anchors.""" dv, eps = [], [] for r in recs: if int(r["state"]) != 0 or int(r["episode"]) not in keep: continue if sel is not None and not sel(r): continue orr = np.asarray(r["onroute"], bool) n = int(r["n_cand"]) if not (0 < int(orr.sum()) < n): continue sc = r["scores"].get(m) if sc is None: continue a = rank_pct(np.asarray(sc, np.float64))[orr].mean() b = rank_pct(-np.arange(n, dtype=float))[orr].mean() dv.append(float(a - b)); eps.append(int(r["episode"])) return np.asarray(dv, float), np.asarray(eps)
# ---------------------------------------------------------------- load -----------------------------raw = {}for a, _lab in ARMS: recs = load_dir(ROOT / a) if recs: raw[a] = recsif CTRL not in raw: raise SystemExit(f"control {CTRL} has no parts on disk -- refusing to print anything")
eps_of = {a: {int(r["episode"]) for r in v if int(r["state"]) == 0} for a, v in raw.items()}common = set.intersection(*eps_of.values())print("landed S0 episodes per arm (completeness line, printed BEFORE any number):")for a, lab in ARMS: print(f" {a:24s} {len(eps_of.get(a, [])):3d} eps {len(raw.get(a, [])):5d} recs {lab}")print(f"\nCOMMON EPISODE SET: {len(common)} episodes -> {sorted(common)}")print("route census of the common set:")cens = {}for e in sorted(common): cens.setdefault(route_of(e), []).append(e)for k, v in sorted(cens.items()): print(f" {k:10s} {len(v)} episodes {v}")
summ = {}for a in raw: r = [x for x in raw[a] if int(x["episode"]) in common] modes = sorted({m for x in r for m in x["scores"]}) summ[a] = summarise_anchors(r, modes, seed=0, n_boot=N_BOOT)["states"]["S0"]
# ---------------------------------------------------------------- SELF-TEST ------------------------print("\n[selftest] recomputed per-anchor flip vs edge_field.summarise_anchors (must be 0.00e+00):")ok = TrueFLIPV, FEPS, FRT = {}, {}, {}for a in raw: modes = sorted({m for x in raw[a] for m in x["scores"]}) + ["greedy_idx", "random"] v, e, rt = flip_vectors([x for x in raw[a] if int(x["episode"]) in common], common, modes) FLIPV[a], FEPS[a], FRT[a] = v, e, rt # `random` is NOT comparable bitwise: summarise_anchors advances a single rng across its # (mode, anchor) loop, so an independent recomputation draws a different permutation. It is a # null column, not a measurement, so the self-test asserts 0 on the DETERMINISTIC modes and # prints the random column's difference instead of asserting on it. errs, per = [], [] for m, fv in v.items(): ref = summ[a]["flip"].get(m, {}).get("rate_covered_anchors", np.nan) if not (np.isfinite(ref) and len(fv)): continue e = abs(float(np.nanmean(fv)) - float(ref)) per.append(f"{m}={e:.0e}") if m != "random": errs.append(e) e_max = max(errs) if errs else float("nan") n_ref = summ[a]["flip"].get("rsm", {}).get("n_covered", -1) good = np.isfinite(e_max) and e_max < 1e-12 and len(v["rsm"]) == n_ref ok &= bool(good) print(f" {a:24s} n_flip={len(v['rsm']):4d} (harness {n_ref:4d}) max abs err (deterministic " f"modes) {e_max:.2e} {'OK' if good else '*** MISMATCH'} [{' '.join(per)}]")# rank delta must also reproduce the published celldv, de = rank_delta_vec([x for x in raw[CTRL] if int(x["episode"]) in common], common, "rsm")ref = summ[CTRL]["scorers"]["rsm"]["delta_vs_greedy"]["mean"]err = abs(float(dv.mean()) - float(ref))print(f" {CTRL:24s} rank delta recomputed {dv.mean():+.6f} vs harness {ref:+.6f} err {err:.2e}" f" {'OK' if err < 1e-12 else '*** MISMATCH'}")ok &= err < 1e-12if not ok: raise SystemExit("*** SELF-TEST FAILED -- no number is reported from a harness that disagrees " "with its own metric")
# ---------------------------------------------------------------- clause 3 table -------------------print("\n### CLAUSE 3 -- counterfactual flip rate at failure anchors (contract b89c430: " '"the sharpest number")')print(" rate over the covered failure anchors; episode-cluster bootstrap over the SAME episodes")hdr = (f"{'arm':24s} {'nflip':>5s} {'eps':>4s} | {'rsm':>22s} {'permuted:rsm':>22s} " f"{'greedy':>22s} {'idql':>22s} | {'rsm-greedy':>24s} {'rsm-perm':>24s}")print(hdr); print("-" * len(hdr))FLIP = {}for a, lab in ARMS: if a not in raw: continue v, e = FLIPV[a], FEPS[a] cells = {m: boot_ci(v[m], e) for m in ("rsm", "permuted:rsm", "greedy_idx", "idql") if m in v} dg = boot_ci(v["rsm"] - v["greedy_idx"], e) dp = boot_ci(v["rsm"] - v["permuted:rsm"], e) if "permuted:rsm" in v else None FLIP[a] = dict(label=lab, n=int(len(v["rsm"])), n_eps=int(len(set(e.tolist()))), rates={m: c for m, c in cells.items()}, d_vs_greedy=dg, d_vs_perm=dp) print(f"{a:24s} {len(v['rsm']):5d} {len(set(e.tolist())):4d} | " f"{fr(cells.get('rsm'))} {fr(cells.get('permuted:rsm'))} " f"{fr(cells.get('greedy_idx'))} {fr(cells.get('idql'))} | {f(dg)} {f(dp)}")
# ---------------------------------------------------------------- the overlap ----------------------print("\n### THE OVERLAP -- clause 3 and clause 2 are read out of the SAME route")rts = FRT[CTRL]comp = {}for r in rts: comp[r] = comp.get(r, 0) + 1print(f" routes contributing clause-3 anchors: {comp}")print(" (at S0 the only logged failure first edge is 0->5, so clause 3 is a SUBSET of the route that")print(" run 33 measured as carrying the pooled clause-2 number: 0->5 d=+0.1340 vs on-route +0.0448)")d_in, e_in = rank_delta_vec([x for x in raw[CTRL] if int(x["episode"]) in common], common, "rsm", sel=lambda r: bool(r["true_is_failure"]))d_out, e_out = rank_delta_vec([x for x in raw[CTRL] if int(x["episode"]) in common], common, "rsm", sel=lambda r: not bool(r["true_is_failure"]))ci_in, ci_out = boot_ci(d_in, e_in), boot_ci(d_out, e_out)print(f" clause-2 delta ON the failure-edge anchors {f(ci_in)} n={ci_in['n']} eps={ci_in['n_episodes']}")print(f" clause-2 delta OFF them (the other three routes){f(ci_out)} n={ci_out['n']} eps={ci_out['n_episodes']}")
# ---------------------------------------------------------------- the three clauses ----------------print("\n### THE PRE-REGISTERED BAR, ALL THREE CLAUSES, AT THE BEST CELL (contract b89c430 verbatim)")c = summ[CTRL]cov = c["coverage"]rk = c["scorers"]["rsm"]c2_dg, c2_dp = rk["delta_vs_greedy"], rk["delta_vs_permuted"]fl = FLIP[CTRL]c1 = cov >= 0.8c2 = (c2_dg["mean"] >= BAR) and (c2_dp["mean"] > 0) and (c2_dg["lo"] > 0)c3 = (fl["rates"]["rsm"]["mean"] >= FLIP_BAR and fl["rates"]["rsm"]["mean"] > fl["rates"]["greedy_idx"]["mean"])c3_strict = c3 and fl["d_vs_greedy"]["lo"] > 0for i, (flagv, txt, ev) in enumerate([ (c1, CLAUSES[1], f"coverage {cov:.3f} (S0 only; no S2 arm at this cell)"), (c2, CLAUSES[2], f"d_vs_greedy {f(c2_dg).strip()} vs bar +{BAR:.2f}; d_vs_perm {f(c2_dp).strip()}"), (c3, CLAUSES[3], f"flip {fr(fl['rates']['rsm']).strip()} vs bar {FLIP_BAR:.2f}; " f"greedy {fr(fl['rates']['greedy_idx']).strip()}; " f"paired rsm-greedy {f(fl['d_vs_greedy']).strip()}")], 1): print(f" CLAUSE {i}: {'PASS' if flagv else 'FAIL'} {txt}") print(f" evidence: {ev}")print(f" CLAUSE 3 with the interval as well (paired rsm-greedy excludes 0): " f"{'PASS' if c3_strict else 'FAIL'}")print(f"\n CONJUNCTION (the bar as written): {'PASS' if (c1 and c2 and c3) else 'FAIL'}" f" -- clauses passing: {sum([c1, c2, c3])}/3, failing: " f"{[i for i, x in enumerate([c1, c2, c3], 1) if not x]}")print(" The bar is a CONJUNCTION, so the verdict on #278 is unchanged: FAIL. What changes is the")print(" auditable description of the failure -- it fails on clause 2 ALONE, with clauses 1 and 3")print(" passing at the best cell, and clause 3 is the one the contract calls the sharpest number.")print(" Caveat carried with clause 3: it lives on the 0->5 route, 5 held-out episodes, so its")print(" cluster interval is wide and it is NOT independent evidence from the pooled clause-2 number.")
out = {"_meta": dict(common_episodes=sorted(common), n_boot=N_BOOT, bar=BAR, flip_bar=FLIP_BAR, control=CTRL, contract="rise_stack/EDGE_TEST.md b89c430 (unchanged)", route_census={k: v for k, v in sorted(cens.items())}), "_clauses": {"text": CLAUSES, "control_result": {"clause1_coverage": bool(c1), "clause2_rank": bool(c2), "clause3_flip": bool(c3), "clause3_flip_interval_too": bool(c3_strict), "conjunction": bool(c1 and c2 and c3), "n_passing": int(sum([c1, c2, c3]))}}, "_overlap": {"routes_of_clause3_anchors": comp, "clause2_on_failure_edge_anchors": ci_in, "clause2_off_failure_edge_anchors": ci_out}, "arms": {a: dict(coverage=summ[a]["coverage"], n_anchors=summ[a]["n_anchors"], d_vs_greedy=summ[a]["scorers"]["rsm"].get("delta_vs_greedy"), d_vs_perm=summ[a]["scorers"]["rsm"].get("delta_vs_permuted"), flip=FLIP.get(a)) for a in raw}, "_reading": ("Clause 3 of the pre-registered three-clause bar PASSES at the best cell " "(flip 0.745 >= 0.50 and > greedy 0.519) and clause 1 passes (coverage 0.904); " "the conjunction FAILS on clause 2 alone (+0.0909 < +0.10). Clause 3's anchors " "are the 0->5 route only, the same route that carries the pooled clause-2 " "number, so the two are not independent evidence.")}p = ROOT / "EDGE_FLIP_AUDIT.json"json.dump(out, open(p, "w"), indent=1, default=float)print(f"\nwrote {p}")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246r"""#278 run 35 (reduction, no new arm, no model call): IS THERE **ANY** ALREADY-MEASURED CONFIGURATIONTHAT RANKS THE DIRECTIONALLY-CORRECT ACTIONS ABOVE THE WRONG ONES AT THE **GOAL-BOUND** S0 ANCHORS,IN UNITS THE PRE-REGISTERED BAR CANNOT REACH THERE?
Run 34 proved a property of the metric, not of a model: the headline d_vs_greedy is LEVERAGE-WEIGHTED(w = n_off/(n-1)), and at the goal-bound anchors w_bar is 0.070-0.203, so clearing the pooled +0.10would need a per-anchor AUC of 1.053 (destiny=goal) to 1.920 (route 0->2->3) -- ABOVE 1, i.e.IMPOSSIBLE for a perfect scorer. Every ladder number since run 20 has therefore been reported in aunit that is structurally incapable of certifying the states a planner actually needs.
The leverage-free statistic already exists inside the same identity (edge_ceiling2.py, verified to4 dp against edge_field.rank_pct): mean rank_pct over on-route = [ (n_on-1)/2 + n_off * AUC ] / (n-1)The per-anchor Mann-Whitney AUC is the ONLY scorer-dependent term. Averaging it UNWEIGHTED overanchors asks the planner question directly -- "does the scorer put on-route candidates aboveoff-route ones at this state" -- with chance at 0.5 and no leverage factor. This run reports thatnumber, with its cluster bootstrap and its permuted null, for EVERY arm on disk at the common S0anchor set. It is a reduction of shards already measured; it cannot and does not move the firedpre-registered rule on #278 (which stays FAIL / CLOSED and is printed unchanged beside it).
**IT IS A SECONDARY DIAGNOSTIC, NOT THE BAR.** The pre-registered metric and the +0.10 bar inrise_stack/EDGE_TEST.md are untouched and byte-identical to b89c430.
MULTIPLICITY IS PRE-REGISTERED, because ~40 arms are screened: an arm COUNTS as clearing only if itsBonferroni-adjusted interval (alpha = 0.05/K, K = number of arms screened, two-sided) excludes thenull. Raw 95% intervals are printed too and are explicitly labelled as screening-only.
PRE-REGISTERED READING (written before any goal-bound AUC was computed; the only goal-bound numberspublished so far are the CONTROL arm's AUCw 0.616 / greedy 0.475 from run 34, in WEIGHTED units): (i) At least one arm has goal-bound AUC_u > 0.5 AND paired (rsm - permuted) > 0, BOTH with Bonferroni intervals excluding the null -> the scorer DOES rank directionally-correct actions at the goal-bound states; the pooled FAIL is then a limit of the leverage-weighted metric at those anchors, not an absence of signal. Name the arm, its number, and say plainly that this is not a pass of the pre-registered bar. (ii) No arm clears both under Bonferroni, and the CONTROL's raw interval does not exclude the null either -> the closed negative is ROBUST in leverage-free units: there is no measurable preference for the correct direction at the goal-bound anchors on anything trained so far. (iii) Point estimates above the null but no interval excludes it -> UNDERPOWERED at 8-10 held-out episodes; report the episode count a half-width would need and say the cell cannot decide.
CAVEAT THAT MUST TRAVEL WITH EVERY NUMBER HERE (measured from data/derived/cooking_v5_split.json):NO held-out S0 episode reaches S4. The "goal-bound" group is routes 0->1->3 and 0->2->3, i.e.COOKING-bound; route 2->3->4 does not start at S0. That is the owner's stitching point itself --answering "what to do at S0 to reach the goal" requires composing across episodes -- and it meansthis cell measures destiny=cooking, never destiny=S4.
Cross-arm comparisons carry run 33's candidate gate: the anchors are identical across arms(ee_xyz and logged action 291/291) but 45-99 % of the 128 candidates are redrawn, so between-armdifferences include sampling noise (candidate-matched rho 0.903 at this cell, rung AB). Each arm'sOWN AUC vs its OWN greedy/permuted is within-arm and unaffected."""import sys, os, json, globimport numpy as np
sys.path.insert(0, "/proj/dmfexp/zwhong/rsm_rise/scripts/real")from edge_ceiling2 import arm as ceiling_arm, auc as mw_auc
ROOT = "/proj/dmfexp/zwhong/rsm_rise/status/real"SPLIT = json.load(open("/proj/dmfexp/zwhong/rsm_rise/data/derived/cooking_v5_split.json"))["episodes"]COMMON = [7, 9, 12, 22, 46, 52, 54, 68, 73, 86, 105, 107, 120, 131, 137, 204, 223, 224, 230, 231]CONTROL = "edge_T_rise"NB, SEED = 20000, 0COLS = {"rsm": "score_rsm", "perm": "score_permuted__rsm", "idql": "score_idql", "permi": "score_permuted__idql"}
def route_of(e): return "->".join(str(x) for x in SPLIT[str(int(e))]["path"])
def destiny_of(e): return "goalbound" if SPLIT[str(int(e))]["final_state"] in (3, 4) else "failure"
GOALBOUND = [e for e in COMMON if destiny_of(e) == "goalbound"]FAILURE = [e for e in COMMON if destiny_of(e) == "failure"]GROUPS = [("DEST_goalbound", GOALBOUND), ("DEST_failure", FAILURE), ("ALL", COMMON)]
def per_anchor(d, keep): """Per-anchor Mann-Whitney AUC of on-route vs off-route candidates, per scorer. Same loop, same filters, same `auc` as edge_ceiling2.arm -- only the aggregation differs.""" out = {k: [] for k in COLS} out["greedy"] = [] EP, W = [], [] for f in sorted(glob.glob(f"{d}/edge_parts/*.npz")): e = int(f.split("/")[-1][2:-4]) if e not in keep: continue z = np.load(f, allow_pickle=True) if "onroute" not in z.files: continue onr = np.asarray(z["onroute"], bool) for i in range(onr.shape[0]): o = onr[i] n = o.size n_on = int(o.sum()) if not (0 < n_on < n): continue EP.append(e) W.append((n - n_on) / (n - 1.0)) out["greedy"].append(mw_auc(-np.arange(n, dtype=float), o)) for k, key in COLS.items(): out[k].append(mw_auc(z[key][i].astype(np.float64), o) if key in z.files else np.nan) return ({k: np.asarray(v) for k, v in out.items()}, np.asarray(EP, int), np.asarray(W, float))
def boot_matrix(EP, nb=NB, seed=SEED): """Cluster (episode) bootstrap as an exact count matrix: B[b,i] = times anchor i's episode drawn.""" u = np.unique(EP) rng = np.random.default_rng(seed) draw = rng.choice(u.size, (nb, u.size), replace=True) cnt = np.zeros((nb, u.size), np.int32) np.add.at(cnt, (np.repeat(np.arange(nb), u.size), draw.ravel()), 1) idx = np.searchsorted(u, EP) return cnt[:, idx].astype(np.float64), u.size
def ci(v, B, alpha): """Mean of v with a cluster-bootstrap percentile interval at level alpha (two-sided).""" m = float(np.mean(v)) bm = (B @ v) / B.sum(1) return m, float(np.percentile(bm, 100 * alpha / 2)), float(np.percentile(bm, 100 * (1 - alpha / 2)))
# ---------------- arms on disk at the common S0 anchor set ----------------ARMS = []for d in sorted(glob.glob(f"{ROOT}/edge_*")): have = {int(f.split("/")[-1][2:-4]) for f in glob.glob(f"{d}/edge_parts/*.npz")} if set(COMMON).issubset(have): ARMS.append(d.rstrip("/").split("/")[-1])K = len(ARMS)ALPHA_B = 0.05 / max(K, 1)print(f"S0 arms covering all {len(COMMON)} common held-out episodes: K = {K}")print(f" goal-bound (destiny cooking) episodes: {GOALBOUND} routes " f"{sorted({route_of(e) for e in GOALBOUND})}")print(f" failure episodes: {FAILURE} routes " f"{sorted({route_of(e) for e in FAILURE})}")print(f" NO held-out S0 episode reaches S4: final states " f"{sorted({SPLIT[str(e)]['final_state'] for e in COMMON})}")print(f" Bonferroni alpha = 0.05/{K} = {ALPHA_B:.5f} (two-sided, {NB} cluster bootstraps)\n")
# ---------------- SELF-TEST, printed before any new number ----------------print("SELF-TEST -- per-anchor AUCs must reproduce edge_ceiling2.arm() exactly (it produced every")print("published ceiling/%ceil number), on the CONTROL arm, for every group:")ok = Truefor g, eps in GROUPS: A, EP, W = per_anchor(f"{ROOT}/{CONTROL}", set(eps)) r = ceiling_arm(f"{ROOT}/{CONTROL}", keep=set(eps)) w_rsm = float((W * A["rsm"]).sum() / W.sum()) d_rsm = float((W * (A["rsm"] - A["greedy"])).mean()) e1 = abs(w_rsm - r["auc_rsm"]["weighted"]) e2 = abs(d_rsm - r["d_vs_greedy_rsm"]) e3 = abs(len(W) - r["n_anchors"]) ok &= (e1 < 1e-12 and e2 < 1e-12 and e3 == 0) print(f" {g:16s} n={len(W):4d} (harness {r['n_anchors']:4d}) AUCw err {e1:.2e} " f"d_vs_greedy err {e2:.2e} [harness d_rsm {r['d_vs_greedy_rsm']:+.4f}]")assert ok, "self-test FAILED -- no number printed"print(" PASS -- the reduction reads the same anchors and the same scores as every published cell.\n")
# ---------------- the table ----------------res = {"_meta": dict(K=K, arms=ARMS, alpha_bonf=ALPHA_B, nb=NB, goalbound_episodes=GOALBOUND, failure_episodes=FAILURE, note="UNWEIGHTED per-anchor Mann-Whitney AUC, on-route vs off-route candidates; " "chance 0.5; secondary diagnostic, NOT the pre-registered bar")}for g, eps in GROUPS: print(f"\n### GROUP {g} ({len(eps)} episodes: {eps})") hdr = (f"{'arm':38s} {'ep':>2s} {'anc':>4s} | {'AUCu_rsm':>8s} {'raw95':>17s} " f"{'bonf':>17s} | {'greedy':>6s} {'perm':>6s} {'idql':>6s} | " f"{'rsm-perm':>9s} {'bonf':>17s}") print(hdr) print("-" * len(hdr)) res[g] = {} for a in ARMS: A, EP, W = per_anchor(f"{ROOT}/{a}", set(eps)) if not len(W): continue B, nep = boot_matrix(EP) m, lo, hi = ci(A["rsm"], B, 0.05) _, blo, bhi = ci(A["rsm"], B, ALPHA_B) dp, dplo, dphi = ci(A["rsm"] - A["perm"], B, 0.05) _, dpblo, dpbhi = ci(A["rsm"] - A["perm"], B, ALPHA_B) dg, dglo, dghi = ci(A["rsm"] - A["greedy"], B, 0.05) _, dgblo, dgbhi = ci(A["rsm"] - A["greedy"], B, ALPHA_B) row = dict(n_episodes=int(nep), n_anchors=int(len(W)), w_bar=float(W.mean()), auc_rsm=m, auc_rsm_raw95=[lo, hi], auc_rsm_bonf=[blo, bhi], auc_greedy=float(A["greedy"].mean()), auc_perm=float(np.nanmean(A["perm"])), auc_idql=float(np.nanmean(A["idql"])), auc_permi=float(np.nanmean(A["permi"])), d_rsm_perm=dp, d_rsm_perm_raw95=[dplo, dphi], d_rsm_perm_bonf=[dpblo, dpbhi], d_rsm_greedy=dg, d_rsm_greedy_raw95=[dglo, dghi], d_rsm_greedy_bonf=[dgblo, dgbhi], clears_bonf=bool(blo > 0.5 and dpblo > 0.0), clears_raw=bool(lo > 0.5 and dplo > 0.0)) res[g][a] = row star = "**" if row["clears_bonf"] else (" *" if row["clears_raw"] else " ") print(f"{a:38s} {nep:2d} {len(W):4d} | {m:8.3f} [{lo:+.3f},{hi:+.3f}] " f"[{blo:+.3f},{bhi:+.3f}] | {A['greedy'].mean():6.3f} " f"{np.nanmean(A['perm']):6.3f} {np.nanmean(A['idql']):6.3f} | " f"{dp:+9.4f} [{dpblo:+.3f},{dpbhi:+.3f}]{star}")
# ---------------- the mechanical reading ----------------G = res["DEST_goalbound"]clear_b = [a for a, r in G.items() if r["clears_bonf"]]clear_r = [a for a, r in G.items() if r["clears_raw"]]above = [a for a, r in G.items() if r["auc_rsm"] > 0.5 and r["d_rsm_perm"] > 0]ctrl = G.get(CONTROL, {})print("\n" + "=" * 100)print(f"GOAL-BOUND CELL: {len(G)} arms screened; {len(above)} have point estimates above BOTH nulls; " f"{len(clear_r)} clear at raw 95 %; {len(clear_b)} clear under Bonferroni.")if clear_b: best = max(clear_b, key=lambda a: G[a]["auc_rsm"]) print(f"READING (i) FIRES: {len(clear_b)} arm(s) clear both nulls under Bonferroni. Best: {best} " f"AUC_u {G[best]['auc_rsm']:.3f} bonf {G[best]['auc_rsm_bonf']}, " f"rsm-perm {G[best]['d_rsm_perm']:+.4f} bonf {G[best]['d_rsm_perm_bonf']}.") print(" -> the scorer ranks directionally-correct actions at the goal-bound S0 anchors; the " "pooled FAIL is a limit of the leverage-weighted metric there. NOT a pass of the bar.")elif not clear_r and not (ctrl and ctrl["auc_rsm_raw95"][0] > 0.5): print("READING (ii) FIRES: no arm clears under Bonferroni and the control's raw interval does not " "exclude chance either -> the closed negative is ROBUST in leverage-free units.") if ctrl: hw = (ctrl["auc_rsm_raw95"][1] - ctrl["auc_rsm_raw95"][0]) / 2 need = ctrl["auc_rsm"] - 0.5 print(f" control AUC_u {ctrl['auc_rsm']:.3f} raw95 {ctrl['auc_rsm_raw95']}, " f"half-width {hw:.4f}, distance from chance {need:+.4f}, " f"episodes needed for the point estimate to clear chance: " f"{(ctrl['n_episodes'] * (hw / max(need, 1e-9)) ** 2):.0f} (vs {ctrl['n_episodes']} today)")else: print("READING (iii) FIRES: point estimates above the nulls but no arm clears under Bonferroni " "-> the cell is UNDERPOWERED at this episode count and cannot decide.") if ctrl: hw = (ctrl["auc_rsm_raw95"][1] - ctrl["auc_rsm_raw95"][0]) / 2 need = max(ctrl["auc_rsm"] - 0.5, 1e-9) print(f" control AUC_u {ctrl['auc_rsm']:.3f} raw95 {ctrl['auc_rsm_raw95']} " f"(raw-95 clearing arms: {clear_r})") print(f" half-width {hw:.4f} vs distance from chance {need:+.4f} -> " f"~{ctrl['n_episodes'] * (hw / need) ** 2:.0f} held-out goal-bound episodes needed " f"(today {ctrl['n_episodes']}).")print("=" * 100)print("\nThe pre-registered #278 verdict is UNCHANGED and is not a function of anything above:")print(" clause 1 coverage 0.904 PASS | clause 2 +0.0909 [+0.0373,+0.1480] vs +0.10 FAIL | " "clause 3 flip 0.745 vs greedy 0.519 PASS -> CONJUNCTION FAIL, #278 stays CLOSED.")
out = f"{ROOT}/EDGE_GOALBOUND_AUC.json"json.dump(res, open(out, "w"), indent=1, default=float)print("\nwrote", out)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798r"""#278 run 29: the PAIRED interaction of the successor x depth 2x2, with a cluster bootstrap.
Run 28's `_edgeAA_matched.json` reports the interaction as a difference of four independentlybootstrapped arm means (-0.0061) with no interval, so it cannot say whether the landscape is aplane. This re-reads the SAME edge_parts/*.npz and computes the statistic PAIRED at the anchorlevel -- every anchor that exists in all four arms -- so the arm-to-arm anchor noise cancels and thebootstrap is over episodes only. No model call, no new experiment: CPU re-read.
d(arm, anchor) = rank_pct_rsm - rank_pct_greedy (the metric's own per-anchor contribution) successor effect = mean_a [ d(T,a) - d(V,a) ] at depth h 1.01 mean_a [ d(AA,a) - d(ha,a) ] at depth h 0.34 depth effect = mean_a [ d(ha,a) - d(V,a) ] on R_XL_ft_v0 mean_a [ d(AA,a) - d(T,a) ] on R_XL INTERACTION = mean_a [ (d(AA,a)-d(T,a)) - (d(ha,a)-d(V,a)) ]
An interaction whose CI covers 0 means the two axes ADD: the four measured corners then determinethe whole plane, and no unmeasured combination of successor x depth can reach the +0.10 bar."""import sys, jsonimport numpy as npfrom pathlib import Path
sys.path.insert(0, "/proj/dmfexp/zwhong/rsm_rise/scripts/real")from edge_report import load_dirfrom edge_field import rank_pct
ROOT = Path("/proj/dmfexp/zwhong/rsm_rise/status/real")ARMS = {"AA": "edge_AA_rxl_ha", # R_XL, h 0.34 "T": "edge_T_rise", # R_XL, h 1.01 "ha": "edge_Z_goalep_ha", # R_XL_ft_v0, h 0.34 "V": "edge_V_goalep"} # R_XL_ft_v0, h 1.01N_BOOT, SEED, STATE = 4000, 0, 0
def per_anchor(d): """{(episode, frame): d_vs_greedy} over contrastive S0 anchors.""" out = {} for r in load_dir(ROOT / d): if int(r["state"]) != STATE: continue orr = np.asarray(r["onroute"], bool) n = int(r["n_cand"]) if not (0 < int(orr.sum()) < n): # needs both classes to order anything continue sc = r["scores"].get("rsm") if sc is None: continue g = rank_pct(-np.arange(n, dtype=float))[orr].mean() out[(int(r["episode"]), int(r["frame"]))] = float(rank_pct(np.asarray(sc, np.float64))[orr].mean() - g) return out
P = {k: per_anchor(v) for k, v in ARMS.items()}for k, v in P.items(): print(f"{ARMS[k]:22s} {len(v):4d} contrastive S0 anchors, {len({e for e, _ in v}):3d} episodes")keys = sorted(set.intersection(*[set(v) for v in P.values()]))eps = np.array([e for e, _ in keys])print(f"\nPAIRED anchor set present in ALL FOUR arms: {len(keys)} anchors over {len(set(eps.tolist()))} episodes\n")D = {k: np.array([P[k][a] for a in keys]) for k in ARMS}
uniq = np.unique(eps)rng = np.random.default_rng(SEED)draws = [np.concatenate([np.where(eps == e)[0] for e in rng.choice(uniq, len(uniq), replace=True)]) for _ in range(N_BOOT)]
def ci(v): b = np.array([v[i].mean() for i in draws]) return dict(mean=float(v.mean()), lo=float(np.percentile(b, 2.5)), hi=float(np.percentile(b, 97.5)), p_ne0=float(2 * min((b <= 0).mean(), (b >= 0).mean())), n=int(len(v)))
def f(d): return f"{d['mean']:+.4f} [{d['lo']:+.4f},{d['hi']:+.4f}] p={d['p_ne0']:.3f}"
out = {"n_paired_anchors": len(keys), "n_episodes": int(len(uniq)), "n_boot": N_BOOT, "arms": {k: ci(D[k]) for k in ARMS}, "succ_effect_h101": ci(D["T"] - D["V"]), "succ_effect_h034": ci(D["AA"] - D["ha"]), "depth_effect_rxlftv0": ci(D["ha"] - D["V"]), "depth_effect_rxl": ci(D["AA"] - D["T"]), "interaction": ci((D["AA"] - D["T"]) - (D["ha"] - D["V"])), "best_corner": ci(np.max(np.stack([D[k] for k in ARMS]), axis=0))}print("ARM MEANS on the paired set (d_vs_greedy):")for k, a in ARMS.items(): print(f" {a:22s} {f(out['arms'][k])}")print("\nPAIRED EFFECTS:")print(f" successor (R_XL - R_XL_ft_v0) at h 1.01 {f(out['succ_effect_h101'])}")print(f" successor (R_XL - R_XL_ft_v0) at h 0.34 {f(out['succ_effect_h034'])}")print(f" depth (h 0.34 - h 1.01) on R_XL_ft_v0 {f(out['depth_effect_rxlftv0'])}")print(f" depth (h 0.34 - h 1.01) on R_XL {f(out['depth_effect_rxl'])}")print(f" INTERACTION {f(out['interaction'])}")i = out["interaction"]out["additive"] = bool(i["lo"] <= 0 <= i["hi"])print("\nVERDICT: the two axes are " + ("ADDITIVE (interaction CI covers 0) -- the four measured corners " "determine the plane and no unmeasured successor x depth combination reaches +0.10" if out["additive"] else "NON-ADDITIVE (interaction CI excludes 0)"))json.dump(out, open(ROOT / "_edgeAA_interaction.json", "w"), indent=1)print("-> status/real/_edgeAA_interaction.json")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123r"""#278 run 28: RUNG AA -- the last empty cell of the successor x depth 2x2, read on a COMMONanchor set, with its rule PRE-REGISTERED in this file before any AA part existed.
THE 2x2. Rung T measured the successor at depth h 1.01 and rung Z measured the depth axis on theGOAL_EPISODE successor. Their two best settings were never combined:
depth h 1.01 (b0.99 g0.995) depth h 0.34 (b0.99 g0.9925) R_XL (shipped) edge_T_rise +0.0909 edge_AA_rxl_ha <- THIS WAVE R_XL_ft_v0 (GOAL_EP) edge_V_goalep +0.0872 edge_Z_goalep_ha +0.0879
Main effects measured on identical anchors: successor +0.0037 (T-V), depth +0.0007 (ha-V). If thetwo are additive, AA lands near +0.0916 -- still under the +0.10 bar. Running it is what makes thenegative a complete factorial instead of a hole in the design.
PRE-REGISTERED RULE (control = edge_T_rise, the best cell measured to date; every number below isread on the COMMON landed episode set, with the per-arm n printed, per the standing rule from run 27): (a) edge_AA_rxl_ha >= +0.10 AND above its permuted control -> BAR CLEARED. Write the configuration into configs/baselines.yaml and rise_stack/EDGE_TEST.md with these numbers, post the passing table, close #278. (b) edge_AA_rxl_ha < +0.10 -> the 2x2 is complete and every standard-practice rung on this test is closed. Write the negative into rise_stack/EDGE_TEST.md with the ladder table, name the near-miss configuration and its number, and close #278 on the failed rung. ADDITIVITY, reported either way: interaction = (AA - T) - (ha - V). |interaction| inside the bootstrap noise -> the successor and depth axes are additive and the landscape is a plane, so no unmeasured combination of them can reach the bar; that is the statement that closes the design."""import sys, jsonimport numpy as npsys.path.insert(0, "/proj/dmfexp/zwhong/rsm_rise/scripts/real")from pathlib import Pathfrom edge_report import load_dirfrom edge_field import summarise_anchors
ROOT = Path("/proj/dmfexp/zwhong/rsm_rise/status/real")# arm -> (successor, beta, gamma, h = E[extra hops], E[reads], horizon frames, cap)ARMS = [("edge_AA_rxl_ha", "R_XL", 0.99, 0.9925, 0.34, 1.34, 132, 6), ("edge_T_rise", "R_XL", 0.99, 0.9950, 1.01, 2.01, 199, 11), ("edge_Z_goalep_ha", "R_XL_ft_v0", 0.99, 0.9925, 0.34, 1.34, 132, 6), ("edge_V_goalep", "R_XL_ft_v0", 0.99, 0.9950, 1.01, 2.01, 199, 11)]BAR = 0.10CTRL = "edge_T_rise"CELL = {("R_XL", 0.34): "edge_AA_rxl_ha", ("R_XL", 1.01): "edge_T_rise", ("R_XL_ft_v0", 0.34): "edge_Z_goalep_ha", ("R_XL_ft_v0", 1.01): "edge_V_goalep"}
def stats(recs, keep): r = [x for x in recs if int(x["episode"]) in keep] if not r: return None modes = sorted({m for x in r for m in x["scores"]}) s = summarise_anchors(r, modes, seed=0, n_boot=2000)["states"].get("S0", {}) sr = s.get("scorers", {}).get("rsm", {}) return dict(n=s.get("n_anchors"), cov=s.get("coverage"), dg=sr.get("delta_vs_greedy", {}), dp=sr.get("delta_vs_permuted", {}))
def f(d): return f"{d['mean']:+.4f}[{d['lo']:+.4f},{d['hi']:+.4f}]"
raw = {}for a, *_ in ARMS: recs = load_dir(ROOT / a) if recs: raw[a] = recs
eps = {a: {int(r["episode"]) for r in v} for a, v in raw.items()}common = set.intersection(*eps.values()) if eps else set()print("landed episodes per arm:")for a, *_ in ARMS: print(f" {a:22s} {len(eps.get(a, [])):3d} episodes, {len(raw.get(a, [])):4d} records")print(f"\nCOMMON EPISODE SET: {len(common)} episodes -> {sorted(common)}\n")
hdr = (f"{'arm':22s} {'successor':12s} {'beta':>6s} {'gamma':>7s} {'h':>5s} {'cap':>4s} " f"{'anc':>4s} {'cov':>5s} | {'d_vs_greedy (COMMON)':>26s} | {'d_vs_perm':>26s}")print(hdr)print("-" * len(hdr))out = {}for a, succ, b, g, h, rds, horiz, cap in ARMS: if a not in raw: print(f"{a:22s} -- no parts") continue s = stats(raw[a], common) if s is None: print(f"{a:22s} -- no S0 anchors on the common episodes") continue out[a] = dict(successor=succ, beta=b, gamma=g, h=h, e_reads=rds, horizon=horiz, cap=cap, **s) tag = " <- CONTROL" if a == CTRL else (" <- CLEARS BAR" if s["dg"].get("mean", 0) >= BAR else "") print(f"{a:22s} {succ:12s} {b:6.3f} {g:7.4f} {h:5.2f} {cap:4d} " f"{s['n']:4d} {s['cov']:5.3f} | {f(s['dg']):>26s} | {f(s['dp']):>26s}{tag}")
print("\n2x2 (d_vs_greedy on the COMMON episodes):")print(f" {'':12s} {'h 1.01':>10s} {'h 0.34':>10s} {'depth effect':>14s}")rows = {}for succ in ("R_XL", "R_XL_ft_v0"): a1, a0 = CELL[(succ, 1.01)], CELL[(succ, 0.34)] if a1 in out and a0 in out: v1, v0 = out[a1]["dg"]["mean"], out[a0]["dg"]["mean"] rows[succ] = (v1, v0) print(f" {succ:12s} {v1:+10.4f} {v0:+10.4f} {v0 - v1:+14.4f}") else: print(f" {succ:12s} -- incomplete")if len(rows) == 2: se = rows["R_XL"][0] - rows["R_XL_ft_v0"][0] se0 = rows["R_XL"][1] - rows["R_XL_ft_v0"][1] inter = (rows["R_XL"][1] - rows["R_XL"][0]) - (rows["R_XL_ft_v0"][1] - rows["R_XL_ft_v0"][0]) print(f" successor effect at h 1.01 {se:+.4f} at h 0.34 {se0:+.4f} INTERACTION {inter:+.4f}") out["_2x2"] = dict(succ_effect_h101=se, succ_effect_h034=se0, interaction=inter)
if CTRL in out and "edge_AA_rxl_ha" in out: aa = out["edge_AA_rxl_ha"]["dg"] ct = out[CTRL]["dg"] clears = aa["mean"] >= BAR and out["edge_AA_rxl_ha"]["dp"]["mean"] > 0 verdict = ("(a) BAR CLEARED by edge_AA_rxl_ha -- write configs/baselines.yaml + EDGE_TEST.md and close #278" if clears else "(b) BAR NOT CLEARED -- the successor x depth 2x2 is complete and every standard-practice rung on " "this test is closed; write the negative with the near-miss configuration and close #278") print(f"\ncontrol {CTRL} = {f(ct)} AA = {f(aa)} bar +{BAR:.2f}") print(f"PRE-REGISTERED VERDICT: {verdict}") out["_rule"] = dict(bar=BAR, control=CTRL, ctrl=ct, aa=aa, cleared=bool(clears), n_common_episodes=len(common), verdict=verdict)json.dump(out, open(ROOT / "_edgeAA_matched.json", "w"), indent=1, default=float)print("-> status/real/_edgeAA_matched.json")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183r"""#278 run 30: RUNG AB -- the PARTICLE axis measured AT THE BEST CELL, on a COMMON anchor set,with its rule PRE-REGISTERED (status/real/EDGE_RUNG_AB_RULE.md, gen_q 097da065) before any AB partexisted.
THE HOLE. Rung 4 closed the particle axis with "16 -> 256 buys 0.0000" and the fitted attenuationlaw d(n) = d_inf / sqrt(1 + k/n), d_inf +0.0669, k 4.87. Every arm behind that law pinned proposerpi05_cooking_sn1_knn0p03/ws_s0/9999 at gamma 0.999. The best cell edge_T_rise (+0.0909) pinspi05_cooking_rise/rise_s0/29999 at gamma 0.995 and has only ever run at 16 particles.
THE NUMBER THAT CHOSE IT. RANK_CTRL (#276, 2026-09-24T13:14:55Z): on the same anchors and the samecheckpoint the 'rise' proposer's candidate score CV is 0.008 against ~0.045-0.050 on the sn arms(var_t 3.4e-05 vs ~1e-03). Six times tighter scores -> particle noise is a far larger share of thescore spread here -> k is expected to be LARGER and the sn1k3 saturation does not transfer.
PRE-REGISTERED PREDICTION, transferring k = 4.87 unchanged to d(16) = +0.0909: d_inf +0.1038 d(256) +0.1028 d(128) +0.1018 d(64) +0.1000 d(32) +0.0967
PRE-REGISTERED RULE (control = edge_T_rise; COMMON landed episodes; per-arm n printed): (a) edge_AB_rise_p256 >= +0.10 AND above its own permuted control -> BAR CLEARED; write configs/baselines.yaml + rise_stack/EDGE_TEST.md, post the passing table, close #278 on a PASS. (b) < +0.10 -> refit the law on THIS arm's points (16, 32 free, 64, 256) and report d_inf, k beside (+0.0669, 4.87). (b1) refit d_inf >= +0.10 -> the asymptote clears but no runnable particle count does; name the count that would be needed and leave #278 open under NEEDS OWNER. (b2) refit d_inf < +0.10 -> the read-out-noise axis is exhausted at the best cell too; #278 closes again on the negative with the refit as rung AB of the ladder.
No second harness: the anchor reduction is edge_field.summarise_anchors via edge_report.load_dir(as every other rung), and the curve/free-32-point construction is edge_scorer_noise +edge_particle_curve's own fit form."""import sys, jsonimport numpy as npfrom scipy.optimize import curve_fitsys.path.insert(0, "/proj/dmfexp/zwhong/rsm_rise/scripts/real")from pathlib import Pathfrom scipy.stats import spearmanrfrom edge_report import load_dirfrom edge_field import summarise_anchorsimport edge_scorer_noise as esn
ROOT = Path("/proj/dmfexp/zwhong/rsm_rise/status/real")# arm -> (particles, label)ARMS = [("edge_T_rise", 16, "p16 (control, shipped best cell)"), ("edge_AB_rise_p16_s202", 16, "p16, scorer-seed 202 (replicate)"), ("edge_AB_rise_p64", 64, "p64"), ("edge_AB_rise_p256", 256, "p256 <- the pre-registered headline")]BAR = 0.10CTRL = "edge_T_rise"HEAD = "edge_AB_rise_p256"PRED = {16: 0.0909, 32: 0.0967, 64: 0.1000, 128: 0.1018, 256: 0.1028}SN1K3 = dict(d_inf=0.0669494433403113, k=4.874319282134451)
def stats(recs, keep): r = [x for x in recs if int(x["episode"]) in keep] if not r: return None modes = sorted({m for x in r for m in x["scores"]}) s = summarise_anchors(r, modes, seed=0, n_boot=2000)["states"].get("S0", {}) sr = s.get("scorers", {}).get("rsm", {}) return dict(n=s.get("n_anchors"), cov=s.get("coverage"), dg=sr.get("delta_vs_greedy", {}), dp=sr.get("delta_vs_permuted", {}))
def f(d): return f"{d['mean']:+.4f}[{d['lo']:+.4f},{d['hi']:+.4f}]" if d else " --"
raw = {}for a, *_ in ARMS: recs = load_dir(ROOT / a) if recs: raw[a] = recs
eps = {a: {int(r["episode"]) for r in v} for a, v in raw.items()}common = set.intersection(*eps.values()) if eps else set()print("landed episodes per arm (the completeness line, printed BEFORE any number):")for a, p, lab in ARMS: print(f" {a:24s} {len(eps.get(a, [])):3d} episodes, {len(raw.get(a, [])):4d} records {lab}")print(f"\nCOMMON EPISODE SET: {len(common)} episodes -> {sorted(common)}\n")
hdr = (f"{'arm':24s} {'P':>5s} {'anc':>4s} {'cov':>5s} | {'d_vs_greedy (COMMON)':>26s} | " f"{'d_vs_perm':>26s} | {'pred':>8s}")print(hdr); print("-" * len(hdr))out = {}for a, p, lab in ARMS: if a not in raw: print(f"{a:24s} {p:5d} -- no parts yet"); continue s = stats(raw[a], common) if s is None: print(f"{a:24s} {p:5d} -- no S0 anchors on the common episodes"); continue out[a] = dict(particles=p, label=lab, **s) tag = " <- CONTROL" if a == CTRL else (" <- CLEARS BAR" if s["dg"].get("mean", 0) >= BAR else "") print(f"{a:24s} {p:5d} {s['n']:4d} {s['cov']:5.3f} | {f(s['dg']):>26s} | {f(s['dp']):>26s} | " f"{PRED.get(p, float('nan')):+8.4f}{tag}")
# ---- the free 32-particle point + the candidate-matched reliability, on THIS arm ----curve = {"points": [], "source": "edge_scorer_noise (same reduction as rung 4)"}pairs = [r for r in ARMS if r[1] == 16 and r[0] in raw]if len(pairs) == 2: tags = [pairs[0][0], pairs[1][0]] sets = [[r for r in esn.load_tag(t) if r["state"] == 0 and int(r["ep"]) in common] for t in tags] if sets[0] and len(sets[0]) == len(sets[1]): recs = sets[0] ds = [esn.delta_vs_greedy(recs, [r["score"] for r in s]) for s in sets] d16 = float(np.mean([d["mean"] for d in ds])) avg = [np.mean([s[i]["score"] for s in sets], axis=0) for i in range(len(recs))] d32 = esn.delta_vs_greedy(recs, avg) curve["points"] += [{"effective_particles": 16, "d_vs_greedy": d16, "source": f"mean of {tags}"}, {"effective_particles": 32, "d_vs_greedy": d32["mean"], "ci": [d32["lo"], d32["hi"]], "source": f"seed-average of {tags}"}] rho = [spearmanr(np.asarray(sets[0][i]["score"], float), np.asarray(sets[1][i]["score"], float)).correlation for i in range(len(recs))] rho = [x for x in rho if np.isfinite(x)] # esn.load_tag exposes no raw action, so candidate identity is checked through the # onroute mask, which is computed FROM the candidates: identical masks on every anchor means # the two arms scored the same candidate set (the property that makes rho an exact # reliability rather than a floor -- it held for rung 4's p16 pair and failed for its p64 # pair, where proposer float nondeterminism across GPUs perturbed the candidates). ident = bool(all(np.array_equal(sets[0][i]["onroute"], sets[1][i]["onroute"]) for i in range(len(recs)))) curve["reliability_p16"] = {"median_rho": float(np.median(rho)), "n": len(rho), "candidates_bitwise_identical": ident, "sn1k3_reference_median_rho": 0.514} print(f"\ncandidate-matched scorer reliability at P=16 on THIS arm: median rho " f"{np.median(rho):.3f} (n={len(rho)}, candidates identical={ident}) " f"vs 0.514 measured on sn1k3") print(f"free 32-particle point (seed-average): {d32['mean']:+.4f}" f"[{d32['lo']:+.4f},{d32['hi']:+.4f}] predicted {PRED[32]:+.4f}")
for a, p, lab in ARMS: if p != 16 and a in out: curve["points"].append({"effective_particles": p, "d_vs_greedy": out[a]["dg"]["mean"], "ci": [out[a]["dg"]["lo"], out[a]["dg"]["hi"]], "source": a})
pts = sorted({(q["effective_particles"], q["d_vs_greedy"]) for q in curve["points"]})if len(pts) >= 3: n = np.array([q[0] for q in pts], float); d = np.array([q[1] for q in pts], float) fn = lambda x, dinf, k: dinf / np.sqrt(1.0 + k / x) try: (dinf, k), _ = curve_fit(fn, n, d, p0=[0.10, 5.0], maxfev=40000) curve["curve_fit"] = {"d_infinite_particles": float(dinf), "k_noise_over_signal_at_1_particle": float(k), "predicted": {int(x): float(fn(x, dinf, k)) for x in n}, "residual_max": float(np.max(np.abs(fn(n, dinf, k) - d))), "sn1k3_reference": SN1K3} print(f"\nREFIT ON THIS ARM: d_inf {dinf:+.4f}, k {k:.3f} " f"(sn1k3: d_inf {SN1K3['d_inf']:+.4f}, k {SN1K3['k']:.3f}) " f"max residual {curve['curve_fit']['residual_max']:.4f}") print(" points: " + " ".join(f"n={int(x)} {y:+.4f}" for x, y in pts)) except Exception as e: # noqa: BLE001 curve["curve_fit_error"] = str(e) print(f"\nREFIT FAILED: {e}")out["_curve"] = curve
# ---- the mechanical rule ----if CTRL in out and HEAD in out: hd, ct = out[HEAD]["dg"], out[CTRL]["dg"] clears = hd["mean"] >= BAR and out[HEAD]["dp"]["mean"] > 0 dinf = curve.get("curve_fit", {}).get("d_infinite_particles") if clears: verdict = ("(a) BAR CLEARED by edge_AB_rise_p256 -- write configs/baselines.yaml + " "rise_stack/EDGE_TEST.md and close #278 on the PASS") elif dinf is not None and dinf >= BAR: verdict = ("(b1) p256 under the bar but the REFIT ASYMPTOTE clears it -- report the particle " "count that would be needed and leave #278 open under NEEDS OWNER (a cost " "decision, not a science one)") else: verdict = ("(b2) p256 under the bar AND the refit asymptote under it -- the read-out-noise " "axis is exhausted at the best cell too; close #278 again on the negative with " "rung AB added to the ladder") print(f"\ncontrol {CTRL} = {f(ct)} p256 = {f(hd)} bar +{BAR:.2f}") print(f"pre-registered prediction for p256 was {PRED[256]:+.4f}") print(f"PRE-REGISTERED VERDICT: {verdict}") out["_rule"] = dict(bar=BAR, control=CTRL, head=HEAD, ctrl=ct, p256=hd, cleared=bool(clears), refit_d_inf=dinf, prediction=PRED, n_common_episodes=len(common), verdict=verdict)else: print("\nRULE NOT APPLIED -- the p256 arm or the control is missing; this read is DIRECTIONAL ONLY.")json.dump(out, open(ROOT / "_edgeAB_matched.json", "w"), indent=1, default=float)print("-> status/real/_edgeAB_matched.json")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135r"""#278 run 31: RUNG AC -- the FLOW-STEP (integration) axis measured AT THE BEST CELL, on a COMMONanchor set, with its rule PRE-REGISTERED (scripts/real/payloads/EDGE_RUNG_AC_RULE.md) before any ACpart existed.
THE HOLE. Rung R closed the flow axis as FLAT (flow 4/8/16/32 -> +0.0727/+0.0716/+0.0679/+0.0696)but every arm behind it -- edgeR_flow{4,16,32} and their control edgeQ_hz_g0995 -- pinned proposerpi05_cooking_sn1_knn0p03/ws_s0/9999. The best cell edge_T_rise pins pi05_cooking_rise/rise_s0/29999and EVERY rise-cell arm ever run (T, V, Z, AA, AB) has EDGE_FLOW=8. Same defect class as rung AB.After this rung it is the LAST one: proposer (T), depth (AA's 2x2), successor (AA), label (V/Z) andparticles/N (AB) are all already measured AT this cell.
THE NUMBER THAT CHOSE IT (measured in rung AB's own output, status/real/_edgeAB_matched.jsonfield `_curve`): candidate-matched scorer reliability at P=16 is median rho 0.903 (n=291) at thiscell against 0.514 at sn1k3, and the refit particle law here is k 0.029 (vs 4.874) -- the read-outis already at its asymptote. Rung R's null was measured through ~2x more read-out noise than thisarm carries, so a systematic integration effect is masked far less here.
PRE-REGISTERED PREDICTION (rung R transferred unchanged to d(flow 8) = +0.0909): flow 4 +0.0920 flow 8 +0.0909 (control) flow 16 +0.0872 flow 32 +0.0889 -- FLAT, all < barRung AB is why it is tested and not assumed: the transferred particle law predicted +0.1028 at p256and the truth was +0.0913, with k off by a factor of 170.
PRE-REGISTERED RULE (control = edge_T_rise; COMMON landed episodes; per-arm n printed): (a) ANY arm >= +0.10 AND above its own permuted control -> BAR CLEARED; report the SMALLEST passing flow, write configs/baselines.yaml + rise_stack/EDGE_TEST.md, close #278 on a PASS. (b) every arm < +0.10: (b1) best arm above the control's point estimate AND d MONOTONE NON-DECREASING over flow 8 -> 16 -> 32 -> integration still buying at the top of the range; name the flow count that would be needed and leave #278 open under NEEDS OWNER (a cost decision). (b2) otherwise (flat, non-monotone, or below the control) -> the INTEGRATION axis is exhausted at the best cell too; every ladder axis has then been measured AT the best cell. Close #278 on the negative with rungs AB and AC added to the ladder.
No second harness: the anchor reduction is edge_field.summarise_anchors via edge_report.load_dir,exactly as in every other rung."""import sys, jsonimport numpy as npsys.path.insert(0, "/proj/dmfexp/zwhong/rsm_rise/scripts/real")from pathlib import Pathfrom edge_report import load_dirfrom edge_field import summarise_anchors
ROOT = Path("/proj/dmfexp/zwhong/rsm_rise/status/real")# arm -> (flow steps, label)ARMS = [("edge_AC_rise_flow4", 4, "flow 4"), ("edge_T_rise", 8, "flow 8 (control, shipped best cell)"), ("edge_AC_rise_flow16", 16, "flow 16"), ("edge_AC_rise_flow32", 32, "flow 32 <- top of the pre-registered range")]BAR = 0.10CTRL = "edge_T_rise"PRED = {4: 0.0920, 8: 0.0909, 16: 0.0872, 32: 0.0889}
def stats(recs, keep): r = [x for x in recs if int(x["episode"]) in keep] if not r: return None modes = sorted({m for x in r for m in x["scores"]}) s = summarise_anchors(r, modes, seed=0, n_boot=2000)["states"].get("S0", {}) sr = s.get("scorers", {}).get("rsm", {}) return dict(n=s.get("n_anchors"), cov=s.get("coverage"), dg=sr.get("delta_vs_greedy", {}), dp=sr.get("delta_vs_permuted", {}))
def f(d): return f"{d['mean']:+.4f}[{d['lo']:+.4f},{d['hi']:+.4f}]" if d else " --"
raw = {}for a, *_ in ARMS: recs = load_dir(ROOT / a) if recs: raw[a] = recs
eps = {a: {int(r["episode"]) for r in v} for a, v in raw.items()}common = set.intersection(*eps.values()) if eps else set()print("landed episodes per arm (the completeness line, printed BEFORE any number):")for a, fl, lab in ARMS: print(f" {a:24s} {len(eps.get(a, [])):3d} episodes, {len(raw.get(a, [])):4d} records {lab}")print(f"\nCOMMON EPISODE SET: {len(common)} episodes -> {sorted(common)}\n")
hdr = (f"{'arm':24s} {'flow':>5s} {'anc':>4s} {'cov':>5s} | {'d_vs_greedy (COMMON)':>26s} | " f"{'d_vs_perm':>26s} | {'pred':>8s}")print(hdr); print("-" * len(hdr))out = {}for a, fl, lab in ARMS: if a not in raw: print(f"{a:24s} {fl:5d} -- no parts yet"); continue s = stats(raw[a], common) if s is None: print(f"{a:24s} {fl:5d} -- no S0 anchors on the common episodes"); continue out[a] = dict(flow=fl, label=lab, **s) tag = " <- CONTROL" if a == CTRL else (" <- CLEARS BAR" if s["dg"].get("mean", 0) >= BAR else "") print(f"{a:24s} {fl:5d} {s['n']:4d} {s['cov']:5.3f} | {f(s['dg']):>26s} | {f(s['dp']):>26s} | " f"{PRED.get(fl, float('nan')):+8.4f}{tag}")
# ---- the mechanical rule ----have = [(a, o) for a, o in out.items() if a != "_rule"]if CTRL in out and len(have) >= 2: ct = out[CTRL]["dg"] passing = [(out[a]["flow"], a) for a, o in have if o["dg"].get("mean", 0) >= BAR and o["dp"].get("mean", 0) > 0] passing.sort() # monotonicity over the arms ABOVE the control (8 -> 16 -> 32), in flow order up = sorted([(out[a]["flow"], out[a]["dg"]["mean"]) for a, o in have if out[a]["flow"] >= 8]) monotone = all(up[i + 1][1] >= up[i][1] - 1e-12 for i in range(len(up) - 1)) and len(up) >= 3 best_arm = max(have, key=lambda kv: kv[1]["dg"].get("mean", -9)) best = best_arm[1]["dg"]["mean"] above_ctrl = best > ct["mean"] if passing: verdict = (f"(a) BAR CLEARED -- smallest passing flow = {passing[0][0]} ({passing[0][1]}); " "write configs/baselines.yaml + rise_stack/EDGE_TEST.md and close #278 on the PASS") elif above_ctrl and monotone: verdict = ("(b1) every arm under the bar BUT d is monotone non-decreasing over flow 8->16->32 " "and the best arm beats the control -- integration is still buying; name the flow " "count that would be needed and leave #278 open under NEEDS OWNER (a cost decision)") else: verdict = ("(b2) every arm under the bar and the flow trend is flat / non-monotone / below the " "control -- the INTEGRATION axis is exhausted at the best cell too. Every ladder " "axis is now measured AT the best cell; close #278 on the negative with rungs AB " "and AC added to the ladder") print(f"\ncontrol {CTRL} = {f(ct)} best arm {best_arm[0]} = {best:+.4f} bar +{BAR:.2f}") print(f"monotone over flow>=8: {monotone} best above control: {above_ctrl}") print(f"flow-ordered d: " + " ".join(f"{fl}:{d:+.4f}" for fl, d in sorted( [(out[a]["flow"], out[a]["dg"]["mean"]) for a, o in have]))) print(f"PRE-REGISTERED VERDICT: {verdict}") out["_rule"] = dict(bar=BAR, control=CTRL, ctrl=ct, best_arm=best_arm[0], best=best, cleared=bool(passing), smallest_passing_flow=(passing[0][0] if passing else None), monotone_over_flow_ge_8=bool(monotone), best_above_control=bool(above_ctrl), prediction=PRED, n_common_episodes=len(common), verdict=verdict)else: print("\nRULE NOT APPLIED -- the control or the new arms are missing; this read is DIRECTIONAL ONLY.")json.dump(out, open(ROOT / "_edgeAC_matched.json", "w"), indent=1, default=float)print("-> status/real/_edgeAC_matched.json")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293"""#278 run 19: rung U -- the SUCCESSOR CHECKPOINT varied at the rung-T winning cell.
ONE factor moves: the successor. Proposer (pi0.5 RISE rise_s0/29999), beta 0.99 / gamma 0.995,flow 8, N=128, 16 particles, S0 anchors, seed 0, and the identical 25 held-out episodes are pinnedto edge_T_rise, which is therefore the control AND the fifth point of the same design.
Reported in BOTH units -- d_vs_greedy (the unit the +0.10 bar is written in) and theleverage-weighted AUC_w from edge_ceiling2's exact identity -- with w_bar, the per-arm ceiling and%ceiling, exactly as rung T reported.
Each arm also carries its SUCCESSOR GATE minmse_train/staymse_train (run 15 / the owner's2026-09-23 12:35 note): < 1 means the successor's samples beat the trivial stay-put predictor onits own training split. The pre-registered rung-U rule (posted on #278 before these numbersexisted) reads the gate against the ranking: (a) xlnt > ctrl AND the gate orders the arms monotonically -> the gate is the binding constraint and the next move is successor CAPACITY; (b) the gate does NOT order the arms -> it is a necessary-not-sufficient screen, the +0.0909 ceiling is a property of the reward/latent rather than of sample quality, and the next rung is #277's reward-NAME axis measured on the RISE proposer; (c) xlnt >= +0.10 -> the bar is cleared."""import sys, jsonimport numpy as npsys.path.insert(0, "/proj/dmfexp/zwhong/rsm_rise/scripts/real")from pathlib import Pathfrom edge_report import load_dirfrom edge_field import summarise_anchorsimport edge_ceiling2 as C
ROOT = Path("/proj/dmfexp/zwhong/rsm_rise/status/real")CTRL = "edge_T_rise" # successor R_XL/ckpt_s100000.ptARMS = {"edge_U_xlnt": ("R_XL_ft_nt/ckpt_s110000.pt", 0.5490), "edge_T_rise": ("R_XL/ckpt_s100000.pt (control)", 0.5784), "edge_U_aug": ("AUG_invariant_t0p02_s0/ckpt_s100000.pt", 0.9863), "edge_U_mlong": ("R_M_long/ckpt_s300000.pt", 0.9869), "edge_U_m": ("R_M/ckpt_s100000.pt", 0.9992)}
def stats(recs): modes = sorted({m for x in recs for m in x["scores"]}) s = summarise_anchors(recs, modes, seed=0, n_boot=2000)["states"].get("S0", {}) sr = s.get("scorers", {}).get("rsm", {}) return dict(n=s.get("n_anchors"), cov=s.get("coverage"), dg=sr.get("delta_vs_greedy", {}), dp=sr.get("delta_vs_permuted", {}), rank=sr.get("onroute_rank_pct", {}))
def f(d): return f"{d['mean']:+.4f}[{d['lo']:+.4f},{d['hi']:+.4f}]"
out, order = {}, []print(f"{'arm':13s} {'successor':40s} {'gate':>6s} {'eps':>3s} {'cov':>5s} {'anc':>4s} {'wbar':>5s} " f"{'d_ceil':>7s} | {'d_vs_greedy':>24s} | {'d_vs_permuted':>24s} | {'AUCw':>6s} {'prm':>5s} " f"{'need':>5s} {'%ceil':>6s}")for a, (succ, gate) in ARMS.items(): recs = load_dir(ROOT / a) if not recs: print(f"{a:13s} {succ:40s} -- no parts yet") continue eps = sorted({int(r["episode"]) for r in recs}) A = stats(recs) c = C.arm(str(ROOT / a)) # AUC_w the +0.10 bar demands at THIS arm's own leverage: d_bar / d_ceil of the AUC headroom need = c["auc_perm"]["weighted"] + 0.10 / c["d_ceiling"] * (1.0 - c["auc_perm"]["weighted"]) \ if c["d_ceiling"] else float("nan") pct = 100.0 * A["dg"]["mean"] / c["d_ceiling"] if c["d_ceiling"] else float("nan") out[a] = dict(successor=succ, gate=gate, episodes=eps, arm=A, ceiling=c, auc_w_needed=need, pct_of_ceiling=pct) order.append((a, gate, A["dg"]["mean"], c["auc_rsm"]["weighted"])) print(f"{a:13s} {succ:40s} {gate:6.4f} {len(eps):3d} {A['cov']:5.3f} {c['n_anchors']:4d} " f"{c['w_mean']:5.3f} {c['d_ceiling']:+7.4f} | {f(A['dg']):>24s} | {f(A['dp']):>24s} | " f"{c['auc_rsm']['weighted']:6.3f} {c['auc_perm']['weighted']:5.3f} {need:5.3f} {pct:5.1f}%")
# --- the pre-registered rule, evaluated mechanically -------------------------------------------g = np.array([o[1] for o in order]); d = np.array([o[2] for o in order]); au = np.array([o[3] for o in order])rho_d = float(np.corrcoef(np.argsort(np.argsort(g)), np.argsort(np.argsort(d)))[0, 1])rho_a = float(np.corrcoef(np.argsort(np.argsort(g)), np.argsort(np.argsort(au)))[0, 1])best = max(order, key=lambda o: o[2])ctrl_d = dict((o[0], o[2]) for o in order)[CTRL]xl = dict((o[0], o[2]) for o in order).get("edge_U_xlnt")verdict = ("(c) BAR CLEARED" if xl is not None and xl >= 0.10 else "(a) gate binding -> capacity" if (xl is not None and xl > ctrl_d and rho_d <= -0.9) else "(b) gate is necessary-not-sufficient -> reward-NAME axis on the RISE proposer")print()print(f"spearman(gate, d_vs_greedy) = {rho_d:+.3f} (gate is LOWER-is-better, so -1 = perfect ordering)")print(f"spearman(gate, AUC_w) = {rho_a:+.3f}")print(f"best arm = {best[0]} d = {best[2]:+.4f} control edge_T_rise d = {ctrl_d:+.4f}")print(f"PRE-REGISTERED VERDICT: {verdict}")out["_rule"] = dict(spearman_gate_d=rho_d, spearman_gate_aucw=rho_a, best=best[0], best_d=best[2], ctrl_d=ctrl_d, xlnt_d=xl, verdict=verdict)json.dump(out, open(ROOT / "_edgeU_matched.json", "w"), indent=1, default=float)print("-> status/real/_edgeU_matched.json")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110"""#278 run 20: rung V -- the REWARD LABEL varied at the rung-T winning cell.
ONE factor moves: the reward label. Proposer (pi0.5 RISE rise_s0/29999), beta 0.99 / gamma 0.995,flow 8, N=128, 16 particles, S0 anchors, seed 0, and the identical 25 held-out episodes are pinnedto edge_T_rise, which is therefore the control AND the fifth point of the same design. All four Varms are 10k-step fine-tunes from the SAME base R_XL/ckpt_s100000.pt with beta_trunc_eps 0.02unchanged, so capacity, steps and truncation are held fixed.
MEASURED BEFORE THE RUN (runs/real_cooking_v5/rsm/*/history.json, last row with the gate keys):the stay-put gate minmse_train/staymse_train is IDENTICAL to 3 decimals across all four arms -- R_XL_ft_v0 0.5596, R_XL_ft_v1 0.5584, R_XL_ft_B 0.5588, R_XL_ft_B400 0.5592, base R_XL 0.5784.The label trains the reward head, not the flow model, so sample quality is held fixed BYCONSTRUCTION and any spread in the ranking is attributable to the label alone. That is what makesrung V the clean test of the rung-U branch-(b) conclusion (the +0.0909 ceiling is a property ofthe REWARD/LATENT rather than of sample quality).
Canonical reward names (rise_stack/REWARD_NAMES.md) with their positive-frame shares.
PRE-REGISTERED RUNG-V RULE (posted on #278 before these numbers existed): (1) edge_V_goalep ~ edge_T_rise (inside its interval) -> the 10k extra steps are neutral and the spread across the other three arms is the LABEL alone. If goalep DIFFERS from the control, the label comparison is confounded by fine-tuning itself and differences are reported against goalep instead. (2) ANY arm >= +0.10 -> bar cleared. (3) ALL FOUR inside the control's interval -> the reward-label axis is closed and the standard-practice ladder on this test is exhausted at +0.0909 [+0.0373,+0.1480]."""import sys, jsonimport numpy as npsys.path.insert(0, "/proj/dmfexp/zwhong/rsm_rise/scripts/real")from pathlib import Pathfrom edge_report import load_dirfrom edge_field import summarise_anchorsimport edge_ceiling2 as C
ROOT = Path("/proj/dmfexp/zwhong/rsm_rise/status/real")CTRL = "edge_T_rise" # R_XL/ckpt_s100000.pt, shipped GOAL_EPISODE head# arm -> (label + checkpoint, stay-put gate measured from that checkpoint's own history.json)ARMS = {"edge_T_rise": ("GOAL_EPISODE R_XL s100000 (control, shipped)", 0.5784), "edge_V_goalep": ("GOAL_EPISODE R_XL_ft_v0 s110000 0.294", 0.5596), "edge_V_goalseg": ("GOAL_SEGMENT R_XL_ft_v1 s110000 0.167", 0.5584), "edge_V_win400": ("GOAL_WINDOW_400 R_XL_ft_B400 s110000 0.111", 0.5592), "edge_V_win100": ("GOAL_WINDOW_100 R_XL_ft_B s110000 0.028", 0.5588)}
def stats(recs): modes = sorted({m for x in recs for m in x["scores"]}) s = summarise_anchors(recs, modes, seed=0, n_boot=2000)["states"].get("S0", {}) sr = s.get("scorers", {}).get("rsm", {}) return dict(n=s.get("n_anchors"), cov=s.get("coverage"), dg=sr.get("delta_vs_greedy", {}), dp=sr.get("delta_vs_permuted", {}), rank=sr.get("onroute_rank_pct", {}))
def f(d): return f"{d['mean']:+.4f}[{d['lo']:+.4f},{d['hi']:+.4f}]"
out, order = {}, []print(f"{'arm':15s} {'reward label / checkpoint / pos share':44s} {'gate':>6s} {'eps':>3s} {'cov':>5s} " f"{'anc':>4s} {'wbar':>5s} {'d_ceil':>7s} | {'d_vs_greedy':>24s} | {'d_vs_permuted':>24s} | " f"{'AUCw':>6s} {'prm':>5s} {'need':>5s} {'%ceil':>6s}")for a, (lab, gate) in ARMS.items(): recs = load_dir(ROOT / a) if not recs: print(f"{a:15s} {lab:44s} -- no parts yet") continue eps = sorted({int(r["episode"]) for r in recs}) A = stats(recs) c = C.arm(str(ROOT / a)) need = c["auc_perm"]["weighted"] + 0.10 / c["d_ceiling"] * (1.0 - c["auc_perm"]["weighted"]) \ if c["d_ceiling"] else float("nan") pct = 100.0 * A["dg"]["mean"] / c["d_ceiling"] if c["d_ceiling"] else float("nan") out[a] = dict(label=lab, gate=gate, episodes=eps, arm=A, ceiling=c, auc_w_needed=need, pct_of_ceiling=pct) order.append((a, gate, A["dg"]["mean"], c["auc_rsm"]["weighted"], A["dg"])) print(f"{a:15s} {lab:44s} {gate:6.4f} {len(eps):3d} {A['cov']:5.3f} {c['n_anchors']:4d} " f"{c['w_mean']:5.3f} {c['d_ceiling']:+7.4f} | {f(A['dg']):>24s} | {f(A['dp']):>24s} | " f"{c['auc_rsm']['weighted']:6.3f} {c['auc_perm']['weighted']:5.3f} {need:5.3f} {pct:5.1f}%")
# --- the pre-registered rule, evaluated mechanically -------------------------------------------if order: D = {o[0]: o[2] for o in order} ctrl = D.get(CTRL) ci = {o[0]: o[4] for o in order} best = max(order, key=lambda o: o[2]) cleared = [o[0] for o in order if o[2] >= 0.10] # (1) is the +10k-step control neutral? goalep inside the control's interval, both ways. gp = D.get("edge_V_goalep") neutral = (gp is not None and ctrl is not None and ci[CTRL]["lo"] <= gp <= ci[CTRL]["hi"] and ci["edge_V_goalep"]["lo"] <= ctrl <= ci["edge_V_goalep"]["hi"]) inside = [o[0] for o in order if o[0] != CTRL and ctrl is not None and ci[CTRL]["lo"] <= o[2] <= ci[CTRL]["hi"]] verdict = ("(2) BAR CLEARED by " + ",".join(cleared) if cleared else "(3) label axis CLOSED -- all arms inside the control's interval" if len(inside) == len(order) - 1 else "(1b) a label MOVES the number: " + ",".join(o[0] for o in order if o[0] != CTRL and o[0] not in inside)) print() print(f"control edge_T_rise d = {ctrl:+.4f} {f(ci[CTRL])}" if ctrl is not None else "control missing") print(f"+10k-step control neutral (goalep ~ ctrl, both ways)? {neutral}") print(f"best arm = {best[0]} d = {best[2]:+.4f} AUC_w {best[3]:.3f}") print(f"arms inside the control's interval: {inside}") print(f"PRE-REGISTERED VERDICT: {verdict}") out["_rule"] = dict(ctrl_d=ctrl, goalep_d=gp, ft_control_neutral=bool(neutral), inside_ctrl_interval=inside, best=best[0], best_d=best[2], cleared=cleared, verdict=verdict)json.dump(out, open(ROOT / "_edgeV_matched.json", "w"), indent=1, default=float)print("-> status/real/_edgeV_matched.json")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132"""#278 run 22: rung W -- the REWARD LABEL x READ-OUT HORIZON interaction.
ONE factor moves off rung V: gamma 0.995 -> 0.999. Proposer (pi0.5 RISE rise_s0/29999), beta 0.99,flow 8, N=128, 16 particles, S0 anchors, seed 0 and the same 25 held-out episodes are pinned, soevery g999 arm has an ALREADY-MEASURED matched control at g995 (status/real/_edgeV_matched.json)and the design is a complete 4-label x 2-gamma table.
THE NUMBER THAT CHOSE IT (rung V, complete, anchor-for-anchor matched, stay-put gate held fixed at0.5584-0.5596 so sample quality cannot vary across the label arms): GOAL_EPISODE 0.294 -> +0.0872[+0.0436,+0.1368] | GOAL_WINDOW_400 0.111 -> +0.0125[-0.0114,+0.0296] GOAL_SEGMENT 0.167 -> -0.0672[-0.1238,-0.0163] | GOAL_WINDOW_100 0.028 -> -0.0671[-0.1355,-0.0081]The label is the largest lever on this test (spread 0.158 of d vs 0.005 for flow and 0.000 forparticles) but it only moves DOWN. REACHABILITY is the pre-registered explanation and it isarithmetic: these are S0 anchors and the first GOAL_SEGMENT positive is ~673 frames away(SEGMENTS.json: rest of 0->2 ~209 + 2->3 464) against a 199-frame horizon at gamma 0.995. Thecorroborating number is #277's -- the SAME GOAL_SEGMENT checkpoint scores AUC 0.931 [0.89,0.96] ongoal detection at S0, measured at gamma 0.999 where the horizon (999) covers the 673. Rung Q closedthe horizon at +0.0690 but swept gamma with the DENSE shipped label ONLY, whose positives are alreadyreachable at 0.995 -- the one case where more horizon can only dilute. The interaction is untested.
PRE-REGISTERED RUNG-W RULE (posted on #278 before these numbers existed): (a) ANY g999 arm >= +0.10 -> bar cleared; write the configuration and close #278. (b) edge_W_goalseg_g999 ABOVE the upper bound of edge_V_goalseg's interval (-0.0163) -> the label x horizon interaction is REAL and -0.0672 was a reachability artefact, not a verdict on the label. Next rung is gamma 0.9995 on that label (horizon 1999). (c) edge_W_goalep_g999 BELOW edge_V_goalep -> the dilution rung Q measured on the dense label is reproduced, and (b)+(c) together mean the optimal gamma is LABEL-DEPENDENT: a publishable structural finding about the read-out, not a tuning artefact. (d) ALL FOUR g999 arms inside their own g995 arm's interval -> the interaction is NULL, the label axis is closed at the dense default, and the standard-practice ladder on this test is EXHAUSTED at +0.0909 [+0.0373,+0.1480]. Write the negative with the localised cause."""import sys, jsonimport numpy as npsys.path.insert(0, "/proj/dmfexp/zwhong/rsm_rise/scripts/real")from pathlib import Pathfrom edge_report import load_dirfrom edge_field import summarise_anchorsimport edge_ceiling2 as C
ROOT = Path("/proj/dmfexp/zwhong/rsm_rise/status/real")# label -> (canonical name + pos share, g995 arm dir, g999 arm dir, stay-put gate)PAIRS = [("GOAL_EPISODE 0.294 R_XL_ft_v0", "edge_V_goalep", "edge_W_goalep_g999", 0.5596), ("GOAL_SEGMENT 0.167 R_XL_ft_v1", "edge_V_goalseg", "edge_W_goalseg_g999", 0.5584), ("GOAL_WINDOW_400 0.111 R_XL_ft_B400", "edge_V_win400", "edge_W_win400_g999", 0.5592), ("GOAL_WINDOW_100 0.028 R_XL_ft_B", "edge_V_win100", "edge_W_win100_g999", 0.5588)]SHIPPED = "edge_T_rise" # R_XL s100000 at gamma 0.995, the best cell measured to date: +0.0909
def stats(recs): modes = sorted({m for x in recs for m in x["scores"]}) s = summarise_anchors(recs, modes, seed=0, n_boot=2000)["states"].get("S0", {}) sr = s.get("scorers", {}).get("rsm", {}) return dict(n=s.get("n_anchors"), cov=s.get("coverage"), dg=sr.get("delta_vs_greedy", {}), dp=sr.get("delta_vs_permuted", {}), rank=sr.get("onroute_rank_pct", {}))
def f(d): return f"{d['mean']:+.4f}[{d['lo']:+.4f},{d['hi']:+.4f}]"
def read(a): recs = load_dir(ROOT / a) if not recs: return None A = stats(recs) c = C.arm(str(ROOT / a)) need = (c["auc_perm"]["weighted"] + 0.10 / c["d_ceiling"] * (1.0 - c["auc_perm"]["weighted"]) if c["d_ceiling"] else float("nan")) pct = 100.0 * A["dg"]["mean"] / c["d_ceiling"] if c["d_ceiling"] else float("nan") return dict(episodes=sorted({int(r["episode"]) for r in recs}), arm=A, ceiling=c, auc_w_needed=need, pct_of_ceiling=pct)
out = {}hdr = (f"{'label / checkpoint':30s} {'gate':>6s} {'gamma':>6s} {'eps':>3s} {'anc':>4s} {'cov':>5s} " f"{'wbar':>5s} | {'d_vs_greedy':>24s} | {'AUCw':>6s} {'prm':>5s} {'need':>5s} {'%ceil':>7s}")print(hdr); print("-" * len(hdr))for lab, a995, a999, gate in PAIRS: for g, a in (("0.995", a995), ("0.999", a999)): r = read(a) if r is None: print(f"{lab:30s} {gate:6.4f} {g:>6s} -- no parts yet ({a})") continue out[a] = dict(label=lab, gamma=float(g), gate=gate, **r) c, A = r["ceiling"], r["arm"] print(f"{lab:30s} {gate:6.4f} {g:>6s} {len(r['episodes']):3d} {c['n_anchors']:4d} " f"{A['cov']:5.3f} {c['w_mean']:5.3f} | {f(A['dg']):>24s} | " f"{c['auc_rsm']['weighted']:6.3f} {c['auc_perm']['weighted']:5.3f} " f"{r['auc_w_needed']:5.3f} {r['pct_of_ceiling']:6.1f}%") print()
# --- the pre-registered rule, evaluated mechanically -------------------------------------------D = {a: v["arm"]["dg"] for a, v in out.items()}g999 = [a for a in D if a.endswith("_g999")]if g999: cleared = [a for a in g999 if D[a]["mean"] >= 0.10] # (b) the sparse label rescued by the reachable horizon? seg_ok = ("edge_W_goalseg_g999" in D and "edge_V_goalseg" in D and D["edge_W_goalseg_g999"]["mean"] > D["edge_V_goalseg"]["hi"]) # (c) the dense label diluted by the longer horizon (rung Q's mechanism reproduced)? ep_down = ("edge_W_goalep_g999" in D and "edge_V_goalep" in D and D["edge_W_goalep_g999"]["mean"] < D["edge_V_goalep"]["lo"]) # (d) every g999 arm inside its own g995 control's interval -> interaction NULL pairs_done = [(a995, a999) for _, a995, a999, _ in PAIRS if a995 in D and a999 in D] inside = [a999 for a995, a999 in pairs_done if D[a995]["lo"] <= D[a999]["mean"] <= D[a995]["hi"]] null = len(pairs_done) == len(PAIRS) and len(inside) == len(PAIRS) best = max(D, key=lambda a: D[a]["mean"]) verdict = ("(a) BAR CLEARED by " + ",".join(cleared) if cleared else "(d) interaction NULL -- every gamma 0.999 arm inside its own gamma 0.995 interval; " "label axis closed at the dense default and the standard-practice ladder is EXHAUSTED" if null else "(b)+(c) optimal gamma is LABEL-DEPENDENT: sparse label rescued by the reachable " "horizon AND dense label diluted by it" if (seg_ok and ep_down) else "(b) sparse label RESCUED by the reachable horizon" if seg_ok else "(c) dense label DILUTED by the longer horizon only" if ep_down else "partial: horizon moves some arm outside its control, neither (b) nor (c) cleanly") print(f"pairs complete: {len(pairs_done)}/{len(PAIRS)} g999 arms inside their g995 interval: {inside}") print(f"(b) goalseg rescued (> {D['edge_V_goalseg']['hi']:+.4f})? {seg_ok}" if "edge_V_goalseg" in D else "(b) goalseg control missing") print(f"(c) goalep diluted (< {D['edge_V_goalep']['lo']:+.4f})? {ep_down}" if "edge_V_goalep" in D else "(c) goalep control missing") print(f"best arm overall = {best} d = {D[best]['mean']:+.4f} " f"(shipped best to date edge_T_rise +0.0909; bar +0.10)") print(f"PRE-REGISTERED VERDICT: {verdict}") out["_rule"] = dict(cleared=cleared, seg_rescued=bool(seg_ok), goalep_diluted=bool(ep_down), pairs_complete=len(pairs_done), inside_own_ctrl=inside, interaction_null=bool(null), best=best, best_d=D[best]["mean"], verdict=verdict)json.dump(out, open(ROOT / "_edgeW_matched.json", "w"), indent=1, default=float)print("-> status/real/_edgeW_matched.json")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136"""#278 run 24: rung X -- the REWARD LABEL x READ-OUT HORIZON interaction, second step of gamma.
ONE factor moves off rung W: gamma 0.999 -> 0.9995. Proposer (pi0.5 RISE rise_s0/29999), beta 0.99(inside the trained range beta_lo 0.95 / beta_hi 0.99), flow 8, N=128, 16 particles, S0 anchors,seed 0 and the same 25 held-out episodes stay pinned, so every g9995 arm has an ALREADY-MEASUREDmatched control at g999 (status/real/_edgeW_matched.json) and the design completes a 4-label x3-gamma table. Nothing retrained, nothing bespoke.
THE NUMBER THAT CHOSE IT (rung W, COMPLETE 25/25, anchor-for-anchor matched, stay-put gate heldfixed per label so sample quality cannot vary across the horizon): GOAL_WINDOW_400 0.111: +0.0125[-0.0114,+0.0296] at g0.995 -> +0.0546[+0.0107,+0.1030] at g0.999 -- the ONLY arm at any rung that a horizon change pushed clean OUTSIDE its own control's interval (+0.0546 > +0.0296), and its AUC_w more than doubled away from the permuted null (0.543 -> 0.654 against perm 0.491 -> 0.500). The other three stayed inside their own controls: GOAL_EPISODE +0.0872 -> +0.0741 | GOAL_SEGMENT -0.0672 -> -0.0629 | GOAL_WINDOW_100 -0.0671 -> -0.0516.
THE MECHANISM UNDER TEST IS ARITHMETIC (cache SEGMENTS.json, S0 anchors, horizon = 1/(1-gamma)): first positive of... frames from an S0 anchor g0.995=199 g0.999=999 g0.9995=1999 GOAL_WINDOW_400 ~849 (209 + 464 + 176) no YES yes GOAL_SEGMENT ~673 (209 + 464) no yes yes GOAL_WINDOW_100 ~1149 (209 + 464 + 476) no no YES S4 arrival itself ~1249 (209 + 464 + 576) no no YESSo if reachability is the mechanism, GOAL_WINDOW_100 is the arm that moves NEXT, and it moves atgamma 0.9995 and NOT before. That was posted on #278 (run 23) BEFORE these numbers existed.
PRE-REGISTERED RUNG-X RULE (posted on #278 run 23, before any X part was read): (a) ANY g9995 arm >= +0.10 -> bar cleared; write the configuration into configs/baselines.yaml and rise_stack/EDGE_TEST.md with the numbers, post the passing table, close #278. (b) edge_X_win100_g9995 ABOVE the upper bound of edge_W_win100_g999's interval -> the reachability pre-registration is CONFIRMED: the horizon a label needs is a property of its positive geometry. (c) edge_X_win400_g9995 keeps rising above edge_W_win400_g999 -> report the SMALLEST gamma that clears the bar, per the owner's "report the smallest that passes". (d) NOTHING moves (every g9995 arm inside its own g999 interval) -> the horizon axis is EXHAUSTED at gamma 0.999 and the standard-practice ladder on this test is done; write the negative with the localised cause (RISE proposer supplies cov 0.904 / ceiling +0.1898; the RSM scorer realises 47.9% of it, significantly above its permuted null 0.508, but 0.023 of AUC_w short of the bar)."""import sys, jsonimport numpy as npsys.path.insert(0, "/proj/dmfexp/zwhong/rsm_rise/scripts/real")from pathlib import Pathfrom edge_report import load_dirfrom edge_field import summarise_anchorsimport edge_ceiling2 as C
ROOT = Path("/proj/dmfexp/zwhong/rsm_rise/status/real")# label -> (canonical name + pos share, g999 control dir, g9995 arm dir, stay-put gate)PAIRS = [("GOAL_EPISODE 0.294 R_XL_ft_v0", "edge_W_goalep_g999", "edge_X_goalep_g9995", 0.5596), ("GOAL_SEGMENT 0.167 R_XL_ft_v1", "edge_W_goalseg_g999", "edge_X_goalseg_g9995", 0.5584), ("GOAL_WINDOW_400 0.111 R_XL_ft_B400", "edge_W_win400_g999", "edge_X_win400_g9995", 0.5592), ("GOAL_WINDOW_100 0.028 R_XL_ft_B", "edge_W_win100_g999", "edge_X_win100_g9995", 0.5588)]BEST_TO_DATE = ("edge_T_rise", 0.0909) # R_XL s100000, GOAL_EPISODE, gamma 0.995; bar is +0.10
def stats(recs): modes = sorted({m for x in recs for m in x["scores"]}) s = summarise_anchors(recs, modes, seed=0, n_boot=2000)["states"].get("S0", {}) sr = s.get("scorers", {}).get("rsm", {}) return dict(n=s.get("n_anchors"), cov=s.get("coverage"), dg=sr.get("delta_vs_greedy", {}), dp=sr.get("delta_vs_permuted", {}), rank=sr.get("onroute_rank_pct", {}))
def f(d): return f"{d['mean']:+.4f}[{d['lo']:+.4f},{d['hi']:+.4f}]"
def read(a): recs = load_dir(ROOT / a) if not recs: return None A = stats(recs) c = C.arm(str(ROOT / a)) need = (c["auc_perm"]["weighted"] + 0.10 / c["d_ceiling"] * (1.0 - c["auc_perm"]["weighted"]) if c["d_ceiling"] else float("nan")) pct = 100.0 * A["dg"]["mean"] / c["d_ceiling"] if c["d_ceiling"] else float("nan") return dict(episodes=sorted({int(r["episode"]) for r in recs}), arm=A, ceiling=c, auc_w_needed=need, pct_of_ceiling=pct)
out = {}hdr = (f"{'label / checkpoint':30s} {'gate':>6s} {'gamma':>7s} {'eps':>3s} {'anc':>4s} {'cov':>5s} " f"{'wbar':>5s} | {'d_vs_greedy':>24s} | {'AUCw':>6s} {'prm':>5s} {'need':>5s} {'%ceil':>7s}")print(hdr); print("-" * len(hdr))for lab, a999, a9995, gate in PAIRS: for g, a in (("0.999", a999), ("0.9995", a9995)): r = read(a) if r is None: print(f"{lab:30s} {gate:6.4f} {g:>7s} -- no parts yet ({a})") continue out[a] = dict(label=lab, gamma=float(g), gate=gate, **r) c, A = r["ceiling"], r["arm"] print(f"{lab:30s} {gate:6.4f} {g:>7s} {len(r['episodes']):3d} {c['n_anchors']:4d} " f"{A['cov']:5.3f} {c['w_mean']:5.3f} | {f(A['dg']):>24s} | " f"{c['auc_rsm']['weighted']:6.3f} {c['auc_perm']['weighted']:5.3f} " f"{r['auc_w_needed']:5.3f} {r['pct_of_ceiling']:6.1f}%") print()
# --- the pre-registered rule, evaluated mechanically -------------------------------------------D = {a: v["arm"]["dg"] for a, v in out.items()}g9995 = [a for a in D if a.endswith("_g9995")]if g9995: cleared = [a for a in g9995 if D[a]["mean"] >= 0.10] # (b) the reachability pre-registration: GOAL_WINDOW_100 is the arm that moves at 0.9995 w100_ok = ("edge_X_win100_g9995" in D and "edge_W_win100_g999" in D and D["edge_X_win100_g9995"]["mean"] > D["edge_W_win100_g999"]["hi"]) # (c) GOAL_WINDOW_400 keeps rising past its own g999 interval w400_up = ("edge_X_win400_g9995" in D and "edge_W_win400_g999" in D and D["edge_X_win400_g9995"]["mean"] > D["edge_W_win400_g999"]["hi"]) pairs_done = [(a999, a9995) for _, a999, a9995, _ in PAIRS if a999 in D and a9995 in D] inside = [a for a999, a in pairs_done if D[a999]["lo"] <= D[a]["mean"] <= D[a999]["hi"]] null = len(pairs_done) == len(PAIRS) and len(inside) == len(PAIRS) best = max(D, key=lambda a: D[a]["mean"]) verdict = ("(a) BAR CLEARED by " + ",".join(cleared) if cleared else "(d) horizon axis EXHAUSTED at gamma 0.999 -- every gamma 0.9995 arm inside its own " "gamma 0.999 interval; the standard-practice ladder on this test is done" if null else "(b)+(c) reachability CONFIRMED on both windows: the horizon a label needs is a " "property of its positive geometry" if (w100_ok and w400_up) else "(b) reachability CONFIRMED -- GOAL_WINDOW_100 moves at 0.9995 and not before" if w100_ok else "(c) GOAL_WINDOW_400 keeps rising; GOAL_WINDOW_100 did not move" if w400_up else "partial: some arm moves outside its control, neither (b) nor (c) cleanly") print(f"pairs complete: {len(pairs_done)}/{len(PAIRS)} g9995 arms inside their g999 interval: {inside}") if "edge_W_win100_g999" in D: print(f"(b) win100 moves (> {D['edge_W_win100_g999']['hi']:+.4f})? {w100_ok}") if "edge_W_win400_g999" in D: print(f"(c) win400 keeps rising (> {D['edge_W_win400_g999']['hi']:+.4f})? {w400_up}") print(f"best arm overall = {best} d = {D[best]['mean']:+.4f} " f"(best cell measured to date {BEST_TO_DATE[0]} {BEST_TO_DATE[1]:+.4f}; bar +0.10)") print(f"PRE-REGISTERED VERDICT: {verdict}") out["_rule"] = dict(cleared=cleared, win100_moved=bool(w100_ok), win400_rose=bool(w400_up), pairs_complete=len(pairs_done), inside_own_ctrl=inside, horizon_exhausted=bool(null), best=best, best_d=D[best]["mean"], verdict=verdict)json.dump(out, open(ROOT / "_edgeX_matched.json", "w"), indent=1, default=float)print("-> status/real/_edgeX_matched.json")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141"""#278 run 25: rung Y -- COMPOSITION DEPTH. The chain's beta, the one standard-practice scoreraxis every edge measurement to date left PINNED at 0.99.
ONE factor moves off the rung-W control. Proposer (pi0.5 RISE rise_s0/29999), label GOAL_EPISODE(0.294 pos share, R_XL_ft_v0/ckpt_s110000.pt -- the best arm at every rung), gamma 0.999, flow 8,N=128, 16 particles, S0 anchors, seed 0 and the same 25 held-out episodes stay pinned, so both betaarms have an ALREADY-MEASURED matched control (status/real/_edgeW_matched.json): edge_W_goalep_g999, beta 0.99 = +0.0741[+0.0324,+0.1229], AUC_w 0.709 vs perm 0.512, 40.0% ceil.
THE NUMBER THAT CHOSE IT: rung X fired its pre-registered clause (d) -- every gamma 0.9995 armlanded INSIDE its own gamma 0.999 interval (goalep +0.0741 -> +0.0569, win400 +0.0546 -> +0.0670,win100 -0.0516 -> -0.0526, goalseg -0.0629 -> -0.0472), `horizon_exhausted: true`. So the HORIZONaxis is done. beta is a DIFFERENT axis: gamma sets how far the read-out looks, beta sets how manyCOMPOSITION steps the walk takes to get there -- and composition is the property this test claimsto measure. It has never been varied here.
THE DESIGN HOLDS THE HORIZON FIXED AND VARIES ONLY THE NUMBER OF HOPS IT IS BUILT FROM. Withp = (g-b)/(g(1-b)), E[extra hops] = p/(1-p), E[model reads] = 1/(1-p), frames/hop = b/(1-b),E[total frames] = g/(1-g) -- at gamma 0.999 that last term is 999 for EVERY beta: beta 0.99 (control) p 0.9009 E[extra] 9.1 E[reads] 10.1 99 frames/hop cap 67 beta 0.98 p 0.9510 E[extra] 19.4 E[reads] 20.4 49 frames/hop cap 138 beta 0.95 p 0.9810 E[extra] 51.6 E[reads] 52.6 19 frames/hop cap 360so a difference between these arms is composition depth and nothing else.
IN THE TRAINED RANGE, CHECKED ON THE CHECKPOINT ITSELF: R_XL_ft_v0/ckpt_s110000.pt carriesbeta_lo 0.95, beta_hi 0.99, beta_q 0.98, beta_trunc_eps 0.02, chunk 8. Both arms are inside it;nothing below 0.95 is run (an out-of-range beta is a defect, not a data point).
PRE-REGISTERED RUNG-Y RULE (written and committed BEFORE any Y part was read): (a) EITHER beta arm >= +0.10 -> BAR CLEARED; write the configuration into configs/baselines.yaml and rise_stack/EDGE_TEST.md with the numbers, post the passing table, close #278. (b) EITHER beta arm ABOVE the control's upper bound (+0.1229) -> composition depth IS a lever; report the beta that wins and carry it to the GOAL_WINDOW_400 label (the other arm that a horizon change moved) before anything else. (c) BOTH arms BELOW the control's lower bound (+0.0324) -> deeper composition HURTS monotonically: each extra hop compounds the successor's off-manifold error (the stay-put gate 0.5596 already says its samples sit farther from the data than staying put), which LOCALISES the loss to the chain's DEPTH rather than its horizon or its label. Publishable, and it says the next fix is the successor's sample quality, not any knob of the read-out. (d) BOTH arms INSIDE the control's interval -> the beta axis is FLAT over 9.1 -> 51.6 hops: composition depth does not matter to this metric, the standard-practice ladder on this test is EXHAUSTED, and the negative gets written with its localised cause and #278 closed."""import sys, jsonimport numpy as npsys.path.insert(0, "/proj/dmfexp/zwhong/rsm_rise/scripts/real")from pathlib import Pathfrom edge_report import load_dirfrom edge_field import summarise_anchorsimport edge_ceiling2 as C
ROOT = Path("/proj/dmfexp/zwhong/rsm_rise/status/real")CTRL = "edge_W_goalep_g999"# arm dir -> (beta, p, E[extra hops], E[model reads], frames/hop, cap)ARMS = [(CTRL, 0.99, 0.9009, 9.1, 10.1, 99, 67), ("edge_Y_goalep_b98", 0.98, 0.9510, 19.4, 20.4, 49, 138), ("edge_Y_goalep_b95", 0.95, 0.9810, 51.6, 52.6, 19, 360)]GATE = 0.5596 # stay-put gate of the GOAL_EPISODE successor, fixed by constructionBEST_TO_DATE = ("edge_T_rise", 0.0909) # R_XL s100000, GOAL_EPISODE, gamma 0.995; bar is +0.10
def stats(recs): modes = sorted({m for x in recs for m in x["scores"]}) s = summarise_anchors(recs, modes, seed=0, n_boot=2000)["states"].get("S0", {}) sr = s.get("scorers", {}).get("rsm", {}) return dict(n=s.get("n_anchors"), cov=s.get("coverage"), dg=sr.get("delta_vs_greedy", {}), dp=sr.get("delta_vs_permuted", {}), rank=sr.get("onroute_rank_pct", {}))
def f(d): return f"{d['mean']:+.4f}[{d['lo']:+.4f},{d['hi']:+.4f}]"
def read(a): recs = load_dir(ROOT / a) if not recs: return None A = stats(recs) c = C.arm(str(ROOT / a)) need = (c["auc_perm"]["weighted"] + 0.10 / c["d_ceiling"] * (1.0 - c["auc_perm"]["weighted"]) if c["d_ceiling"] else float("nan")) pct = 100.0 * A["dg"]["mean"] / c["d_ceiling"] if c["d_ceiling"] else float("nan") return dict(episodes=sorted({int(r["episode"]) for r in recs}), arm=A, ceiling=c, auc_w_needed=need, pct_of_ceiling=pct)
out = {}hdr = (f"{'beta hops reads cap':22s} {'gate':>6s} {'eps':>3s} {'anc':>4s} {'cov':>5s} {'wbar':>5s} | " f"{'d_vs_greedy':>24s} {'d_vs_permuted':>24s} | {'AUCw':>6s} {'prm':>5s} {'need':>5s} {'%ceil':>7s}")print("=== rung Y: COMPOSITION DEPTH at fixed horizon (gamma 0.999, GOAL_EPISODE, RISE proposer) ===")print(hdr); print("-" * len(hdr))for a, beta, p, extra, reads, fph, cap in ARMS: r = read(a) if r is None: print(f"{beta:<5.2f} {extra:5.1f} {reads:6.1f} {cap:4d} -- no parts yet ({a})") continue out[a] = dict(beta=beta, p=p, e_extra_hops=extra, e_reads=reads, frames_per_hop=fph, cap=cap, gate=GATE, is_control=(a == CTRL), **r) c, A = r["ceiling"], r["arm"] print(f"{beta:<5.2f} {extra:5.1f} {reads:6.1f} {cap:4d} {GATE:6.4f} {len(r['episodes']):3d} " f"{c['n_anchors']:4d} {A['cov']:5.3f} {c['w_mean']:5.3f} | {f(A['dg']):>24s} {f(A['dp']):>24s} | " f"{c['auc_rsm']['weighted']:6.3f} {c['auc_perm']['weighted']:5.3f} " f"{r['auc_w_needed']:5.3f} {r['pct_of_ceiling']:6.1f}%" + (" <- CONTROL (rung W, beta 0.99)" if a == CTRL else ""))
# --- the pre-registered rule, evaluated mechanically -------------------------------------------D = {a: v["arm"]["dg"] for a, v in out.items()}if CTRL in D and len(D) > 1: lo, hi = D[CTRL]["lo"], D[CTRL]["hi"] beta_arms = [a for a in D if a != CTRL] cleared = [a for a in beta_arms if D[a]["mean"] >= 0.10] above = [a for a in beta_arms if D[a]["mean"] > hi] below = [a for a in beta_arms if D[a]["mean"] < lo] inside = [a for a in beta_arms if lo <= D[a]["mean"] <= hi] complete = len(beta_arms) == len(ARMS) - 1 monotone_down = complete and len(below) == len(beta_arms) flat = complete and len(inside) == len(beta_arms) best = max(D, key=lambda a: D[a]["mean"]) verdict = ("(a) BAR CLEARED by " + ",".join(cleared) if cleared else "(c) deeper composition HURTS monotonically -- both beta arms below the control's " "lower bound; the loss localises to the chain's DEPTH (off-manifold error compounding " "per hop), not its horizon or its label" if monotone_down else "(d) the beta axis is FLAT over 9.1 -> 51.6 hops: composition depth does not move this " "metric and the standard-practice ladder on this test is EXHAUSTED" if flat else "(b) composition depth IS a lever -- " + ",".join(above) + " above the control's upper bound" if above else f"partial: {len(beta_arms)}/{len(ARMS)-1} beta arms read, no clause fires yet") print() print(f"control edge_W_goalep_g999 (beta 0.99) = {f(D[CTRL])}") print(f"beta arms complete: {len(beta_arms)}/{len(ARMS)-1} above {hi:+.4f}: {above} " f"below {lo:+.4f}: {below} inside: {inside}") print(f"best arm overall = {best} d = {D[best]['mean']:+.4f} " f"(best cell measured to date {BEST_TO_DATE[0]} {BEST_TO_DATE[1]:+.4f}; bar +0.10)") print(f"PRE-REGISTERED VERDICT: {verdict}") out["_rule"] = dict(control=CTRL, ctrl_lo=lo, ctrl_hi=hi, cleared=cleared, above=above, below=below, inside_own_ctrl=inside, arms_complete=len(beta_arms), depth_hurts=bool(monotone_down), beta_axis_flat=bool(flat), best=best, best_d=D[best]["mean"], verdict=verdict)json.dump(out, open(ROOT / "_edgeY_matched.json", "w"), indent=1, default=float)print("-> status/real/_edgeY_matched.json")gen_q_rsm/rsm_rise/pipeline/scripts/launch_e1_grid.pyAdded+521
gen_q_rsm/rsm_rise/pipeline/scripts/launch_flagship_topup.pyAdded+299
gen_q_rsm/rsm_rise/pipeline/scripts/launch_hopfam_on_actor.pyAdded+67
gen_q_rsm/rsm_rise/pipeline/scripts/launch_ifql.pyAdded+238
gen_q_rsm/rsm_rise/pipeline/scripts/launch_lewm_on_actor.pyAdded+89
gen_q_rsm/rsm_rise/pipeline/scripts/launch_problog_on_actor.pyAdded+171
gen_q_rsm/rsm_rise/pipeline/scripts/launch_readout_on_actor.pyAdded+76
gen_q_rsm/rsm_rise/pipeline/scripts/launch_rsm_on_actor.pyAdded+186
gen_q_rsm/rsm_rise/pipeline/scripts/launch_tdflow_on_actor.pyAdded+168
gen_q_rsm/rsm_rise/pipeline/scripts/launch_temp_on_actor.pyAdded+94
gen_q_rsm/rsm_rise/pipeline/scripts/lewm_gate.shAdded+54
gen_q_rsm/rsm_rise/pipeline/scripts/lewm_smoke.shAdded+47
gen_q_rsm/rsm_rise/pipeline/scripts/master_table.pyAdded+1189
gen_q_rsm/rsm_rise/pipeline/scripts/mc_target_spread.pyAdded+69
gen_q_rsm/rsm_rise/pipeline/scripts/parity_sweep.pyAdded+106
gen_q_rsm/rsm_rise/pipeline/scripts/problog_table.pyAdded+195
gen_q_rsm/rsm_rise/pipeline/scripts/problog_watcher.shAdded+34
gen_q_rsm/rsm_rise/pipeline/scripts/real/build_2x2_table.pyAdded+45
gen_q_rsm/rsm_rise/pipeline/scripts/real/build_decisive_tables.pyAdded+244
gen_q_rsm/rsm_rise/pipeline/scripts/real/build_real_report_tables.pyAdded+270
gen_q_rsm/rsm_rise/pipeline/scripts/real/build_reward_study2.pyAdded+199
gen_q_rsm/rsm_rise/pipeline/scripts/real/build_reward_tables.pyAdded+276
gen_q_rsm/rsm_rise/pipeline/scripts/real/build_successor_tables.pyAdded+232
gen_q_rsm/rsm_rise/pipeline/scripts/real/cam_dlt.pyAdded+307
gen_q_rsm/rsm_rise/pipeline/scripts/real/cam_dump_frames.pyAdded+77
gen_q_rsm/rsm_rise/pipeline/scripts/real/decisive_reward.pyAdded+197
gen_q_rsm/rsm_rise/pipeline/scripts/real/destiny_route_split.pyAdded+65
gen_q_rsm/rsm_rise/pipeline/scripts/real/destiny_test.pyAdded+324
gen_q_rsm/rsm_rise/pipeline/scripts/real/dirdump_screen.shAdded+25
gen_q_rsm/rsm_rise/pipeline/scripts/real/edge_AD_read.pyAdded+337
gen_q_rsm/rsm_rise/pipeline/scripts/real/edge_AH_read.pyAdded+256
gen_q_rsm/rsm_rise/pipeline/scripts/real/edge_AJ_read.pyAdded+222
gen_q_rsm/rsm_rise/pipeline/scripts/real/edge_arrival_check.pyAdded+88
gen_q_rsm/rsm_rise/pipeline/scripts/real/edge_candidate_gate.pyAdded+79
gen_q_rsm/rsm_rise/pipeline/scripts/real/edge_ceiling2.pyAdded+128
gen_q_rsm/rsm_rise/pipeline/scripts/real/edge_ceiling_route.pyAdded+118
gen_q_rsm/rsm_rise/pipeline/scripts/real/edge_dirfig.pyAdded+204
gen_q_rsm/rsm_rise/pipeline/scripts/real/edge_field.pyAdded+283
gen_q_rsm/rsm_rise/pipeline/scripts/real/edge_field_validate.pyAdded+173
gen_q_rsm/rsm_rise/pipeline/scripts/real/edge_flip_audit.pyAdded+306
gen_q_rsm/rsm_rise/pipeline/scripts/real/edge_goalbound_auc.pyAdded+246
gen_q_rsm/rsm_rise/pipeline/scripts/real/edge_interaction_AA.pyAdded+98
gen_q_rsm/rsm_rise/pipeline/scripts/real/edge_matched_AA.pyAdded+123
gen_q_rsm/rsm_rise/pipeline/scripts/real/edge_matched_AB.pyAdded+183
gen_q_rsm/rsm_rise/pipeline/scripts/real/edge_matched_AC.pyAdded+135
gen_q_rsm/rsm_rise/pipeline/scripts/real/edge_matched_U.pyAdded+93
gen_q_rsm/rsm_rise/pipeline/scripts/real/edge_matched_V.pyAdded+110
gen_q_rsm/rsm_rise/pipeline/scripts/real/edge_matched_W.pyAdded+132
gen_q_rsm/rsm_rise/pipeline/scripts/real/edge_matched_X.pyAdded+136
gen_q_rsm/rsm_rise/pipeline/scripts/real/edge_matched_Y.pyAdded+141