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
- gen_q_rsm/rsm_rise/pipeline/scripts/launch_e1_grid.py +521 -0
- gen_q_rsm/rsm_rise/pipeline/scripts/launch_flagship_topup.py +299 -0
- gen_q_rsm/rsm_rise/pipeline/scripts/launch_hopfam_on_actor.py +67 -0
- gen_q_rsm/rsm_rise/pipeline/scripts/launch_ifql.py +238 -0
- gen_q_rsm/rsm_rise/pipeline/scripts/launch_lewm_on_actor.py +89 -0
- gen_q_rsm/rsm_rise/pipeline/scripts/launch_problog_on_actor.py +171 -0
- gen_q_rsm/rsm_rise/pipeline/scripts/launch_readout_on_actor.py +76 -0
- gen_q_rsm/rsm_rise/pipeline/scripts/launch_rsm_on_actor.py +186 -0
- gen_q_rsm/rsm_rise/pipeline/scripts/launch_tdflow_on_actor.py +168 -0
- gen_q_rsm/rsm_rise/pipeline/scripts/launch_temp_on_actor.py +94 -0
- gen_q_rsm/rsm_rise/pipeline/scripts/lewm_gate.sh +54 -0
- gen_q_rsm/rsm_rise/pipeline/scripts/lewm_smoke.sh +47 -0
- gen_q_rsm/rsm_rise/pipeline/scripts/master_table.py +1189 -0
- gen_q_rsm/rsm_rise/pipeline/scripts/mc_target_spread.py +69 -0
- gen_q_rsm/rsm_rise/pipeline/scripts/parity_sweep.py +106 -0
- gen_q_rsm/rsm_rise/pipeline/scripts/problog_table.py +195 -0
- gen_q_rsm/rsm_rise/pipeline/scripts/problog_watcher.sh +34 -0
- gen_q_rsm/rsm_rise/pipeline/scripts/real/build_2x2_table.py +45 -0
- gen_q_rsm/rsm_rise/pipeline/scripts/real/build_decisive_tables.py +244 -0
- gen_q_rsm/rsm_rise/pipeline/scripts/real/build_real_report_tables.py +270 -0
- gen_q_rsm/rsm_rise/pipeline/scripts/real/build_reward_study2.py +199 -0
- gen_q_rsm/rsm_rise/pipeline/scripts/real/build_reward_tables.py +276 -0
- gen_q_rsm/rsm_rise/pipeline/scripts/real/build_successor_tables.py +232 -0
- gen_q_rsm/rsm_rise/pipeline/scripts/real/cam_dlt.py +307 -0
- gen_q_rsm/rsm_rise/pipeline/scripts/real/cam_dump_frames.py +77 -0
- gen_q_rsm/rsm_rise/pipeline/scripts/real/decisive_reward.py +197 -0
- gen_q_rsm/rsm_rise/pipeline/scripts/real/destiny_route_split.py +65 -0
- gen_q_rsm/rsm_rise/pipeline/scripts/real/destiny_test.py +324 -0
- gen_q_rsm/rsm_rise/pipeline/scripts/real/dirdump_screen.sh +25 -0
- gen_q_rsm/rsm_rise/pipeline/scripts/real/edge_AD_read.py +337 -0
- gen_q_rsm/rsm_rise/pipeline/scripts/real/edge_AH_read.py +256 -0
- gen_q_rsm/rsm_rise/pipeline/scripts/real/edge_AJ_read.py +222 -0
- gen_q_rsm/rsm_rise/pipeline/scripts/real/edge_arrival_check.py +88 -0
- gen_q_rsm/rsm_rise/pipeline/scripts/real/edge_candidate_gate.py +79 -0
- gen_q_rsm/rsm_rise/pipeline/scripts/real/edge_ceiling2.py +128 -0
- gen_q_rsm/rsm_rise/pipeline/scripts/real/edge_ceiling_route.py +118 -0
- gen_q_rsm/rsm_rise/pipeline/scripts/real/edge_dirfig.py +204 -0
- gen_q_rsm/rsm_rise/pipeline/scripts/real/edge_field.py +283 -0
- gen_q_rsm/rsm_rise/pipeline/scripts/real/edge_field_validate.py +173 -0
- gen_q_rsm/rsm_rise/pipeline/scripts/real/edge_flip_audit.py +306 -0
- gen_q_rsm/rsm_rise/pipeline/scripts/real/edge_goalbound_auc.py +246 -0
- gen_q_rsm/rsm_rise/pipeline/scripts/real/edge_interaction_AA.py +98 -0
- gen_q_rsm/rsm_rise/pipeline/scripts/real/edge_matched_AA.py +123 -0
- gen_q_rsm/rsm_rise/pipeline/scripts/real/edge_matched_AB.py +183 -0
- gen_q_rsm/rsm_rise/pipeline/scripts/real/edge_matched_AC.py +135 -0
- gen_q_rsm/rsm_rise/pipeline/scripts/real/edge_matched_U.py +93 -0
- gen_q_rsm/rsm_rise/pipeline/scripts/real/edge_matched_V.py +110 -0
- gen_q_rsm/rsm_rise/pipeline/scripts/real/edge_matched_W.py +132 -0
- gen_q_rsm/rsm_rise/pipeline/scripts/real/edge_matched_X.py +136 -0
- gen_q_rsm/rsm_rise/pipeline/scripts/real/edge_matched_Y.py +141 -0
gen_q_rsm/rsm_rise/pipeline/scripts/launch_e1_grid.py
ADDED
|
@@ -0,0 +1,521 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Launch the rsm_rise E1 evaluation grid (best-of-N planning over pi_beta with an RSM scorer) on LSF.
|
| 3 |
+
|
| 4 |
+
One cell = one eval of one pi_beta seed checkpoint with one planner configuration; its result is
|
| 5 |
+
runs/<task>/eval/<cell>.json (scripts/eval_cell.sh -> scripts/eval.py, exp.results_json). Cells whose JSON
|
| 6 |
+
already exists are skipped (resubmit-missing pattern); `--pack K` runs K cells sequentially in one GPU job.
|
| 7 |
+
|
| 8 |
+
Cell names E1-<model>-R<beta>-<L>[-rec]-N<n>-<rule>-s<seed> e.g. E1-M-R0.95-2-N64-argmax-s0
|
| 9 |
+
E1-<model>-R<beta>-<L>-N<n>-<rule>-s<seed> with rule in {argmax, softmax0.05, softmax0.2, topk8,
|
| 10 |
+
random, permuted}; controls: BC-s<seed> (plan_n=1), S3H4-N64-s<seed> (IQL critic of an S0A ckpt).
|
| 11 |
+
|
| 12 |
+
Usage (see --help):
|
| 13 |
+
launch_e1_grid.py --task square_expert_play --env robomimic_square_coverage \
|
| 14 |
+
--model M=runs/square_expert_play/rsm/M/ckpt_best.pt:mlp \
|
| 15 |
+
--model L40=runs/square_expert_play/rsm/L40/ckpt_best.pt:mlp \
|
| 16 |
+
--model DWM=runs/square_expert_play/rsm/DWM/ckpt_best.pt:dwm \
|
| 17 |
+
--hop runs/square_expert_play/hop/gauss/policy_r1.pt \
|
| 18 |
+
--policy s0=runs/square_expert_play/policy/S0B_seed0 --policy s1=... --policy s2=... \
|
| 19 |
+
--s0a s0=runs/square_expert_play/policy/S0A_seed0 ... \
|
| 20 |
+
--grid a b c controls --pack 4 --queue preemptable [--dry-run] [--print-only]
|
| 21 |
+
|
| 22 |
+
--grid a : full factorial on the first --model (16 read-outs x N{8,16,64,128,256} x rules{argmax,softmax0.05,
|
| 23 |
+
softmax0.2,topk8} x seeds)
|
| 24 |
+
--grid b : models x read-outs at N=--n-primary (128) argmax (all --model entries after the first; --b-all-models: all)
|
| 25 |
+
--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)
|
| 26 |
+
--grid d : N x rule at --best "<model>:<beta>:<L>" (repeatable), the E1 winner of L40/DWM
|
| 27 |
+
--grid controls : BC (plan_n=1), S3H2 random, S3H3 permuted, S3H4 IQL critic (needs --s0a), all at N=--n-primary;
|
| 28 |
+
--mc <blob> adds S3H5 (MC critic)
|
| 29 |
+
--cells : explicit cell specs "model,beta,L,mode,n,rule,seed" (comma-separated, repeatable) for ad-hoc runs
|
| 30 |
+
"""
|
| 31 |
+
from __future__ import annotations
|
| 32 |
+
|
| 33 |
+
import argparse
|
| 34 |
+
import itertools
|
| 35 |
+
import json
|
| 36 |
+
import os
|
| 37 |
+
import re
|
| 38 |
+
import shlex
|
| 39 |
+
import subprocess
|
| 40 |
+
import sys
|
| 41 |
+
from pathlib import Path
|
| 42 |
+
|
| 43 |
+
ROOT = Path("/proj/dmfexp/zwhong/rsm_rise")
|
| 44 |
+
BETAS = (0.90, 0.95, 0.98, 0.99)
|
| 45 |
+
DEPTHS = (1, 2, 3, 4)
|
| 46 |
+
REC_BETAS = (0.90, 0.95, 0.98)
|
| 47 |
+
REC_DEPTHS = (2, 3)
|
| 48 |
+
N_LIST = (8, 16, 64, 128, 256) # 128 = RISE's released eval setting (critic argmax over 128 samples); 64 = paper
|
| 49 |
+
RULES = ("argmax", "softmax0.05", "softmax0.2", "topk8")
|
| 50 |
+
ENV_OF = {"square_expert_play": "robomimic_square_coverage", "mug_expert_suboptimal": "robomimic_mug",
|
| 51 |
+
"square_expert_suboptimal": "robomimic_square",
|
| 52 |
+
# orchestrator 15:38: paper-regime square suboptimal (20 expert + 80 suboptimal, no augmentation);
|
| 53 |
+
# same eval env as the released-file task, its own runs/ tree so the numbers never mix.
|
| 54 |
+
"square_sub_paper": "robomimic_square",
|
| 55 |
+
"square_sub_paper2": "robomimic_square",
|
| 56 |
+
"square_sub_20100": "robomimic_square",
|
| 57 |
+
# orchestrator 17:16: the released HDF5s hold more demos than Table IV, so every task gets a
|
| 58 |
+
# <task>_paper sibling subsampled to the Table IV amounts (stream A builds the files). The eval env
|
| 59 |
+
# is the same as the released-file task it comes from -- only the TRAINING data differs.
|
| 60 |
+
"threading_expert_play": "robomimic_threading_coverage",
|
| 61 |
+
"threading_paper": "robomimic_threading_coverage",
|
| 62 |
+
"mug_paper": "robomimic_mug",
|
| 63 |
+
"two_piece_expert_suboptimal": "robomimic_three_piece_assembly_top_right",
|
| 64 |
+
"piecesub_paper": "robomimic_three_piece_assembly_top_right",
|
| 65 |
+
# FIXED 2026-09-19 05:10 (stream D). This read `_top_right` -- the EXPERT's own quadrant
|
| 66 |
+
# (p0) -- which is the one thing a COVERAGE eval must not be: the whole point of the play/
|
| 67 |
+
# coverage task is that p_test = the whole table while the expert data lives in the top-right.
|
| 68 |
+
# stream A settled this in status/A_env_stage0.md:500 ("Piece1 x,y in [-0.22,0.22] = whole
|
| 69 |
+
# table = p_test; expert p0 = top right"), scripts/all_init_region.py agrees, and
|
| 70 |
+
# launch_stage0_evals.sh:52 always used the stock config -- so the grids disagreed with the
|
| 71 |
+
# policy evals and every two_piece_expert_play planner cell was measured on p0. The value
|
| 72 |
+
# below was almost certainly copied from the two_piece_expert_SUBOPTIMAL line above, whose
|
| 73 |
+
# top-right eval IS correct (the paper evaluates the suboptimal tasks from p0).
|
| 74 |
+
"two_piece_expert_play": "robomimic_three_piece_assembly",
|
| 75 |
+
"two_piece_expert_play_tipping": "robomimic_three_piece_assembly_tipped",
|
| 76 |
+
"piecetip_paper": "robomimic_three_piece_assembly_tipped"}
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def _busy_cells(out_dir):
|
| 80 |
+
"""Cells owned by a PEND/RUN LSF job right now.
|
| 81 |
+
|
| 82 |
+
Since eval.py resumes from `<cell>.json.partial`, two concurrent jobs on the same cell would interleave
|
| 83 |
+
writes to the same resume state and pool each other's episodes. The grid skips finished cells by JSON,
|
| 84 |
+
which is not enough for a cell that is merely *running*, so the owning job's script (jobs/<jname>.sh,
|
| 85 |
+
which carries one `exp.eval_cell=<name>` per packed cell) is consulted as well. --force overrides.
|
| 86 |
+
"""
|
| 87 |
+
try:
|
| 88 |
+
r = subprocess.run(["bjobs", "-o", "stat job_name", "-noheader"],
|
| 89 |
+
capture_output=True, text=True, timeout=120)
|
| 90 |
+
except Exception:
|
| 91 |
+
return set()
|
| 92 |
+
busy = set()
|
| 93 |
+
for line in r.stdout.splitlines():
|
| 94 |
+
f = line.split()
|
| 95 |
+
if len(f) < 2 or f[0] not in ("PEND", "RUN", "PSUSP", "USUSP", "SSUSP"):
|
| 96 |
+
continue
|
| 97 |
+
sh = Path(out_dir) / "jobs" / f"{f[1]}.sh"
|
| 98 |
+
if sh.is_file():
|
| 99 |
+
txt = sh.read_text()
|
| 100 |
+
busy.update(re.findall(r"exp\.eval_cell=(\S+)", txt))
|
| 101 |
+
_BUSY_ARMS.update(_arm_keys(txt))
|
| 102 |
+
return busy
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
# Semantic keys of the cells inside live jobs, for the different-TAG duplicate warning below.
|
| 106 |
+
_BUSY_ARMS = {}
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def _arm_key(line):
|
| 110 |
+
"""What a cell MEASURES, independent of the --tag its name carries.
|
| 111 |
+
|
| 112 |
+
(policy checkpoint, eval seed, plan_n, rule, backend) is the whole measurement for a control arm: the
|
| 113 |
+
eval seed fixes the init states and the checkpoint fixes the policy, so two cells agreeing on these
|
| 114 |
+
replay the same episodes no matter what they are called.
|
| 115 |
+
"""
|
| 116 |
+
def g(pat, default=None):
|
| 117 |
+
m = re.search(pat, line)
|
| 118 |
+
return m.group(1) if m else default
|
| 119 |
+
# The policy checkpoint reaches eval_cell.sh as a POSITIONAL argument, not as `ckpt=` -- matching on
|
| 120 |
+
# `ckpt=` found it only on S3H4 lines (where it doubles as `training.rsm_ckpt`), so three cells of every
|
| 121 |
+
# four-cell control job were invisible to the duplicate check. Match the path itself.
|
| 122 |
+
pol = g(r"(/\S*/policy/\S+\.pth)")
|
| 123 |
+
if pol is None:
|
| 124 |
+
return None
|
| 125 |
+
n, rule = g(r"\bplan_n=(\d+)"), g(r"\bplan_rule=(\S+)", "argmax")
|
| 126 |
+
# Everything else the planner was configured with, so two cells of one (beta, L) grid are never called
|
| 127 |
+
# duplicates of each other. Collected generically -- a knob added later (plan_rescore_top,
|
| 128 |
+
# plan_temperature, plan_lcb_quantile, ...) enters the key without touching this function.
|
| 129 |
+
knobs = frozenset((k, v) for k, v in re.findall(r"\b(?:training\.)?((?:plan|rsm)_[a-z_]+)=(\S+)", line)
|
| 130 |
+
if k not in ("plan_n", "plan_rule"))
|
| 131 |
+
# The value function is part of the measurement -- the RISE flagship (rsm_backend=iql) and an RSM cell
|
| 132 |
+
# on the same policy share (n, rule) but rank with different critics, so the backend and the successor
|
| 133 |
+
# checkpoint must be in the key or the two get called duplicates of each other. They drop OUT of the key
|
| 134 |
+
# when nothing is ranked (plan_n=1) or when the rule is `random`, because the scorer is then never built
|
| 135 |
+
# -- so a `random-of-N` control launched from the M grid and one from the L40 grid ARE duplicates.
|
| 136 |
+
inert = rule == "random" or n in (None, "1")
|
| 137 |
+
backend = "-" if inert else g(r"\b(?:plan|rsm)_backend=(\S+)", "rsm")
|
| 138 |
+
vf = "-" if inert else g(r"\brsm_ckpt=(\S+)", "-")
|
| 139 |
+
# The IQL critic (the RISE flagship) is a single-step Q over (obs, action): the successor knobs on its
|
| 140 |
+
# command line (plan_particles, plan_score, plan_beta, ...) are carried by the launcher but never read,
|
| 141 |
+
# so two flagship cells that differ only there are the same 100 episodes under two tags.
|
| 142 |
+
return (pol, g(r"\beval_seed=(\d+)"), n, rule, backend, vf,
|
| 143 |
+
frozenset() if inert or backend == "iql" else knobs)
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
def _arm_keys(txt):
|
| 147 |
+
"""{arm key: cell name} for every cell in one job script."""
|
| 148 |
+
out = {}
|
| 149 |
+
for line in txt.splitlines():
|
| 150 |
+
m = re.search(r"exp\.eval_cell=(\S+)", line)
|
| 151 |
+
k = _arm_key(line) if m else None
|
| 152 |
+
if k is not None:
|
| 153 |
+
out[k] = m.group(1)
|
| 154 |
+
return out
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
def _excl_hosts(a):
|
| 158 |
+
"""Hosts whose MuJoCo/EGL renderer SIGABRTs (exit 134, no traceback), to keep out of select[].
|
| 159 |
+
|
| 160 |
+
The failure is host-correlated, not cell-correlated: as of 17:25 the blacklist holds 36 hosts and one of
|
| 161 |
+
them (p4-r09-n3) alone ate 22 eval cells. List regenerated by scripts/eval_host_stats.sh --write, which
|
| 162 |
+
now counts rr_e1_* cells as well as stream A's rr_ev_* policy evals. RR_EXCL_HOSTS overrides the file;
|
| 163 |
+
--no-excl-hosts turns the mechanism off.
|
| 164 |
+
"""
|
| 165 |
+
if getattr(a, "no_excl_hosts", False):
|
| 166 |
+
return []
|
| 167 |
+
env = os.environ.get("RR_EXCL_HOSTS")
|
| 168 |
+
if env is not None:
|
| 169 |
+
return env.split()
|
| 170 |
+
f = ROOT / "status" / "bad_eval_hosts.txt"
|
| 171 |
+
return f.read_text().split() if f.is_file() else []
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
def _res(a):
|
| 175 |
+
sel = " && ".join(f"hname!='{h}'" for h in _excl_hosts(a))
|
| 176 |
+
return (f"select[{sel}] " if sel else "") + f"rusage[mem={a.mem}]"
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
def _abs(p):
|
| 180 |
+
"""eval_cell.sh cd's into code/rise_code before scripts/eval.py runs, so every path override must be absolute."""
|
| 181 |
+
return str(Path(p).expanduser().resolve()) if p else p
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
def rule_overrides(rule):
|
| 185 |
+
if rule.startswith("softmax"):
|
| 186 |
+
return {"plan_rule": "softmax", "plan_temp": float(rule[len("softmax"):])}
|
| 187 |
+
if rule.startswith("topk"):
|
| 188 |
+
return {"plan_rule": "topk_uniform", "plan_topk": int(rule[len("topk"):])}
|
| 189 |
+
return {"plan_rule": rule}
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
def readout_overrides(beta, L, mode):
|
| 193 |
+
# COIN CHAIN (gen_q#267): in chain mode `L` is not a fold depth, it is the TRUNCATION CAP, and it is
|
| 194 |
+
# passed through as plan_chain_cap so the cell name and the run can never disagree. The launcher
|
| 195 |
+
# computes it with rsm_scorer.chain_cap(beta, gamma) -- it is never hard-coded, and a value that is not
|
| 196 |
+
# the computed cap only ever appears when the cap itself is being swept. plan_depth is meaningless
|
| 197 |
+
# here and is pinned to 1 so a stale depth cannot leak into the read-out.
|
| 198 |
+
if mode in ("chain", "chain_rb"):
|
| 199 |
+
return {"plan_mode": mode, "plan_depth": 1, "plan_beta": float(beta),
|
| 200 |
+
"plan_chain_cap": int(L)}
|
| 201 |
+
return {"plan_mode": mode, "plan_depth": int(L), "plan_beta": float(beta)}
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
def seed_tag(seed):
|
| 205 |
+
"""seed labels may be given as 0/1/2 or s0/s1/s2; cells always end in -s<k>."""
|
| 206 |
+
s = str(seed)
|
| 207 |
+
return s if s.startswith("s") else f"s{s}"
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
def cell_name(model, beta, L, mode, n, rule, seed, tag=""):
|
| 211 |
+
"""tag (--tag) is inserted before the seed so that otherwise identical read-outs that differ only in an
|
| 212 |
+
--extra override (particles, plan_score, temperature, ...) land in different JSONs."""
|
| 213 |
+
# The chain gets its OWN tag so the loader can never confuse a chain cell with a fold cell of the same
|
| 214 |
+
# (model, beta, number). Extending the key, not reusing the fold's, is the point (owner 2026-09-22).
|
| 215 |
+
rec = {"recursive": "-rec", "chain": "-ch", "chain_rb": "-chrb"}.get(mode, "")
|
| 216 |
+
t = f"-{tag}" if tag else ""
|
| 217 |
+
return f"E1-{model}-R{beta:.2f}-{L}{rec}-N{n}-{rule}{t}-{seed_tag(seed)}"
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
class Grid:
|
| 221 |
+
def __init__(self, a):
|
| 222 |
+
self.a = a
|
| 223 |
+
self.models = {} # name -> (path, backend)
|
| 224 |
+
for m in a.model:
|
| 225 |
+
name, rest = m.split("=", 1)
|
| 226 |
+
parts = rest.split(":")
|
| 227 |
+
self.models[name] = (parts[0], parts[1] if len(parts) > 1 else "mlp")
|
| 228 |
+
self.policies = {k: _abs(v) for k, v in (p.split("=", 1) for p in a.policy)} # seed label -> S0B ckpt/dir
|
| 229 |
+
self.s0a = {k: _abs(v) for k, v in (p.split("=", 1) for p in (a.s0a or []))}
|
| 230 |
+
self.seeds = sorted(self.policies)
|
| 231 |
+
self.tag = a.tag or ""
|
| 232 |
+
self.cells = {} # name -> dict(overrides)
|
| 233 |
+
|
| 234 |
+
def tagged(self, base, seed):
|
| 235 |
+
"""control-cell names: <base>[-<tag>]-s<seed>"""
|
| 236 |
+
t = f"-{self.tag}" if self.tag else ""
|
| 237 |
+
return f"{base}{t}-{seed_tag(seed)}"
|
| 238 |
+
|
| 239 |
+
def add(self, name, overrides, seed, backend_model=None):
|
| 240 |
+
if name in self.cells:
|
| 241 |
+
return
|
| 242 |
+
ov = dict(overrides)
|
| 243 |
+
ov["policy"] = self.policies[seed]
|
| 244 |
+
self.cells[name] = ov
|
| 245 |
+
|
| 246 |
+
def model_ov(self, model):
|
| 247 |
+
path, backend = self.models[model]
|
| 248 |
+
ov = {"rsm_backend": backend, "rsm_ckpt": _abs(path), "rsm_feat_stats": str(ROOT / "cache" / self.a.task / "feat_stats.npz")}
|
| 249 |
+
if self.a.hop:
|
| 250 |
+
ov["rsm_hop_ckpt"] = _abs(self.a.hop)
|
| 251 |
+
return ov
|
| 252 |
+
|
| 253 |
+
def e1(self, model, beta, L, mode, n, rule, seed):
|
| 254 |
+
ov = {"plan_n": n, **rule_overrides(rule), **readout_overrides(beta, L, mode), **self.model_ov(model)}
|
| 255 |
+
self.add(cell_name(model, beta, L, mode, n, rule, seed, self.tag), ov, seed)
|
| 256 |
+
|
| 257 |
+
def grid_a(self):
|
| 258 |
+
model = list(self.models)[0]
|
| 259 |
+
for beta, L, n, rule, seed in itertools.product(BETAS, DEPTHS, N_LIST, RULES, self.seeds):
|
| 260 |
+
self.e1(model, beta, L, "d1" if L == 1 else "fold", n, rule, seed)
|
| 261 |
+
|
| 262 |
+
def grid_b(self):
|
| 263 |
+
models = list(self.models)[1:] if not self.a.b_all_models else list(self.models)
|
| 264 |
+
for model in models:
|
| 265 |
+
for beta, L, seed in itertools.product(BETAS, DEPTHS, self.seeds):
|
| 266 |
+
self.e1(model, beta, L, "d1" if L == 1 else "fold", self.a.n_primary, "argmax", seed)
|
| 267 |
+
|
| 268 |
+
def grid_c(self):
|
| 269 |
+
for model, (_, backend) in self.models.items():
|
| 270 |
+
if backend == "dwm":
|
| 271 |
+
continue
|
| 272 |
+
for beta, L, seed in itertools.product(REC_BETAS, REC_DEPTHS, self.seeds):
|
| 273 |
+
self.e1(model, beta, L, "recursive", self.a.n_primary, "argmax", seed)
|
| 274 |
+
|
| 275 |
+
def grid_d(self):
|
| 276 |
+
for best in self.a.best or []:
|
| 277 |
+
model, beta, L = best.split(":")
|
| 278 |
+
beta, L = float(beta), int(L)
|
| 279 |
+
for n, rule, seed in itertools.product(N_LIST, RULES, self.seeds):
|
| 280 |
+
if n == self.a.n_primary and rule == "argmax":
|
| 281 |
+
continue # already in b
|
| 282 |
+
self.e1(model, beta, L, "d1" if L == 1 else "fold", n, rule, seed)
|
| 283 |
+
|
| 284 |
+
def controls(self):
|
| 285 |
+
model = list(self.models)[0]
|
| 286 |
+
beta, L = self.a.primary_beta, self.a.primary_depth
|
| 287 |
+
mode = "d1" if L == 1 else "fold"
|
| 288 |
+
want = self.a.controls_subset
|
| 289 |
+
for seed in self.seeds:
|
| 290 |
+
if "bc" in want:
|
| 291 |
+
self.add(self.tagged("BC", seed), {"plan_n": 1}, seed)
|
| 292 |
+
if "random" in want:
|
| 293 |
+
self.e1(model, beta, L, mode, self.a.n_primary, "random", seed) # S3H2
|
| 294 |
+
if "permuted" in want:
|
| 295 |
+
self.e1(model, beta, L, mode, self.a.n_primary, "permuted", seed) # S3H3
|
| 296 |
+
if seed in self.s0a and "s3h4" in want: # S3H4: the paper's IDQL best-of-64
|
| 297 |
+
self.add(self.tagged(f"S3H4-N{self.a.n_primary}", seed), {"plan_n": self.a.n_primary, "plan_rule": "argmax", "rsm_backend": "iql",
|
| 298 |
+
"rsm_ckpt": self.s0a[seed]}, seed)
|
| 299 |
+
|
| 300 |
+
def s3h5(self):
|
| 301 |
+
if not self.a.mc:
|
| 302 |
+
return
|
| 303 |
+
for seed in self.seeds:
|
| 304 |
+
self.add(self.tagged(f"S3H5-N{self.a.n_primary}", seed),
|
| 305 |
+
{"plan_n": self.a.n_primary, "plan_rule": "argmax", "rsm_backend": "mc", "rsm_ckpt": _abs(self.a.mc),
|
| 306 |
+
"rsm_feat_stats": str(ROOT / "cache" / self.a.task / "feat_stats.npz")}, seed)
|
| 307 |
+
|
| 308 |
+
def explicit(self):
|
| 309 |
+
for spec in self.a.cells or []:
|
| 310 |
+
model, beta, L, mode, n, rule, seed = spec.split(",")
|
| 311 |
+
self.e1(model, float(beta), int(L), mode, int(n), rule, seed)
|
| 312 |
+
|
| 313 |
+
|
| 314 |
+
def hydra_overrides(ov):
|
| 315 |
+
out = []
|
| 316 |
+
for k, v in ov.items():
|
| 317 |
+
if k == "policy":
|
| 318 |
+
continue
|
| 319 |
+
if isinstance(v, bool):
|
| 320 |
+
v = str(v)
|
| 321 |
+
out.append(f"training.{k}={v}")
|
| 322 |
+
return out
|
| 323 |
+
|
| 324 |
+
|
| 325 |
+
# INERT-KNOB GUARD (2026-09-21). A whole 54-cell temperature sweep was spent on `training.plan_temp` -- the
|
| 326 |
+
# softmax-RULE temperature on Qbar, read only when plan_rule=softmax -- when the sigmoid read-out T that
|
| 327 |
+
# c_k = sigma(R(z_k)/T) uses is `training.plan_temperature`. Every cell ran at the checkpoint default and
|
| 328 |
+
# was a duplicate of the arm it was meant to vary; it was caught only because two settings produced
|
| 329 |
+
# bit-identical tie counts. Hydra accepts any `training.*` key the config defines, so the config cannot
|
| 330 |
+
# reject it. This guard refuses, before a single job is submitted, (a) a `training.plan_*` override that is
|
| 331 |
+
# not a real planner field and (b) the small set of fields that are inert under the rule the cells use.
|
| 332 |
+
# It is in the CONSUMER of --extra (this script), not in each launcher, so a new launcher inherits it.
|
| 333 |
+
_PLAN_INERT_UNDER = {"plan_temp": ("softmax",), "plan_topk": ("topk_uniform", "topk")}
|
| 334 |
+
|
| 335 |
+
|
| 336 |
+
def _check_extra(a):
|
| 337 |
+
import ast as _ast, re as _re
|
| 338 |
+
# The field set is read by AST, NOT by import: `import robomimic.algo.rsm_planner` needs torch +
|
| 339 |
+
# torchvision, which exist in the JOB env and not on the submit host, so an import-based guard
|
| 340 |
+
# silently degraded to "accept everything" -- the same silent no-op it exists to prevent. A guard
|
| 341 |
+
# that cannot establish its reference must fail, so an unreadable source is an error here.
|
| 342 |
+
_src = ROOT / "code/rise_robomimic/robomimic/algo/rsm_planner.py"
|
| 343 |
+
known = set()
|
| 344 |
+
for _n in _ast.walk(_ast.parse(_src.read_text())):
|
| 345 |
+
if isinstance(_n, _ast.Assign) and any(
|
| 346 |
+
getattr(t, "id", "") in ("PLANNER_DEFAULTS", "ADV_DEFAULTS") for t in _n.targets):
|
| 347 |
+
v = _n.value
|
| 348 |
+
known |= {kw.arg for kw in getattr(v, "keywords", []) if kw.arg}
|
| 349 |
+
known |= {k.value for k in getattr(v, "keys", []) or [] if isinstance(k, _ast.Constant)}
|
| 350 |
+
if not any(k.startswith("plan_") for k in known):
|
| 351 |
+
raise SystemExit(f"launch_e1_grid: cannot read planner fields from {_src}; refusing to submit "
|
| 352 |
+
"rather than accept any --extra unchecked")
|
| 353 |
+
rules = {c.split(",")[5] for c in (a.cells or []) if len(c.split(",")) > 5}
|
| 354 |
+
modes = {c.split(",")[3] for c in (a.cells or []) if len(c.split(",")) > 3}
|
| 355 |
+
bad = []
|
| 356 |
+
# Same lesson as the plan_temp sweep, for the coin chain: in chain mode the read-out's only length
|
| 357 |
+
# parameter is the CAP (plan_chain_cap). plan_depth is carried and never read, so a "depth sweep" on
|
| 358 |
+
# chain cells would be 4 bit-identical duplicates of one arm. Refuse it before it is submitted.
|
| 359 |
+
if modes and modes <= {"chain", "chain_rb"}:
|
| 360 |
+
for ov in a.extra:
|
| 361 |
+
if _re.match(r"^training\.plan_depth=", ov):
|
| 362 |
+
bad.append("plan_depth: INERT in chain mode (the chain's length parameter is the cap, "
|
| 363 |
+
"training.plan_chain_cap) -- the sweep would duplicate one arm")
|
| 364 |
+
for ov in a.extra:
|
| 365 |
+
m = _re.match(r"^training\.(plan_[A-Za-z0-9_]+)=", ov)
|
| 366 |
+
if not m:
|
| 367 |
+
continue
|
| 368 |
+
f = m.group(1)
|
| 369 |
+
if known is not None and f not in known:
|
| 370 |
+
bad.append(f"{f}: not a planner field (nearest: "
|
| 371 |
+
f"{sorted(k for k in known if k[:9] == f[:9])[:4]})")
|
| 372 |
+
continue
|
| 373 |
+
need = _PLAN_INERT_UNDER.get(f)
|
| 374 |
+
if need and rules and not (rules & set(need)):
|
| 375 |
+
bad.append(f"{f}: read only when plan_rule in {need}, but these cells use {sorted(rules)} "
|
| 376 |
+
f"-- it would be INERT and the sweep would silently duplicate one arm")
|
| 377 |
+
if bad:
|
| 378 |
+
raise SystemExit("launch_e1_grid: refusing to submit, inert/unknown --extra override(s):\n "
|
| 379 |
+
+ "\n ".join(bad))
|
| 380 |
+
|
| 381 |
+
|
| 382 |
+
def main():
|
| 383 |
+
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
| 384 |
+
ap.add_argument("--task", required=True)
|
| 385 |
+
ap.add_argument("--env", default=None, help="hydra env config; default from the task")
|
| 386 |
+
ap.add_argument("--model", action="append", default=[], help="NAME=path[:backend] (first = grid a's model)")
|
| 387 |
+
ap.add_argument("--hop", default="", help="hop head policy_r1.pt (needed for L>=2)")
|
| 388 |
+
ap.add_argument("--policy", action="append", default=[], help="SEED=S0B checkpoint (.pth or run dir)")
|
| 389 |
+
ap.add_argument("--s0a", action="append", default=[], help="SEED=S0A checkpoint for S3H4")
|
| 390 |
+
ap.add_argument("--grid", nargs="*", default=[], choices=["a", "b", "c", "d", "controls"])
|
| 391 |
+
ap.add_argument("--controls-subset", default="bc,random,permuted,s3h4",
|
| 392 |
+
type=lambda v: {x.strip().lower() for x in v.split(",") if x.strip()},
|
| 393 |
+
help="which --grid controls rows to emit (bc,random,permuted,s3h4)")
|
| 394 |
+
ap.add_argument("--best", action="append", default=[], help="grid d: MODEL:beta:L")
|
| 395 |
+
ap.add_argument("--cells", action="append", default=[], help="explicit cells model,beta,L,mode,n,rule,seed")
|
| 396 |
+
ap.add_argument("--n-primary", type=int, default=128, help="N of grids b/c and the controls (128 = RISE eval setting)")
|
| 397 |
+
ap.add_argument("--b-all-models", action="store_true", help="grid b on every --model (default: all but the first)")
|
| 398 |
+
ap.add_argument("--mc", default="", help="MC critic blob for S3H5 (scripts/mc_critic.py) -> S3H5-N<n>-s<k> cells")
|
| 399 |
+
ap.add_argument("--primary-beta", type=float, default=0.95)
|
| 400 |
+
ap.add_argument("--primary-depth", type=int, default=2)
|
| 401 |
+
ap.add_argument("--num-rollouts", type=int, default=100)
|
| 402 |
+
ap.add_argument("--horizon", type=int, default=400, help="exp.rollout_horizon (eval_cell.sh default 400)")
|
| 403 |
+
ap.add_argument("--eval-seed", type=int, default=0)
|
| 404 |
+
ap.add_argument("--extra", nargs="*", default=[], help="extra hydra overrides for every cell")
|
| 405 |
+
ap.add_argument("--tag", default="", help="name tag inserted before -s<seed> in every cell name; use it "
|
| 406 |
+
"whenever --extra changes the recipe (e.g. --tag P4096-logit)")
|
| 407 |
+
ap.add_argument("--pack", type=int, default=4, help="cells per GPU job (sequential)")
|
| 408 |
+
ap.add_argument("--queue", default="preemptable")
|
| 409 |
+
ap.add_argument("--no-excl-hosts", action="store_true",
|
| 410 |
+
help="do not exclude status/bad_eval_hosts.txt from select[] (see _excl_hosts)")
|
| 411 |
+
ap.add_argument("--group", default=None, help="LSF -G; default grp_preemptable for the preemptable queue, else grp_runtime")
|
| 412 |
+
ap.add_argument("--mem", default="64G")
|
| 413 |
+
ap.add_argument("--out-dir", default=None, help="default runs/<task>/eval")
|
| 414 |
+
ap.add_argument("--dry-run", action="store_true", help="print the bsub commands, submit nothing")
|
| 415 |
+
ap.add_argument("--print-only", action="store_true", help="list the cells and exit")
|
| 416 |
+
ap.add_argument("--force", action="store_true", help="resubmit cells whose JSON exists")
|
| 417 |
+
ap.add_argument("--max-jobs", type=int, default=0, help="submit at most this many jobs (0 = all)")
|
| 418 |
+
a = ap.parse_args()
|
| 419 |
+
_check_extra(a)
|
| 420 |
+
env = a.env or ENV_OF[a.task]
|
| 421 |
+
out_dir = Path(a.out_dir).resolve() if a.out_dir else ROOT / "runs" / a.task / "eval"
|
| 422 |
+
out_dir.mkdir(parents=True, exist_ok=True)
|
| 423 |
+
|
| 424 |
+
g = Grid(a)
|
| 425 |
+
for which in a.grid:
|
| 426 |
+
{"a": g.grid_a, "b": g.grid_b, "c": g.grid_c, "d": g.grid_d, "controls": g.controls}[which]()
|
| 427 |
+
g.s3h5()
|
| 428 |
+
g.explicit()
|
| 429 |
+
|
| 430 |
+
todo = []
|
| 431 |
+
busy = set() if a.force else _busy_cells(out_dir)
|
| 432 |
+
n_busy = 0
|
| 433 |
+
for name, ov in g.cells.items():
|
| 434 |
+
js = out_dir / f"{name}.json"
|
| 435 |
+
if js.exists() and not a.force:
|
| 436 |
+
continue
|
| 437 |
+
if name in busy:
|
| 438 |
+
n_busy += 1
|
| 439 |
+
continue
|
| 440 |
+
todo.append((name, ov, js))
|
| 441 |
+
print(f"[launch_e1] {len(g.cells)} cells in the grid, {len(todo)} missing"
|
| 442 |
+
+ (f" ({n_busy} skipped: already PEND/RUN)" if n_busy else ""), file=sys.stderr)
|
| 443 |
+
|
| 444 |
+
# The busy check above matches on the cell NAME, which carries --tag -- so the SAME measurement launched
|
| 445 |
+
# under a second tag looks like a new cell and is submitted again. This is not hypothetical: on
|
| 446 |
+
# 2026-09-19 `BC-s0a-e5000-...-es0` and `S3H4-N128-s0a-e5000-...-es0` were queued on square play while a
|
| 447 |
+
# live packed job already held `BC-FLAG5000-es0-s0a` and `S3H4-N128-FLAG5000-es0-s0a` -- the same policy
|
| 448 |
+
# checkpoint, eval seed and rule, i.e. the same 100 episodes. Warn rather than skip: a deliberate
|
| 449 |
+
# re-measurement is legitimate, but it must not happen by accident.
|
| 450 |
+
for name, ov, js in todo:
|
| 451 |
+
line = " ".join(hydra_overrides(ov) + [f"eval_seed={a.eval_seed}", f"ckpt={ov['policy']}"])
|
| 452 |
+
k = _arm_key(line)
|
| 453 |
+
other = _BUSY_ARMS.get(k) if k else None
|
| 454 |
+
if other and other != name:
|
| 455 |
+
print(f"[launch_e1] WARNING {name} measures the same arm as the live cell {other} "
|
| 456 |
+
f"(same policy ckpt, eval seed {a.eval_seed}, rule) -- duplicate episodes, not new "
|
| 457 |
+
f"evidence. Use --force only if you mean to re-measure it.", file=sys.stderr)
|
| 458 |
+
if a.print_only:
|
| 459 |
+
# --extra MUST be printed too. It was omitted, so a dry run of the temperature sweep showed a
|
| 460 |
+
# command with no temperature in it at all and still looked correct; the one override that
|
| 461 |
+
# distinguished 54 cells from the flagship arm was the one the dry run hid.
|
| 462 |
+
for name, ov, js in todo:
|
| 463 |
+
print(name, " ".join([*hydra_overrides(ov), *a.extra]))
|
| 464 |
+
return
|
| 465 |
+
|
| 466 |
+
log_dir = ROOT / "logs" / "lsf"
|
| 467 |
+
log_dir.mkdir(parents=True, exist_ok=True)
|
| 468 |
+
jobs = 0
|
| 469 |
+
for i in range(0, len(todo), max(a.pack, 1)):
|
| 470 |
+
chunk = todo[i:i + max(a.pack, 1)]
|
| 471 |
+
lines = ["#!/usr/bin/env bash", "set -uo pipefail", f"cd {ROOT}", "rc_all=0",
|
| 472 |
+
f"mkdir -p {shlex.quote(str(out_dir / 'logs'))}",
|
| 473 |
+
"echo \"[launch_e1] host=$(hostname) job=${LSB_JOBID:-none} gpu=$(nvidia-smi --query-gpu=name,memory.used --format=csv,noheader | head -1)\""]
|
| 474 |
+
for name, ov, js in chunk:
|
| 475 |
+
cmd = [str(ROOT / "scripts" / "eval_cell.sh"), a.task, ov["policy"], env, str(js),
|
| 476 |
+
f"exp.num_rollouts={a.num_rollouts}", f"exp.rollout_horizon={a.horizon}",
|
| 477 |
+
f"exp.eval_seed={a.eval_seed}", f"exp.eval_cell={name}", f"exp.eval_task={a.task}",
|
| 478 |
+
*hydra_overrides(ov), *a.extra]
|
| 479 |
+
q = shlex.quote
|
| 480 |
+
log = out_dir / "logs" / f"{name}.log"
|
| 481 |
+
# one cell: run, tee to a per-cell log. On failure the per-episode partial is KEPT (eval_cell.sh
|
| 482 |
+
# moves it to <js>.partial_best and eval.py resumes from it on the next attempt -- LSF reruns
|
| 483 |
+
# preempted jobs, `-r` below), only the atomic-write .tmp is cleaned up. OOM is reported explicitly.
|
| 484 |
+
lines.append(
|
| 485 |
+
f"if [ -f {q(str(js))} ]; then echo \"[launch_e1] {name} exists, skip\"; else\n"
|
| 486 |
+
f" {' '.join(q(c) for c in cmd)} 2>&1 | tee {q(str(log))}; rc=${{PIPESTATUS[0]}}\n"
|
| 487 |
+
f" if [ -f {q(str(js))} ]; then python {ROOT}/scripts/wandb_log_eval.py {q(str(js))} || true\n"
|
| 488 |
+
f" else rm -f {q(str(js) + '.tmp')}; rc_all=${{rc:-1}}\n"
|
| 489 |
+
f" if grep -qE \"CUDA out of memory|CUDA error|cudaErrorMemoryAllocation\" {q(str(log))}; then "
|
| 490 |
+
f"echo \"[launch_e1] CUDA OOM/error in {name} (rc=$rc) -> partial removed, resubmit\"; "
|
| 491 |
+
f"nvidia-smi --query-gpu=memory.used,memory.total --format=csv,noheader; "
|
| 492 |
+
f"else echo \"[launch_e1] {name} FAILED rc=$rc -> partial removed\"; fi\n"
|
| 493 |
+
f" fi\nfi")
|
| 494 |
+
lines.append("exit $rc_all")
|
| 495 |
+
script = "\n".join(lines) + "\n"
|
| 496 |
+
first = chunk[0][0]
|
| 497 |
+
jname = f"rr_e1_{a.task}_{first}" + (f"_p{len(chunk)}" if len(chunk) > 1 else "")
|
| 498 |
+
sh = out_dir / "jobs" / f"{jname}.sh"
|
| 499 |
+
sh.parent.mkdir(parents=True, exist_ok=True)
|
| 500 |
+
sh.write_text(script)
|
| 501 |
+
sh.chmod(0o755)
|
| 502 |
+
group = a.group or ("grp_preemptable" if a.queue == "preemptable" else "grp_runtime")
|
| 503 |
+
# -Q "EXCLUDE(99)": eval_cell.sh exits 99 to mean "this HOST is unusable for me" (EGL 0x8cdd,
|
| 504 |
+
# repeated read_pixels SIGABRT, CUDA-unknown-error at init). bsub_gpu.sh has always passed it;
|
| 505 |
+
# this launcher did not, so every such cell simply DIED instead of being requeued elsewhere
|
| 506 |
+
# (stream D 08:2x UTC: jobs 1781538/1781540, both on p2-r03-n1, exit 99 after 58 s).
|
| 507 |
+
bsub = ["bsub", "-G", group, "-q", a.queue, "-gpu", "num=1:j_exclusive=yes:mode=shared", "-n", "8", "-M", a.mem,
|
| 508 |
+
"-R", _res(a), "-r", "-Q", "EXCLUDE(99)", "-J", jname,
|
| 509 |
+
"-o", str(log_dir / f"{jname}.%J.out"), "-e", str(log_dir / f"{jname}.%J.err"), str(sh)]
|
| 510 |
+
print(" ".join(shlex.quote(c) for c in bsub))
|
| 511 |
+
if not a.dry_run:
|
| 512 |
+
subprocess.run(bsub, check=False)
|
| 513 |
+
jobs += 1
|
| 514 |
+
if a.max_jobs and jobs >= a.max_jobs:
|
| 515 |
+
break
|
| 516 |
+
print(f"[launch_e1] {jobs} jobs {'would be ' if a.dry_run else ''}submitted "
|
| 517 |
+
f"({len(todo)} cells, pack {a.pack}, queue {a.queue})", file=sys.stderr)
|
| 518 |
+
|
| 519 |
+
|
| 520 |
+
if __name__ == "__main__":
|
| 521 |
+
main()
|
gen_q_rsm/rsm_rise/pipeline/scripts/launch_flagship_topup.py
ADDED
|
@@ -0,0 +1,299 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Top up the FLAGSHIP arms of docs/MASTER_TABLE.md to 3 training seeds x 3 eval seeds.
|
| 3 |
+
|
| 4 |
+
The flagship admits the best matched-reward arm whatever its seed count (user 2026-09-20: "for flagship we
|
| 5 |
+
can admit the best numbers and config if seed needs to be refilled -- we top up"), so the rows that carry
|
| 6 |
+
the paper's claim are exactly the rows that must be filled in. This driver takes ONE arm per task -- the
|
| 7 |
+
arm the table is currently reporting -- and submits only the (policy seed, eval seed) cells that are
|
| 8 |
+
missing, skipping anything a live job already owns.
|
| 9 |
+
|
| 10 |
+
The arm identity is (successor ckpt, beta, depth, N, proposer family); pooling in verdict_table.cells() is
|
| 11 |
+
by that identity plus the policy checkpoint, NOT by cell name or directory, so a top-up cell pools with the
|
| 12 |
+
originals no matter which --tag or --out-dir it lands in.
|
| 13 |
+
|
| 14 |
+
usage: launch_flagship_topup.py [task ...] [--print-only] [--queue preemptable]
|
| 15 |
+
"""
|
| 16 |
+
import argparse, glob, json, math, os, re, subprocess, sys
|
| 17 |
+
from pathlib import Path
|
| 18 |
+
|
| 19 |
+
ROOT = Path("/proj/dmfexp/zwhong/rsm_rise")
|
| 20 |
+
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
| 21 |
+
POLF = {"BC-unified": "S0B", "BC-expert": "S3H1", "RISE policy": "S0A", "IDQL policy": "S0Aidql"}
|
| 22 |
+
POLF_INV = POLF
|
| 23 |
+
|
| 24 |
+
# task -> (env config, model label, rsm ckpt, beta, depth, proposer family)
|
| 25 |
+
# The env MUST be the one the task's canonical region declares, or verdict_table drops every new cell:
|
| 26 |
+
# square_expert_play -> the OOD box (user: "by default use robomimic square image ood")
|
| 27 |
+
# two_piece_expert_play-> the WHOLE TABLE (the _top_right launcher bug, fixed 2026-09-19)
|
| 28 |
+
# two_piece_expert_suboptimal -> top_right IS correct; the paper evaluates suboptimal from p0
|
| 29 |
+
# EVALUATION ENVIRONMENT per task. This stays explicit because it is a CORRECTNESS constraint that is
|
| 30 |
+
# not derivable from the arm: verdict_table drops every cell measured outside the task's canonical
|
| 31 |
+
# region, so a top-up launched into the wrong env silently produces nothing the table will read.
|
| 32 |
+
# square_expert_play -> the OOD box (user: "by default use robomimic square image ood")
|
| 33 |
+
# two_piece_expert_play -> the WHOLE TABLE (the _top_right launcher bug, fixed 2026-09-19)
|
| 34 |
+
# two_piece_expert_suboptimal -> top_right IS correct; the paper evaluates suboptimal from p0
|
| 35 |
+
ENVS = {
|
| 36 |
+
"square_sub_20100": "robomimic_square",
|
| 37 |
+
"square_expert_play": "robomimic_square_image_ood",
|
| 38 |
+
"two_piece_expert_suboptimal": "robomimic_three_piece_assembly_top_right",
|
| 39 |
+
"two_piece_expert_play": "robomimic_three_piece_assembly",
|
| 40 |
+
"mug_expert_suboptimal": "robomimic_mug",
|
| 41 |
+
"threading_expert_play": "robomimic_threading_coverage",
|
| 42 |
+
"two_piece_expert_play_tipping": "robomimic_three_piece_assembly_tipped",
|
| 43 |
+
# rsm_rise #267: MimicGen-generated variants (same eval envs as the released rows they replace)
|
| 44 |
+
"mug_mgen": "robomimic_mug",
|
| 45 |
+
"threading_mgen": "robomimic_threading_coverage",
|
| 46 |
+
}
|
| 47 |
+
# Cell names encode BOTH the successor model and WHICH checkpoint of it, matching the names already on
|
| 48 |
+
# disk (Mb = M@best, Ms1b = M_s1@best, L40b = L40@best, Ms100k = M@s100000). Labelling an
|
| 49 |
+
# `M@s100000` arm "Mb" would name the cell after ckpt_best while pointing at ckpt_s100000 -- the path
|
| 50 |
+
# is passed explicitly so it would still evaluate correctly, but the JSON would be misfiled for anyone
|
| 51 |
+
# reading cell names later.
|
| 52 |
+
BASE_LABEL = {"M": "M", "M_s1": "Ms1", "M_s2": "Ms2", "L40": "L40", "L40_s1": "L40s1"}
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def _ck_suffix(ck):
|
| 56 |
+
if ck == "best":
|
| 57 |
+
return "b"
|
| 58 |
+
m = re.fullmatch(r"s(\d+)", ck)
|
| 59 |
+
if m and int(m.group(1)) % 1000 == 0:
|
| 60 |
+
return f"s{int(m.group(1)) // 1000}k"
|
| 61 |
+
return ck
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
# READ-OUT SCOPE (gen_q#267, 2026-09-23). This launcher SPENDS GPU: it nominates under-seeded arms
|
| 65 |
+
# and runs them at 3x3. It pooled every `rsm:membership` arm at any read-out, so it kept seeding arms
|
| 66 |
+
# of the RETIRED deterministic fold -- 9 cells each for an estimator that appears only in the paper's
|
| 67 |
+
# ablation table. Chain-only by default, matching the column the flagship prints; set
|
| 68 |
+
# RSM_TOPUP_READOUT=any (or =fold) to seed the ablation deliberately.
|
| 69 |
+
import os as _os
|
| 70 |
+
_READOUT = _os.environ.get("RSM_TOPUP_READOUT", "chain")
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def _readout_ok(arm_str):
|
| 74 |
+
if _READOUT == "any":
|
| 75 |
+
return True
|
| 76 |
+
from flagship_latex import _recipe_is_chain as _isch
|
| 77 |
+
return _isch(arm_str) == (_READOUT == "chain")
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def _refuse(task, arm_str):
|
| 81 |
+
r"""THIS LAUNCHER CANNOT TOP UP A CHAIN ARM, AND MUST SAY SO (gen_q#267, found 2026-09-23 12:15Z).
|
| 82 |
+
|
| 83 |
+
The arm-key regex above matches only the fold grammar `b<beta> L<depth> N<n>`, and the cell spec it
|
| 84 |
+
emits hardcodes `mode = "d1" if depth == 1 else "fold"`. A coin-chain key
|
| 85 |
+
(`b0.95 CH33 N128 P16 prob`) therefore failed the match and was SILENTLY skipped -- so the only arms
|
| 86 |
+
this tool could ever seed were arms of the RETIRED estimator, while the flagship column it exists to
|
| 87 |
+
fill is chain-only.
|
| 88 |
+
|
| 89 |
+
It is deliberately NOT ported here: `launch_e1_grid.py --cells` takes
|
| 90 |
+
"model,beta,L,mode,n,rule,seed", which has no field for the chain's PARTICLE COUNT or its
|
| 91 |
+
prob/logit read-out. Emitting a chain cell through it would top up an arm with different
|
| 92 |
+
particles from the one the table reports -- a top-up of a different arm under the same name, which
|
| 93 |
+
is the exact failure this file's own docstring was written about. Chain top-ups go through
|
| 94 |
+
scripts/launch_rsm_on_actor.py, which carries those fields.
|
| 95 |
+
"""
|
| 96 |
+
print(f"### {task}: the reported arm {arm_str!r} is a COIN-CHAIN arm and this launcher only emits "
|
| 97 |
+
f"fold cells (its --cells grammar has no particle/read-out field, so it would seed a "
|
| 98 |
+
f"DIFFERENT arm under the same name). Use scripts/launch_rsm_on_actor.py for chain top-ups. "
|
| 99 |
+
f"Set RSM_TOPUP_READOUT=fold to work on the retired ablation arms instead.")
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def reported_arm(task):
|
| 103 |
+
"""The arm the TABLE reports: the plain maximum, with the deterministic (score, episodes) tie-break.
|
| 104 |
+
|
| 105 |
+
Kept separate from topup_target() on purpose. Conflating the two made the watcher print "mug 9/9"
|
| 106 |
+
while the table showed mug at one seed -- both true, about different arms, and impossible to read.
|
| 107 |
+
"""
|
| 108 |
+
from verdict_table import cells as _c, pool as _p, rate as _r
|
| 109 |
+
c = _c(task)
|
| 110 |
+
out = None
|
| 111 |
+
for (arm, prop) in sorted({(a, p) for (a, p, _, _) in c if a[0] == "rsm:membership"}):
|
| 112 |
+
if not _readout_ok(arm[1]):
|
| 113 |
+
continue
|
| 114 |
+
g = _p(c, lambda x, q, A=arm, P=prop: x == A and q == P)
|
| 115 |
+
sr, n_ = _r(g)
|
| 116 |
+
ns = len({ps for (_, ps, _) in g})
|
| 117 |
+
if out is None or (sr, n_) > (out[0], out[1]):
|
| 118 |
+
out = (sr, n_, ns, arm[1], prop)
|
| 119 |
+
return out
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
def top_arms(task, k):
|
| 123 |
+
"""The k best membership arms, as (rsm_ckpt, beta, depth, n, fam, label, arm_str, prop).
|
| 124 |
+
|
| 125 |
+
Topping up only the current maximum does not converge on a task whose arms are within noise of
|
| 126 |
+
each other: verifying the leader knocks it down, a different one-seed arm becomes the leader, and
|
| 127 |
+
the top-up starts over. Mug and threading cycled through four arms each this way. Bringing the
|
| 128 |
+
top k arms to three seeds each ends the cycle, because the eventual maximum is then taken over
|
| 129 |
+
arms that are all properly verified rather than over one-seed noise.
|
| 130 |
+
"""
|
| 131 |
+
from verdict_table import cells as _c, pool as _p, rate as _r
|
| 132 |
+
c = _c(task)
|
| 133 |
+
scored = []
|
| 134 |
+
for (arm, prop) in sorted({(a, p) for (a, p, _, _) in c if a[0] == "rsm:membership"}):
|
| 135 |
+
if not _readout_ok(arm[1]):
|
| 136 |
+
continue
|
| 137 |
+
g = _p(c, lambda x, q, A=arm, P=prop: x == A and q == P)
|
| 138 |
+
sr, n_ = _r(g)
|
| 139 |
+
scored.append((sr, n_, arm[1], prop))
|
| 140 |
+
scored.sort(key=lambda x: (-x[0], -x[1]))
|
| 141 |
+
out = []
|
| 142 |
+
for sr, n_, arm_str, prop in scored[:k]:
|
| 143 |
+
m = re.match(r"([A-Za-z0-9_]+)@(\S+) b([\d.]+) L(\d+) N(\d+)", arm_str)
|
| 144 |
+
if not m:
|
| 145 |
+
_refuse(task, arm_str)
|
| 146 |
+
continue
|
| 147 |
+
model, ck, beta, depth, nn = m.group(1), m.group(2), float(m.group(3)), int(m.group(4)), int(m.group(5))
|
| 148 |
+
out.append((f"runs/{task}/rsm/{model}/ckpt_{ck}.pt", beta, depth, nn,
|
| 149 |
+
POLF_INV[prop], BASE_LABEL.get(model, model) + _ck_suffix(ck), arm_str, prop))
|
| 150 |
+
return out
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
def topup_target(task):
|
| 154 |
+
"""The arm to top up: exactly the arm the TABLE reports.
|
| 155 |
+
|
| 156 |
+
An earlier version invested instead in whichever statistically-tied arm was nearest verification.
|
| 157 |
+
That converged, but it verified the WRONG arm: mug's table row (12.0%, one seed) and its top-up
|
| 158 |
+
target became different arms, so the number the paper would print had no path to three seeds while
|
| 159 |
+
compute went to an arm nobody would quote. The standing rule is the opposite -- admit the best
|
| 160 |
+
number and top IT up -- so the target is the reported arm, full stop.
|
| 161 |
+
|
| 162 |
+
The churn that motivated the sticky rule had a different cause and is fixed at its root: three mug
|
| 163 |
+
arms sat at exactly 12.0% and the argmax flipped on set-iteration order. reported_arm() iterates
|
| 164 |
+
sorted and breaks ties by (score, episodes), so identical data now always yields the same arm and
|
| 165 |
+
the target stops moving on its own.
|
| 166 |
+
|
| 167 |
+
-> (rsm_ckpt, beta, depth, n, proposer family, model label) or None
|
| 168 |
+
"""
|
| 169 |
+
rep = reported_arm(task)
|
| 170 |
+
if not rep:
|
| 171 |
+
return None
|
| 172 |
+
m = re.match(r"([A-Za-z0-9_]+)@(\S+) b([\d.]+) L(\d+) N(\d+)", rep[3])
|
| 173 |
+
if not m:
|
| 174 |
+
_refuse(task, rep[3])
|
| 175 |
+
return None
|
| 176 |
+
model, ck, beta, depth, n_ = m.group(1), m.group(2), float(m.group(3)), int(m.group(4)), int(m.group(5))
|
| 177 |
+
ckpt = f"runs/{task}/rsm/{model}/ckpt_{ck}.pt"
|
| 178 |
+
label = BASE_LABEL.get(model, model) + _ck_suffix(ck)
|
| 179 |
+
return ckpt, beta, depth, n_, POLF_INV[rep[4]], label, rep[3], rep[4]
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
def have(task, arm_str, prop):
|
| 183 |
+
"""{(policy seed, eval seed)} the TABLE accepts for this arm.
|
| 184 |
+
|
| 185 |
+
This used to glob runs/<task>/eval_*/*.json and match on the planner overrides directly, which
|
| 186 |
+
counted cells that verdict_table.cells() DISCARDS -- wrong evaluation region, wrong horizon, wrong
|
| 187 |
+
policy epoch, no episodes. Threading had nine such cells (run with SquareNut init bounds on a
|
| 188 |
+
threading task), so the driver reported 9/9 and launched nothing while the table, seeing only the
|
| 189 |
+
one valid cell, went on reporting a single-seed number that could never be topped up.
|
| 190 |
+
|
| 191 |
+
Counting through cells() makes the two agree by construction: "9/9" can only mean nine cells the
|
| 192 |
+
table actually reads.
|
| 193 |
+
"""
|
| 194 |
+
from verdict_table import cells as _c
|
| 195 |
+
got = set()
|
| 196 |
+
for (arm, pol, ps, es), v in _c(task).items():
|
| 197 |
+
if arm[0] != "rsm:membership" or arm[1] != arm_str or pol != prop or not v:
|
| 198 |
+
continue
|
| 199 |
+
got.add((ps, es))
|
| 200 |
+
return got
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
def ckpt(task, fam, seed, epoch=5000):
|
| 204 |
+
"""The saved checkpoint of family `fam`, seed `seed` at `epoch` (every family saves 500..5000 in steps of
|
| 205 |
+
500). Epoch became a proposer axis on 2026-09-21: the IDQL recipe on threading is a 28 % proposer at epoch
|
| 206 |
+
500 and a 13.8 % one at 5000, so a proposer is now (family, epoch), not family alone."""
|
| 207 |
+
g = sorted(glob.glob(str(ROOT / "runs" / task / "policy" / f"{fam}_seed{seed}" / "*" / "*" / "models" / f"model_epoch_{epoch}.pth")))
|
| 208 |
+
if g:
|
| 209 |
+
return g[0]
|
| 210 |
+
# ROLLING FALLBACK (2026-09-21). A sweep arm whose training stopped early keeps only
|
| 211 |
+
# rolling/model_epoch_<E>.pth (the last one written). Admit it so the arm can be screened at that
|
| 212 |
+
# epoch; the eval JSON records the exact path, and verdict_table reads the epoch from it, so a later
|
| 213 |
+
# overwrite of the rolling file can never be confused with this cell.
|
| 214 |
+
r = ROOT / "runs" / task / "policy" / f"{fam}_seed{seed}" / "rolling" / f"model_epoch_{epoch}.pth"
|
| 215 |
+
return str(r) if r.is_file() else None
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
def main():
|
| 219 |
+
ap = argparse.ArgumentParser()
|
| 220 |
+
ap.add_argument("tasks", nargs="*", default=[])
|
| 221 |
+
ap.add_argument("--print-only", action="store_true")
|
| 222 |
+
ap.add_argument("--queue", default="preemptable")
|
| 223 |
+
ap.add_argument("--rollouts", type=int, default=50)
|
| 224 |
+
ap.add_argument("--top-k", type=int, default=1,
|
| 225 |
+
help="top up the k best arms per task, not just the reported one. Use this on tasks "
|
| 226 |
+
"whose arms are within noise of each other, where verifying only the leader "
|
| 227 |
+
"never converges (see top_arms).")
|
| 228 |
+
ap.add_argument("--status", action="store_true",
|
| 229 |
+
help="print '<task>:<have>/9' for the CURRENT flagship arms and exit (submits nothing). "
|
| 230 |
+
"Progress must be reported against the arm the table is reporting NOW; a watcher "
|
| 231 |
+
"with its own copy of the arm list silently tracks a stale one once a recipe "
|
| 232 |
+
"sweep moves the flagship.")
|
| 233 |
+
a = ap.parse_args()
|
| 234 |
+
|
| 235 |
+
if a.status:
|
| 236 |
+
for task in (a.tasks or list(ENVS)):
|
| 237 |
+
rep = reported_arm(task)
|
| 238 |
+
arm = topup_target(task)
|
| 239 |
+
if not arm or not rep:
|
| 240 |
+
print(f"{task}: no membership arm yet")
|
| 241 |
+
continue
|
| 242 |
+
rsm, beta, depth, n_, fam, mlabel, arm_str, prop = arm
|
| 243 |
+
got = have(task, arm_str, prop)
|
| 244 |
+
same = rep[3] == f"{mlabel}" # cosmetic only; the two are compared by value below
|
| 245 |
+
print(f"{task}: TABLE {rep[0]:.1f}% ({rep[2]} seed(s), {rep[3]}) | "
|
| 246 |
+
f"TOPUP {len(got)}/9 cells on {mlabel} b{beta} L{depth} N{n_}"
|
| 247 |
+
+ ("" if rep[3].startswith(mlabel[:2]) else ""))
|
| 248 |
+
return
|
| 249 |
+
for task in (a.tasks or list(ENVS)):
|
| 250 |
+
env = ENVS[task]
|
| 251 |
+
if a.top_k > 1:
|
| 252 |
+
targets = top_arms(task, a.top_k)
|
| 253 |
+
else:
|
| 254 |
+
t0 = topup_target(task)
|
| 255 |
+
targets = [t0] if t0 else []
|
| 256 |
+
if not targets:
|
| 257 |
+
print(f"\n### {task}: no membership arm yet -- nothing to top up")
|
| 258 |
+
continue
|
| 259 |
+
for rsm, beta, depth, n_, fam, mlabel, arm_str, prop in targets:
|
| 260 |
+
if not (ROOT / rsm).is_file():
|
| 261 |
+
print(f"\n### {task}: arm references {rsm}, which is missing -- skipped")
|
| 262 |
+
continue
|
| 263 |
+
got = have(task, arm_str, prop)
|
| 264 |
+
want = {(pp, ee) for pp in (0, 1, 2) for ee in (0, 1, 2)}
|
| 265 |
+
miss = sorted(want - got)
|
| 266 |
+
print(f"\n### {task} {mlabel} b{beta} L{depth} N{n_} / {fam}")
|
| 267 |
+
print(f" have {len(got)}/9 missing {len(miss)}: {miss}")
|
| 268 |
+
if not miss:
|
| 269 |
+
continue
|
| 270 |
+
mode = "d1" if depth == 1 else "fold"
|
| 271 |
+
for es in sorted({e for _, e in miss}):
|
| 272 |
+
ps = sorted({pp for pp, ee in miss if ee == es})
|
| 273 |
+
pol, cells_ = [], []
|
| 274 |
+
for pp in ps:
|
| 275 |
+
ck_ = ckpt(task, fam, pp)
|
| 276 |
+
if not ck_:
|
| 277 |
+
print(f" SKIP pseed {pp}: no model_epoch_5000.pth")
|
| 278 |
+
continue
|
| 279 |
+
lab = f"{fam}s{pp}"
|
| 280 |
+
pol += ["--policy", f"{lab}={ck_}"]
|
| 281 |
+
cells_ += ["--cells", f"{mlabel},{beta},{depth},{mode},{n_},argmax,{lab}"]
|
| 282 |
+
if not cells_:
|
| 283 |
+
continue
|
| 284 |
+
cmd = [sys.executable, str(ROOT / "scripts" / "launch_e1_grid.py"),
|
| 285 |
+
"--task", task, "--env", env,
|
| 286 |
+
"--model", f"{mlabel}={ROOT/rsm}:mlp",
|
| 287 |
+
"--hop", str(ROOT / "runs" / task / "hop" / "gauss" / "policy_r1.pt"),
|
| 288 |
+
*pol, *cells_,
|
| 289 |
+
"--num-rollouts", str(a.rollouts), "--horizon", "400",
|
| 290 |
+
"--eval-seed", str(es), "--tag", f"FLAGTOPUP-es{es}",
|
| 291 |
+
"--out-dir", str(ROOT / "runs" / task / "eval_flagtopup"),
|
| 292 |
+
"--pack", "3", "--queue", a.queue]
|
| 293 |
+
if a.print_only:
|
| 294 |
+
cmd.append("--print-only")
|
| 295 |
+
subprocess.run(cmd, check=False)
|
| 296 |
+
|
| 297 |
+
|
| 298 |
+
if __name__ == "__main__":
|
| 299 |
+
main()
|
gen_q_rsm/rsm_rise/pipeline/scripts/launch_hopfam_on_actor.py
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Hop-head FAMILY control for the sim flagship arms that use depth > 1.
|
| 3 |
+
|
| 4 |
+
MOTIVATION CORRECTED (2026-09-21). This was launched on a reported ~56x fit gap between the `flow` and
|
| 5 |
+
`gauss` hop heads on the real cooking cache (sampled-action MSE 0.00042 vs 0.02352). That figure was a
|
| 6 |
+
step-3000 artefact -- gauss had simply not converged; by ~22.5k steps the two are within 1.3x (gauss 0.00028,
|
| 7 |
+
flow 0.00021), so gauss is NOT broken and the "a mis-sampling hop head degrades every multi-hop score"
|
| 8 |
+
argument does not apply to a converged gauss head. The control is still worth running, for the opposite
|
| 9 |
+
reason: the `fold` read-out chains the hop policy and every sim flagship arm with depth > 1 (piece Cov at 8
|
| 10 |
+
hops, piece Sub at 3, square Cov at 2, piece-tip at 8) has only ever been evaluated with `gauss`, a family we
|
| 11 |
+
never swept. If the two families agree, the depth curve reads as a property of the successor rather than of
|
| 12 |
+
hop-sample quality -- which is what we want to be able to say. 36 cells is cheap for turning an unswept axis
|
| 13 |
+
into a measured one.
|
| 14 |
+
|
| 15 |
+
usage: launch_hopfam_on_actor.py [--print-only]
|
| 16 |
+
"""
|
| 17 |
+
import subprocess
|
| 18 |
+
import sys
|
| 19 |
+
from pathlib import Path
|
| 20 |
+
|
| 21 |
+
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
| 22 |
+
from launch_flagship_topup import ENVS, BASE_LABEL, _ck_suffix, ckpt # noqa: E402
|
| 23 |
+
|
| 24 |
+
ROOT = Path("/proj/dmfexp/zwhong/rsm_rise")
|
| 25 |
+
# only the flagship arms whose read-out actually uses the hop head (depth > 1), and only where a flow head
|
| 26 |
+
# exists. square_sub_20100 has no flow head; mug and threading are depth 1, so their rows cannot move.
|
| 27 |
+
ARMS = {
|
| 28 |
+
"square_expert_play": ("L40", "best", 0.9, 2),
|
| 29 |
+
"two_piece_expert_suboptimal": ("M", "s100000", 0.9, 3),
|
| 30 |
+
"two_piece_expert_play": ("L40", "best", 0.95, 8),
|
| 31 |
+
"two_piece_expert_play_tipping": ("M", "best", 0.95, 8),
|
| 32 |
+
}
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def main():
|
| 36 |
+
dry = "--print-only" in sys.argv
|
| 37 |
+
for task, (model, ck, b, L) in ARMS.items():
|
| 38 |
+
hop = ROOT / f"runs/{task}/hop/flow/policy_r1.pt"
|
| 39 |
+
rsm = ROOT / f"runs/{task}/rsm/{model}/ckpt_{ck}.pt"
|
| 40 |
+
if not hop.is_file() or not rsm.is_file():
|
| 41 |
+
print(f"{task}: missing {'flow hop head' if not hop.is_file() else 'successor ckpt'}")
|
| 42 |
+
continue
|
| 43 |
+
lab = BASE_LABEL.get(model, model) + _ck_suffix(ck)
|
| 44 |
+
pol, cells = [], []
|
| 45 |
+
for p in (0, 1, 2):
|
| 46 |
+
c = ckpt(task, "S0A", p)
|
| 47 |
+
if not c:
|
| 48 |
+
continue
|
| 49 |
+
pol += ["--policy", f"S0As{p}={c}"]
|
| 50 |
+
cells += ["--cells", f"{lab},{b},{L},{'d1' if L == 1 else 'fold'},128,argmax,S0As{p}"]
|
| 51 |
+
if not cells:
|
| 52 |
+
print(f"{task}: no epoch-5000 S0A"); continue
|
| 53 |
+
for es in (0, 1, 2):
|
| 54 |
+
cmd = [sys.executable, str(ROOT / "scripts/launch_e1_grid.py"), "--task", task,
|
| 55 |
+
"--env", ENVS[task], "--model", f"{lab}={rsm}:mlp", "--hop", str(hop), *pol, *cells,
|
| 56 |
+
"--num-rollouts", "50", "--horizon", "400", "--eval-seed", str(es),
|
| 57 |
+
"--tag", f"HOPFLOW-es{es}", "--out-dir", str(ROOT / f"runs/{task}/eval_hopfam"),
|
| 58 |
+
"--pack", "3", "--queue", "preemptable"]
|
| 59 |
+
if dry:
|
| 60 |
+
cmd.append("--print-only")
|
| 61 |
+
r = subprocess.run(cmd, capture_output=True, text=True)
|
| 62 |
+
tail = [l for l in r.stderr.splitlines() if "jobs submitted" in l or "missing" in l]
|
| 63 |
+
print(f" {task} b{b} L{L} flow-hop es{es}:", tail[-1:] or r.stderr.strip()[-160:])
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
if __name__ == "__main__":
|
| 67 |
+
main()
|
gen_q_rsm/rsm_rise/pipeline/scripts/launch_ifql.py
ADDED
|
@@ -0,0 +1,238 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Launch the IFQL baseline of the flagship table -- training and both eval columns (gen_q#264).
|
| 3 |
+
|
| 4 |
+
IFQL = implicit flow Q-learning, the flow variant of IDQL: an unweighted flow-matching BC actor plus an
|
| 5 |
+
IQL expectile critic with an HL-Gauss two-hot value head, which at action time draws `num_samples` noises,
|
| 6 |
+
integrates the flow and takes the arg-max Q. The agent is the verbatim ogbench implementation, vendored
|
| 7 |
+
under code/ifql/impls; code/ifql/train_ifql.py supplies the rsm_rise loader and the fairness constants.
|
| 8 |
+
|
| 9 |
+
THE TWO COLUMNS, which never pool (verdict_table keys the arm by scorer AND proposer):
|
| 10 |
+
|
| 11 |
+
(a) `--eval-policy` IFQL AS PUBLISHED. Its own flow actor proposes 128 candidates and its own critic
|
| 12 |
+
picks one, one action per env step. Policy family `S0Aifql` -> verdict_table's "IFQL policy".
|
| 13 |
+
Runs through eval_cell.sh with exp.ifql_policy=True (eval.get_policy's IFQL branch).
|
| 14 |
+
|
| 15 |
+
(b) `--eval-critic` IFQL's CRITIC ON THE RISE ACTOR. The same critic ranks the 128 chunks the S0A
|
| 16 |
+
actor emits -- the single-actor comparison the flagship table is built on (compare
|
| 17 |
+
scripts/launch_rsm_on_actor.py, which is the same protocol with the RSM scorer). Policy family
|
| 18 |
+
`S0A` -> "RISE policy", scorer arm ("critic:ifql", "N=128"). Plain planner cells:
|
| 19 |
+
training.rsm_backend=ifql with the IFQL bundle as training.rsm_ckpt.
|
| 20 |
+
|
| 21 |
+
(b-controls) `--eval-controls` the same two controls every scorer column gets: `random` (ignore the
|
| 22 |
+
scores, pick a candidate at random) and `permuted` (identical scores, shuffled over candidates).
|
| 23 |
+
Both are attributed to the IFQL scorer, so the column is tested against ITS OWN controls.
|
| 24 |
+
|
| 25 |
+
FAIRNESS CONSTANTS, identical to every other column: N = 128 candidates per decision step, 3 policy
|
| 26 |
+
seeds x 3 eval seeds x 50 episodes, horizon 400, the task's canonical eval env (ENVS, imported from
|
| 27 |
+
launch_flagship_topup so the two can never drift), the binary data-provenance reward, and
|
| 28 |
+
exp.eval_seed driving both the env's initial conditions and the action draws. The critic seed is paired
|
| 29 |
+
with the actor seed (IFQL seed p ranks S0A seed p), matching how RISE's own critic is co-trained with its
|
| 30 |
+
actor, so the column carries three independent (actor, critic) pairs rather than one critic reused.
|
| 31 |
+
|
| 32 |
+
usage:
|
| 33 |
+
launch_ifql.py --train [task ...] # 7 x 3 GPU jobs, skips what exists
|
| 34 |
+
launch_ifql.py --eval-critic [task ...] # column (b)
|
| 35 |
+
launch_ifql.py --eval-policy [task ...] # column (a)
|
| 36 |
+
launch_ifql.py --eval-controls [task ...] # column (b)'s random / permuted controls
|
| 37 |
+
launch_ifql.py --status [task ...]
|
| 38 |
+
add --print-only to see the cells / commands without submitting anything.
|
| 39 |
+
"""
|
| 40 |
+
from __future__ import annotations
|
| 41 |
+
|
| 42 |
+
import argparse
|
| 43 |
+
import glob
|
| 44 |
+
import os
|
| 45 |
+
import subprocess
|
| 46 |
+
import sys
|
| 47 |
+
from pathlib import Path
|
| 48 |
+
|
| 49 |
+
ROOT = Path("/proj/dmfexp/zwhong/rsm_rise")
|
| 50 |
+
sys.path.insert(0, str(ROOT / "scripts"))
|
| 51 |
+
from launch_flagship_topup import ENVS, ckpt as policy_ckpt # noqa: E402
|
| 52 |
+
|
| 53 |
+
# Priority order (owner's instruction on gen_q#264).
|
| 54 |
+
TASKS = ["two_piece_expert_suboptimal", "two_piece_expert_play", "threading_expert_play",
|
| 55 |
+
"mug_expert_suboptimal", "square_expert_play", "two_piece_expert_play_tipping",
|
| 56 |
+
"square_sub_20100"]
|
| 57 |
+
SHORT = {"two_piece_expert_suboptimal": "piecesub", "two_piece_expert_play": "pieceplay",
|
| 58 |
+
"threading_expert_play": "threading", "mug_expert_suboptimal": "mug",
|
| 59 |
+
"square_expert_play": "squareplay", "two_piece_expert_play_tipping": "piecetip",
|
| 60 |
+
"square_sub_20100": "sq20100"}
|
| 61 |
+
SEEDS = (0, 1, 2)
|
| 62 |
+
ESEEDS = (0, 1, 2)
|
| 63 |
+
N = 128
|
| 64 |
+
# The IFQL critic is a single-step Q over (state, first action): the successor-model knobs below are
|
| 65 |
+
# carried by launch_e1_grid for every cell and are never read by the ifql backend (exactly as for the
|
| 66 |
+
# `iql` backend). They are pinned to one value so that two IFQL cells can never look like two
|
| 67 |
+
# different arms to launch_e1_grid's duplicate check.
|
| 68 |
+
BETA, DEPTH, MODE = 0.95, 1, "d1"
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def bundle(task, seed):
|
| 72 |
+
return ROOT / "runs" / task / "ifql" / f"s{seed}" / "ifql_bundle.pt"
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def published(task, seed):
|
| 76 |
+
"""The IFQL bundle where eval_cell.sh / verdict_table expect a policy checkpoint (rr_ifql.sh)."""
|
| 77 |
+
return ROOT / "runs" / task / "policy" / f"S0Aifql_seed{seed}" / "ifql" / "ifql" / "models" / "model_epoch_5000.pth"
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def live_jobs():
|
| 81 |
+
try:
|
| 82 |
+
r = subprocess.run(["bjobs", "-o", "stat job_name", "-noheader"], capture_output=True,
|
| 83 |
+
text=True, timeout=120)
|
| 84 |
+
except Exception:
|
| 85 |
+
return set()
|
| 86 |
+
out = set()
|
| 87 |
+
for line in r.stdout.splitlines():
|
| 88 |
+
f = line.split()
|
| 89 |
+
if len(f) >= 2 and f[0] in ("PEND", "RUN", "PSUSP", "USUSP", "SSUSP"):
|
| 90 |
+
out.add(f[1])
|
| 91 |
+
return out
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def train(tasks, dry):
|
| 95 |
+
busy = live_jobs()
|
| 96 |
+
n = 0
|
| 97 |
+
for task in tasks:
|
| 98 |
+
if not (ROOT / "cache" / task / "z.f16.npy").is_file():
|
| 99 |
+
print(f" {task}: no DINO cache (cache/{task}/z.f16.npy) -- skipped")
|
| 100 |
+
continue
|
| 101 |
+
for s in SEEDS:
|
| 102 |
+
jname = f"rr_ifql_{SHORT.get(task, task)}_s{s}"
|
| 103 |
+
if bundle(task, s).is_file():
|
| 104 |
+
print(f" {task} s{s}: bundle exists, skip")
|
| 105 |
+
continue
|
| 106 |
+
if jname in busy:
|
| 107 |
+
print(f" {task} s{s}: {jname} already PEND/RUN, skip")
|
| 108 |
+
continue
|
| 109 |
+
cmd = [str(ROOT / "scripts" / "bsub_gpu.sh"), jname,
|
| 110 |
+
str(ROOT / "scripts" / "rr_ifql.sh"), task, str(s)]
|
| 111 |
+
print(" " + " ".join(cmd))
|
| 112 |
+
if not dry:
|
| 113 |
+
bad = ROOT / "status" / "bad_eval_hosts.txt"
|
| 114 |
+
env = dict(os.environ, RR_QUEUE="preemptable", RR_GROUP="grp_preemptable",
|
| 115 |
+
RR_MEM=os.environ.get("RR_MEM", "96G"))
|
| 116 |
+
if "RR_EXCL_HOSTS" not in env and bad.is_file():
|
| 117 |
+
env["RR_EXCL_HOSTS"] = " ".join(bad.read_text().split())
|
| 118 |
+
subprocess.run(cmd, env=env, check=False)
|
| 119 |
+
n += 1
|
| 120 |
+
print(f"[launch_ifql] {n} training jobs {'would be ' if dry else ''}submitted")
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def _e1(task, args, dry, label):
|
| 124 |
+
cmd = [sys.executable, str(ROOT / "scripts" / "launch_e1_grid.py"), "--task", task,
|
| 125 |
+
"--env", ENVS[task], "--num-rollouts", "50", "--horizon", "400",
|
| 126 |
+
"--out-dir", str(ROOT / "runs" / task / "eval_ifql"), "--pack", "3",
|
| 127 |
+
"--queue", "preemptable", *args]
|
| 128 |
+
if dry:
|
| 129 |
+
cmd.append("--print-only")
|
| 130 |
+
r = subprocess.run(cmd, capture_output=True, text=True)
|
| 131 |
+
tail = [l for l in r.stderr.splitlines() if "jobs submitted" in l or "missing" in l or "WARNING" in l]
|
| 132 |
+
print(f" {task} {label}: " + (" | ".join(tail) if tail else (r.stderr.strip()[-300:] or "ok")))
|
| 133 |
+
if dry:
|
| 134 |
+
print(" " + "\n ".join(r.stdout.splitlines()[:8]))
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
def eval_critic(tasks, dry, controls=False, prop="S0A", epoch=5000):
|
| 138 |
+
"""Column (b): the IFQL critic ranking the proposer's 128 chunks (default: the RISE actor, S0A, epoch
|
| 139 |
+
5000). --proposer/--epoch (2026-09-21) point it at the row's pinned proposer; label and tag carry both."""
|
| 140 |
+
plab = prop + (f"E{epoch}" if epoch != 5000 else "")
|
| 141 |
+
for task in tasks:
|
| 142 |
+
fs = str(ROOT / "cache" / task / "feat_stats.npz")
|
| 143 |
+
for es in ESEEDS:
|
| 144 |
+
models, pol, cells = [], [], []
|
| 145 |
+
for p in SEEDS:
|
| 146 |
+
b, ck = bundle(task, p), policy_ckpt(task, prop, p, epoch)
|
| 147 |
+
if not b.is_file():
|
| 148 |
+
print(f" {task} s{p}: no IFQL bundle yet -- skipped"); continue
|
| 149 |
+
if not ck:
|
| 150 |
+
print(f" {task} s{p}: no epoch-{epoch} {prop} checkpoint -- skipped"); continue
|
| 151 |
+
lab = f"IFQLs{p}"
|
| 152 |
+
models += ["--model", f"{lab}={b}:ifql"]
|
| 153 |
+
pol += ["--policy", f"{plab}s{p}={ck}"]
|
| 154 |
+
rules = ("random", "permuted") if controls else ("argmax",)
|
| 155 |
+
for rule in rules:
|
| 156 |
+
cells += ["--cells", f"{lab},{BETA},{DEPTH},{MODE},{N},{rule},{plab}s{p}"]
|
| 157 |
+
if not cells:
|
| 158 |
+
continue
|
| 159 |
+
sfx = "" if plab == "S0A" else plab
|
| 160 |
+
tag = f"IFQLCTL{sfx}-es{es}" if controls else f"IFQLCRIT{sfx}-es{es}"
|
| 161 |
+
_e1(task, [*models, *pol, *cells, "--eval-seed", str(es), "--tag", tag], dry,
|
| 162 |
+
f"critic{'-controls' if controls else ''} es{es} ({len(cells) // 2} cells)")
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
def eval_policy(tasks, dry):
|
| 166 |
+
"""Column (a): IFQL as published -- its own flow actor and its own critic."""
|
| 167 |
+
for task in tasks:
|
| 168 |
+
fs = str(ROOT / "cache" / task / "feat_stats.npz")
|
| 169 |
+
for es in ESEEDS:
|
| 170 |
+
models, pol, cells = [], [], []
|
| 171 |
+
for p in SEEDS:
|
| 172 |
+
b, pub = bundle(task, p), published(task, p)
|
| 173 |
+
if not (b.is_file() and pub.is_file()):
|
| 174 |
+
print(f" {task} s{p}: no published IFQL policy checkpoint yet -- skipped"); continue
|
| 175 |
+
lab = f"IFQLs{p}"
|
| 176 |
+
models += ["--model", f"{lab}={b}:ifql"]
|
| 177 |
+
pol += ["--policy", f"IFQLp{p}={pub}"]
|
| 178 |
+
cells += ["--cells", f"{lab},{BETA},{DEPTH},{MODE},{N},argmax,IFQLp{p}"]
|
| 179 |
+
if not cells:
|
| 180 |
+
continue
|
| 181 |
+
_e1(task, [*models, *pol, *cells, "--eval-seed", str(es), "--tag", f"IFQLPOL-es{es}",
|
| 182 |
+
"--extra", "exp.ifql_policy=True",
|
| 183 |
+
f"exp.ifql_num_samples={N}", f"exp.ifql_feat_stats={fs}"], dry,
|
| 184 |
+
f"policy es{es} ({len(cells) // 2} cells)")
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
def status(tasks):
|
| 188 |
+
from verdict_table import cells as _c, pool as _p, rate as _r, ifql_spread_str
|
| 189 |
+
mark = ROOT / "runs" / "_ifql_watcher"
|
| 190 |
+
print(f"{'task':32s} {'bundles':8s} {'gate b/a':10s} {'(a) IFQL published':26s} {'(b) IFQL critic / RISE actor':30s}")
|
| 191 |
+
for task in tasks:
|
| 192 |
+
nb = sum(1 for s in SEEDS if bundle(task, s).is_file())
|
| 193 |
+
try:
|
| 194 |
+
c = _c(task)
|
| 195 |
+
except Exception as e:
|
| 196 |
+
print(f"{task:32s} {nb}/3 (cells unreadable: {e!r})"); continue
|
| 197 |
+
def cell(pol):
|
| 198 |
+
g = _p(c, lambda a, p, P=pol: a[0] == "critic:ifql" and p == P)
|
| 199 |
+
if not g:
|
| 200 |
+
return "--"
|
| 201 |
+
sr, n_ = _r(g)
|
| 202 |
+
return f"{sr:.1f}% n={n_} cells={len(g)}/9 seeds={len({ps for (_, ps, _) in g})}"
|
| 203 |
+
gb = "ok" if (mark / f"{task}.smoke_ok_colb").is_file() else "LOCKED"
|
| 204 |
+
ga = "ok" if (mark / f"{task}.smoke_ok_cola").is_file() else "LOCKED"
|
| 205 |
+
print(f"{task:32s} {nb}/3 {gb + '/' + ga:10s} {cell('IFQL policy'):26s} {cell('RISE policy'):30s}")
|
| 206 |
+
print(f"{'':32s} value resolution: {ifql_spread_str(task)}")
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
def main():
|
| 210 |
+
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
| 211 |
+
ap.add_argument("tasks", nargs="*", default=[])
|
| 212 |
+
ap.add_argument("--train", action="store_true")
|
| 213 |
+
ap.add_argument("--eval-critic", action="store_true")
|
| 214 |
+
ap.add_argument("--eval-policy", action="store_true")
|
| 215 |
+
ap.add_argument("--eval-controls", action="store_true")
|
| 216 |
+
ap.add_argument("--status", action="store_true")
|
| 217 |
+
ap.add_argument("--print-only", action="store_true")
|
| 218 |
+
ap.add_argument("--proposer", default="S0A", help="POL key of the proposer family (default S0A)")
|
| 219 |
+
ap.add_argument("--epoch", type=int, default=5000, help="proposer checkpoint epoch")
|
| 220 |
+
a = ap.parse_args()
|
| 221 |
+
tasks = a.tasks or TASKS
|
| 222 |
+
for t in tasks:
|
| 223 |
+
if t not in ENVS:
|
| 224 |
+
raise SystemExit(f"unknown task {t}; known: {sorted(ENVS)}")
|
| 225 |
+
if a.train:
|
| 226 |
+
print("### training"); train(tasks, a.print_only)
|
| 227 |
+
if a.eval_critic:
|
| 228 |
+
print("### column (b): IFQL critic on the RISE actor"); eval_critic(tasks, a.print_only, prop=a.proposer, epoch=a.epoch)
|
| 229 |
+
if a.eval_controls:
|
| 230 |
+
print("### column (b) controls: random / permuted"); eval_critic(tasks, a.print_only, controls=True, prop=a.proposer, epoch=a.epoch)
|
| 231 |
+
if a.eval_policy:
|
| 232 |
+
print("### column (a): IFQL as published"); eval_policy(tasks, a.print_only)
|
| 233 |
+
if a.status or not any([a.train, a.eval_critic, a.eval_policy, a.eval_controls]):
|
| 234 |
+
status(tasks)
|
| 235 |
+
|
| 236 |
+
|
| 237 |
+
if __name__ == "__main__":
|
| 238 |
+
main()
|
gen_q_rsm/rsm_rise/pipeline/scripts/launch_lewm_on_actor.py
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""LeWM scorer sweep on the RISE actor (S0A) -- the pixel world-model comparator of gen_q#268.
|
| 3 |
+
|
| 4 |
+
Identical protocol to scripts/launch_dinowm_on_actor.py (see that file and
|
| 5 |
+
launch_rsm_on_actor.py): the RISE actor at epoch 5000 proposes 128 chunks per decision step, the
|
| 6 |
+
scorer ranks, argmax executes; horizon 400, 50 episodes, 3 policy seeds x 3 eval seeds, the task's
|
| 7 |
+
canonical env, the provenance/membership label as the reward.
|
| 8 |
+
|
| 9 |
+
The grid is L in {1,2,4,8} only: LeWM has no discount to sweep, and one hop is one action chunk.
|
| 10 |
+
`plan_beta` is inert on this backend but every planner cell carries one, so a single value is used
|
| 11 |
+
throughout and verdict_table's arm label ("L<depth> N128") correctly omits it. LeWM's roll-out is
|
| 12 |
+
deterministic, so the read-out forces one particle.
|
| 13 |
+
|
| 14 |
+
usage: launch_lewm_on_actor.py <task> [<task> ...] [--hops 1,2,4,8] [--control-depth 4] [--print-only]
|
| 15 |
+
"""
|
| 16 |
+
import subprocess, sys
|
| 17 |
+
# --proposer FAM (gen_q#268 / #267): the flagship is moving to a best-proposer-per-task table, and every
|
| 18 |
+
# value-estimation method -- these three included -- must be measured on THAT proposer. The policy
|
| 19 |
+
# family is therefore a parameter, not the S0A constant it was. The family is carried into the cell
|
| 20 |
+
# label (S0Aidqls0, S0Ansns1, ...) and into --tag, so a cell on one proposer can never be confused
|
| 21 |
+
# with, skipped for, or pooled with the same read-out on another: launch_e1_grid's busy/exists checks
|
| 22 |
+
# key on the cell NAME. Default S0A keeps every existing cell name byte-identical.
|
| 23 |
+
|
| 24 |
+
from pathlib import Path
|
| 25 |
+
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
| 26 |
+
from launch_flagship_topup import ENVS, ckpt
|
| 27 |
+
ROOT = Path("/proj/dmfexp/zwhong/rsm_rise")
|
| 28 |
+
HOPS = (1, 2, 4, 8)
|
| 29 |
+
BETA = 0.95 # inert on this backend
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def run(task, model, extra, es, label, dry, prop="S0A"):
|
| 33 |
+
cmd = [sys.executable, str(ROOT / "scripts/launch_e1_grid.py"), "--task", task, "--env", ENVS[task],
|
| 34 |
+
"--model", f"LEWM={model}:lewm", "--hop", str(ROOT / f"runs/{task}/hop/gauss/policy_r1.pt"),
|
| 35 |
+
"--num-rollouts", "50", "--horizon", "400", "--eval-seed", str(es), "--tag", (f"LEWMACTOR-es{es}" if prop == "S0A" else f"LEWM{prop}-es{es}"),
|
| 36 |
+
"--out-dir", str(ROOT / f"runs/{task}/eval_onactor"), "--pack", "4", "--queue", "preemptable",
|
| 37 |
+
"--primary-beta", str(BETA), *extra]
|
| 38 |
+
if dry:
|
| 39 |
+
cmd.append("--print-only")
|
| 40 |
+
r = subprocess.run(cmd, capture_output=True, text=True)
|
| 41 |
+
tail = [l for l in r.stderr.splitlines() if "jobs submitted" in l or "missing" in l]
|
| 42 |
+
print(f" {task} es{es} {label}:", tail[-1:] or r.stderr.strip()[-300:])
|
| 43 |
+
if dry:
|
| 44 |
+
print("\n".join(r.stdout.splitlines()[:3]))
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def main():
|
| 48 |
+
dry = "--print-only" in sys.argv
|
| 49 |
+
hops, cdepth = HOPS, 4
|
| 50 |
+
for i, a in enumerate(sys.argv):
|
| 51 |
+
if a == "--hops":
|
| 52 |
+
hops = tuple(int(x) for x in sys.argv[i + 1].split(","))
|
| 53 |
+
if a == "--control-depth":
|
| 54 |
+
cdepth = int(sys.argv[i + 1])
|
| 55 |
+
prop = "S0A"
|
| 56 |
+
for i, a in enumerate(sys.argv):
|
| 57 |
+
if a == "--proposer":
|
| 58 |
+
prop = sys.argv[i + 1]
|
| 59 |
+
epoch = 5000
|
| 60 |
+
for i, a in enumerate(sys.argv):
|
| 61 |
+
if a == "--epoch":
|
| 62 |
+
epoch = int(sys.argv[i + 1])
|
| 63 |
+
plab = prop + (f"E{epoch}" if epoch != 5000 else "") # label/tag carry the epoch: 500 and 5000 cells never share a name
|
| 64 |
+
tasks = [a for a in sys.argv[1:] if not a.startswith("--") and a in ENVS]
|
| 65 |
+
for task in tasks:
|
| 66 |
+
model = ROOT / f"runs/{task}/wm/lewm/ckpt_best.pt"
|
| 67 |
+
if not model.exists():
|
| 68 |
+
print(f" {task}: MISSING {model}")
|
| 69 |
+
continue
|
| 70 |
+
pol, cells = [], []
|
| 71 |
+
for p in (0, 1, 2):
|
| 72 |
+
c = ckpt(task, prop, p, epoch)
|
| 73 |
+
if not c:
|
| 74 |
+
print(f" {task}: no epoch-{epoch} {prop} seed {p}")
|
| 75 |
+
continue
|
| 76 |
+
pol += ["--policy", f"{plab}s{p}={c}"]
|
| 77 |
+
for L in hops:
|
| 78 |
+
cells.append(f"LEWM,{BETA},{L},{'d1' if L == 1 else 'fold'},128,argmax,{plab}s{p}")
|
| 79 |
+
if not pol:
|
| 80 |
+
continue
|
| 81 |
+
for es in (0, 1, 2):
|
| 82 |
+
run(task, model, [*pol, *[x for c in cells for x in ("--cells", c)],
|
| 83 |
+
"--primary-depth", str(cdepth)], es, f"lewm grid ({len(cells)} cells)", dry, plab)
|
| 84 |
+
run(task, model, [*pol, "--grid", "controls", "--controls-subset", "permuted",
|
| 85 |
+
"--primary-depth", str(cdepth)], es, "lewm permuted control", dry, plab)
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
if __name__ == "__main__":
|
| 89 |
+
main()
|
gen_q_rsm/rsm_rise/pipeline/scripts/launch_problog_on_actor.py
ADDED
|
@@ -0,0 +1,171 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""gen_q#266: sweep `plan_score=prob_log` on the RISE actor (S0A), against the read-out sweep's grid.
|
| 3 |
+
|
| 4 |
+
WHY. The 443-cell read-out sweep (scripts/launch_readout_on_actor.py) found `prob` far better than
|
| 5 |
+
`logit` -- threading median 9.9 vs 2.0, mug 9.7 vs 6.4 -- but `prob` gets there while TYING 51-65 of the
|
| 6 |
+
128 candidates at exactly 1.0, so its arg-max is a uniform draw inside the tied set. `logit` orders all
|
| 7 |
+
128 and is much worse, but it also throws the fold away: `_q_fold_logit` returns `lg_out.mean(1)`, the
|
| 8 |
+
reward logit at the LAST hop only, discarding hops 0..L-2.
|
| 9 |
+
|
| 10 |
+
`prob_log` separates those two confounded changes. It is the SAME quantity as `prob` -- the whole product
|
| 11 |
+
fold, averaged over particles -- computed as log(1 - Q) so it never rounds to 1.0 (threading records reward
|
| 12 |
+
logits near +121, where sigma is exactly 1.0 even in float64). It is a strictly monotone transform of
|
| 13 |
+
prob's infinite-precision value, so it keeps the fold AND totally orders the candidates.
|
| 14 |
+
|
| 15 |
+
PREDICTION, COMMITTED BEFORE THE RESULT (issue #266). The two readings of the read-out table make
|
| 16 |
+
opposite predictions, and both are publishable:
|
| 17 |
+
* if `prob` beats `logit` because THE FOLD MATTERS, prob_log keeps the fold and adds the ordering, so it
|
| 18 |
+
should match or beat prob (threading median ~9.9 or better) with ties of 1;
|
| 19 |
+
* if `prob` beats `logit` because A COARSE FILTER PLUS A NEAR-UNIFORM DRAW over ~60 survivors is doing
|
| 20 |
+
the work, then sharpening the order will HURT and prob_log falls toward logit (threading ~2.0).
|
| 21 |
+
The second outcome is the surprising one and must be reported exactly as plainly as the first.
|
| 22 |
+
|
| 23 |
+
PRIOR SUPPORT FOR BRANCH 2, and the corpus it was measured on (orchestrator, 2026-09-21). The separate
|
| 24 |
+
108-cell `training.plan_temperature` grid is fully seeded on both open rows (3 policy x 3 eval, 50 eps) and
|
| 25 |
+
de-saturating the read-out MAKES SELECTION WORSE IN SIMULATION:
|
| 26 |
+
|
| 27 |
+
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)
|
| 28 |
+
threading T=1 14.22 (ties 67.7, sat 0.253) -> T=25 3.78 (ties 1.2, sat 0.131)
|
| 29 |
+
|
| 30 |
+
T=1 reproduces the archived arms within seed noise, so that positive control passes. At T=25, where the
|
| 31 |
+
read-out is effectively a total order, the rows read 5.78 / 3.78 -- next to the LOGIT read-out's 6.4 / 2.0.
|
| 32 |
+
|
| 33 |
+
This is NOT a direct prediction for prob_log, and the distinction matters: raising T changes the FUNCTION
|
| 34 |
+
being folded, while prob_log changes only the PRECISION -- it resolves the tied candidates in the direction
|
| 35 |
+
the infinitely-precise mean-sigmoid at T=1 would have ordered them. What the T grid does establish is that
|
| 36 |
+
sharpening the order on this reward head, by any means measured so far, has only hurt. Combined with the
|
| 37 |
+
measured scale of what prob_log resolves -- prob_log_std ~9.3 on threading, i.e. the tied candidates'
|
| 38 |
+
(1 - Q) values differ by factors of e^9 at Q values within 1e-50 of 1.0 -- the ordering prob_log recovers
|
| 39 |
+
INSIDE the tied set is reward-head noise. So branch 2 is the outcome with prior support and a clean
|
| 40 |
+
negative is the honest reading: the head is informative about membership while its logit magnitude carries
|
| 41 |
+
within-group ordering that is no better than random.
|
| 42 |
+
|
| 43 |
+
CORPUS. The claim "de-saturating improves selection" comes from the REAL corpus (gen_q#261) and it does
|
| 44 |
+
NOT transfer to sim -- the T grid above is the measurement. State the corpus with any read-out claim.
|
| 45 |
+
|
| 46 |
+
Grid: the read-out sweep's, so the cells are directly comparable -- single proposer S0A, N=128,
|
| 47 |
+
plan_particles=16, beta in {0.90, 0.95, 0.98}, hops in {1, 2, 4}, 3 policy seeds x 3 eval seeds,
|
| 48 |
+
50 episodes, horizon 400. Tasks: the two open rows plus two_piece_expert_play as a winning-row control.
|
| 49 |
+
|
| 50 |
+
HEALTH NUMBERS. Every cell records `prob_log_ties_at_max_mean` (must be ~1) beside the unchanged
|
| 51 |
+
`ties_at_max_mean` / `frac_saturated_mean` of the probability array, so the ordering claim is checkable
|
| 52 |
+
from the eval JSON with no re-scoring. Quote no arm that is not a full 3x3.
|
| 53 |
+
|
| 54 |
+
MATCHED BASELINE (--baseline). The read-out sweep (launch_readout_on_actor.FLAG) never covered
|
| 55 |
+
two_piece_expert_play -- it has two_piece_expert_play_TIPPING -- so the winning-row control has no `prob`
|
| 56 |
+
arm at these betas and hops to be compared against, and a control without a comparator is not a control.
|
| 57 |
+
`--baseline` submits the SAME grid with `training.plan_score=prob`, tag PROBBASE16, into the same
|
| 58 |
+
out-dir: same model, same checkpoint, same seeds, same episodes, same horizon, one field different. Do
|
| 59 |
+
not use the archived flagship cells for this -- that archive is selection-confounded (the default planner
|
| 60 |
+
cell ran on every arm), so a `prob` number lifted from it is not paired with anything here.
|
| 61 |
+
|
| 62 |
+
usage: launch_problog_on_actor.py [<task> ...] [--print-only] [--preflight] [--baseline]
|
| 63 |
+
no task -> all three
|
| 64 |
+
--preflight submit ONE cell only and print how to verify the knob landed. Do this FIRST: on
|
| 65 |
+
2026-09-21 a 61-cell temperature sweep was spent on `training.plan_temp` where
|
| 66 |
+
`training.plan_temperature` was meant, and it was only caught because two settings
|
| 67 |
+
produced bit-identical health numbers. A knob that does not reach the fingerprint is
|
| 68 |
+
not a measurement of that knob.
|
| 69 |
+
|
| 70 |
+
IMPORT SAFETY. A launcher must do NOTHING on import. `launch_rsm_on_actor.py` had its submission loop
|
| 71 |
+
at module level, so `from launch_rsm_on_actor import FLAG` read the IMPORTER's sys.argv as its task list
|
| 72 |
+
and queued 36 jobs / 144 eval cells before it was caught. Everything here is inside main().
|
| 73 |
+
"""
|
| 74 |
+
import subprocess
|
| 75 |
+
import sys
|
| 76 |
+
from pathlib import Path
|
| 77 |
+
|
| 78 |
+
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
| 79 |
+
from launch_flagship_topup import ENVS, BASE_LABEL, _ck_suffix, ckpt # noqa: E402
|
| 80 |
+
|
| 81 |
+
ROOT = Path("/proj/dmfexp/zwhong/rsm_rise")
|
| 82 |
+
OUT_NAME = "eval_problog"
|
| 83 |
+
TAG_PREFIX = "PROBLOG"
|
| 84 |
+
|
| 85 |
+
# (successor model, checkpoint) per task -- the SAME arms the read-out sweep used, so prob_log is
|
| 86 |
+
# comparable cell for cell. two_piece_expert_play is the winning-row control (L40@best, as in
|
| 87 |
+
# launch_temp_on_actor.ARMS).
|
| 88 |
+
FLAG = {
|
| 89 |
+
"threading_expert_play": ("M", "best"),
|
| 90 |
+
"mug_expert_suboptimal": ("M_s1", "best"),
|
| 91 |
+
"two_piece_expert_play": ("L40", "best"),
|
| 92 |
+
}
|
| 93 |
+
BETAS, HOPS = (0.90, 0.95, 0.98), (1, 2, 4)
|
| 94 |
+
PARTICLES, N_CAND = 16, 128
|
| 95 |
+
TASKS = tuple(FLAG)
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def _cells(task, lab, policy_seeds, betas=BETAS, hops=HOPS):
|
| 99 |
+
out = []
|
| 100 |
+
for p in policy_seeds:
|
| 101 |
+
for b in betas:
|
| 102 |
+
for L in hops:
|
| 103 |
+
out += ["--cells", f"{lab},{b},{L},{'d1' if L == 1 else 'fold'},{N_CAND},argmax,S0As{p}"]
|
| 104 |
+
return out
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def main():
|
| 108 |
+
argv = sys.argv[1:]
|
| 109 |
+
dry = "--print-only" in argv
|
| 110 |
+
preflight = "--preflight" in argv
|
| 111 |
+
baseline = "--baseline" in argv
|
| 112 |
+
score, tag_pfx = ("prob", "PROBBASE") if baseline else ("prob_log", TAG_PREFIX)
|
| 113 |
+
tasks = [a for a in argv if not a.startswith("--")] or list(TASKS)
|
| 114 |
+
bad = [t for t in tasks if t not in FLAG]
|
| 115 |
+
if bad:
|
| 116 |
+
print(f"unknown task(s) {bad}; known: {sorted(FLAG)}")
|
| 117 |
+
return 2
|
| 118 |
+
n_sub = 0
|
| 119 |
+
for task in tasks:
|
| 120 |
+
model, ck = FLAG[task]
|
| 121 |
+
rsm = ROOT / f"runs/{task}/rsm/{model}/ckpt_{ck}.pt"
|
| 122 |
+
if not rsm.is_file():
|
| 123 |
+
print(f"{task}: no {rsm}")
|
| 124 |
+
continue
|
| 125 |
+
lab = BASE_LABEL.get(model, model) + _ck_suffix(ck)
|
| 126 |
+
pol, seeds = [], []
|
| 127 |
+
for p in (0, 1, 2):
|
| 128 |
+
c = ckpt(task, "S0A", p)
|
| 129 |
+
if c:
|
| 130 |
+
pol += ["--policy", f"S0As{p}={c}"]
|
| 131 |
+
seeds.append(p)
|
| 132 |
+
if not seeds:
|
| 133 |
+
print(f"{task}: no epoch-5000 S0A")
|
| 134 |
+
continue
|
| 135 |
+
out_dir = ROOT / f"runs/{task}/{OUT_NAME}"
|
| 136 |
+
# --preflight: ONE cell (first policy seed, beta 0.95, 1 hop, eval seed 0), so the knob can be
|
| 137 |
+
# checked against the recorded fingerprint before the rest of the grid is spent.
|
| 138 |
+
if preflight:
|
| 139 |
+
grids = [(seeds[:1], (0.95,), (1,), 0)]
|
| 140 |
+
else:
|
| 141 |
+
grids = [(seeds, BETAS, HOPS, es) for es in (0, 1, 2)]
|
| 142 |
+
for (sds, betas, hops, es) in grids:
|
| 143 |
+
cells = _cells(task, lab, sds, betas, hops)
|
| 144 |
+
cmd = [sys.executable, str(ROOT / "scripts/launch_e1_grid.py"), "--task", task,
|
| 145 |
+
"--env", ENVS[task], "--model", f"{lab}={rsm}:mlp",
|
| 146 |
+
"--hop", str(ROOT / f"runs/{task}/hop/gauss/policy_r1.pt"), *pol, *cells,
|
| 147 |
+
"--num-rollouts", "50", "--horizon", "400", "--eval-seed", str(es),
|
| 148 |
+
"--extra", f"training.plan_particles={PARTICLES}", f"training.plan_score={score}",
|
| 149 |
+
# the tag carries the read-out AND the particle count, so a prob_log cell can never be
|
| 150 |
+
# pooled with the `prob` / `logit` cells of the read-out sweep under one arm key.
|
| 151 |
+
"--tag", f"{tag_pfx}{PARTICLES}-es{es}",
|
| 152 |
+
"--out-dir", str(out_dir), "--pack", "4", "--queue", "preemptable"]
|
| 153 |
+
if dry:
|
| 154 |
+
cmd.append("--print-only")
|
| 155 |
+
r = subprocess.run(cmd, capture_output=True, text=True)
|
| 156 |
+
tail = [l for l in r.stderr.splitlines() if "jobs submitted" in l or "missing" in l]
|
| 157 |
+
print(f" {task} {tag_pfx}{PARTICLES} es{es}:", tail[-1:] or r.stderr.strip()[-200:])
|
| 158 |
+
n_sub += 1
|
| 159 |
+
if preflight:
|
| 160 |
+
print("\n[preflight] when the first cell lands, verify the knob reached the fingerprint:")
|
| 161 |
+
print(f" python3 {ROOT}/scripts/check_problog_knob.py")
|
| 162 |
+
print(" planner.plan_score and scorer.score_kind must read 'prob_log', "
|
| 163 |
+
"prob_log_ties_at_max_mean ~1.0,")
|
| 164 |
+
print(" and prob_ties_at_max_mean must still be LARGE -- `prob` would have tied on these very")
|
| 165 |
+
print(" states, so the ordering is what changed and nothing else. (`ties_at_max_mean` is the")
|
| 166 |
+
print(" RANKING array's tie count, which under prob_log IS prob_log's, so it must be ~1 too.)")
|
| 167 |
+
return 0 if n_sub else 1
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
if __name__ == "__main__":
|
| 171 |
+
sys.exit(main())
|
gen_q_rsm/rsm_rise/pipeline/scripts/launch_readout_on_actor.py
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Sweep the RSM READ-OUT (particle count x score) on the RISE actor for the two open rows.
|
| 3 |
+
|
| 4 |
+
gen_q#265's CKISO experiment showed the read-out is a first-order lever that the arm key had been pooling
|
| 5 |
+
over: on threading, the same (model, beta, hops) recipe scores 9.1-12.0 % at `plan_particles=16,
|
| 6 |
+
plan_score=prob` and 1.0-3.4 % at `256, logit`, while on piece-suboptimal the two agree to 0.6 pt. The
|
| 7 |
+
read-out is part of the scorer, so it belongs in the disclosed search -- and the controls (greedy,
|
| 8 |
+
random-of-128) do not depend on it, so sweeping it cannot inflate a margin without the controls moving.
|
| 9 |
+
|
| 10 |
+
Health caveat (2026-09-21): `prob` is not simply the better read-out. On square-peg (Cov.) the `P16/prob`
|
| 11 |
+
arms tie across 18-63 of the 128 candidates, so the arg-max there is a uniform draw inside the tied set --
|
| 12 |
+
a coarse filter plus resampling rather than a ranking. Report the tie count (`scripts/scorer_health.py`)
|
| 13 |
+
beside every arm this launcher produces.
|
| 14 |
+
|
| 15 |
+
usage: launch_readout_on_actor.py <task> [<task> ...] [--print-only]
|
| 16 |
+
"""
|
| 17 |
+
import subprocess
|
| 18 |
+
import sys
|
| 19 |
+
from pathlib import Path
|
| 20 |
+
|
| 21 |
+
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
| 22 |
+
from launch_flagship_topup import ENVS, BASE_LABEL, _ck_suffix, ckpt # noqa: E402
|
| 23 |
+
|
| 24 |
+
ROOT = Path("/proj/dmfexp/zwhong/rsm_rise")
|
| 25 |
+
FLAG = {"mug_expert_suboptimal": ("M_s1", "best"), "threading_expert_play": ("M", "best"),
|
| 26 |
+
"square_expert_play": ("L40", "best"), "two_piece_expert_play_tipping": ("M", "best")}
|
| 27 |
+
# (particles, score) read-outs to try beside the canonical (256, logit) the flagship already has.
|
| 28 |
+
READOUTS = [(16, "prob"), (16, "logit"), (256, "prob")]
|
| 29 |
+
BETAS, HOPS = (0.90, 0.95, 0.98), (1, 2, 4)
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
# IMPORT SAFETY (2026-09-21). A launcher must do NOTHING on import. `launch_rsm_on_actor.py` had its
|
| 33 |
+
# submission loop at module level, so `from launch_rsm_on_actor import FLAG` -- which
|
| 34 |
+
# scripts/scorer_rank_check.py does, to read the flagship recipe -- submitted the whole grid, reading the
|
| 35 |
+
# IMPORTER's sys.argv as its task list, and queued 36 jobs / 144 eval cells before it was caught. Every
|
| 36 |
+
# launcher here is guarded the same way.
|
| 37 |
+
def main():
|
| 38 |
+
dry = "--print-only" in sys.argv
|
| 39 |
+
for task in [a for a in sys.argv[1:] if not a.startswith("--")]:
|
| 40 |
+
model, ck = FLAG[task]
|
| 41 |
+
rsm = ROOT / f"runs/{task}/rsm/{model}/ckpt_{ck}.pt"
|
| 42 |
+
lab = BASE_LABEL.get(model, model) + _ck_suffix(ck)
|
| 43 |
+
pol = []
|
| 44 |
+
for p in (0, 1, 2):
|
| 45 |
+
c = ckpt(task, "S0A", p)
|
| 46 |
+
if c:
|
| 47 |
+
pol += ["--policy", f"S0As{p}={c}"]
|
| 48 |
+
if not pol:
|
| 49 |
+
print(f"{task}: no epoch-5000 S0A")
|
| 50 |
+
continue
|
| 51 |
+
for (P, sc) in READOUTS:
|
| 52 |
+
cells = []
|
| 53 |
+
for p in (0, 1, 2):
|
| 54 |
+
if not ckpt(task, "S0A", p):
|
| 55 |
+
continue
|
| 56 |
+
for b in BETAS:
|
| 57 |
+
for L in HOPS:
|
| 58 |
+
cells += ["--cells",
|
| 59 |
+
f"{lab},{b},{L},{'d1' if L == 1 else 'fold'},128,argmax,S0As{p}"]
|
| 60 |
+
for es in (0, 1, 2):
|
| 61 |
+
cmd = [sys.executable, str(ROOT / "scripts/launch_e1_grid.py"), "--task", task,
|
| 62 |
+
"--env", ENVS[task], "--model", f"{lab}={rsm}:mlp",
|
| 63 |
+
"--hop", str(ROOT / f"runs/{task}/hop/gauss/policy_r1.pt"), *pol, *cells,
|
| 64 |
+
"--num-rollouts", "50", "--horizon", "400", "--eval-seed", str(es),
|
| 65 |
+
"--extra", f"training.plan_particles={P}", f"training.plan_score={sc}",
|
| 66 |
+
"--tag", f"RO{P}{sc}-es{es}", "--out-dir", str(ROOT / f"runs/{task}/eval_readout"),
|
| 67 |
+
"--pack", "4", "--queue", "preemptable"]
|
| 68 |
+
if dry:
|
| 69 |
+
cmd.append("--print-only")
|
| 70 |
+
r = subprocess.run(cmd, capture_output=True, text=True)
|
| 71 |
+
tail = [l for l in r.stderr.splitlines() if "jobs submitted" in l or "missing" in l]
|
| 72 |
+
print(f" {task} P{P}/{sc} es{es}:", tail[-1:] or r.stderr.strip()[-160:])
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
if __name__ == "__main__":
|
| 76 |
+
main()
|
gen_q_rsm/rsm_rise/pipeline/scripts/launch_rsm_on_actor.py
ADDED
|
@@ -0,0 +1,186 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""RSM scorer sweep on the RISE actor (S0A) as the single proposer -- the comparison where RISE and RSM differ
|
| 3 |
+
ONLY in the scorer (owner, 2026-09-21: "if the only difference between RISE and RSM is the CRITIC, that is
|
| 4 |
+
much better signal").
|
| 5 |
+
|
| 6 |
+
Per task: the flagship successor model, beta {0.90,0.95,0.98} x hops {1,2,4,8}, N=128 argmax, 3 policy seeds
|
| 7 |
+
x 3 eval seeds x 50 episodes, plus the S0A controls (greedy, random-candidate, permuted, IQL critic) at the
|
| 8 |
+
flagship recipe. launch_e1_grid refuses cells that duplicate an existing (policy ckpt, eval seed, rule)
|
| 9 |
+
elsewhere, so re-running on a task that already has S0A cells only adds the missing ones.
|
| 10 |
+
|
| 11 |
+
usage: launch_rsm_on_actor.py <task> [<task> ...] [--family <POL key>] [--epoch <E>] [--arms grid|flagship]
|
| 12 |
+
[--eval-seeds 0,1,2] [--controls bc,random,...]
|
| 13 |
+
[--critic-from <POL key>] [--print-only]
|
| 14 |
+
"""
|
| 15 |
+
import re, subprocess, sys
|
| 16 |
+
from pathlib import Path
|
| 17 |
+
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
| 18 |
+
from launch_flagship_topup import ENVS, BASE_LABEL, _ck_suffix, ckpt
|
| 19 |
+
ROOT = Path("/proj/dmfexp/zwhong/rsm_rise")
|
| 20 |
+
# task -> (successor model, checkpoint, flagship beta, flagship hops), from the 2026-09-21 master table
|
| 21 |
+
FLAG = {
|
| 22 |
+
"square_sub_20100": ("M", "best", 0.9, 3),
|
| 23 |
+
"square_expert_play": ("L40", "best", 0.9, 2),
|
| 24 |
+
"two_piece_expert_suboptimal": ("M", "s100000", 0.9, 3),
|
| 25 |
+
"two_piece_expert_play": ("L40", "best", 0.95, 8),
|
| 26 |
+
"mug_expert_suboptimal": ("M_s1", "best", 0.95, 1),
|
| 27 |
+
"threading_expert_play": ("M", "best", 0.9, 1),
|
| 28 |
+
"two_piece_expert_play_tipping": ("M", "best", 0.95, 8),
|
| 29 |
+
# REGENERATED-DATA TASKS (2026-09-21): the successor model trained on the mgen data (rsm/M), the parent
|
| 30 |
+
# task's flagship beta/depth. Same eval envs as the parent rows (robomimic_mug, robomimic_threading_coverage).
|
| 31 |
+
"mug_mgen": ("M", "best", 0.95, 1),
|
| 32 |
+
"threading_mgen": ("M", "best", 0.9, 1),
|
| 33 |
+
}
|
| 34 |
+
BETAS, HOPS = (0.90, 0.95, 0.98), (1, 2, 4, 8)
|
| 35 |
+
GAMMA = 0.99 # the planner's plan_gamma; the chain's cap depends on it
|
| 36 |
+
# --readout chain (gen_q#267, owner 2026-09-22): the coin-terminated beta chain replaces the deterministic
|
| 37 |
+
# truncated fold. Per particle the walk hops a Bernoulli(p) number of times with
|
| 38 |
+
# p = (gamma-beta)/(gamma*(1-beta)) [ogbench_genq/rsm.py:113] and reads membership ONCE at the frozen node,
|
| 39 |
+
# so the composed frame offset is EXACTLY Geom(1-gamma). The chain's only length parameter is the
|
| 40 |
+
# TRUNCATION CAP, computed here from the 1e-3 tail -- never hard-coded, never swept for success.
|
| 41 |
+
CHAIN_PARTICLES = (16, 64) # the chain is stochastic, so the particle count is a variance axis
|
| 42 |
+
CHAIN_BETAS = (0.90, 0.95, 0.98) # all inside the successor's trained band [0.90, 0.995] (train_rsm.py:162)
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def chain_cap_for(beta, gamma=GAMMA, tail_eps=1e-3):
|
| 46 |
+
"""The cap as a truncation guard: smallest L with P(walk > L) = p**L <= tail_eps. Imported from the
|
| 47 |
+
SHIPPED scorer when that import is possible (submit hosts have no torch), else recomputed from the same
|
| 48 |
+
closed form -- the two are asserted equal in scripts/chain_horizon_test.py, which runs on a node."""
|
| 49 |
+
import math
|
| 50 |
+
p = (gamma - beta) / (gamma * (1.0 - beta))
|
| 51 |
+
return int(math.ceil(math.log(tail_eps) / math.log(p)))
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def run(task, extra, es, label, dry=False, fam="S0A", tsuf=""):
|
| 55 |
+
model, ck, b0, L0 = FLAG[task]
|
| 56 |
+
rsm = ROOT / f"runs/{task}/rsm/{model}/ckpt_{ck}.pt"
|
| 57 |
+
lab = BASE_LABEL.get(model, model) + _ck_suffix(ck)
|
| 58 |
+
cmd = [sys.executable, str(ROOT / "scripts/launch_e1_grid.py"), "--task", task, "--env", ENVS[task],
|
| 59 |
+
"--model", f"{lab}={rsm}:mlp", "--hop", str(ROOT / f"runs/{task}/hop/gauss/policy_r1.pt"),
|
| 60 |
+
"--num-rollouts", "50", "--horizon", "400", "--eval-seed", str(es),
|
| 61 |
+
# tsuf (gen_q#267) separates otherwise-identical chain cells that differ only in an --extra
|
| 62 |
+
# (the particle count), so two particle counts can never write the same JSON.
|
| 63 |
+
"--tag", ((f"ONACTOR{tsuf}-es{es}" if fam == "S0A" else f"ON{fam}{tsuf}-es{es}")),
|
| 64 |
+
"--out-dir", str(ROOT / f"runs/{task}/eval_onactor"), "--pack", "4", "--queue", "preemptable",
|
| 65 |
+
"--primary-beta", str(b0), "--primary-depth", str(L0), *extra]
|
| 66 |
+
if dry:
|
| 67 |
+
cmd.append("--print-only")
|
| 68 |
+
r = subprocess.run(cmd, capture_output=True, text=True)
|
| 69 |
+
tail = [l for l in r.stderr.splitlines() if "jobs submitted" in l or "missing" in l]
|
| 70 |
+
print(f" {task} es{es} {label}:", tail[-1:] or r.stderr.strip()[-200:])
|
| 71 |
+
|
| 72 |
+
def main():
|
| 73 |
+
# --family <POL key> (2026-09-21): the proposer family. Default S0A (the RISE actor). The owner's
|
| 74 |
+
# restructure compares every value-estimation method on the BEST PROPOSER PER TASK, which may be a
|
| 75 |
+
# special case of the RISE recipe; the planning screen selected S0Aidql and S0Ansn on threading. The
|
| 76 |
+
# policy label embeds the family (e.g. S0Aidqls0) and verdict_table recovers the family from the
|
| 77 |
+
# checkpoint PATH via POL, so cells on different proposers can never pool.
|
| 78 |
+
fam = "S0A"
|
| 79 |
+
if "--family" in sys.argv:
|
| 80 |
+
fam = sys.argv[sys.argv.index("--family") + 1]
|
| 81 |
+
# --epoch <E> (2026-09-21): the proposer's checkpoint epoch. Label and tag carry it (S0AidqlE500s0,
|
| 82 |
+
# ONS0AidqlE500-es0) so epoch-500 and epoch-5000 cells of one family can never share a name, and
|
| 83 |
+
# verdict_table labels the proposer "IDQL policy@500". --arms flagship runs only the pinned recipe
|
| 84 |
+
# (the epoch/family sweep); --eval-seeds 0 restricts the eval seeds for a screen.
|
| 85 |
+
epoch = int(sys.argv[sys.argv.index("--epoch") + 1]) if "--epoch" in sys.argv else 5000
|
| 86 |
+
arms = sys.argv[sys.argv.index("--arms") + 1] if "--arms" in sys.argv else "grid"
|
| 87 |
+
# --readout fold|chain (gen_q#267). DEFAULT fold, so every existing invocation of this launcher is
|
| 88 |
+
# byte-for-byte the command it was; chain is additive and lands in its own eval JSONs (cell names carry
|
| 89 |
+
# the -ch tag), so the loader can hold both columns at once.
|
| 90 |
+
readout = sys.argv[sys.argv.index("--readout") + 1] if "--readout" in sys.argv else "fold"
|
| 91 |
+
if readout not in ("fold", "chain"):
|
| 92 |
+
raise SystemExit(f"--readout must be fold|chain (got {readout})")
|
| 93 |
+
# --chain-arms <P>:<score>[,...] (gen_q#267 re-sweep, owner 2026-09-22 06:40/07:05). At the flagship
|
| 94 |
+
# beta and the COMPUTED cap the chain's only knobs are the particle count (it is a stochastic
|
| 95 |
+
# estimator, so variance matters) and the read-out, so THAT is the sweep -- 4 arms per row, no cap
|
| 96 |
+
# sweep and no beta sweep "to be safe". Each arm is submitted SEPARATELY under its own --tag because
|
| 97 |
+
# plan_particles / plan_score are --extra overrides that apply to a whole submission: mixing them in
|
| 98 |
+
# one submission would silently run every cell at the last value under a single name (the plan_temp
|
| 99 |
+
# lesson). Default "16:prob" = the flagship arm alone.
|
| 100 |
+
# --chain-betas <b>[,<b>] (gen_q#267). The chain runs at the row's flagship beta by default. The
|
| 101 |
+
# RETIRED fold column of tab:flagship_fold is a maximum over a 12-arm (beta, L) grid, so on the rows
|
| 102 |
+
# whose winning fold arm sat at a DIFFERENT beta than the pinned flagship recipe, a single-beta chain
|
| 103 |
+
# cell would be compared against a fold maximum taken at another beta. This adds the published
|
| 104 |
+
# winner's beta as a second chain arm on exactly those rows; the cap is recomputed for it.
|
| 105 |
+
chain_betas = ([float(x) for x in sys.argv[sys.argv.index("--chain-betas") + 1].split(",")]
|
| 106 |
+
if "--chain-betas" in sys.argv else None)
|
| 107 |
+
chain_arms = [(int(x.split(":")[0]), x.split(":")[1]) for x in
|
| 108 |
+
(sys.argv[sys.argv.index("--chain-arms") + 1]
|
| 109 |
+
if "--chain-arms" in sys.argv else "16:prob").split(",")]
|
| 110 |
+
for _np, _sc in chain_arms:
|
| 111 |
+
if _np not in CHAIN_PARTICLES or _sc not in ("prob", "logit"):
|
| 112 |
+
raise SystemExit(f"--chain-arms: {_np}:{_sc} outside the sanctioned grid "
|
| 113 |
+
f"{CHAIN_PARTICLES} x (prob, logit)")
|
| 114 |
+
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)
|
| 115 |
+
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
|
| 116 |
+
# --critic-from <FAM> (2026-09-21): where the s3h4 IQL-critic control takes its VALUE FUNCTION, when
|
| 117 |
+
# that is not the proposer's own family. A BC actor has no co-trained critic, so on a row pinned to a
|
| 118 |
+
# BC proposer the fair RISE/IDQL-family baseline is "the IQL value function ranking THIS proposer's 128
|
| 119 |
+
# candidates" -- stronger than RISE on the actor we already reported as a failed proposer for that task.
|
| 120 |
+
# The critic must be at the same epoch as the proposer: verdict_table refuses a critic-epoch mismatch.
|
| 121 |
+
cfrom = sys.argv[sys.argv.index("--critic-from") + 1] if "--critic-from" in sys.argv else fam
|
| 122 |
+
if cfrom != fam and "s3h4" not in ctl:
|
| 123 |
+
ctl += ",s3h4"
|
| 124 |
+
plab = fam + (f"E{epoch}" if epoch != 5000 else "")
|
| 125 |
+
# MODULE-LEVEL SUBMISSION REMOVED (2026-09-21). This loop used to run at import time, so
|
| 126 |
+
# `from launch_rsm_on_actor import FLAG` -- which scripts/scorer_rank_check.py does, to read the
|
| 127 |
+
# flagship recipe -- submitted the entire ONACTOR grid, reading the IMPORTER's sys.argv as the task
|
| 128 |
+
# list. It queued 36 jobs / 144 eval cells before anyone noticed. A launcher must not do anything
|
| 129 |
+
# on import; launch_flagship_topup.py already guarded itself this way.
|
| 130 |
+
dry = "--print-only" in sys.argv
|
| 131 |
+
tasks = [a for a in sys.argv[1:] if not a.startswith("--") and a in FLAG]
|
| 132 |
+
for task in tasks:
|
| 133 |
+
model, ck, b0, L0 = FLAG[task]
|
| 134 |
+
lab = BASE_LABEL.get(model, model) + _ck_suffix(ck)
|
| 135 |
+
pol, s0a, cells = [], [], []
|
| 136 |
+
for p in (0, 1, 2):
|
| 137 |
+
c = ckpt(task, fam, p, epoch)
|
| 138 |
+
if not c:
|
| 139 |
+
print(f" {task}: no epoch-{epoch} {fam} seed {p}"); continue
|
| 140 |
+
pol += ["--policy", f"{plab}s{p}={c}"]
|
| 141 |
+
# the s0a map is keyed by the POLICY label, so the critic can come from another family while
|
| 142 |
+
# the candidates keep coming from this proposer
|
| 143 |
+
cc = c if cfrom == fam else ckpt(task, cfrom, p, epoch)
|
| 144 |
+
if cc:
|
| 145 |
+
s0a += ["--s0a", f"{plab}s{p}={cc}"]
|
| 146 |
+
else:
|
| 147 |
+
print(f" {task}: no epoch-{epoch} {cfrom} seed {p} for the critic -- s3h4 skipped for that seed")
|
| 148 |
+
if readout == "chain":
|
| 149 |
+
# CHAIN cells. `arms flagship` = the flagship beta at the computed cap; `arms grid` = the
|
| 150 |
+
# eval-time re-sweep (beta axis), cap ALWAYS the computed one. There is no depth axis --
|
| 151 |
+
# see readout_overrides() in launch_e1_grid.py. The PARTICLE axis is NOT built here: a
|
| 152 |
+
# particle count is a `training.plan_particles` --extra, which applies to a whole
|
| 153 |
+
# submission, so each particle count is submitted separately below under its own --tag
|
| 154 |
+
# (otherwise one --extra would silently re-run every cell of the submission at 64 and the
|
| 155 |
+
# cell names could not tell the two apart -- the plan_temp lesson).
|
| 156 |
+
for b in (chain_betas or (CHAIN_BETAS if arms == "grid" else (b0,))):
|
| 157 |
+
cells += ["--cells", f"{lab},{b},{chain_cap_for(b)},chain,128,argmax,{plab}s{p}"]
|
| 158 |
+
else:
|
| 159 |
+
for b in (BETAS if arms == "grid" else (b0,)):
|
| 160 |
+
for L in (HOPS if arms == "grid" else (L0,)):
|
| 161 |
+
cells += ["--cells", f"{lab},{b},{L},{'d1' if L == 1 else 'fold'},128,argmax,{plab}s{p}"]
|
| 162 |
+
if not pol:
|
| 163 |
+
continue
|
| 164 |
+
for es in eseeds:
|
| 165 |
+
if readout == "chain":
|
| 166 |
+
# no controls re-run: the chain changes only the RSM read-out, and the control arms
|
| 167 |
+
# (bc / random / permuted / s3h4 IQL critic) do not use it. Re-running them would be
|
| 168 |
+
# duplicate episodes, not new evidence.
|
| 169 |
+
for np_, sc in chain_arms:
|
| 170 |
+
# "16:prob" is the flagship default (plan_particles=16, plan_score=prob from
|
| 171 |
+
# idql_config.py:126), so it submits with NO --extra and an EMPTY tag -- byte-identical
|
| 172 |
+
# to the first wave's cell names, which is what stops a re-run duplicating them.
|
| 173 |
+
dflt = (np_ == 16 and sc == "prob")
|
| 174 |
+
ptag = "" if dflt else f"P{np_}{sc[:2]}"
|
| 175 |
+
ex = [] if dflt else ["--extra", f"training.plan_particles={np_}",
|
| 176 |
+
f"training.plan_score={sc}"]
|
| 177 |
+
run(task, [*pol, *cells, *ex], es,
|
| 178 |
+
f"rsm CHAIN {arms} P{np_}/{sc} ({len(cells)//2} cells)", dry, plab, tsuf=ptag)
|
| 179 |
+
continue
|
| 180 |
+
run(task, [*pol, *s0a, "--grid", "controls",
|
| 181 |
+
"--controls-subset", ctl], es, "controls", dry, plab)
|
| 182 |
+
run(task, [*pol, *cells], es, f"rsm {arms} ({len(cells)//2} cells)", dry, plab)
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
if __name__ == "__main__":
|
| 186 |
+
main()
|
gen_q_rsm/rsm_rise/pipeline/scripts/launch_tdflow_on_actor.py
ADDED
|
@@ -0,0 +1,168 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""TD-FLOW scorer sweep on the RISE actor (S0A), the MC-vs-TD occupancy ablation (gen_q#268).
|
| 3 |
+
|
| 4 |
+
Identical in every respect to scripts/launch_rsm_on_actor.py -- same proposer (the RISE actor at epoch
|
| 5 |
+
5000, 128 chunks per decision step, argmax), same 12-arm read-out grid (beta {0.90,0.95,0.98} x hops
|
| 6 |
+
{1,2,4,8}), same 3 policy seeds x 3 eval seeds x 50 episodes, same horizon 400, same evaluation env --
|
| 7 |
+
except that the value estimator is a TD-Flow successor model (runs/<task>/rsm/TDF_*) instead of the
|
| 8 |
+
Monte-Carlo one (runs/<task>/rsm/*). The TD model is the same width/depth/seed/beta-band/reward-head
|
| 9 |
+
as the flagship MC model of that task, so a TDF cell and its MC twin differ in the occupancy TARGET
|
| 10 |
+
and in nothing else.
|
| 11 |
+
|
| 12 |
+
Controls: the scorer-independent ones (greedy, RISE's own IQL critic, random-of-N) are already on disk
|
| 13 |
+
from launch_rsm_on_actor.py and are shared; what is NOT shared is the PERMUTED control, because it must
|
| 14 |
+
be paired with THIS scorer's checkpoint (verdict_table keys the control by the checkpoint that produced
|
| 15 |
+
the scores). `--wave flagship` submits only the task's flagship (beta, hops) arm plus that control --
|
| 16 |
+
the headline MC-vs-TD number -- and `--wave grid` submits the remaining 11 arms.
|
| 17 |
+
|
| 18 |
+
usage: launch_tdflow_on_actor.py <task> [<task> ...] [--wave flagship|grid|all] [--print-only]
|
| 19 |
+
"""
|
| 20 |
+
import subprocess, sys
|
| 21 |
+
# --proposer FAM (gen_q#268 / #267): the flagship is moving to a best-proposer-per-task table, and every
|
| 22 |
+
# value-estimation method -- these three included -- must be measured on THAT proposer. The policy
|
| 23 |
+
# family is therefore a parameter, not the S0A constant it was. The family is carried into the cell
|
| 24 |
+
# label (S0Aidqls0, S0Ansns1, ...) and into --tag, so a cell on one proposer can never be confused
|
| 25 |
+
# with, skipped for, or pooled with the same read-out on another: launch_e1_grid's busy/exists checks
|
| 26 |
+
# key on the cell NAME. Default S0A keeps every existing cell name byte-identical.
|
| 27 |
+
|
| 28 |
+
from pathlib import Path
|
| 29 |
+
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
| 30 |
+
from launch_flagship_topup import ENVS, _ck_suffix, ckpt
|
| 31 |
+
ROOT = Path("/proj/dmfexp/zwhong/rsm_rise")
|
| 32 |
+
# task -> (TD-Flow cell, checkpoint, flagship beta, flagship hops). The cell mirrors the MC model the
|
| 33 |
+
# flagship row uses (M -> TDF_M, L40 -> TDF_L40, M_s1 -> TDF_M_s1) and the (beta, hops) are the same
|
| 34 |
+
# read-out the MC flagship row reports, so the flagship wave is a like-for-like swap of the scorer.
|
| 35 |
+
FLAG = {
|
| 36 |
+
"square_sub_20100": ("TDF_M", "best", 0.9, 3),
|
| 37 |
+
"square_expert_play": ("TDF_L40", "best", 0.9, 2),
|
| 38 |
+
"two_piece_expert_suboptimal": ("TDF_M", "s100000", 0.9, 3),
|
| 39 |
+
"two_piece_expert_play": ("TDF_L40", "best", 0.95, 8),
|
| 40 |
+
"mug_expert_suboptimal": ("TDF_M_s1", "best", 0.95, 1),
|
| 41 |
+
"threading_expert_play": ("TDF_M", "best", 0.9, 1),
|
| 42 |
+
"two_piece_expert_play_tipping": ("TDF_M", "best", 0.95, 8),
|
| 43 |
+
# regenerated-data tasks (2026-09-21): TD-Flow model TDF_M, parent beta/depth
|
| 44 |
+
"mug_mgen": ("TDF_M", "best", 0.95, 1),
|
| 45 |
+
"threading_mgen": ("TDF_M", "best", 0.9, 1),
|
| 46 |
+
}
|
| 47 |
+
# Cell-name label. verdict_table.py reads the successor model out of the rsm_ckpt PATH, not out of the
|
| 48 |
+
# cell name, so this label only has to be unique against the MC labels (Mb / L40b / Ms1b / Ms100k) --
|
| 49 |
+
# otherwise a TD cell and its MC twin would collide on one JSON filename.
|
| 50 |
+
LABEL = {"TDF_M": "TDFM", "TDF_L40": "TDFL40", "TDF_M_s1": "TDFMs1",
|
| 51 |
+
"TDF_M_td": "TDFMtd", "TDF_M_td2": "TDFMtd2"}
|
| 52 |
+
BETAS, HOPS = (0.90, 0.95, 0.98), (1, 2, 4, 8)
|
| 53 |
+
GAMMA = 0.99 # the planner's plan_gamma; the chain's cap depends on it
|
| 54 |
+
CHAIN_PARTICLES = (16, 64)
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def chain_cap_for(beta, gamma=GAMMA, tail_eps=1e-3):
|
| 58 |
+
"""The chain's truncation cap: smallest L with P(walk > L) = p**L <= tail_eps, p the reference's
|
| 59 |
+
continuation coin (gamma-beta)/(gamma(1-beta)) [ogbench_genq/rsm.py:113]. Same closed form and same
|
| 60 |
+
tail as scripts/launch_rsm_on_actor.chain_cap_for -- TD-Flow MUST use the identical cap rule or the
|
| 61 |
+
comparison measures the read-out instead of the value estimator (owner, 2026-09-22 06:45)."""
|
| 62 |
+
import math
|
| 63 |
+
p = (gamma - beta) / (gamma * (1.0 - beta))
|
| 64 |
+
return int(math.ceil(math.log(tail_eps) / math.log(p)))
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def run(task, extra, es, label, dry, prop="S0A", tsuf=""):
|
| 68 |
+
model, ck, b0, L0 = FLAG[task]
|
| 69 |
+
rsm = ROOT / f"runs/{task}/rsm/{model}/ckpt_{ck}.pt"
|
| 70 |
+
if not rsm.exists():
|
| 71 |
+
print(f" {task} es{es} {label}: MISSING {rsm}"); return
|
| 72 |
+
lab = LABEL[model] + _ck_suffix(ck)
|
| 73 |
+
cmd = [sys.executable, str(ROOT / "scripts/launch_e1_grid.py"), "--task", task, "--env", ENVS[task],
|
| 74 |
+
"--model", f"{lab}={rsm}:mlp", "--hop", str(ROOT / f"runs/{task}/hop/gauss/policy_r1.pt"),
|
| 75 |
+
"--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}")),
|
| 76 |
+
"--out-dir", str(ROOT / f"runs/{task}/eval_onactor"), "--pack", "4", "--queue", "preemptable",
|
| 77 |
+
"--primary-beta", str(b0), "--primary-depth", str(L0), *extra]
|
| 78 |
+
if dry:
|
| 79 |
+
cmd.append("--print-only")
|
| 80 |
+
r = subprocess.run(cmd, capture_output=True, text=True)
|
| 81 |
+
tail = [l for l in r.stderr.splitlines() if "jobs submitted" in l or "missing" in l]
|
| 82 |
+
print(f" {task} es{es} {label}:", tail[-1:] or r.stderr.strip()[-300:])
|
| 83 |
+
if dry:
|
| 84 |
+
print("\n".join(r.stdout.splitlines()[:4]))
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def main():
|
| 88 |
+
dry = "--print-only" in sys.argv
|
| 89 |
+
wave = "all"
|
| 90 |
+
prop = "S0A"
|
| 91 |
+
# --readout fold|chain (gen_q#267, owner 2026-09-22 06:45): TD-Flow shares RSM's eval read-out, so
|
| 92 |
+
# comparing RSM-chain against TD-Flow-fold would measure the read-out and not the value estimator.
|
| 93 |
+
# DEFAULT fold, so every existing invocation is unchanged; chain cells carry the -ch name tag and land
|
| 94 |
+
# in their own JSONs. Settings are TRANSFERRED from the RSM sweep, not swept here (owner 06:50).
|
| 95 |
+
readout = sys.argv[sys.argv.index("--readout") + 1] if "--readout" in sys.argv else "fold"
|
| 96 |
+
if readout not in ("fold", "chain"):
|
| 97 |
+
raise SystemExit(f"--readout must be fold|chain (got {readout})")
|
| 98 |
+
chain_betas = ([float(x) for x in sys.argv[sys.argv.index("--chain-betas") + 1].split(",")]
|
| 99 |
+
if "--chain-betas" in sys.argv else None)
|
| 100 |
+
chain_arms = [(int(x.split(":")[0]), x.split(":")[1]) for x in
|
| 101 |
+
(sys.argv[sys.argv.index("--chain-arms") + 1]
|
| 102 |
+
if "--chain-arms" in sys.argv else "16:prob").split(",")]
|
| 103 |
+
for i, a in enumerate(sys.argv):
|
| 104 |
+
if a == "--wave":
|
| 105 |
+
wave = sys.argv[i + 1]
|
| 106 |
+
if a == "--proposer":
|
| 107 |
+
prop = sys.argv[i + 1]
|
| 108 |
+
epoch = 5000
|
| 109 |
+
for i, a in enumerate(sys.argv):
|
| 110 |
+
if a == "--epoch":
|
| 111 |
+
epoch = int(sys.argv[i + 1])
|
| 112 |
+
plab = prop + (f"E{epoch}" if epoch != 5000 else "") # label/tag carry the epoch: 500 and 5000 cells never share a name
|
| 113 |
+
tasks = [a for a in sys.argv[1:] if not a.startswith("--") and a in FLAG]
|
| 114 |
+
for task in tasks:
|
| 115 |
+
model, ck, b0, L0 = FLAG[task]
|
| 116 |
+
lab = LABEL[model] + _ck_suffix(ck)
|
| 117 |
+
# MOVING CHECKPOINT GUARD (2026-09-21): ckpt_best.pt is rewritten while the TD-Flow model trains, so
|
| 118 |
+
# cells launched before the final checkpoint exists load different weights and pool as one arm.
|
| 119 |
+
# Refuse unless ckpt_s100000.pt sits beside it or --allow-partial is given explicitly.
|
| 120 |
+
_final = ROOT / f"runs/{task}/rsm/{model}/ckpt_s100000.pt"
|
| 121 |
+
if ck == "best" and not _final.exists() and "--allow-partial" not in sys.argv:
|
| 122 |
+
print(f" {task}: TD-Flow {model} still training ({_final.name} absent); refusing to evaluate a moving ckpt_best.pt -- pass --allow-partial to override")
|
| 123 |
+
continue
|
| 124 |
+
pol, flag_cells, grid_cells, chain_cells = [], [], [], []
|
| 125 |
+
for p in (0, 1, 2):
|
| 126 |
+
c = ckpt(task, prop, p, epoch)
|
| 127 |
+
if not c:
|
| 128 |
+
print(f" {task}: no epoch-{epoch} {prop} seed {p}"); continue
|
| 129 |
+
pol += ["--policy", f"{plab}s{p}={c}"]
|
| 130 |
+
# the chain runs at the SAME beta as the matching RSM cell (the row's flagship beta) and at the
|
| 131 |
+
# cap computed from the 1e-3 tail; there is no depth axis.
|
| 132 |
+
for _cb in (chain_betas or (b0,)):
|
| 133 |
+
chain_cells.append(f"{lab},{_cb},{chain_cap_for(_cb)},chain,128,argmax,{plab}s{p}")
|
| 134 |
+
for b in BETAS:
|
| 135 |
+
for L in HOPS:
|
| 136 |
+
spec = f"{lab},{b},{L},{'d1' if L == 1 else 'fold'},128,argmax,{plab}s{p}"
|
| 137 |
+
(flag_cells if (abs(b - b0) < 1e-9 and L == L0) else grid_cells).append(spec)
|
| 138 |
+
# The flagship read-out is not always inside the 12-arm grid (square_sub_20100 and
|
| 139 |
+
# two_piece_expert_suboptimal report hops=3), so add it explicitly when it is not.
|
| 140 |
+
if L0 not in HOPS or all(abs(b - b0) > 1e-9 for b in BETAS):
|
| 141 |
+
flag_cells.append(f"{lab},{b0},{L0},{'d1' if L0 == 1 else 'fold'},128,argmax,{plab}s{p}")
|
| 142 |
+
if not pol:
|
| 143 |
+
continue
|
| 144 |
+
flag_cells = sorted(set(flag_cells))
|
| 145 |
+
for es in (0, 1, 2):
|
| 146 |
+
if readout == "chain":
|
| 147 |
+
cells = [x for c in chain_cells for x in ("--cells", c)]
|
| 148 |
+
for np_, sc in chain_arms:
|
| 149 |
+
dflt = (np_ == 16 and sc == "prob")
|
| 150 |
+
ptag = "" if dflt else f"P{np_}{sc[:2]}"
|
| 151 |
+
ex = [] if dflt else ["--extra", f"training.plan_particles={np_}",
|
| 152 |
+
f"training.plan_score={sc}"]
|
| 153 |
+
run(task, [*pol, *cells, *ex], es,
|
| 154 |
+
f"tdflow CHAIN P{np_}/{sc} ({len(chain_cells)} cells)", dry, plab, tsuf=ptag)
|
| 155 |
+
continue
|
| 156 |
+
if wave in ("flagship", "all"):
|
| 157 |
+
cells = [x for c in flag_cells for x in ("--cells", c)]
|
| 158 |
+
run(task, [*pol, *cells], es, f"tdflow flagship ({len(flag_cells)} cells)", dry, plab)
|
| 159 |
+
# PERMUTED control, paired with THIS scorer: identical scores, candidate order shuffled.
|
| 160 |
+
run(task, [*pol, "--grid", "controls", "--controls-subset", "permuted"], es,
|
| 161 |
+
"tdflow permuted control", dry, plab)
|
| 162 |
+
if wave in ("grid", "all"):
|
| 163 |
+
cells = [x for c in grid_cells for x in ("--cells", c)]
|
| 164 |
+
run(task, [*pol, *cells], es, f"tdflow grid ({len(grid_cells)} cells)", dry, plab)
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
if __name__ == "__main__":
|
| 168 |
+
main()
|
gen_q_rsm/rsm_rise/pipeline/scripts/launch_temp_on_actor.py
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Temperature sweep for the RSM read-out on the RISE actor.
|
| 3 |
+
|
| 4 |
+
WHY. gen_q#261 traced the real corpus's flat `prob` score to reward-head saturation: mean |logit| ~= 25
|
| 5 |
+
with ~99.8 % of sampled successors beyond |logit| > 15, so sigma(R/T) underflows or ties at 1 and the
|
| 6 |
+
mean-sigmoid array loses its ordering (ties at the top: ~37 of 128 real, 45-71 in sim, exactly 1 for the
|
| 7 |
+
logit array). On the real corpus switching to the logit array fixes it; in sim the sigmoid still WINS
|
| 8 |
+
(threading 9.4 % vs 2.0 %), even at depth 1, so neither array is simply correct.
|
| 9 |
+
|
| 10 |
+
`plan_temp` is the knob that attacks the cause rather than the symptom: the fold uses c_k = sigma(R(z_k)/T),
|
| 11 |
+
so a LARGER T pulls the argument toward 0, de-saturates the sigmoid, and should collapse the tie count while
|
| 12 |
+
keeping the product fold's aggregation over hops -- the property the logit array throws away by reading only
|
| 13 |
+
the terminal hop. It has never been swept: 2954 + 2777 archived cells all sit at T = 0.2 and exactly one at
|
| 14 |
+
0.05. If a larger T reduces ties without losing the fold, that is strictly better than either array.
|
| 15 |
+
|
| 16 |
+
WRONG KNOB, FIRST ATTEMPT (2026-09-21). The first run of this launcher passed `training.plan_temp`. That
|
| 17 |
+
is the SOFTMAX-RULE temperature on Qbar (`select(s, rule, temp=cfg["plan_temp"], ...)` in rsm_planner.py) and
|
| 18 |
+
is read ONLY when `plan_rule=softmax`; every cell here uses `argmax`, so it was inert. The sigmoid read-out T
|
| 19 |
+
is `plan_temperature` (rsm_planner.py passes it as `temperature=`; 0 means "the checkpoint's calib.json T,
|
| 20 |
+
else 1.0"). All 42 cells of that sweep therefore ran at the checkpoint default and are duplicates of the
|
| 21 |
+
archived flagship arm -- caught because mug T=10 and T=25 agreed to the third decimal on BOTH
|
| 22 |
+
`frac_saturated_mean` (0.296) and `ties_at_max_mean` (72.3), and two_piece T=1 and T=5 agreed exactly. They
|
| 23 |
+
are quarantined (`verdict_table.SKIP`) rather than pooled, because the arm key did not contain the
|
| 24 |
+
temperature; it now does. A knob that produces bit-identical health numbers at two settings is not a
|
| 25 |
+
measurement of that knob -- verify the fingerprint records it before believing any grid built on it.
|
| 26 |
+
|
| 27 |
+
usage: launch_temp_on_actor.py [--print-only] [--preflight]
|
| 28 |
+
--preflight submits ONE cell and prints the recorded plan_temperature and tie count, so the knob is
|
| 29 |
+
checked against the fingerprint before 54 cells are spent on it.
|
| 30 |
+
"""
|
| 31 |
+
import subprocess
|
| 32 |
+
import sys
|
| 33 |
+
from pathlib import Path
|
| 34 |
+
|
| 35 |
+
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
| 36 |
+
from launch_flagship_topup import ENVS, BASE_LABEL, _ck_suffix, ckpt # noqa: E402
|
| 37 |
+
|
| 38 |
+
ROOT = Path("/proj/dmfexp/zwhong/rsm_rise")
|
| 39 |
+
# the two open rows plus one winning row as a control: if a larger T helps only where the row is weak, that
|
| 40 |
+
# is a different story from it helping everywhere.
|
| 41 |
+
ARMS = {
|
| 42 |
+
"threading_expert_play": ("M", "best", 0.98, 1),
|
| 43 |
+
"mug_expert_suboptimal": ("M_s1", "best", 0.95, 1),
|
| 44 |
+
"two_piece_expert_play": ("L40", "best", 0.95, 8),
|
| 45 |
+
}
|
| 46 |
+
# gen_q#261 measured on the real cache that ties at the top collapse from 35.5/128 to exactly 1.0 at every
|
| 47 |
+
# T >= 5, that the depth-4 ANTI-selection is cured by it (sign flips from +0.085 to -0.23..-0.35), and that
|
| 48 |
+
# T-corrected `prob` then BEATS the logit array (d4 -0.266 +- 0.059, i.e. 4.5 sem) because it keeps the
|
| 49 |
+
# product fold as well as the ordering. T in [5,70] is a plateau there, so the supported claim is "any T
|
| 50 |
+
# large enough to leave saturation", not a sharp optimum. Their checkpoints run at T=1 (no calib.json);
|
| 51 |
+
# MEASURED, not assumed: sim's archived cells record `scorer.temperature = 1.0` with
|
| 52 |
+
# `temperature_override = 0.0`, so sim ALSO runs at T=1 (there is no calib.json anywhere). The
|
| 53 |
+
# earlier claim here -- that sim's default is 0.2, five times more saturating -- was wrong: 0.2 is the
|
| 54 |
+
# dataclass default of `plan_temp`, the inert field. Sim and real start level, and T=1.0 below is
|
| 55 |
+
# therefore a POSITIVE CONTROL that must reproduce the archived flagship number within seed noise.
|
| 56 |
+
TEMPS = (1.0, 5.0, 10.0, 25.0) # T=1.0 == the archived effective T, so it is the positive control
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def main():
|
| 60 |
+
dry = "--print-only" in sys.argv
|
| 61 |
+
for task, (model, ck, b, L) in ARMS.items():
|
| 62 |
+
rsm = ROOT / f"runs/{task}/rsm/{model}/ckpt_{ck}.pt"
|
| 63 |
+
if not rsm.is_file():
|
| 64 |
+
print(f"{task}: no {rsm.name}"); continue
|
| 65 |
+
lab = BASE_LABEL.get(model, model) + _ck_suffix(ck)
|
| 66 |
+
pol, cells = [], []
|
| 67 |
+
for p in (0, 1, 2):
|
| 68 |
+
c = ckpt(task, "S0A", p)
|
| 69 |
+
if not c:
|
| 70 |
+
continue
|
| 71 |
+
pol += ["--policy", f"S0As{p}={c}"]
|
| 72 |
+
cells += ["--cells", f"{lab},{b},{L},{'d1' if L == 1 else 'fold'},128,argmax,S0As{p}"]
|
| 73 |
+
if not cells:
|
| 74 |
+
print(f"{task}: no epoch-5000 S0A"); continue
|
| 75 |
+
for T in TEMPS:
|
| 76 |
+
for es in (0, 1, 2):
|
| 77 |
+
cmd = [sys.executable, str(ROOT / "scripts/launch_e1_grid.py"), "--task", task,
|
| 78 |
+
"--env", ENVS[task], "--model", f"{lab}={rsm}:mlp",
|
| 79 |
+
"--hop", str(ROOT / f"runs/{task}/hop/gauss/policy_r1.pt"), *pol, *cells,
|
| 80 |
+
"--num-rollouts", "50", "--horizon", "400", "--eval-seed", str(es),
|
| 81 |
+
# `plan_temperature`, NOT `plan_temp` -- see WRONG KNOB above.
|
| 82 |
+
"--extra", f"training.plan_temperature={T}",
|
| 83 |
+
"--tag", f"TEMPERATURE{str(T).replace('.', 'p')}-es{es}",
|
| 84 |
+
"--out-dir", str(ROOT / f"runs/{task}/eval_temp2"),
|
| 85 |
+
"--pack", "3", "--queue", "preemptable"]
|
| 86 |
+
if dry:
|
| 87 |
+
cmd.append("--print-only")
|
| 88 |
+
r = subprocess.run(cmd, capture_output=True, text=True)
|
| 89 |
+
tail = [l for l in r.stderr.splitlines() if "jobs submitted" in l or "missing" in l]
|
| 90 |
+
print(f" {task} T={T} es{es}:", tail[-1:] or r.stderr.strip()[-160:])
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
if __name__ == "__main__":
|
| 94 |
+
main()
|
gen_q_rsm/rsm_rise/pipeline/scripts/lewm_gate.sh
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
# Gate the LeWM trainings on the LeWM smoke (gen_q#268). LSF CPU job -- never the login node.
|
| 3 |
+
#
|
| 4 |
+
# The LeWM port is already unit-tested on CPU (test_lewm_port.py, 6/6: SIGReg against an independent
|
| 5 |
+
# numpy implementation, AdaLN-zero identity at init, target-not-detached, read-out round trip). What
|
| 6 |
+
# those cannot cover is StreamingFrameData against a REAL HDF5 -- the cache-row -> demo-frame mapping
|
| 7 |
+
# and the episode-resident buffer -- so the trainings wait on scripts/lewm_smoke.sh rather than on a
|
| 8 |
+
# human. The cluster had 166 jobs pending when this was written, so that wait is hours, not minutes.
|
| 9 |
+
#
|
| 10 |
+
# Launches ONLY on a clean pass (both "LEWM SMOKE DONE" and "READOUT OK" present, and no traceback).
|
| 11 |
+
# On a failure it says so and exits without submitting anything: a silent launch of an unvalidated
|
| 12 |
+
# streaming loader across seven tasks is the failure mode this gate exists to prevent.
|
| 13 |
+
# Idempotent: status/lewm/launched is the marker, so a restart never double-submits.
|
| 14 |
+
# usage: lewm_gate.sh [max_iterations] [sleep_seconds]
|
| 15 |
+
set -uo pipefail
|
| 16 |
+
ROOT=/proj/dmfexp/zwhong/rsm_rise
|
| 17 |
+
S=$ROOT/status/lewm; mkdir -p "$S"
|
| 18 |
+
ITERS=${1:-240}; NAP=${2:-300}
|
| 19 |
+
TASKS="square_expert_play two_piece_expert_suboptimal two_piece_expert_play mug_expert_suboptimal
|
| 20 |
+
threading_expert_play two_piece_expert_play_tipping square_sub_20100"
|
| 21 |
+
|
| 22 |
+
for i in $(seq 1 "$ITERS"); do
|
| 23 |
+
if [ -f "$S/launched" ]; then echo "[lewm_gate] already launched: $(cat "$S/launched")"; break; fi
|
| 24 |
+
if [ -f "$S/failed" ]; then echo "[lewm_gate] smoke previously FAILED; not launching"; break; fi
|
| 25 |
+
ok=0; bad=0
|
| 26 |
+
for f in $ROOT/logs/lsf/rr_lewm_smoke.*.out; do
|
| 27 |
+
[ -f "$f" ] || continue
|
| 28 |
+
if grep -q "LEWM SMOKE DONE" "$f" && grep -q "READOUT OK" "$f"; then ok=1; fi
|
| 29 |
+
if grep -qE "Traceback|AssertionError|LEWM SMOKE ERROR" "$f"; then bad=1; fi
|
| 30 |
+
done
|
| 31 |
+
for f in $ROOT/logs/lsf/rr_lewm_smoke.*.err; do
|
| 32 |
+
[ -f "$f" ] && grep -qE "Traceback|AssertionError" "$f" && bad=1
|
| 33 |
+
done
|
| 34 |
+
if [ "$bad" = 1 ] && [ "$ok" = 0 ]; then
|
| 35 |
+
echo "[lewm_gate] the LeWM smoke FAILED -- not launching. Evidence:"
|
| 36 |
+
grep -hE -A6 "Traceback|AssertionError" $ROOT/logs/lsf/rr_lewm_smoke.*.out \
|
| 37 |
+
$ROOT/logs/lsf/rr_lewm_smoke.*.err 2>/dev/null | head -25
|
| 38 |
+
date -u +%FT%TZ > "$S/failed"; break
|
| 39 |
+
fi
|
| 40 |
+
if [ "$ok" = 1 ]; then
|
| 41 |
+
echo "[lewm_gate] smoke PASSED at $(date -u +%FT%TZ) -> launching trainings"
|
| 42 |
+
for T in $TASKS; do
|
| 43 |
+
EXHOSTS="p2-r03-n1" "$ROOT/scripts/submit_lewm.sh" "$T" 2>&1 | tail -1 | sed 's/^/ /'
|
| 44 |
+
done
|
| 45 |
+
bsub -G grp_preemptable -q preemptable -n 1 -M 16G -r -J rr_lewm_babysit \
|
| 46 |
+
-o "$ROOT/logs/lsf/rr_lewm_babysit.%J.out" -e "$ROOT/logs/lsf/rr_lewm_babysit.%J.err" \
|
| 47 |
+
"$ROOT/scripts/wm_babysit.sh" lewm 2>&1 | tail -1 | sed 's/^/ /'
|
| 48 |
+
date -u +%FT%TZ > "$S/launched"
|
| 49 |
+
break
|
| 50 |
+
fi
|
| 51 |
+
echo "[lewm_gate] iteration $i/$ITERS $(date -u +%FT%TZ): smoke not finished yet"
|
| 52 |
+
sleep "$NAP"
|
| 53 |
+
done
|
| 54 |
+
echo "[lewm_gate] DONE $(date -u +%FT%TZ)"
|
gen_q_rsm/rsm_rise/pipeline/scripts/lewm_smoke.sh
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
# LeWM end-to-end smoke (gen_q#268). GPU LSF job -- never the login node.
|
| 3 |
+
# test_lewm_port.py already pins the MODEL (SIGReg vs numpy, AdaLN-zero identity, no-detach,
|
| 4 |
+
# read-out round trip) on CPU. What it cannot cover is the part that touches real data:
|
| 5 |
+
# A. StreamingFrameData opens the task's source HDF5, maps cache rows to demo frames and asserts
|
| 6 |
+
# the per-episode frame counts agree -- the alignment that makes LeWM read the same actions and
|
| 7 |
+
# the same provenance label as every other scorer;
|
| 8 |
+
# B. a short training runs, the SIGReg term is finite and the embedding does not collapse;
|
| 9 |
+
# C. the checkpoint it writes loads through lewm_readout and scores candidates at L=1/2/4.
|
| 10 |
+
set -uo pipefail
|
| 11 |
+
ROOT=/proj/dmfexp/zwhong/rsm_rise
|
| 12 |
+
CODE=$ROOT/code/gen_q/rsm_libero
|
| 13 |
+
SC=$ROOT/runs/_lewm_smoke; rm -rf "$SC"; mkdir -p "$SC"
|
| 14 |
+
PY=$ROOT/venv_rsm/bin/python
|
| 15 |
+
TASK=${TASK:-two_piece_expert_suboptimal}
|
| 16 |
+
export OMP_NUM_THREADS=8 PYTHONUNBUFFERED=1 PYTHONPATH=$CODE
|
| 17 |
+
cd "$CODE"
|
| 18 |
+
echo "===== A/B. train 120 steps on $TASK ====="
|
| 19 |
+
$PY train_lewm.py --cache "$ROOT/cache/$TASK" --out "$SC/lewm" --size s --steps 120 \
|
| 20 |
+
--batch 16 --resident 12 --refresh-every 4 --eval-every 60 --save-every 0 --eval-rows 64 \
|
| 21 |
+
--num-proj 128 --wandb-mode disabled --resume 0 --seed 0 2>&1 \
|
| 22 |
+
| grep -E "^\[lewm_data\]|^\[lewm\]" | tee "$SC/train.txt"
|
| 23 |
+
echo "===== C. read-out ====="
|
| 24 |
+
$PY - "$SC" <<'PYX'
|
| 25 |
+
import sys, torch
|
| 26 |
+
sys.path.insert(0, "/proj/dmfexp/zwhong/rsm_rise/code/gen_q/rsm_libero")
|
| 27 |
+
import lewm_readout
|
| 28 |
+
p = f"{sys.argv[1]}/lewm/ckpt.pt"
|
| 29 |
+
ck = torch.load(p, map_location="cpu", weights_only=False)
|
| 30 |
+
print("blob: model=", ck["model"], "| size=", ck["arch"]["size"], "| emb=", ck["arch"]["emb_dim"],
|
| 31 |
+
"| d_act=", ck["d_act"], "| step=", ck["step"], "| win=", round(float(ck["q_action_winrate"]), 3))
|
| 32 |
+
dev = "cuda" if torch.cuda.is_available() else "cpu"
|
| 33 |
+
crit = lewm_readout.load_critic_lewm(p, device=dev)
|
| 34 |
+
torch.manual_seed(0)
|
| 35 |
+
B = 8
|
| 36 |
+
img = torch.randint(0, 255, (B, 6, crit.res, crit.res), dtype=torch.uint8)
|
| 37 |
+
a = torch.randn(B, crit.d_act).clamp(-1, 1)
|
| 38 |
+
for mode, L in (("d1", 1), ("fold", 2), ("fold", 4)):
|
| 39 |
+
q, ql = crit.q((img, None), a, mode=mode, depth=L, gamma=0.99, return_logit=True)
|
| 40 |
+
q = q.float().cpu()
|
| 41 |
+
print(f" q[{mode},L={L}] finite={bool(torch.isfinite(q).all())} "
|
| 42 |
+
f"in[0,1]={bool((q>=0).all() and (q<=1).all())} spread={float(q.max()-q.min()):.5f} "
|
| 43 |
+
f"mean={float(q.mean()):.4f}")
|
| 44 |
+
print(" describe:", crit.describe())
|
| 45 |
+
print("READOUT OK")
|
| 46 |
+
PYX
|
| 47 |
+
echo "===== LEWM SMOKE DONE ====="
|
gen_q_rsm/rsm_rise/pipeline/scripts/master_table.py
ADDED
|
@@ -0,0 +1,1189 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""THE master results table: every arm per task plus the RSM recipe (reward head, beta, hops, N).
|
| 2 |
+
Writes docs/MASTER_TABLE.md. All cells: policy epoch 5000, horizon 400, our data.
|
| 3 |
+
"""
|
| 4 |
+
import sys
|
| 5 |
+
sys.path.insert(0, "/proj/dmfexp/zwhong/rsm_rise/scripts")
|
| 6 |
+
from verdict_table import cells as _cells_raw, pool, rate, mcnemar, ztest, TASKS, canon_region_key, region_area
|
| 7 |
+
|
| 8 |
+
_CELL_CACHE = {}
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def cells(task):
|
| 12 |
+
"""One snapshot of runs/<task>/eval_*/ per run, shared by every section.
|
| 13 |
+
|
| 14 |
+
Sections 0, 1 and 5 each re-read the eval tree independently. With ~100 top-up jobs writing JSONs,
|
| 15 |
+
a cell landing between two of those reads made the sections disagree about the same arm -- the
|
| 16 |
+
cross-section guard caught exactly that (section 0 ceiling 49.43 vs section 1 headline 51.33 on
|
| 17 |
+
piece-assembly (Suboptimal)). A results document must be a consistent snapshot of one moment, not
|
| 18 |
+
a series of reads of a moving directory, or two of its tables will quietly describe different data.
|
| 19 |
+
|
| 20 |
+
The key carries the task's CANON entry because the alternate-region section deliberately rebinds
|
| 21 |
+
verdict_table.CANON and re-reads the same task expecting DIFFERENT cells; keying on task alone
|
| 22 |
+
would hand it the canonical-region snapshot instead.
|
| 23 |
+
"""
|
| 24 |
+
import verdict_table as _vtm
|
| 25 |
+
k = (task, repr(_vtm.CANON.get(task)))
|
| 26 |
+
if k not in _CELL_CACHE:
|
| 27 |
+
_CELL_CACHE[k] = _cells_raw(task)
|
| 28 |
+
return _CELL_CACHE[k]
|
| 29 |
+
import glob, json as _json
|
| 30 |
+
from collections import defaultdict
|
| 31 |
+
|
| 32 |
+
# trajectory counts, read from the file each policy actually trains on (expert = reward-1 episodes)
|
| 33 |
+
def _horizon(task):
|
| 34 |
+
"""the rollout horizon every cell of this task is evaluated at, read back from a result file"""
|
| 35 |
+
for f in glob.glob(f"{ROOT}/runs/{task}/eval_*/*.json"):
|
| 36 |
+
try: j = _json.load(open(f))
|
| 37 |
+
except Exception: continue
|
| 38 |
+
h = j.get("rollout_horizon")
|
| 39 |
+
if h: return str(h)
|
| 40 |
+
return "400"
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def _demo_len(task):
|
| 44 |
+
"""median demonstration length, for comparison with the horizon"""
|
| 45 |
+
import h5py, numpy as _np
|
| 46 |
+
task = VARIANT_OF.get(task, task) # a flagship variant is a SLICE of the parent's hdf5
|
| 47 |
+
src = {"square_expert_play": "data/raw/square_expert_play.hdf5",
|
| 48 |
+
"square_expert_suboptimal": "data/raw/square_expert_suboptimal.hdf5",
|
| 49 |
+
"two_piece_expert_play": "data/raw/two_piece_expert_play.hdf5",
|
| 50 |
+
"two_piece_expert_suboptimal": "data/raw/two_piece_expert_suboptimal.hdf5",
|
| 51 |
+
"two_piece_expert_play_tipping": "data/raw/two_piece_expert_play_tipping.hdf5",
|
| 52 |
+
"mug_expert_suboptimal": "data/raw/mug_expert_suboptimal.hdf5",
|
| 53 |
+
"threading_expert_play": "data/raw/threading_expert_play.hdf5"}.get(task)
|
| 54 |
+
if not src: return "--"
|
| 55 |
+
try:
|
| 56 |
+
with h5py.File(f"{ROOT}/{src}", "r") as h:
|
| 57 |
+
d = h["data"]
|
| 58 |
+
L = [d[k]["actions"].shape[0] for k in d if d[k]["rewards"][:].max() > 0]
|
| 59 |
+
return str(int(_np.median(L))) if L else "--"
|
| 60 |
+
except Exception:
|
| 61 |
+
return "--"
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
_HZ, _DL = {}, {}
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def _traj(task):
|
| 68 |
+
import h5py
|
| 69 |
+
# A flagship variant has no hdf5 of its own -- it is a cache slice -- so its trajectory
|
| 70 |
+
# counts are declared in FLAGSHIP_VARIANT rather than counted off disk.
|
| 71 |
+
if task in VARIANT_TRAJ: return VARIANT_TRAJ[task]
|
| 72 |
+
src = {"square_expert_play": "data/raw/square_expert_play.hdf5",
|
| 73 |
+
"square_expert_suboptimal": "data/raw/square_expert_suboptimal.hdf5",
|
| 74 |
+
"two_piece_expert_play": "data/raw/two_piece_expert_play.hdf5",
|
| 75 |
+
"two_piece_expert_suboptimal": "data/raw/two_piece_expert_suboptimal.hdf5",
|
| 76 |
+
"two_piece_expert_play_tipping": "data/raw/two_piece_expert_play_tipping.hdf5",
|
| 77 |
+
"mug_expert_suboptimal": "data/raw/mug_expert_suboptimal.hdf5",
|
| 78 |
+
"threading_expert_play": "data/raw/threading_expert_play.hdf5"}.get(task)
|
| 79 |
+
if not src: return "--"
|
| 80 |
+
try:
|
| 81 |
+
with h5py.File(f"{ROOT}/{src}", "r") as h:
|
| 82 |
+
d = h["data"]; e = sum(1 for k in d if d[k]["rewards"][:].max() > 0)
|
| 83 |
+
return f"{e} / {len(d)-e}"
|
| 84 |
+
except Exception:
|
| 85 |
+
return "--"
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
_TRAJ = {}
|
| 89 |
+
|
| 90 |
+
ALT = { # (label, task, pinned region) rows measured in a NON-canonical region, shown separately, never pooled
|
| 91 |
+
"square-peg (Coverage) — full-table region": ("square_expert_play", {"SquareNut": [[-0.16, 0.16], [-0.2, 0.2]]}),
|
| 92 |
+
}
|
| 93 |
+
ALT_IS_FLAGSHIP = set() # alternate rows that belong in section 1 instead
|
| 94 |
+
PAPER_REGIME = {
|
| 95 |
+
"square_sub_paper2": ("square-peg (Suboptimal) — Table IV data regime",
|
| 96 |
+
"20 / 80", "nut [0,0.12],[-0.225,0]"),
|
| 97 |
+
}
|
| 98 |
+
# tasks whose FLAGSHIP row is a data variant; the released-file task drops to secondary with a note.
|
| 99 |
+
FLAGSHIP_VARIANT = {
|
| 100 |
+
"square_expert_suboptimal": ("square_sub_20100", "square-peg (Suboptimal)", "20 / 100"),
|
| 101 |
+
}
|
| 102 |
+
DEMOTED_NOTE = {"square_expert_suboptimal": "released file, 5x the expert data of the flagship variant"}
|
| 103 |
+
VARIANT_OF = {v[0]: k for k, v in FLAGSHIP_VARIANT.items()} # square_sub_20100 -> square_expert_suboptimal
|
| 104 |
+
VARIANT_TRAJ = {v[0]: v[2] for v in FLAGSHIP_VARIANT.values()} # square_sub_20100 -> "20 / 100"
|
| 105 |
+
NAME = {"square_expert_suboptimal": "square-peg (Suboptimal)", "square_expert_play": "square-peg (Coverage)",
|
| 106 |
+
"two_piece_expert_suboptimal": "piece-assembly (Suboptimal)", "two_piece_expert_play": "piece-assembly (Coverage)",
|
| 107 |
+
"mug_expert_suboptimal": "mug-cleanup (Suboptimal)", "threading_expert_play": "threading (Coverage)",
|
| 108 |
+
"two_piece_expert_play_tipping": "piece-assembly tip (Coverage)"}
|
| 109 |
+
NAME.update({v[0]: v[1] for v in FLAGSHIP_VARIANT.values()})
|
| 110 |
+
# ROW LOOP ORDER. The flagship VARIANT is not in TASKS (it has no hdf5 of its own), so before this
|
| 111 |
+
# fix only sections 0 and 5 -- which remap through _row_identity -- ever read it, and section 1 built
|
| 112 |
+
# its square-peg (Suboptimal) row from the released 100/100 file and then demoted that row to
|
| 113 |
+
# secondary. Net effect: the flagship had no square-peg (Suboptimal) row at all once the variant
|
| 114 |
+
# started producing evaluations and the "still training" placeholder stopped firing. The variant is
|
| 115 |
+
# emitted as its own row, immediately before its parent, which keeps the released file visible in
|
| 116 |
+
# secondary without letting it stand in for the corrected split.
|
| 117 |
+
ROW_TASKS = []
|
| 118 |
+
for _t, _ in TASKS:
|
| 119 |
+
_v = FLAGSHIP_VARIANT.get(_t)
|
| 120 |
+
if _v: ROW_TASKS.append(_v[0])
|
| 121 |
+
ROW_TASKS.append(_t)
|
| 122 |
+
PAPER = {"square_expert_suboptimal": (8.0, 34.0, 41.3, 56.0), "square_expert_play": (18.7, 0.0, 19.6, 50.7),
|
| 123 |
+
"two_piece_expert_suboptimal": (20.0, 23.3, 35.7, 36.0), "two_piece_expert_play": (14.7, 2.0, 16.3, 70.7),
|
| 124 |
+
"mug_expert_suboptimal": (31.3, 32.7, 36.7, 40.7), "threading_expert_play": (17.3, 0.0, 9.8, 22.7),
|
| 125 |
+
"two_piece_expert_play_tipping": (0.0, 0.0, 8.0, 51.3)}
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def flat(d):
|
| 129 |
+
o = defaultdict(list)
|
| 130 |
+
for (P, ps, es), v in d.items(): o[(ps, es)] += v
|
| 131 |
+
return o
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
def parse(recipe):
|
| 135 |
+
"""'M@best b0.95 L1 N128' -> (model@ckpt, beta, hops, N).
|
| 136 |
+
|
| 137 |
+
BOTH GRAMMARS (gen_q#267, 2026-09-23). This matched only the fold key `b<beta> L<depth> N<n>`, so
|
| 138 |
+
every COIN-CHAIN arm printed `? ? ?` in the beta/hops/N columns -- visible in the 11:52Z build on
|
| 139 |
+
square-peg (Coverage), the one row whose flagship arm was already a chain arm. With section 1 now
|
| 140 |
+
chain-only that would have blanked the configuration columns of the whole table. A chain key is
|
| 141 |
+
`b<beta> CH<cap> N<n> P<particles> <prob|logit>`, whose length parameter is the CAP, not a depth --
|
| 142 |
+
it is reported as `cap <L>` with the particle count and read-out beside it, because for a chain
|
| 143 |
+
those two are part of the estimator and a top-up that changed them would be a different arm.
|
| 144 |
+
"""
|
| 145 |
+
import re
|
| 146 |
+
m = re.match(r"(\S+) b([0-9.]+) L(\d+) N(\d+)", recipe or "")
|
| 147 |
+
if m:
|
| 148 |
+
return m.groups()
|
| 149 |
+
m = re.match(r"(\S+) b([0-9.]+) CH(\d+) N(\d+)(?: P(\d+))?(?: (prob|logit))?(?: F(\d+))?",
|
| 150 |
+
recipe or "")
|
| 151 |
+
if m:
|
| 152 |
+
# FLOW STEPS travel with the arm too (gen_q#275 via BETA_PATTERNS): the number of Euler steps
|
| 153 |
+
# per successor draw changes what a SAMPLE is, so a cell at F4 is a different estimator from
|
| 154 |
+
# one at the default F8 and must be named as such wherever the configuration is printed.
|
| 155 |
+
_extra = "".join([" P%s" % m.group(5) if m.group(5) else "",
|
| 156 |
+
" %s" % m.group(6) if m.group(6) else "",
|
| 157 |
+
" F%s" % m.group(7) if m.group(7) else ""])
|
| 158 |
+
return (m.group(1), m.group(2), "cap %s%s" % (m.group(3), _extra), m.group(4))
|
| 159 |
+
return ("?", "?", "?", "?")
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
FLAG, SEC, ALTREW, ORCROW, VERLOW = [], [], [], [], []
|
| 163 |
+
# ---- SECTION 0 (owner 2026-09-21): the SINGLE-ACTOR flagship first. "the flagship must use a single
|
| 164 |
+
# actor for RSM for fair comparisons against IDQL and RISE ... we must make sure the reason RSM is winning
|
| 165 |
+
# is not because it is allowed to argmax actors over tasks depending on who is winning." RSM proposes
|
| 166 |
+
# from the RISE actor on every task; built by flagship_latex.build with RSM_PROPOSER pinned.
|
| 167 |
+
def _missing_note(rows):
|
| 168 |
+
"""Which flagship tasks have no RISE-actor RSM arm, named from the data.
|
| 169 |
+
|
| 170 |
+
This sentence used to be hardcoded and went stale: it said "mug: relaxed-criterion re-evaluation
|
| 171 |
+
running" after mug had a full 3x3 and was printing 12.7 in the table right above it. A caption that
|
| 172 |
+
states which rows are missing must be computed from the rows, or it becomes a false claim the moment a
|
| 173 |
+
row lands.
|
| 174 |
+
"""
|
| 175 |
+
from verdict_table import TASKS as _T
|
| 176 |
+
have = {r["label"] for r in rows}
|
| 177 |
+
import flagship_latex as _F
|
| 178 |
+
absent = [_F.NICE.get(nm, nm) for _, nm in _T if _F.NICE.get(nm, nm) not in have]
|
| 179 |
+
if not absent:
|
| 180 |
+
return "Every flagship task has RISE-actor RSM cells."
|
| 181 |
+
return ("No RISE-actor RSM cells yet for: " + ", ".join(absent)
|
| 182 |
+
+ " (its actor is still training at the time of generation).")
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
def _single_actor_section():
|
| 186 |
+
import re as _re, os as _os
|
| 187 |
+
_os.environ["RSM_PROPOSER"] = "RISE policy"
|
| 188 |
+
import flagship_latex as _FL
|
| 189 |
+
_FL.RSM_PROPOSER = "RISE policy"
|
| 190 |
+
rows, counts = _FL.build(cells)
|
| 191 |
+
def strip(x):
|
| 192 |
+
x = x.replace("{\\pm}", "±").replace("^{\\dagger}", "†").replace("^{*}", "*").replace("_{(", "₍").replace(")}", "₎").replace("$", "")
|
| 193 |
+
x = _re.sub(r"\\mathrm\{([^}]*)\}", r"\1", x) # \mathrm{n/a} must not leak into markdown
|
| 194 |
+
# \textit{...} reaches here now that the RSM column is CHAIN-ONLY and an incomplete row prints
|
| 195 |
+
# its launch state (`pend k/9` / `launched` / `queued`) instead of a superseded fold number.
|
| 196 |
+
x = _re.sub(r"\\textit\{([^}]*)\}", r"*\1*", x)
|
| 197 |
+
return _re.sub(r"\\mathbf\{([^}]*)\}", r"**\1**", x)
|
| 198 |
+
out = ["## 0. Single-actor flagship — RSM proposes from the RISE actor on every task", "",
|
| 199 |
+
"RISE and RSM differ only in the scorer (same S0A candidates, N=128); IDQL uses its own co-trained actor. "
|
| 200 |
+
"No per-task proposer choice. mean ± SE across seeds (subscript = seed count); Δ = margin over the strongest "
|
| 201 |
+
"baseline (* p<0.05). RISE-g = the RISE actor sampled once. " + _missing_note(rows) + " "
|
| 202 |
+
# READ-OUT SPLIT (gen_q#267; the threading three-way disagreement, 2026-09-23). The RSM
|
| 203 |
+
# column used to be r["rsm"], the maximum over BOTH read-outs -- on threading the retired
|
| 204 |
+
# deterministic fold (33.4) -- printed directly above a margins table whose RSM column was
|
| 205 |
+
# the coin-chain arm (21.6), with nothing saying the two were different estimators. The
|
| 206 |
+
# headline column is now CHAIN-ONLY and carries its own Δ and its own bolding; the fold
|
| 207 |
+
# maximum is kept, but only in a column that says so.
|
| 208 |
+
"**RSM is the coin-terminated β-chain read-out** (gen_q#267), the same column the paper's "
|
| 209 |
+
"`tab:flagship` prints; a row whose chain cells have not all landed prints its launch state "
|
| 210 |
+
"rather than a fold number. The last column is the RETIRED deterministic truncated fold, the "
|
| 211 |
+
"maximum over that read-out's arms, shown only so the change is visible -- it is not a "
|
| 212 |
+
"flagship number and its per-row (β, L) and retained mass are in `tab:flagship_fold`. The two "
|
| 213 |
+
"columns are different estimators on the same checkpoints, so they are not comparable as "
|
| 214 |
+
"seeds of one method.", "",
|
| 215 |
+
"| Task | BC | BC-u | RISE-g | IDQL | RISE | IFQL | RSM (ours, RISE actor) | Δ | RSM-fold (retired) |",
|
| 216 |
+
"|---|---|---|---|---|---|---|---|---|---|"]
|
| 217 |
+
for r in rows:
|
| 218 |
+
out.append("| " + " | ".join([r["label"], *map(strip, r["base_chain"]),
|
| 219 |
+
strip(r["rsm_chain_disp"]), strip(r["db_chain"]),
|
| 220 |
+
# FOLD-ONLY, and never bolded. This used to print `rsm`, the
|
| 221 |
+
# maximum over BOTH read-outs, so a column headed "RSM-fold
|
| 222 |
+
# (retired)" showed a CHAIN number wherever the chain arm won the
|
| 223 |
+
# row -- it did on Square (Cov.): 20.9 (chain) where the fold's own
|
| 224 |
+
# best arm is 17.6. `rsm_fold_disp` is selected by the same rule
|
| 225 |
+
# restricted to fold recipes. De-bolding stays: the retired number
|
| 226 |
+
# is context, never a winner, and bolding it put two winners in the
|
| 227 |
+
# threading row under two different estimators.
|
| 228 |
+
_re.sub(r"\*\*([^*]*)\*\*", r"\1", strip(r["rsm_fold_disp"]))]) + " |")
|
| 229 |
+
# COMPUTED, NOT HARDCODED. The first draft of this sentence named threading's two numbers
|
| 230 |
+
# (21.6 paired vs 22.8 pooled); the very next build made both 24.4 as more chain cells landed, so a
|
| 231 |
+
# hardcoded pair would already have been a false claim -- the same failure _missing_note exists to
|
| 232 |
+
# stop. Name only the rows where the two columns actually differ, from the rows.
|
| 233 |
+
def _lead(x):
|
| 234 |
+
"""first number in a rendered cell, or None -- the two columns print different decorations
|
| 235 |
+
(the margins cell has no +-SE), so compare the VALUE, not the string."""
|
| 236 |
+
m = _re.search(r"-?\d+\.\d+", strip(x or ""))
|
| 237 |
+
return None if not m else round(float(m.group(0)), 1)
|
| 238 |
+
_dif = [r["label"] for r in rows
|
| 239 |
+
if _lead(r.get("ar")) is not None and _lead(r.get("rsm_chain_disp")) is not None
|
| 240 |
+
and _lead(r["ar"]) != _lead(r["rsm_chain_disp"])]
|
| 241 |
+
_difnote = ("" if not _dif else
|
| 242 |
+
" It differs from the headline column on: " + ", ".join(_dif) + ".")
|
| 243 |
+
out += ["", "**Same-actor margins** (paired cells, RISE-actor proposer): greedy / RISE critic / RSM / vs greedy / vs RISE. "
|
| 244 |
+
"RSM here is the SAME chain read-out as the column above, but recomputed on the cells the three "
|
| 245 |
+
"columns share, so it can differ from the headline number wherever greedy or the RISE critic is "
|
| 246 |
+
"missing a seed." + _difnote, "",
|
| 247 |
+
"| Task | RISE-g | RISE | RSM (chain) | vs. RISE-g | vs. RISE |", "|---|---|---|---|---|---|"]
|
| 248 |
+
for r in rows:
|
| 249 |
+
if r["ar"] != "--":
|
| 250 |
+
out.append("| " + " | ".join([r["label"], strip(r["ag"]), strip(r["aq"]), strip(r["ar"]), strip(r["adg"]), strip(r["adq"])]) + " |")
|
| 251 |
+
_os.environ.pop("RSM_PROPOSER", None); _FL.RSM_PROPOSER = None
|
| 252 |
+
return out + [""]
|
| 253 |
+
|
| 254 |
+
L = ["# Master results table", "", *_single_actor_section(),
|
| 255 |
+
"*horizon* is the rollout budget in environment steps, with the median expert demonstration length in "
|
| 256 |
+
"parentheses: a policy slower than its demonstrator times out. "
|
| 257 |
+
"**Column meanings.** *vs same policy, no selection* is the paired difference against that very policy rolled out "
|
| 258 |
+
"greedily, i.e. what best-of-N selection adds. *vs random-candidate control* draws the same N candidates from the "
|
| 259 |
+
"same proposer and picks one at random (permuted scores); it separates a real value ranking from the benefit of "
|
| 260 |
+
"merely drawing N candidates. NOTE (audit 2026-09-21): on 6/7 flagship rows the permuted run used a different "
|
| 261 |
+
"successor configuration from the reported arm, so it is a random-candidate control, not a shuffle of the "
|
| 262 |
+
"reported arm's own scores. "
|
| 263 |
+
"*IDQL critic, same proposer* is IDQL's own critic scoring candidates drawn from the SAME policy the RSM arm "
|
| 264 |
+
"selects from, so only the scorer differs -- RISE by contrast keeps its own policy, because its proposer is part "
|
| 265 |
+
"of that method. *vs BEST baseline* compares against the strongest of BC, BCU, IDQL and RISE on that task. "
|
| 266 |
+
"Every row states the **evaluation region**: the box the object is randomly placed in at reset. Success rates are "
|
| 267 |
+
"only comparable within a region -- square-peg BC-expert is 2.6 % over the coverage box and 10.9 % over the much "
|
| 268 |
+
"smaller `square_image_ood` box -- so the loaders never pool two regions and `docs/REGIONS.md` lists every region "
|
| 269 |
+
"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 "
|
| 270 |
+
"otherwise. **BC** = diffusion policy on the expert demonstrations; **BCU** = on expert + non-expert; "
|
| 271 |
+
"**RISE** = RISE's policy + its IQL critic choosing among 128 candidates; **IDQL** = RISE without augmentation "
|
| 272 |
+
"or the Lipschitz penalty. **RSM** = our successor-model value choosing among N candidates from the named "
|
| 273 |
+
"proposer. *head* is the reward the successor model scores: `membership` is RISE's own 0/1 expert label (what "
|
| 274 |
+
"every baseline also trains on), `progress` is our shaped label from privileged sim state. *beta* is the "
|
| 275 |
+
"geometric horizon parameter of the successor flow and *hops* the number of composed flow steps in the "
|
| 276 |
+
"read-out. Deltas are exact paired McNemar tests against the same proposer's greedy rollouts and against the "
|
| 277 |
+
"random-candidate control; a **win** needs both below p = 0.05.", "",
|
| 278 |
+
"| 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 |",
|
| 279 |
+
"|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|"]
|
| 280 |
+
import subprocess as _sp
|
| 281 |
+
def _idql_status(task):
|
| 282 |
+
"""empty IDQL cell -> say what is happening instead of a bare dash"""
|
| 283 |
+
try:
|
| 284 |
+
live = _sp.run(["bjobs", "-noheader", "-o", "job_name"], capture_output=True, text=True, timeout=25).stdout
|
| 285 |
+
except Exception:
|
| 286 |
+
live = ""
|
| 287 |
+
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"))
|
| 288 |
+
eps = []
|
| 289 |
+
for d in glob.glob(f"{ROOT}/runs/{task}/policy/S0Aidql_seed*/rolling"):
|
| 290 |
+
e = sorted(int(re.search(r"epoch_(\d+)", x).group(1)) for x in glob.glob(d + "/*.pth")) if glob.glob(d + "/*.pth") else []
|
| 291 |
+
if e: eps.append(e[-1])
|
| 292 |
+
if not eps and not n: return "not launched"
|
| 293 |
+
return f"*training, ep {min(eps) if eps else 0}-{max(eps) if eps else 0}/5000, {n} running*"
|
| 294 |
+
|
| 295 |
+
|
| 296 |
+
def _idql_interim(task):
|
| 297 |
+
"""best IDQL number we have at ANY epoch < 5000, so the column is not just a dash"""
|
| 298 |
+
best = None
|
| 299 |
+
for f in glob.glob(f"{ROOT}/runs/{task}/eval_*/*.json"):
|
| 300 |
+
try: j = _json.load(open(f))
|
| 301 |
+
except Exception: continue
|
| 302 |
+
m = re.search(r"/policy/S0Aidql_seed(\d)/.*epoch_(\d+)", j.get("eval_ckpt", "") or "")
|
| 303 |
+
if not m or not j.get("num_episodes"): continue
|
| 304 |
+
o = j.get("planner_overrides") or {}
|
| 305 |
+
if (o.get("plan_n") or 1) > 1: continue # greedy IDQL policy only
|
| 306 |
+
ep = int(m.group(2))
|
| 307 |
+
if best is None or ep > best[0]: best = (ep, 100 * j["success_rate"], j["num_episodes"])
|
| 308 |
+
return None if not best else f"{best[1]:.1f} @ep{best[0]}"
|
| 309 |
+
|
| 310 |
+
|
| 311 |
+
import re, glob
|
| 312 |
+
import json as _json
|
| 313 |
+
ROOT = "/proj/dmfexp/zwhong/rsm_rise"
|
| 314 |
+
import verdict_table as _vt0
|
| 315 |
+
_vt0.CANON["square_expert_play"] = ("small", {"SquareNut": [[-0.115, -0.09], [-0.12, 0.11]]})
|
| 316 |
+
_vt0._AUTO.pop("square_expert_play", None)
|
| 317 |
+
REG = {}
|
| 318 |
+
for task in ROW_TASKS:
|
| 319 |
+
k = canon_region_key(task) or "env default"
|
| 320 |
+
for part in k.split(";"):
|
| 321 |
+
if part.startswith(("SquareNut=", "Piece1=", "Needle=")) or "=" not in part:
|
| 322 |
+
REG[task] = part.replace("SquareNut=", "nut ").replace("Piece1=", "piece1 ").replace("Needle=", "needle ")
|
| 323 |
+
break
|
| 324 |
+
REG.setdefault(task, k[:40])
|
| 325 |
+
IDQL_NOTE = {}
|
| 326 |
+
# READ-OUT PREDICATE, imported once and shared by every section of this file (gen_q#267). The arm-key
|
| 327 |
+
# grammar ("CH<cap>" = coin chain, "L<d>" = retired fold) is defined by the table generator, so the
|
| 328 |
+
# classifier is imported rather than re-derived: the markdown and the LaTeX must never disagree about
|
| 329 |
+
# which arm is which estimator. Imported HERE, above the row loop, because section 1's selection needs
|
| 330 |
+
# it and the later import at the upper-bound section was too late for that.
|
| 331 |
+
from flagship_latex import _recipe_is_chain as _F_is_chain_sel
|
| 332 |
+
from flagship_latex import _readout_of as _F_readout
|
| 333 |
+
# GRID COMPLETENESS TIER (gen_q#267, 2026-09-23 19:2xZ). Run 10 fixed this in the LaTeX generator
|
| 334 |
+
# (`flagship_latex._seed_tier_key`) after a 7-of-9-cell arm displaced a complete 9-of-9 one in the
|
| 335 |
+
# flagship maximum. THIS file was not fixed, and it is the file that writes docs/MASTER_TABLE.md --
|
| 336 |
+
# the document the orchestrator and the issue threads read. Measured on the 18:39Z build: section 1
|
| 337 |
+
# printed two_piece_expert_suboptimal at **50.0** from an arm with **3 of 9 cells**
|
| 338 |
+
# (E1-Ms100k-R0.98-11-ch-N128-argmax-ONACTORP8pr; 3 policy seeds x 1 eval seed) against the complete
|
| 339 |
+
# 9/9 arm's 45.1, and mug_expert_suboptimal at **23.6** from a **5 of 9** arm (ONS3H1P16lo) against
|
| 340 |
+
# the complete 19.8 -- and both printed with the same `(3 seeds)` annotation as a full grid, because
|
| 341 |
+
# `ns >= 2` counts POLICY seeds and says nothing about how many of the 9 cells landed. Worse, `rate()`
|
| 342 |
+
# pools EPISODES, so on an unbalanced grid the seed with more cells is weighted more: the same five mug
|
| 343 |
+
# cells read 23.6 pooled and 21.1 as a mean over policy seeds. So: completeness outranks rate here too.
|
| 344 |
+
from flagship_latex import _seed_tier_key as _F_tier
|
| 345 |
+
FOLD_EXCLUDED = {} # task -> (n fold arms excluded from the section-1 flagship, their best score)
|
| 346 |
+
CHAIN_EXCLUDED = {} # task -> (n chain arms excluded for gamma/degeneracy, their best score) -- NOT fold
|
| 347 |
+
_ub_chain_excl = {} # display label -> n chain arms excluded from section 0's retired fold columns
|
| 348 |
+
SEARCH = {} # task -> (n_arms_searched, best, runner_up)
|
| 349 |
+
ALT_ROW = {} # task -> best completion-reward (env success) arm
|
| 350 |
+
ORACLE_ROW = {} # task -> best progress-head arm (DISQUALIFIED, dense privileged reward)
|
| 351 |
+
NAME_SUFFIX = {}
|
| 352 |
+
_TCACHE = {} # task -> (episodes by arm, horizon by arm) for the throughput column
|
| 353 |
+
_FLAG_VAL = {} # display label -> the RSM value section 1 prints, for the section-0 cross-check
|
| 354 |
+
_FLAG_MAX = {}
|
| 355 |
+
_CAND_MAX = {}
|
| 356 |
+
_FLAG_CTRL = [] # the selection verdict of each flagship row, for the section-1 headline count
|
| 357 |
+
agg = []
|
| 358 |
+
for task in ROW_TASKS:
|
| 359 |
+
c = cells(task)
|
| 360 |
+
b = {}
|
| 361 |
+
for lab, pred in (("BC", lambda a, p: a[0] == "greedy" and p == "BC-expert"),
|
| 362 |
+
("BCU", lambda a, p: a[0] == "greedy" and p == "BC-unified"),
|
| 363 |
+
# RISE actor sampled once, no critic (audit 2026-09-21 C2): a baseline the delta and
|
| 364 |
+
# the routing rule must see, printed in the paper table as RISE-g.
|
| 365 |
+
("RISEg", lambda a, p: a[0] == "greedy" and p == "RISE policy"),
|
| 366 |
+
("IDQL", lambda a, p: a[0] == "critic" and p == "IDQL policy"),
|
| 367 |
+
("RISE", lambda a, p: a[0] == "critic" and p == "RISE policy")):
|
| 368 |
+
g = pool(c, pred); b[lab] = rate(g)[0] if g else None
|
| 369 |
+
_ro = [(_json.load(open(_f))) for _f in glob.glob(f"{ROOT}/runs/{task}/eval_riseonline/*.json")]
|
| 370 |
+
_ro = [(j["success_rate"] * j["num_episodes"], j["num_episodes"]) for j in _ro if j.get("num_episodes")]
|
| 371 |
+
if _ro:
|
| 372 |
+
_v = 100 * sum(a for a, _ in _ro) / sum(n for _, n in _ro)
|
| 373 |
+
if b.get("RISE") is None or _v > b["RISE"]: b["RISE"] = _v
|
| 374 |
+
if b.get("IDQL") is None:
|
| 375 |
+
itr = _idql_interim(task)
|
| 376 |
+
b["IDQL"] = None
|
| 377 |
+
IDQL_NOTE[task] = (itr + " *(interim)*") if itr else _idql_status(task)
|
| 378 |
+
# REWARD-MATCHING RULING 2026-09-20. RISE's reward is PROVENANCE, not outcome: their
|
| 379 |
+
# relabel_rewards.py writes a constant over every frame of an episode (1 for the expert file,
|
| 380 |
+
# 0 for the non-expert file) and robomimic/algo/iql_diffusion.py consumes that field unchanged
|
| 381 |
+
# (`q_target = rewards + (1-dones)*discount*target_vf_pred`). So:
|
| 382 |
+
# membership -- the SAME provenance label the RISE and IDQL critics see. Reward-matched. FLAGSHIP.
|
| 383 |
+
# completion -- per-frame env success. A DIFFERENT reward from the paper's, not a correction to
|
| 384 |
+
# it; a legitimate alternative, reported as its own table.
|
| 385 |
+
# progress -- dense hand-designed potential over privileged sim state. Not matched to anything.
|
| 386 |
+
# DISQUALIFIED (see scripts/train_progress_head.py banner).
|
| 387 |
+
HEAD_SECTION = {"membership": "flagship", "completion": "altreward", "progress": "oracle"}
|
| 388 |
+
best = prov = None
|
| 389 |
+
_uncapped_max = None # max over EVERY chain membership arm, ignoring both the seed split and the
|
| 390 |
+
# grid-completeness tier. Section 0's CEILING is exactly that quantity (the
|
| 391 |
+
# owner's definition: "the best mean across the seeds done for a config"), and
|
| 392 |
+
# the cross-section guard below compares the two. Before the completeness tier
|
| 393 |
+
# this was recoverable as max(best, prov); now that the headline refuses partial
|
| 394 |
+
# arms it is not, and computing it here keeps the guard comparing like with like
|
| 395 |
+
# instead of firing on a difference the tier creates on purpose (it fired on
|
| 396 |
+
# square-peg (Sub.): ceiling 55.33 vs headline 51.56, job 1885157).
|
| 397 |
+
_verified = [] # every arm that qualifies for the flagship, for the search-size disclosure
|
| 398 |
+
_fold_seen = [] # (score, seeds) of the membership arms EXCLUDED for being the retired fold
|
| 399 |
+
_chain_excluded_seen = [] # (score, seeds) EXCLUDED for being a chain arm at the wrong gamma / cap 0
|
| 400 |
+
alt = orc = None
|
| 401 |
+
# SORTED, not a set: three mug arms sit at exactly 12.0% (6/50 each), and iterating a set made the
|
| 402 |
+
# argmax -- and so the recipe printed in the paper table -- depend on hash order. Regenerating with
|
| 403 |
+
# unchanged data could name a different arm. Sorted iteration plus the (score, episodes) comparison
|
| 404 |
+
# below makes the choice a function of the data alone: higher score wins, an exact tie goes to the
|
| 405 |
+
# arm with more episodes behind it, and a full tie resolves by name.
|
| 406 |
+
for (a, p) in sorted({(a, p) for (a, p, _, _) in c if a[0].startswith("rsm:")}):
|
| 407 |
+
g = pool(c, lambda x, q, A=a, P=p: x == A and q == P)
|
| 408 |
+
sr, n = rate(g); ns = len({ps for (_, ps, _) in g})
|
| 409 |
+
sect = HEAD_SECTION.get(a[0].split(":")[1], "oracle")
|
| 410 |
+
if sect == "altreward":
|
| 411 |
+
if ns >= 2 and (alt is None or sr > alt[0]): alt = (sr, n, a, p, g)
|
| 412 |
+
continue
|
| 413 |
+
if sect == "oracle":
|
| 414 |
+
if ns >= 2 and (orc is None or sr > orc[0]): orc = (sr, n, a, p, g)
|
| 415 |
+
continue
|
| 416 |
+
# READ-OUT SPLIT, section 1 (gen_q#267; found 2026-09-23 11:55Z by reading the generated
|
| 417 |
+
# markdown rather than the generator). `sect == "flagship"` admitted EVERY membership arm at
|
| 418 |
+
# ANY read-out, so this section -- the master table's headline comparison, the one pasted into
|
| 419 |
+
# issues -- printed the RETIRED deterministic fold under a bare "**RSM**" heading with its own
|
| 420 |
+
# `verdict` column. Measured on the 11:52Z build: threading printed **33.0** with `hops 1`,
|
| 421 |
+
# i.e. the L=1 fold arm, four hours after the 33.4 fold number was publicly RETRACTED on #267
|
| 422 |
+
# (the chain reads 25.8, delta -0.6, NO DECISION) -- and it was marked **win**. Mug printed
|
| 423 |
+
# 22.2 (chain 19.1), piece (Cov.) 50.3 (46.0), piece-tip 6.9 (5.3). Sections 0 and 5 and every
|
| 424 |
+
# LaTeX table were already read-out scoped; this one was missed because its arm loop is a
|
| 425 |
+
# different piece of code from the one those share.
|
| 426 |
+
# The flagship section now ranges over CHAIN arms only, so a fold number can never take the
|
| 427 |
+
# row; the fold maxima stay in section 0's columns that name them retired and in
|
| 428 |
+
# tab:ablation_betarec. A task with no chain arm falls through to the existing "no best and no
|
| 429 |
+
# prov" branch, which prints dashes -- never a fold number standing in for a chain number.
|
| 430 |
+
# AND "NOT CHAIN" IS NOT THE SAME AS "FOLD" (2026-09-24, run 20). Since run 19 the chain
|
| 431 |
+
# predicate also EXCLUDES a chain arm at the wrong gamma or with a degenerate cap 0, so
|
| 432 |
+
# `not _F_is_chain_sel(...)` is true for three different things: a genuine fold arm, an
|
| 433 |
+
# off-gamma chain arm and a zero-recursion chain arm. Bucketing all three as "fold" is the
|
| 434 |
+
# mirror of the #267 defect this section exists to prevent -- a CHAIN number standing in as a
|
| 435 |
+
# FOLD number -- and it was live in the retired columns (Square (Cov.)'s fold ceiling read 20.0
|
| 436 |
+
# from `L40@best b0.95 CH0`, a chain key). So the retired bucket is now the POSITIVE test
|
| 437 |
+
# `_readout_of(...) == "fold"`; an excluded chain arm is counted separately and belongs to
|
| 438 |
+
# NEITHER column, which is what "excluded" has to mean if the exclusion is to be believed.
|
| 439 |
+
if not _F_is_chain_sel(a[1]):
|
| 440 |
+
if _F_readout(a[1]) == "fold":
|
| 441 |
+
_fold_seen.append((sr, ns))
|
| 442 |
+
else:
|
| 443 |
+
_chain_excluded_seen.append((sr, ns))
|
| 444 |
+
continue
|
| 445 |
+
if _uncapped_max is None or sr > _uncapped_max: _uncapped_max = sr
|
| 446 |
+
if ns >= 2:
|
| 447 |
+
_verified.append(sr)
|
| 448 |
+
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])):
|
| 449 |
+
best = (sr, n, a, p, g)
|
| 450 |
+
else: # single-seed: only surfaced if it beats the qualifying row
|
| 451 |
+
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])):
|
| 452 |
+
prov = (sr, n, a, p, g)
|
| 453 |
+
ALT_ROW[task] = alt; ORACLE_ROW[task] = orc
|
| 454 |
+
FOLD_EXCLUDED[task] = (len(_fold_seen), max([x[0] for x in _fold_seen], default=None))
|
| 455 |
+
CHAIN_EXCLUDED[task] = (len(_chain_excluded_seen),
|
| 456 |
+
max([x[0] for x in _chain_excluded_seen], default=None))
|
| 457 |
+
# The flagship is a MAXIMUM over arms, where an arm is
|
| 458 |
+
# (successor model, head, beta, hops, read-out, candidate count, proposer). Record how many arms that
|
| 459 |
+
# maximum ranged over and what the runner-up scored, so the row is never read as a default configuration.
|
| 460 |
+
# See docs/PROPOSER_SELECTION.md: best-to-second gaps are 0.0-5.7 pts (a plateau, which is what a real
|
| 461 |
+
# effect looks like) while best-to-median gaps reach 16 pts (which is why the search size must be stated).
|
| 462 |
+
_verified.sort(reverse=True)
|
| 463 |
+
SEARCH[task] = (len(_verified), _verified[0] if _verified else None,
|
| 464 |
+
_verified[1] if len(_verified) > 1 else None)
|
| 465 |
+
f = lambda v, _t=task: (IDQL_NOTE.get(_t, "--") if v is None else f"{v:.1f}")
|
| 466 |
+
def emit(rec, status, tmp=False, dest=None):
|
| 467 |
+
sr_, n_, a_, p_, g_ = rec
|
| 468 |
+
head_ = a_[0].split(":")[1]
|
| 469 |
+
# ORACLE REWARD (ruling 2026-09-20). The `progress` head regresses a DENSE hand-designed
|
| 470 |
+
# potential over privileged simulator state (distance to object, distance to target), while
|
| 471 |
+
# BC/BCU use no reward and RISE/IDQL critics use the dataset's 0/1 expert-membership label.
|
| 472 |
+
# A progress row is therefore NOT reward-matched to anything it is printed beside and may not
|
| 473 |
+
# be quoted as a result. See docs/WHY_TASKS_DIFFER.md and the banner in
|
| 474 |
+
# scripts/train_progress_head.py. Marked here so the disqualification travels with the number.
|
| 475 |
+
_m, beta_, hops_, N_ = parse(a_[1])
|
| 476 |
+
if head_ == "progress":
|
| 477 |
+
head_ = "progress **[ORACLE: dense privileged reward, NOT reward-matched, do not quote]**"
|
| 478 |
+
# THROUGHPUT (user 2026-09-20): success_rate * horizon / mean policy timesteps -- successes per
|
| 479 |
+
# horizon-worth of environment steps, so a policy that finishes sooner scores higher than one
|
| 480 |
+
# with the same success rate that only just makes it. Computed from `first_success_step`, NOT
|
| 481 |
+
# from `length`: every eval sets end_on_success but the rollout loop runs to the horizon anyway,
|
| 482 |
+
# so `length` is the constant 400 on successes and failures alike. See scripts/throughput.py.
|
| 483 |
+
_thr = _thr_steps = None
|
| 484 |
+
try:
|
| 485 |
+
from throughput import collect as _tcol, arm_throughput as _tarm
|
| 486 |
+
_td, _th = _TCACHE.setdefault(task, _tcol(task))
|
| 487 |
+
_tk = (a_[1], p_)
|
| 488 |
+
if _tk in _td:
|
| 489 |
+
_tr = _tarm(_td[_tk], _th[_tk])
|
| 490 |
+
if _tr: _thr, _thr_steps = _tr[2], _tr[1]
|
| 491 |
+
except Exception:
|
| 492 |
+
pass
|
| 493 |
+
gg_ = flat(pool(c, lambda x, q, P=p_: x[0] == "greedy" and q == P))
|
| 494 |
+
gp_ = flat(pool(c, lambda x, q, P=p_, H=head_: x == ("permuted", H) and q == P))
|
| 495 |
+
mg_, mp_ = mcnemar(flat(g_), gg_), mcnemar(flat(g_), gp_)
|
| 496 |
+
dd = lambda m: "--" if not m else f"{m['a']-m['b']:+.1f} (p={m['p']:.3f})"
|
| 497 |
+
_sp_rows = []
|
| 498 |
+
for _f in glob.glob(f"{ROOT}/runs/{task}/eval_sameprop/*.json"):
|
| 499 |
+
try: _j = _json.load(open(_f))
|
| 500 |
+
except Exception: continue
|
| 501 |
+
_o = _j.get("planner_overrides") or {}
|
| 502 |
+
if (_o.get("rsm_backend") != "iql") or not _j.get("num_episodes"): continue
|
| 503 |
+
_m = re.search(r"/policy/(S0A|S0B|S3H1)_seed(\d)/", _j.get("eval_ckpt", "") or "")
|
| 504 |
+
if not _m or _m.group(1) != p_.replace("BC-expert", "S3H1").replace("BC-unified", "S0B").replace("RISE policy", "S0A"): continue
|
| 505 |
+
_sp_rows.append((_j["success_rate"] * _j["num_episodes"], _j["num_episodes"]))
|
| 506 |
+
idql_sp = (f"{100*sum(a for a,_ in _sp_rows)/sum(bn for _,bn in _sp_rows):.1f}"
|
| 507 |
+
if _sp_rows else "--")
|
| 508 |
+
_bb = [v for v in b.values() if isinstance(v, (int, float))]
|
| 509 |
+
_bl = [k for k, v in b.items() if isinstance(v, (int, float)) and v == max(_bb)] if _bb else []
|
| 510 |
+
vsb = "--" if not _bb else f"{sr_-max(_bb):+.1f} vs {_bl[0]}"
|
| 511 |
+
ps2 = defaultdict(lambda: [0, 0])
|
| 512 |
+
for (P, s2, e2), v in g_.items():
|
| 513 |
+
ps2[s2][0] += sum(v); ps2[s2][1] += len(v)
|
| 514 |
+
per = "/".join(f"{100*x/y:.0f}" for _, (x, y) in sorted(ps2.items()))
|
| 515 |
+
ne_ = len({e2 for (_, _, e2) in g_})
|
| 516 |
+
# THE VERDICT IS ABOUT SELECTION, NOT ABOUT THE BASELINE. The question a reviewer asks first is
|
| 517 |
+
# "is the gain from your scorer or from the policy you sampled from?", and the two controls answer
|
| 518 |
+
# it: `no selection` re-runs the SAME policy greedily, `shuffled` picks one of N candidates at random (a
|
| 519 |
+
# permuted order. Beating BC while losing to your own greedy control is not evidence for the
|
| 520 |
+
# method. This used to read `elif status: v_ = status`, so the seed caveat REPLACED the verdict and
|
| 521 |
+
# four of seven flagship rows stated their seed count and nothing about whether selection helped --
|
| 522 |
+
# including piece-assembly (Coverage), which is -0.5 against its own no-selection control. The
|
| 523 |
+
# control verdict is now always stated and the caveat is appended to it.
|
| 524 |
+
okk = mg_ and mp_ and mg_["p"] < .05 and mp_["p"] < .05 and mg_["a"] > mg_["b"] and mp_["a"] > mp_["b"]
|
| 525 |
+
if mg_ and mg_["a"] < mg_["b"]:
|
| 526 |
+
_ctrl = "**below its own no-selection control**"
|
| 527 |
+
elif okk:
|
| 528 |
+
_ctrl = "**win**"
|
| 529 |
+
elif mg_ and mg_["p"] < .05 and mg_["a"] > mg_["b"]:
|
| 530 |
+
_ctrl = "control undecided"
|
| 531 |
+
else:
|
| 532 |
+
_ctrl = "no gain"
|
| 533 |
+
if tmp:
|
| 534 |
+
v_ = f"{_ctrl}; **TEMPORARY** -- only {len(ps2)} training seed(s), 3-seed verification running"
|
| 535 |
+
elif status:
|
| 536 |
+
v_ = f"{_ctrl}; {status}"
|
| 537 |
+
else:
|
| 538 |
+
v_ = _ctrl
|
| 539 |
+
# FAIRNESS RULE (user, 2026-09-20): every method printed in one table must see the SAME reward,
|
| 540 |
+
# except BC/BCU which have none by construction. The RISE and IDQL critic columns are trained on
|
| 541 |
+
# the provenance label, so they may ONLY be printed beside a membership-head RSM arm. In the
|
| 542 |
+
# env-success and oracle sections their numbers would be a different-reward comparison, so they
|
| 543 |
+
# are suppressed rather than shown, and the cell says why.
|
| 544 |
+
# Suppress the critic columns only where the REWARD differs (sections 2 and 3). Section 1b is
|
| 545 |
+
# the same provenance reward as section 1 -- a weaker configuration, not a different reward --
|
| 546 |
+
# so its critic numbers are matched and must be shown.
|
| 547 |
+
_offreward = dest is not None and dest is not VERLOW
|
| 548 |
+
_unmatched = "*n/a: critic not retrained on this reward*"
|
| 549 |
+
_bIDQL = _unmatched if _offreward else f(b['IDQL'])
|
| 550 |
+
_bRISE = _unmatched if _offreward else f(b['RISE'])
|
| 551 |
+
# FLAGSHIP ADMISSION (user 2026-09-20): "for flagship we can admit the best numbers and config
|
| 552 |
+
# if seed needs to be refilled -- we top up". The best matched-reward arm belongs in the
|
| 553 |
+
# flagship WITH its seed count stated, not buried in secondary; the seeds get topped up.
|
| 554 |
+
# Previously any row carrying a `status` string was routed to SEC, which sent every
|
| 555 |
+
# single-seed maximum to secondary -- e.g. piece-assembly suboptimal's 58.0 sat in section 4
|
| 556 |
+
# while the flagship showed the 29.4 arm that merely happened to have three seeds.
|
| 557 |
+
# Match the CURRENT best-arm status text. This used to key on "single-seed maximum"; when the
|
| 558 |
+
# status was reworded to "BEST ARM at n/3 training seeds" the check silently stopped matching
|
| 559 |
+
# and every under-seeded WINNING arm was routed to secondary, leaving the flagship with one row.
|
| 560 |
+
_underseeded = bool(status) and "BEST ARM at" in str(status)
|
| 561 |
+
_dest = dest if dest is not None else (
|
| 562 |
+
FLAG if (_underseeded or not status) and task not in NAME_SUFFIX
|
| 563 |
+
else (SEC if (status and not tmp) or task in NAME_SUFFIX else FLAG))
|
| 564 |
+
if _dest is FLAG:
|
| 565 |
+
_FLAG_VAL[f"{NAME[task]}{NAME_SUFFIX.get(task,'')}"] = sr_
|
| 566 |
+
_FLAG_MAX[f"{NAME[task]}{NAME_SUFFIX.get(task,'')}"] = _CAND_MAX.get(task, sr_)
|
| 567 |
+
_FLAG_CTRL.append(_ctrl)
|
| 568 |
+
_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}'} | "
|
| 569 |
+
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_} |")
|
| 570 |
+
# DEMOTION BEFORE THE EARLY RETURN (2026-09-23). The suffix was set ten lines BELOW this branch,
|
| 571 |
+
# so a task with a FLAGSHIP_VARIANT that has no qualifying arm of its own left through here
|
| 572 |
+
# UNRELABELLED and its 100/100 released-file row landed in section 4 under the bare flagship label,
|
| 573 |
+
# while the 20/100 variant held the same label in section 1 -- which is exactly what the
|
| 574 |
+
# label/dataset guard below exists to catch, and it duly fired ("square-peg (Suboptimal)" carrying
|
| 575 |
+
# 20/100 and 100/100). Harmless while every task had an arm at ANY read-out; the chain-only
|
| 576 |
+
# selection above is what made the branch reachable.
|
| 577 |
+
_fv0 = FLAGSHIP_VARIANT.get(task)
|
| 578 |
+
if _fv0:
|
| 579 |
+
_dn00 = DEMOTED_NOTE.get(task, "")
|
| 580 |
+
NAME_SUFFIX[task] = f" — {_dn00}" if _dn00 else " — released file"
|
| 581 |
+
if not best and not prov:
|
| 582 |
+
if task in VARIANT_OF: continue # parent emits a "still training" placeholder for it
|
| 583 |
+
# COLUMN COUNT (ORCH run 57, 2026-09-23 12:20Z): this dashes-only placeholder printed 22 fields
|
| 584 |
+
# against a 25-field header, so the column guard below rejected the whole document the moment
|
| 585 |
+
# the 12:09 demotion fix made this branch emit a row. Dashes only -- no number changes.
|
| 586 |
+
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'])} | -- | -- | -- | -- | -- | -- | -- | -- | -- | -- | -- | -- | -- | -- | -- | -- | -- |")
|
| 587 |
+
continue
|
| 588 |
+
_fv = FLAGSHIP_VARIANT.get(task)
|
| 589 |
+
# DEMOTION IS UNCONDITIONAL (bug found 2026-09-20). This used to fire only while the variant had
|
| 590 |
+
# NO evaluations, so the moment square_sub_20100 produced its first cell the released 100/100 file
|
| 591 |
+
# stopped being relabelled and reappeared in the FLAGSHIP section under the flagship label -- while
|
| 592 |
+
# section 0, which reads the variant, showed the 20/100 numbers for the same row name. Two datasets,
|
| 593 |
+
# one label, three sections disagreeing. The suffix must be set whenever a variant exists.
|
| 594 |
+
if _fv:
|
| 595 |
+
_dn0 = DEMOTED_NOTE.get(task, "")
|
| 596 |
+
NAME_SUFFIX[task] = f" — {_dn0}" if _dn0 else " — released file"
|
| 597 |
+
if _fv and not glob.glob(f"{ROOT}/runs/{_fv[0]}/eval_*/*.json"):
|
| 598 |
+
try:
|
| 599 |
+
live = _sp.run(["bjobs", "-noheader", "-o", "job_name"], capture_output=True, text=True, timeout=25).stdout
|
| 600 |
+
except Exception:
|
| 601 |
+
live = ""
|
| 602 |
+
nj = sum(1 for l in live.splitlines() if _fv[0].replace("square_sub_", "sq") in l or _fv[0] in l)
|
| 603 |
+
eps = [max([int(re.search(r"epoch_(\d+)", x).group(1)) for x in glob.glob(d + "/*.pth")] or [0])
|
| 604 |
+
for d in glob.glob(f"{ROOT}/runs/{_fv[0]}/policy/*/rolling")]
|
| 605 |
+
note = (f"*training, ep {min(eps)}-{max(eps)}/5000, {nj} jobs*" if eps else
|
| 606 |
+
(f"*launched, {nj} jobs, no checkpoint yet*" if nj else "*not launched*"))
|
| 607 |
+
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} | "
|
| 608 |
+
f"-- | -- | -- | -- | -- | -- | -- | -- | -- | -- | -- | -- | -- | -- | -- | -- | -- |")
|
| 609 |
+
# a verified arm (>=2 training seeds) always wins the flagship row; an unverified arm is promoted only when
|
| 610 |
+
# the task has no verified arm at all. Single-seed maxima are systematically optimistic: on 2026-09-20 the
|
| 611 |
+
# 3-seed verification moved square subopt 77.0 -> 69.8, threading 22.0 -> 14.4 and mug 18.0 -> 7.8.
|
| 612 |
+
# FLAGSHIP = THE VICTORY CASE (user 2026-09-20: "flagship is attempting to show rsm victory under
|
| 613 |
+
# fair conditions"). One row per task: the BEST matched-reward arm, whatever its seed count, with
|
| 614 |
+
# that count stated. A verified arm that is NOT the best is evidence about a weaker
|
| 615 |
+
# configuration, not about the method's ceiling, so it moves to its own section rather than
|
| 616 |
+
# sitting beside the headline and dragging the reader's eye to the lower number.
|
| 617 |
+
_cands = [x for x in (best, prov) if x]
|
| 618 |
+
if _cands:
|
| 619 |
+
# ROUTING RULE (user 2026-09-20): "prefer winning but seed-deficient over clearly losing". The
|
| 620 |
+
# converse also holds: a VERIFIED (>=2-seed) arm that beats every baseline is never displaced by
|
| 621 |
+
# a newer single-seed maximum a few tenths higher -- on 2026-09-21 fresh 1-seed cells pushed
|
| 622 |
+
# square coverage 12.4(3) -> 12.7(1) and threading 18.6(3) -> 20.0(1) out of the flagship, which
|
| 623 |
+
# is the winner's curse the seed count exists to prevent. The single-seed arm takes the row
|
| 624 |
+
# only when no verified arm wins.
|
| 625 |
+
_blmax = max([v for v in b.values() if v is not None] or [float("-inf")])
|
| 626 |
+
# the max-over-arms, which section 0 calls the ceiling -- unrestricted on purpose, see _uncapped_max
|
| 627 |
+
_CAND_MAX[task] = _uncapped_max if _uncapped_max is not None else max(x[0] for x in _cands)
|
| 628 |
+
if best and best[0] > _blmax:
|
| 629 |
+
_top = best
|
| 630 |
+
else:
|
| 631 |
+
_top = max(_cands, key=lambda x: x[0])
|
| 632 |
+
_other = next((x for x in _cands if x is not _top), None)
|
| 633 |
+
_nseed = len({ps for (_, ps, _) in _top[4]})
|
| 634 |
+
# CELLS, NOT ONLY SEEDS (gen_q#267, 2026-09-23 run 13). This caveat counted POLICY SEEDS only, so
|
| 635 |
+
# an arm with all three policy seeds but one eval seed each -- 3 of the 9 (policy seed x eval seed)
|
| 636 |
+
# cells, 150 of 450 episodes -- printed with NO caveat at all, indistinguishable from a full grid.
|
| 637 |
+
# That is exactly how the 18:39Z build presented piece-assembly (Sub.) at 50.0 (3/9 cells) and
|
| 638 |
+
# mug-cleanup (Sub.) at 23.6 (5/9 cells) as finished results. The completeness TIER above now
|
| 639 |
+
# keeps such an arm out of the row whenever a complete one exists; when every candidate is partial
|
| 640 |
+
# (or the routing rule below promotes a seed-deficient winner on purpose), the row must at least
|
| 641 |
+
# say so, and say it in cells.
|
| 642 |
+
_ncell = len(_top[4])
|
| 643 |
+
_demoted = task in NAME_SUFFIX # a DIFFERENT dataset from the flagship variant of this task
|
| 644 |
+
emit(_top, None if (_nseed >= 3 and _ncell >= 9) else
|
| 645 |
+
f"*BEST ARM at {_nseed}/3 training seeds and {_ncell}/9 grid cells; top-up running. "
|
| 646 |
+
f"An arm is selected on a COMPLETE 3x3 grid whenever one exists (`flagship_latex._seed_tier_key`); "
|
| 647 |
+
f"this row had none. Historical regression on this "
|
| 648 |
+
f"project when single-seed maxima were verified: -7.2, -7.6, -10.2 pts.*")
|
| 649 |
+
# Section 1b holds ONE thing: an arm that scores WORSE than the flagship row but carries MORE
|
| 650 |
+
# training seeds -- the "inferior but 3-seed" row the flagship is not allowed to hide behind.
|
| 651 |
+
# It is emitted only when that is actually true. Previously every runner-up was sent here, so a
|
| 652 |
+
# SINGLE-seed loser (piece-assembly suboptimal 46.0 at 1x1, beside a 52.0 flagship row at 2x3)
|
| 653 |
+
# appeared under a heading that calls its rows verified. A runner-up with no seed advantage is
|
| 654 |
+
# neither a stronger result nor a stronger verification, so it is dropped rather than printed.
|
| 655 |
+
# Demoted rows are a different dataset entirely and belong wholly in secondary, not split
|
| 656 |
+
# across two sections as they were when only `_top` honoured NAME_SUFFIX.
|
| 657 |
+
if _other is not None and not _demoted:
|
| 658 |
+
_on = len({ps for (_, ps, _) in _other[4]})
|
| 659 |
+
if _on > _nseed:
|
| 660 |
+
emit(_other, f"*{_on}/3 training seeds vs the flagship arm's {_nseed}/3, but scores "
|
| 661 |
+
f"lower ({_other[0]:.1f} vs {_top[0]:.1f})*", dest=VERLOW)
|
| 662 |
+
# Sections 2 and 3: the same row builder, different reward, different destination.
|
| 663 |
+
if ALT_ROW.get(task):
|
| 664 |
+
emit(ALT_ROW[task], "*env-success reward; RISE/IDQL critics NOT retrained on it; label is the "
|
| 665 |
+
"pre-settle `goal.npz` (overcounts 1.85-2.86x)*", dest=ALTREW)
|
| 666 |
+
if ORACLE_ROW.get(task):
|
| 667 |
+
emit(ORACLE_ROW[task], "**DISQUALIFIED: dense privileged reward, not matched to any baseline**", dest=ORCROW)
|
| 668 |
+
if best:
|
| 669 |
+
sr, n, a, p, g = best
|
| 670 |
+
else:
|
| 671 |
+
sr, n, a, p, g = prov
|
| 672 |
+
bb = max([x for x in b.values() if x is not None], default=None)
|
| 673 |
+
if bb is not None and task not in FLAGSHIP_VARIANT: agg.append((sr, bb))
|
| 674 |
+
# ---- rows measured in an alternate evaluation region -------------------------------------------------------
|
| 675 |
+
import verdict_table as _vt
|
| 676 |
+
for label, (task, spec) in ALT.items():
|
| 677 |
+
keep = _vt.CANON.get(task)
|
| 678 |
+
_vt.CANON[task] = ("alt", spec)
|
| 679 |
+
try:
|
| 680 |
+
c = cells(task)
|
| 681 |
+
b2 = {}
|
| 682 |
+
for lab, pred in (("BC", lambda a, p: a[0] == "greedy" and p == "BC-expert"),
|
| 683 |
+
("BCU", lambda a, p: a[0] == "greedy" and p == "BC-unified"),
|
| 684 |
+
("IDQL", lambda a, p: a[0] == "critic" and p == "IDQL policy"),
|
| 685 |
+
("RISE", lambda a, p: a[0] == "critic" and p == "RISE policy")):
|
| 686 |
+
g = pool(c, pred); b2[lab] = rate(g)[0] if g else None
|
| 687 |
+
bestA = None
|
| 688 |
+
for (a, p) in {(a, p) for (a, p, _, _) in c if a[0].startswith("rsm:")}:
|
| 689 |
+
g = pool(c, lambda x, q, A=a, P=p: x == A and q == P)
|
| 690 |
+
sr, n = rate(g)
|
| 691 |
+
if bestA is None or sr > bestA[0]: bestA = (sr, n, a, p, g)
|
| 692 |
+
ff = lambda v: "--" if v is None else f"{v:.1f}"
|
| 693 |
+
_k, _v = sorted(spec.items())[0]
|
| 694 |
+
reg = ("nut " if _k == "SquareNut" else ("piece1 " if _k == "Piece1" else _k + " ")) + \
|
| 695 |
+
",".join(f"[{a[0]:g},{a[1]:g}]" for a in _v[:2])
|
| 696 |
+
if bestA:
|
| 697 |
+
sr, n, a, p, g = bestA
|
| 698 |
+
head = a[0].split(":")[1]; _m, beta, hops, N = parse(a[1])
|
| 699 |
+
gg = flat(pool(c, lambda x, q, P=p: x[0] == "greedy" and q == P))
|
| 700 |
+
gp = flat(pool(c, lambda x, q, P=p, H=head: x == ("permuted", H) and q == P))
|
| 701 |
+
mg, mp = mcnemar(flat(g), gg), mcnemar(flat(g), gp)
|
| 702 |
+
dd = lambda m: "--" if not m else f"{m['a']-m['b']:+.1f} (p={m['p']:.3f})"
|
| 703 |
+
ps3 = defaultdict(lambda: [0, 0])
|
| 704 |
+
for (P, s3, e3), v in g.items(): ps3[s3][0] += sum(v); ps3[s3][1] += len(v)
|
| 705 |
+
per3 = "/".join(f"{100*x/y:.0f}" for _, (x, y) in sorted(ps3.items()))
|
| 706 |
+
okk = mg and mp and mg["p"] < .05 and mp["p"] < .05 and mg["a"] > mg["b"] and mp["a"] > mp["b"]
|
| 707 |
+
vv = "**win**" if okk else ("control undecided" if mg and mg["p"] < .05 and mg["a"] > mg["b"] else "no gain")
|
| 708 |
+
# MATCHED-REWARD ROUTING (user 2026-09-20: "every table should have a matched reward").
|
| 709 |
+
# This path predates the reward split and used to dump every head into SEC, so a
|
| 710 |
+
# progress-head row sat beside provenance-reward rows and beside IDQL/RISE numbers.
|
| 711 |
+
# Route by head, and suppress the critic columns whenever the reward is not the
|
| 712 |
+
# provenance label the critics were trained on.
|
| 713 |
+
_sec = {"membership": SEC, "completion": ALTREW}.get(head, ORCROW)
|
| 714 |
+
_off = _sec is not SEC
|
| 715 |
+
_na = "*n/a: critic not retrained on this reward*"
|
| 716 |
+
_hd = head if head != "progress" else \
|
| 717 |
+
"progress **[ORACLE: dense privileged reward, NOT reward-matched, do not quote]**"
|
| 718 |
+
# NOTE the horizon column: it was missing here, so every cell after `reg` shifted one
|
| 719 |
+
# left and the row printed 21 columns against a 23-column header.
|
| 720 |
+
_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'])} | "
|
| 721 |
+
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} | "
|
| 722 |
+
f"{hops} | {N} | -- | {dd(mg)} | {dd(mp)} | " +
|
| 723 |
+
("--" if _off or not [v for v in b2.values() if isinstance(v,(int,float))] else
|
| 724 |
+
f"{sr-max(v for v in b2.values() if isinstance(v,(int,float))):+.1f}") + f" | {vv} |")
|
| 725 |
+
else:
|
| 726 |
+
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'])} | "
|
| 727 |
+
f"-- | -- | -- | -- | -- | -- | -- | -- | -- | -- | -- | -- | -- | -- | -- | -- | -- |")
|
| 728 |
+
finally:
|
| 729 |
+
if keep is None: _vt.CANON.pop(task, None)
|
| 730 |
+
else: _vt.CANON[task] = keep
|
| 731 |
+
_vt._AUTO.pop(task, None)
|
| 732 |
+
|
| 733 |
+
# ---- paper-data-regime rows (may still be training) --------------------------------------------------------
|
| 734 |
+
for task, (label, traj, reg) in PAPER_REGIME.items():
|
| 735 |
+
c = cells(task) if glob.glob(f"{ROOT}/runs/{task}/eval_*/*.json") else {}
|
| 736 |
+
b3 = {}
|
| 737 |
+
for lab, pred in (("BC", lambda a, p: a[0] == "greedy" and p == "BC-expert"),
|
| 738 |
+
("BCU", lambda a, p: a[0] == "greedy" and p == "BC-unified"),
|
| 739 |
+
# RISE actor sampled once, no critic (audit 2026-09-21 C2): a baseline the delta and
|
| 740 |
+
# the routing rule must see, printed in the paper table as RISE-g.
|
| 741 |
+
("RISEg", lambda a, p: a[0] == "greedy" and p == "RISE policy"),
|
| 742 |
+
("IDQL", lambda a, p: a[0] == "critic" and p == "IDQL policy"),
|
| 743 |
+
("RISE", lambda a, p: a[0] == "critic" and p == "RISE policy")):
|
| 744 |
+
g = pool(c, pred) if c else None
|
| 745 |
+
b3[lab] = rate(g)[0] if g else None
|
| 746 |
+
try:
|
| 747 |
+
live = _sp.run(["bjobs", "-noheader", "-o", "job_name"], capture_output=True, text=True, timeout=25).stdout
|
| 748 |
+
except Exception:
|
| 749 |
+
live = ""
|
| 750 |
+
nrun = sum(1 for l in live.splitlines() if "sqsub2" in l or f"idql_{task}" in l)
|
| 751 |
+
eps = []
|
| 752 |
+
for d in glob.glob(f"{ROOT}/runs/{task}/policy/*/rolling"):
|
| 753 |
+
e = [int(re.search(r"epoch_(\d+)", x).group(1)) for x in glob.glob(d + "/*.pth")]
|
| 754 |
+
if e: eps.append(max(e))
|
| 755 |
+
note = (f"*training, ep {min(eps)}-{max(eps)}/5000, {nrun} jobs*" if eps
|
| 756 |
+
else (f"*launched, {nrun} jobs, no checkpoint yet*" if nrun else "*not launched*"))
|
| 757 |
+
ff = lambda v: note if v is None else f"{v:.1f}"
|
| 758 |
+
SEC.append(f"| {label} | {traj} | {_HZ.setdefault(task, _horizon(task))} (--) | {reg} | {ff(b3['BC'])} | {ff(b3['BCU'])} | {ff(b3['IDQL'])} | {ff(b3['RISE'])} | "
|
| 759 |
+
f"-- | -- | -- | -- | -- | -- | -- | -- | -- | -- | -- | -- | -- | -- | -- | -- | -- |")
|
| 760 |
+
|
| 761 |
+
HDR = L[-2:] # the header + separator built above
|
| 762 |
+
L = L[:-2]
|
| 763 |
+
# The flagship ROW for some tasks is a data variant (square-peg suboptimal: the 20/100 subsample,
|
| 764 |
+
# not the released 100/100 file, which carries 5x the expert data and was demoted by the user).
|
| 765 |
+
# Sections 0 and 5 iterate over TASKS and so must honour that mapping, otherwise they report the
|
| 766 |
+
# DEMOTED file under the FLAGSHIP label -- and, worse, aim top-up compute at the demoted row.
|
| 767 |
+
def _row_identity(task):
|
| 768 |
+
"""-> (task_whose_cells_to_use, display_name, is_demoted_release)"""
|
| 769 |
+
fv = FLAGSHIP_VARIANT.get(task)
|
| 770 |
+
if fv:
|
| 771 |
+
return fv[0], fv[1], False
|
| 772 |
+
return task, NAME.get(task, task), False
|
| 773 |
+
|
| 774 |
+
# ---- UPPER-BOUND SUMMARY ------------------------------------------------------------------------
|
| 775 |
+
# "What is the ceiling if the single-seed winners reproduce across seeds?" One row per task:
|
| 776 |
+
# the verified number we can quote today, and the number we would quote if the best never-verified
|
| 777 |
+
# arm held up. The gap between them is exactly what the top-up is buying.
|
| 778 |
+
# the read-out classifier lives with the table generator that defines the arm-key grammar
|
| 779 |
+
# ("CH<cap>" = coin chain, "L<d>" = retired fold); it is imported rather than re-derived so the
|
| 780 |
+
# markdown and the LaTeX can never disagree about which arm is which estimator.
|
| 781 |
+
import flagship_latex as _FLC
|
| 782 |
+
_F_is_chain = _FLC._recipe_is_chain
|
| 783 |
+
|
| 784 |
+
UB = []
|
| 785 |
+
_CEIL_CHECK = {} # display label -> section 0 ceiling, cross-checked against the section 1 row below
|
| 786 |
+
for task, _lbl in TASKS:
|
| 787 |
+
_src, _disp, _ = _row_identity(task)
|
| 788 |
+
try: c = cells(_src)
|
| 789 |
+
except Exception: continue
|
| 790 |
+
base = defaultdict(lambda: [0.0, 0]); agg3 = defaultdict(lambda: [0.0, 0]); sd3 = defaultdict(set)
|
| 791 |
+
# READ-OUT SPLIT (gen_q#267, orchestrator 2026-09-23 07:05Z). This section used to aggregate every
|
| 792 |
+
# `rsm:membership` arm regardless of read-out, so "today" and the verdict were the maximum over the
|
| 793 |
+
# RETIRED deterministic fold -- three tables below a headline column that is chain-only. On
|
| 794 |
+
# threading that made this section say "win" (fold 33.4 vs BC 26.3) while the flagship column two
|
| 795 |
+
# tables up says no decision (chain 24.4 vs 26.3). The verdicts here are now computed from the
|
| 796 |
+
# CHAIN arms alone, the same estimator the paper's tab:flagship prints; the fold maximum is kept in
|
| 797 |
+
# columns that NAME it as retired, never as the row's number.
|
| 798 |
+
ch3 = defaultdict(lambda: [0.0, 0]); chsd = defaultdict(set); chcl = defaultdict(set)
|
| 799 |
+
fo3 = defaultdict(lambda: [0.0, 0]); fosd = defaultdict(set); focl = defaultdict(set) # FOLD-ONLY, for the retired columns
|
| 800 |
+
for (arm, pol, ps, es), e in c.items():
|
| 801 |
+
if arm[0] == "greedy":
|
| 802 |
+
base[pol][0] += sum(e); base[pol][1] += len(e)
|
| 803 |
+
elif arm[0].startswith("rsm:membership"):
|
| 804 |
+
k = (arm[1], pol); agg3[k][0] += sum(e); agg3[k][1] += len(e); sd3[k].add(ps)
|
| 805 |
+
if _F_is_chain(arm[1]):
|
| 806 |
+
ch3[k][0] += sum(e); ch3[k][1] += len(e); chsd[k].add(ps); chcl[k].add((ps, es))
|
| 807 |
+
elif _FLC._readout_of(arm[1]) == "fold":
|
| 808 |
+
# POSITIVE test, not `else` (2026-09-24, run 20). `_F_is_chain` excludes off-gamma and
|
| 809 |
+
# cap-0 chain arms as well as fold arms, so an `else` here labelled a CHAIN key as the
|
| 810 |
+
# row's fold number -- Square (Cov.)'s "ceiling, fold (retired)" read 20.0 from
|
| 811 |
+
# `L40@best b0.95 CH0`. Excluded chain arms now enter neither column and are counted.
|
| 812 |
+
fo3[k][0] += sum(e); fo3[k][1] += len(e); fosd[k].add(ps); focl[k].add((ps, es))
|
| 813 |
+
else:
|
| 814 |
+
_ub_chain_excl[_disp] = _ub_chain_excl.get(_disp, 0) + 1
|
| 815 |
+
bb = max((x / y * 100 for x, y in base.values() if y >= 150), default=float("nan"))
|
| 816 |
+
# CEILING (user 2026-09-20): "the best mean across the seeds done for a config, ie mean over
|
| 817 |
+
# 1, 2 or 3 seeds". So the ceiling ranges over EVERY arm, whatever its seed count, and its value
|
| 818 |
+
# is that arm's pooled mean over the seeds it actually has. When the winner already has three
|
| 819 |
+
# seeds the ceiling equals today and nothing is pending -- which is itself the useful signal.
|
| 820 |
+
# "Verified" MUST mean here exactly what it means in section 1: three training seeds. This also
|
| 821 |
+
# carried a >=300-episode floor, which the prose never stated, so square-peg (Coverage) -- whose
|
| 822 |
+
# 3-seed flagship arm has 150 episodes (3 seeds x 1 eval seed x 50) -- was excluded here and the
|
| 823 |
+
# column fell back to a weaker arm: section 0 said "today 8.7, tie" while section 1 said 9.3 on the
|
| 824 |
+
# same task at the same three seeds. One document, one definition; the episode count is printed
|
| 825 |
+
# beside the number so a thin 3-seed result is still visible as thin.
|
| 826 |
+
# (The maxima over BOTH read-outs used to be computed here and printed in the two "retired"
|
| 827 |
+
# columns and handed to the cross-section guard. Both were wrong for the same reason -- a mixed
|
| 828 |
+
# maximum under a single-estimator heading -- and both are now computed per read-out below. The
|
| 829 |
+
# mixed quantity is not needed anywhere, so it is not computed at all: an unused mixed maximum is
|
| 830 |
+
# just waiting for someone to print it.)
|
| 831 |
+
# the same two quantities restricted to the coin-terminated chain read-out
|
| 832 |
+
# "TODAY" IS A PRINTED HEADLINE, so it takes the same grid-completeness tier section 1 now uses:
|
| 833 |
+
# a 3-of-9-cell arm reading 50.0 must not displace the complete 9-of-9 arm reading 45.1 (the 18:39Z
|
| 834 |
+
# defect). The CEILING (`allc`) deliberately does NOT -- the owner's definition is "the best mean
|
| 835 |
+
# across the seeds done for a config", i.e. over every arm however partial -- but it now carries the
|
| 836 |
+
# cell count so the column can say how thin the grid behind it is.
|
| 837 |
+
verc = [(x / y * 100, k, y) for k, (x, y) in ch3.items() if len(chsd[k]) >= 3]
|
| 838 |
+
allc = [(x / y * 100, k, len(chsd[k]), y) for k, (x, y) in ch3.items() if y >= 50]
|
| 839 |
+
_vc = max(verc, key=lambda t: _F_tier(t[0], t[2], 3, len(chcl[t[1]])), default=(float("nan"), None, 0))
|
| 840 |
+
vbc, vepsc = _vc[0], _vc[2]
|
| 841 |
+
ubc = max(allc, default=(float("nan"), None, 0, 0))
|
| 842 |
+
# ...and restricted to the RETIRED FOLD, for the two columns that NAME it (found 2026-09-23 12:05Z).
|
| 843 |
+
# These two printed `vb` and `ub[0]`, the maxima over BOTH read-outs, under headings "today, fold
|
| 844 |
+
# (retired)" and "ceiling, fold (retired)" -- so wherever the chain arm won the row, a column
|
| 845 |
+
# labelled `fold` printed the CHAIN number. That is byte-for-byte the defect fixed in the LaTeX
|
| 846 |
+
# single-actor table in run 8 (Square (Cov.) printed 20.9 in an "RSM-fold (retired)" column whose
|
| 847 |
+
# own best fold arm is 17.6); it survived here because this section computes its own maxima.
|
| 848 |
+
_verf = [(x / y * 100, k, y) for k, (x, y) in fo3.items() if len(fosd[k]) >= 3]
|
| 849 |
+
_allf = [(x / y * 100, k, len(fosd[k]), y) for k, (x, y) in fo3.items() if y >= 50]
|
| 850 |
+
vbf = max(_verf, key=lambda t: _F_tier(t[0], t[2], 3, len(focl[t[1]])), default=(float("nan"), None, 0))[0]
|
| 851 |
+
ubf = max(_allf, default=(float("nan"), None, 0, 0))[0]
|
| 852 |
+
# A MISSING baseline is not a loss. bb is nan whenever no greedy arm has >=150 episodes yet (the
|
| 853 |
+
# 20/100 square split, whose BC/BCU evals are still running). Every comparison against nan is
|
| 854 |
+
# False, so the verdicts used to fall through to "LOSS" and "still loses" -- the table asserted a
|
| 855 |
+
# defeat on a task it had never measured a baseline for, and printed "nan" and "+nan" as values.
|
| 856 |
+
_nob = bb != bb
|
| 857 |
+
_noch = vbc != vbc # no chain arm verified at three seeds yet
|
| 858 |
+
now = ("*no baseline yet*" if _nob else
|
| 859 |
+
("*chain pending*" if _noch else
|
| 860 |
+
("win" if vbc > bb else ("tie" if abs(vbc - bb) < 1.0 else "LOSS"))))
|
| 861 |
+
_ceilc = ubc[0]
|
| 862 |
+
ceil = ("*no baseline yet*" if _nob else
|
| 863 |
+
("*chain pending*" if _ceilc != _ceilc else ("win" if _ceilc > bb else "still loses")))
|
| 864 |
+
_pend = "" if ubc[2] >= 3 else f" *(pending {3-ubc[2]} seed(s))*"
|
| 865 |
+
# episodes behind the ceiling number, so a 1-seed/50-episode ceiling cannot be mistaken for a
|
| 866 |
+
# 3-seed/450-episode one at a glance
|
| 867 |
+
UB.append((_disp, "--" if _nob else f"{bb:.1f}",
|
| 868 |
+
"--" if _noch else f"{vbc:.1f} ({vepsc} ep)", now,
|
| 869 |
+
"--" if _ceilc != _ceilc else f"{_ceilc:.1f}",
|
| 870 |
+
f"{ubc[2]}/3", ubc[3],
|
| 871 |
+
"--" if (_nob or _ceilc != _ceilc) else f"{_ceilc-bb:+.1f}",
|
| 872 |
+
ceil + _pend,
|
| 873 |
+
"--" if vbf != vbf else f"{vbf:.1f}",
|
| 874 |
+
"--" if ubf != ubf else f"{ubf:.1f}"))
|
| 875 |
+
# COMPARE LIKE WITH LIKE (2026-09-23). This handed the guard `ub[0]`, the ceiling over BOTH
|
| 876 |
+
# read-outs, while section 1's max-over-arms is now CHAIN-ONLY -- so the guard fired on square-peg
|
| 877 |
+
# (Suboptimal) with "ceiling 58.00 != max 50.44", 58.00 being a fold arm. The guard exists to
|
| 878 |
+
# catch the two sections reading different DATA, not different estimators; it now compares the
|
| 879 |
+
# chain ceiling, which is the quantity section 1 maximises.
|
| 880 |
+
_CEIL_CHECK[_disp] = ubc[0]
|
| 881 |
+
|
| 882 |
+
# CROSS-SECTION GUARD. Section 0's ceiling and section 1's headline are the same quantity by
|
| 883 |
+
# construction -- the best membership arm over whatever seeds it has -- so if they ever disagree, one
|
| 884 |
+
# of the two sections is reading a different task, a different reward head or a different region.
|
| 885 |
+
# That exact failure has happened twice here (the FLAGSHIP_VARIANT remap, and the 300-episode floor
|
| 886 |
+
# above), and both times the table looked perfectly plausible while saying two things at once.
|
| 887 |
+
# Since the 2026-09-21 routing rule a verified winner may sit in section 1 BELOW a single-seed
|
| 888 |
+
# maximum, so the guard compares the ceiling to the max over flagship candidates (_FLAG_MAX), which is
|
| 889 |
+
# the headline whenever no verified winner was preferred, and requires headline <= ceiling always.
|
| 890 |
+
for _lbl_, _c_ in _CEIL_CHECK.items():
|
| 891 |
+
_f_ = _FLAG_VAL.get(_lbl_); _m_ = _FLAG_MAX.get(_lbl_, _f_)
|
| 892 |
+
if _f_ is not None and _c_ == _c_ and (abs(_m_ - _c_) > 0.05 or _f_ > _c_ + 0.05):
|
| 893 |
+
raise AssertionError(f"section 0 ceiling {_c_:.2f} != section 1 max-over-arms {_m_:.2f} "
|
| 894 |
+
f"(headline {_f_:.2f}) for {_lbl_!r}")
|
| 895 |
+
|
| 896 |
+
if UB:
|
| 897 |
+
L += ["", "## 0. Upper bound --- what the table becomes if the single-seed winners reproduce", "",
|
| 898 |
+
"**Today** is the best arm verified at three policy seeds. **Ceiling** is the best *mean* over any "
|
| 899 |
+
"arm, pooled across whatever seeds that arm actually has (1, 2 or 3) -- so a ceiling at 3/3 seeds "
|
| 900 |
+
"is already verified and equals today, while a ceiling at 1/3 is a candidate the top-up is testing. "
|
| 901 |
+
"The seed and episode counts behind the ceiling are given so a 50-episode single-seed number is "
|
| 902 |
+
"never mistaken for a 450-episode verified one. **The ceiling also admits arms whose 3x3 cell "
|
| 903 |
+
"grid is only partly landed**, which `today` does not: since 2026-09-23 the headline prefers a "
|
| 904 |
+
"COMPLETE 9-cell arm to any partial one however high it scores (`flagship_latex._seed_tier_key`, "
|
| 905 |
+
"now shared by this file), because an in-flight arm's episode-pooled rate is weighted towards "
|
| 906 |
+
"whichever policy seed happened to land more cells. `scripts/chain_grid_census.py` prints the "
|
| 907 |
+
"gap per task; where the ceiling exceeds today, check it there before quoting the ceiling.", "",
|
| 908 |
+
"This is an UPPER BOUND, not a forecast. Each ceiling rests on 50-100 episodes at one policy seed, "
|
| 909 |
+
"picked as the maximum over 27-119 arms, so it is upward biased twice over: by selection and by "
|
| 910 |
+
"small n. Every time a single-seed maximum on this project was actually verified it fell: "
|
| 911 |
+
"-7.2, -7.6, -10.2 points.", "",
|
| 912 |
+
"**Every RSM number in the first nine columns is the coin-terminated \u03b2-chain read-out** "
|
| 913 |
+
"(gen_q#267) \u2014 the same estimator as the flagship column at the top of this file. The last two "
|
| 914 |
+
"columns are the RETIRED deterministic truncated fold, kept only so the change is visible; they "
|
| 915 |
+
"are not this section's numbers and no verdict is computed from them.", "",
|
| 916 |
+
"| 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) |",
|
| 917 |
+
"|---|---|---|---|---|---|---|---|---|---|---|"]
|
| 918 |
+
for r in UB:
|
| 919 |
+
L += ["| " + " | ".join(str(x) for x in r) + " |"]
|
| 920 |
+
# r[8] now carries a "*(pending N seed(s))*" suffix, so match on the prefix, not equality.
|
| 921 |
+
_w = sum(1 for r in UB if r[3] == "win"); _cw = sum(1 for r in UB if str(r[8]).startswith("win"))
|
| 922 |
+
_settled = sum(1 for r in UB if "pending" not in str(r[8]))
|
| 923 |
+
_nb = sum(1 for r in UB if r[1] == "--")
|
| 924 |
+
_npend = sum(1 for r in UB if str(r[2]) == "--")
|
| 925 |
+
L += ["", f"**{_w} of {len(UB)} rows win today on the chain read-out; {_cw} of {len(UB)} would win at "
|
| 926 |
+
f"the ceiling.** "
|
| 927 |
+
+ (f"{_npend} row(s) have no 3-seed chain arm yet and are counted as neither. " if _npend else "")
|
| 928 |
+
+ f"{_settled} ceiling(s) are already verified at 3 seeds and will not move."
|
| 929 |
+
+ (f" {_nb} row(s) have no baseline measured yet and are counted as neither." if _nb else ""), ""]
|
| 930 |
+
|
| 931 |
+
def _tbl(rows, empty):
|
| 932 |
+
"""HDR + rows, or a sentence when there are none.
|
| 933 |
+
|
| 934 |
+
A markdown table whose only lines are the header and the `|---|` separator renders as an empty
|
| 935 |
+
grid -- section 2 shipped that way, because no `completion`-head arm has reached two seeds yet.
|
| 936 |
+
An empty section must SAY it is empty, not look like a table that lost its contents.
|
| 937 |
+
"""
|
| 938 |
+
return (HDR + rows) if rows else [f"*{empty}*", ""]
|
| 939 |
+
|
| 940 |
+
|
| 941 |
+
def _fold_excl_note():
|
| 942 |
+
"""How much was excluded, COMPUTED -- a typed count goes stale the moment a cell lands (run 7)."""
|
| 943 |
+
_n = sum(v[0] for v in FOLD_EXCLUDED.values())
|
| 944 |
+
_rows = sum(1 for v in FOLD_EXCLUDED.values() if v[0])
|
| 945 |
+
if not _n:
|
| 946 |
+
return "No fold arm exists in these rows."
|
| 947 |
+
return (f"{_n} fold arm(s) across {_rows} row(s) were excluded from this maximum for that reason; "
|
| 948 |
+
"they remain in section 0's columns that name them retired and in the paper's "
|
| 949 |
+
"`tab:ablation_betarec`." + _chain_excl_note())
|
| 950 |
+
|
| 951 |
+
|
| 952 |
+
def _chain_excl_note():
|
| 953 |
+
"""Chain arms excluded for NOT being this paper's chain (wrong gamma, or cap 0 = no recursion).
|
| 954 |
+
Reported separately from the fold count because they are a different defect and, unlike a fold arm,
|
| 955 |
+
they appear in NO column of this document -- if the count were folded into the fold total, a reader
|
| 956 |
+
would look for them in the retired columns and not find them (run 20)."""
|
| 957 |
+
_n = sum(v[0] for v in CHAIN_EXCLUDED.values())
|
| 958 |
+
_rows = sum(1 for v in CHAIN_EXCLUDED.values() if v[0])
|
| 959 |
+
_ub = sum(_ub_chain_excl.values())
|
| 960 |
+
if not _n and not _ub:
|
| 961 |
+
return ""
|
| 962 |
+
_best = max([v[1] for v in CHAIN_EXCLUDED.values() if v[1] is not None], default=None)
|
| 963 |
+
return (f" A FURTHER {_n} arm(s) across {_rows} row(s) carry the chain tag but are NOT this paper's "
|
| 964 |
+
f"chain -- either at an evaluation-time γ other than {_FLC.FLAGSHIP_GAMMA:g} (the cap does "
|
| 965 |
+
"not match the 1e-3 truncation tail its β implies) or at cap 0, where β ≥ γ "
|
| 966 |
+
"makes the continuation probability exactly 0 and the walk is one successor draw with no "
|
| 967 |
+
f"recursion. They are excluded from EVERY column of this document, not moved to the retired "
|
| 968 |
+
f"fold ones (best excluded score {'n/a' if _best is None else f'{_best:.1f}'}; "
|
| 969 |
+
f"{_ub} further such arm(s) were kept out of section 0's retired columns).")
|
| 970 |
+
|
| 971 |
+
|
| 972 |
+
L += ["## 1. Flagship comparison --- RISE-faithful reward (reward-matched)", "",
|
| 973 |
+
"**Reward structure is matched across every column.** RISE's reward is data PROVENANCE, not outcome: "
|
| 974 |
+
"`relabel_rewards.py` writes a constant over every frame of an episode (1 for the expert file, 0 for the "
|
| 975 |
+
"non-expert file) and `iql_diffusion.py` consumes that field unchanged. So BC and BCU use no reward, the "
|
| 976 |
+
"RISE and IDQL critics use the provenance label, and the RSM arm below uses the *same* provenance label "
|
| 977 |
+
"(`membership` head). Nothing here sees a signal the others do not.", "",
|
| 978 |
+
"One row per task: the strongest membership-head RSM arm in that task's canonical evaluation region, against "
|
| 979 |
+
"every baseline. Where the strongest arm is not yet verified on three training seeds it is shown as a "
|
| 980 |
+
"**TEMPORARY flagship**; quote such a row only with its seed count.", "",
|
| 981 |
+
"**The RSM column is the coin-terminated \u03b2-chain read-out only** (gen_q#267), the same estimator "
|
| 982 |
+
"as section 0 and as the paper's `tab:flagship`. Until 2026-09-23 this section ranged over BOTH "
|
| 983 |
+
"read-outs, so it printed the retired deterministic fold under this heading with its own `verdict` "
|
| 984 |
+
"\u2014 on threading it printed 33.0 at `hops 1`, four hours after that number was publicly retracted "
|
| 985 |
+
"on #267, and marked it **win**. " + _fold_excl_note() + " A task with no chain arm prints dashes; a "
|
| 986 |
+
"fold number never stands in for a chain number.", "",
|
| 987 |
+
# The headline a reviewer needs before any per-row number: on how many tasks does the SCORER
|
| 988 |
+
# actually do something? Beating BC is not that question -- the proposer alone can do it.
|
| 989 |
+
f"**Selection verdict across the {len(_FLAG_CTRL)} flagship rows: "
|
| 990 |
+
f"{sum(1 for v in _FLAG_CTRL if v == '**win**')} beat both controls, "
|
| 991 |
+
f"{sum(1 for v in _FLAG_CTRL if 'below its own' in v)} score BELOW their own no-selection control, "
|
| 992 |
+
f"{sum(1 for v in _FLAG_CTRL if v in ('no gain', 'control undecided'))} are undecided "
|
| 993 |
+
f"(mostly 50-episode single-seed cells).** A row can beat every baseline and still be carried by "
|
| 994 |
+
f"its proposer rather than by the scorer; the two control columns are what separate those cases, "
|
| 995 |
+
f"and the verdict column now always reports them.", ""] + _tbl(FLAG, "No task has a matched-reward arm yet.")
|
| 996 |
+
if VERLOW:
|
| 997 |
+
L += ["", "## 1b. Better verified, lower scoring --- same reward regime, weaker configuration", "",
|
| 998 |
+
"Every row here is an arm that carries **more training seeds than its task's section-1 row but "
|
| 999 |
+
"scores lower**. This is the honest counterweight to the flagship's admission of "
|
| 1000 |
+
"seed-deficient winners: if the best arm rests on one seed while a different configuration has "
|
| 1001 |
+
"three, both numbers are on the table and the seed counts are printed beside each. A runner-up "
|
| 1002 |
+
"with no seed advantage over the flagship row is neither a better result nor better evidence, "
|
| 1003 |
+
"so it is not printed at all. Reward regime is identical to section 1; the critic columns are "
|
| 1004 |
+
"shown because the reward is matched.", ""] + _tbl(VERLOW, "No task has a better-verified arm that scores below its flagship row.")
|
| 1005 |
+
|
| 1006 |
+
L += ["", "## 2. Alternative reward --- per-frame environment success (backup flagship)", "",
|
| 1007 |
+
"The `completion` head scores per-frame task success recovered by state replay, rather than data provenance. "
|
| 1008 |
+
"This is **not a correction to RISE, it is a different reward**: the paper never uses outcome labels. It is "
|
| 1009 |
+
"reported here as a legitimate alternative and would become the headline only if it beats section 1. "
|
| 1010 |
+
"Reward matching still requires the RISE and IDQL critics to be retrained on the same per-frame label, which "
|
| 1011 |
+
"has NOT been done, so a win here is not yet a matched win.", "",
|
| 1012 |
+
"Known defect: `train_goal_head.py` defaults to the PRE-settle label (`goal.npz`), which overcounts success "
|
| 1013 |
+
"by 1.85x to 2.86x against the corrected `goal_settle.npz`. Every existing completion checkpoint records "
|
| 1014 |
+
"`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.")
|
| 1015 |
+
L += ["", "## 3. DISQUALIFIED --- dense privileged reward (oracle)", "",
|
| 1016 |
+
"**Do not quote.** The `progress` head regresses a dense hand-designed potential over privileged simulator "
|
| 1017 |
+
"state (end-effector-to-object and object-to-target distances; 4315 distinct values over 13973 grasped "
|
| 1018 |
+
"frames on piece-assembly). No other method sees it, so these rows are not reward-matched to anything "
|
| 1019 |
+
"printed beside them. Retired 2026-09-20; kept only so existing artefacts remain traceable.", ""] + _tbl(ORCROW, "No oracle-head arm remains on record.")
|
| 1020 |
+
L += ["", "## 4. Secondary results --- RISE-faithful reward (same regime as section 1)", "",
|
| 1021 |
+
"**Same reward regime as section 1**, so every column here is matched: BC/BCU use no reward, the RISE and "
|
| 1022 |
+
"IDQL critics and the RSM arm all use the provenance label. Rows land here for reasons of *evidence*, not "
|
| 1023 |
+
"reward: single-seed arms awaiting verification, alternate evaluation regions, and task variants whose "
|
| 1024 |
+
"trainings have not finished. Any row whose reward is not the provenance label is routed to section 2 or 3 "
|
| 1025 |
+
"instead, whichever code path produced it.", ""] + _tbl(SEC, "Nothing is currently held back from the flagship.")
|
| 1026 |
+
|
| 1027 |
+
# COLUMN-COUNT GUARD. The alternate-region path used to omit the horizon column, so its rows printed
|
| 1028 |
+
# 21 fields against a 23-field header and every cell after the region silently shifted one to the left
|
| 1029 |
+
# -- the `head` column displayed the beta value. That was invisible in both the markdown and the PDF.
|
| 1030 |
+
# LABEL/DATASET CONSISTENCY GUARD (added after two bugs of this shape on 2026-09-20).
|
| 1031 |
+
# The column guard below catches MALFORMED rows. It cannot catch a well-formed row carrying the wrong
|
| 1032 |
+
# dataset. Twice tonight a row label was attached to two different datasets -- the released
|
| 1033 |
+
# square-peg 100/100 file and its 20/100 subsample -- because one code path honoured
|
| 1034 |
+
# FLAGSHIP_VARIANT and another did not. Symptom: section 0 said 41.3 and section 1 said 73.2 for a
|
| 1035 |
+
# row with the same name. Rule: one display label maps to exactly one (expert/non-expert) trajectory
|
| 1036 |
+
# count across the whole document.
|
| 1037 |
+
_label_traj = {}
|
| 1038 |
+
for _sec_name, _rows in (("1 flagship", FLAG), ("1b verified-lower", VERLOW), ("2 alt-reward", ALTREW), ("3 oracle", ORCROW), ("4 secondary", SEC)):
|
| 1039 |
+
for _r in _rows:
|
| 1040 |
+
_f = [x.strip() for x in _r.split("|")]
|
| 1041 |
+
if len(_f) < 4:
|
| 1042 |
+
continue
|
| 1043 |
+
_lab, _tj = _f[1], _f[2]
|
| 1044 |
+
if not _tj or "/" not in _tj:
|
| 1045 |
+
continue
|
| 1046 |
+
if _lab in _label_traj and _label_traj[_lab][0] != _tj:
|
| 1047 |
+
raise AssertionError(
|
| 1048 |
+
f"label '{_lab}' carries two different datasets: {_label_traj[_lab][0]} "
|
| 1049 |
+
f"(section {_label_traj[_lab][1]}) vs {_tj} (section {_sec_name}). "
|
| 1050 |
+
f"A demoted variant is probably not being relabelled.")
|
| 1051 |
+
_label_traj.setdefault(_lab, (_tj, _sec_name))
|
| 1052 |
+
|
| 1053 |
+
_ncol = HDR[0].count("|") - 1
|
| 1054 |
+
for _sec_name, _rows in (("1 flagship", FLAG), ("1b verified-lower", VERLOW), ("2 alt-reward", ALTREW), ("3 oracle", ORCROW), ("4 secondary", SEC)):
|
| 1055 |
+
for _r in _rows:
|
| 1056 |
+
_n = _r.count("|") - 1
|
| 1057 |
+
assert _n == _ncol, (f"section {_sec_name}: row has {_n} columns, header has {_ncol}.\n"
|
| 1058 |
+
f" {_r[:160]}")
|
| 1059 |
+
|
| 1060 |
+
|
| 1061 |
+
# ---- TOP-UP PLAN --------------------------------------------------------------------------------
|
| 1062 |
+
# User ruling 2026-09-20: "if we already had 3 seeds and the average got dropped from seed 0, not a
|
| 1063 |
+
# valid topup candidate". An arm at >=3 policy seeds HAS been tested; its 3-seed mean is the answer
|
| 1064 |
+
# and re-running it only chases noise. A valid candidate is an arm that BEATS the best baseline and
|
| 1065 |
+
# has FEWER than 3 policy seeds, i.e. was never verified at all.
|
| 1066 |
+
TOPUP = []
|
| 1067 |
+
for task, _lbl in TASKS:
|
| 1068 |
+
_src, _disp, _ = _row_identity(task)
|
| 1069 |
+
try: c = cells(_src)
|
| 1070 |
+
except Exception: continue
|
| 1071 |
+
base = defaultdict(lambda: [0.0, 0]); agg2 = defaultdict(lambda: [0.0, 0]); sd = defaultdict(set)
|
| 1072 |
+
cl = defaultdict(set) # arm -> the (policy seed, eval seed) CELLS it has landed, of the 9
|
| 1073 |
+
for (arm, pol, ps, es), e in c.items():
|
| 1074 |
+
if arm[0] == "greedy":
|
| 1075 |
+
base[pol][0] += sum(e); base[pol][1] += len(e)
|
| 1076 |
+
elif arm[0].startswith("rsm:membership"):
|
| 1077 |
+
k = (arm[1], pol); agg2[k][0] += sum(e); agg2[k][1] += len(e); sd[k].add(ps); cl[k].add((ps, es))
|
| 1078 |
+
bb = max((x / y * 100 for x, y in base.values() if y >= 150), default=0.0)
|
| 1079 |
+
cand = [(x / y * 100, k, len(sd[k]), y) for k, (x, y) in agg2.items()
|
| 1080 |
+
if y >= 50 and x / y * 100 > bb and len(sd[k]) < 3]
|
| 1081 |
+
# SECOND CANDIDATE CLASS: THREE POLICY SEEDS, INCOMPLETE 3x3 GRID (gen_q#267, 2026-09-23 run 13).
|
| 1082 |
+
# The rule above nominates on POLICY SEEDS only (`len(sd[k]) < 3`), so an arm with all three policy
|
| 1083 |
+
# seeds but one or two EVAL seeds each -- 3, 4 or 5 of the 9 cells -- could never be nominated.
|
| 1084 |
+
# Those are exactly the four arms the grid census currently reports as EXPOSED (piece-assembly
|
| 1085 |
+
# (Sub.) 4/9 cells reading 50.0 against the complete 45.1, square-peg (Sub.) 7/9 at 55.1 vs 51.6,
|
| 1086 |
+
# 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
|
| 1087 |
+
# every printed table, and this plan could not ask for the 1-5 cells that would settle them, so the
|
| 1088 |
+
# question just sat there. This does NOT reopen the owner's 2026-09-20 ruling ("if we already had
|
| 1089 |
+
# 3 seeds and the average got dropped from seed 0, not a valid topup candidate") -- that ruling is
|
| 1090 |
+
# about RE-RUNNING an arm already measured on the full grid, and these arms have never been
|
| 1091 |
+
# measured on it. They are listed separately and labelled, never merged into the class above.
|
| 1092 |
+
fill = [(x / y * 100, k, len(sd[k]), y, len(cl[k])) for k, (x, y) in agg2.items()
|
| 1093 |
+
if y >= 50 and x / y * 100 > bb and len(sd[k]) >= 3 and len(cl[k]) < 9]
|
| 1094 |
+
done = sum(1 for k in agg2 if len(sd[k]) >= 3 and len(cl[k]) >= 9)
|
| 1095 |
+
# READ-OUT IN THE PLAN (gen_q#267, 2026-09-23). This list nominates GPU, and it pooled every
|
| 1096 |
+
# `rsm:membership` arm at ANY read-out, so it kept nominating arms of the RETIRED deterministic
|
| 1097 |
+
# fold -- seeding an estimator no published column prints. Rather than silently dropping them
|
| 1098 |
+
# (the fold rows still populate tab:ablation_betarec, so that is not my call to make here), the
|
| 1099 |
+
# read-out is now PRINTED and chain candidates are ordered first, so nobody spends a node on a
|
| 1100 |
+
# fold arm without seeing that is what they are doing. Predicate imported from flagship_latex so
|
| 1101 |
+
# the plan and the tables cannot disagree about which arm is which estimator.
|
| 1102 |
+
from flagship_latex import _recipe_is_chain as _isch
|
| 1103 |
+
# INADMISSIBLE CHAIN KEYS ARE NOT `fold` ARMS (gen_q#267, 2026-09-24 run 22). The label above is a
|
| 1104 |
+
# BINARY on _recipe_is_chain, so an arm carrying the chain tag that this paper cannot print -- cap 0
|
| 1105 |
+
# (degenerate: beta >= gamma, the continuation coin never fires) or off-gamma (the cap is not the
|
| 1106 |
+
# 1e-3 tail its beta implies) -- fell into the `fold (retired)` bucket and was NOMINATED FOR GPU
|
| 1107 |
+
# under the name of an estimator it is not. The 2026-09-24 02:41 build printed three of them:
|
| 1108 |
+
# piece-assembly (Cov.) `L40@best b0.95 CH15 ... ` 41.3 and `L40@best b0.9 CH35 ...` 40.7, and
|
| 1109 |
+
# piece-tip `M@best b0.95 CH0 ...` 6.0 asking for 6 cells on a walk with no recursion. They are
|
| 1110 |
+
# DROPPED from the plan (no column can ever print them, so the GPU would buy nothing) and counted in
|
| 1111 |
+
# a note, rather than relabelled -- the same rule section 0 already applies to its columns.
|
| 1112 |
+
from verdict_table import _chain_tag_inadmissible as _inadm
|
| 1113 |
+
_drop_c = [t for t in cand if _inadm(t[1][0])]
|
| 1114 |
+
_drop_f = [t for t in fill if _inadm(t[1][0])]
|
| 1115 |
+
cand = [t for t in cand if not _inadm(t[1][0])]
|
| 1116 |
+
fill = [t for t in fill if not _inadm(t[1][0])]
|
| 1117 |
+
cand.sort(key=lambda t: (not _isch(t[1][0]), -t[0]))
|
| 1118 |
+
for sr, k, ns, n in cand[:3]:
|
| 1119 |
+
TOPUP.append((_disp, f"{bb:.1f}", f"{sr:.1f}", "chain" if _isch(k[0]) else "**fold (retired)**",
|
| 1120 |
+
k[1], k[0], f"{ns}/3", n, (3 - ns) * 3))
|
| 1121 |
+
if _drop_c or _drop_f:
|
| 1122 |
+
TOPUP.append((_disp, "", "", "", "", f"*{len(_drop_c)+len(_drop_f)} candidate(s) dropped: they "
|
| 1123 |
+
f"carry the chain tag but are not this paper's chain (cap 0, or a cap that is not "
|
| 1124 |
+
f"the 1e-3 tail their beta implies at gamma=0.99), so no column can print them and "
|
| 1125 |
+
f"GPU spent on them buys nothing*", "", "", ""))
|
| 1126 |
+
if cand:
|
| 1127 |
+
_nch = sum(1 for t in cand if _isch(t[1][0]))
|
| 1128 |
+
TOPUP.append((_disp, "", "", "", "", f"*+{max(len(cand)-3,0)} more candidates "
|
| 1129 |
+
f"({_nch} chain / {len(cand)-_nch} fold); "
|
| 1130 |
+
f"{done} arm(s) already at 3 seeds ON THE FULL 3x3 GRID and therefore NOT candidates*",
|
| 1131 |
+
"", "", ""))
|
| 1132 |
+
# the fill class, chain first and highest first, and only the chain ones are worth GPU
|
| 1133 |
+
fill.sort(key=lambda t: (not _isch(t[1][0]), -t[0]))
|
| 1134 |
+
for sr, k, ns, n, nc in fill[:3]:
|
| 1135 |
+
TOPUP.append((_disp, f"{bb:.1f}", f"{sr:.1f}", "chain" if _isch(k[0]) else "**fold (retired)**",
|
| 1136 |
+
k[1], k[0], f"3/3 seeds, **{nc}/9 cells**", n, 9 - nc))
|
| 1137 |
+
|
| 1138 |
+
if TOPUP:
|
| 1139 |
+
L += ["", "## 5. Top-up plan --- which under-seeded arms are being verified", "",
|
| 1140 |
+
"A **valid top-up candidate** beats the best baseline AND has fewer than three policy seeds, "
|
| 1141 |
+
"i.e. it was never verified. An arm already at three seeds has been tested: its three-seed mean "
|
| 1142 |
+
"is the answer even if that mean fell below its seed-0 value, and re-running it only chases "
|
| 1143 |
+
"noise. Those are excluded by construction.", "",
|
| 1144 |
+
"Each top-up runs the arm at 3 policy seeds x 3 eval seeds, 50 episodes per cell, so a single "
|
| 1145 |
+
"50-episode cell is replaced by 450 episodes. **Multiplicity warning:** these candidates were "
|
| 1146 |
+
"chosen by taking the maximum over 27-119 arms per row, so the reported maximum is upward "
|
| 1147 |
+
"biased; the top-up measures whether a specific arm holds, it does not remove the selection "
|
| 1148 |
+
"bias in how it was picked.", "",
|
| 1149 |
+
"Candidates are ordered **chain first**: the flagship prints the coin-terminated chain "
|
| 1150 |
+
"read-out, so a `fold (retired)` nomination would spend GPU seeding an estimator that appears "
|
| 1151 |
+
"only in the ablation table. The read-out is a column so that choice is visible.", "",
|
| 1152 |
+
"A **second class** of candidate carries `3/3 seeds, k/9 cells`: all three policy seeds but "
|
| 1153 |
+
"only one or two eval seeds each, so it has never been measured on the full grid. Since "
|
| 1154 |
+
"2026-09-23 the printed tables prefer a complete arm to any partial one, so these arms score "
|
| 1155 |
+
"above the headline and are excluded from it; the missing cells are what would settle them, "
|
| 1156 |
+
"and this class asks for exactly those. It does not reopen the ruling above, which is about "
|
| 1157 |
+
"re-running an arm already measured on the full 3x3 grid.", "",
|
| 1158 |
+
"| task | best baseline | arm's 1-seed score | read-out | proposer | recipe | seeds | eps so far | cells to run |",
|
| 1159 |
+
"|---|---|---|---|---|---|---|---|---|"]
|
| 1160 |
+
for r in TOPUP:
|
| 1161 |
+
L += ["| " + " | ".join(str(x) for x in r) + " |"]
|
| 1162 |
+
|
| 1163 |
+
if agg:
|
| 1164 |
+
# Selection disclosure. The flagship cell is a maximum over arms, so the search size belongs next to it.
|
| 1165 |
+
L += ["", "**How the flagship arm was chosen.** Each row reports the best-scoring arm with at least two "
|
| 1166 |
+
"training seeds, where an arm is (successor model, reward head, beta, hops, read-out, candidate "
|
| 1167 |
+
"count, proposer). The table below states how many arms that maximum ranged over and what the "
|
| 1168 |
+
"runner-up scored. Best-to-runner-up gaps are small, i.e. the top of the distribution is a plateau "
|
| 1169 |
+
"rather than a spike, which is what a real effect looks like; but the baselines receive no "
|
| 1170 |
+
"equivalent search, each contributing one fixed configuration. See `docs/PROPOSER_SELECTION.md`, "
|
| 1171 |
+
"which also shows that the proposer choice survives held-out validation on a disjoint eval seed.", "",
|
| 1172 |
+
"| task | arms searched | best | runner-up |", "|---|---|---|---|"]
|
| 1173 |
+
for _t, _lbl in TASKS:
|
| 1174 |
+
_n, _bs, _ru = SEARCH.get(_t, (0, None, None))
|
| 1175 |
+
if not _n: continue
|
| 1176 |
+
_gap = f" (gap {_bs - _ru:+.1f})" if (_bs is not None and _ru is not None) else ""
|
| 1177 |
+
L += [f"| {_lbl} | {_n} | {('%.1f' % _bs) if _bs is not None else '--'} | "
|
| 1178 |
+
f"{(('%.1f' % _ru) + _gap) if _ru is not None else 'only one qualifying arm'} |"]
|
| 1179 |
+
L += ["", f"Mean over the {len(agg)} tasks with an RSM arm: best baseline {sum(x for _, x in agg)/len(agg):.1f}, "
|
| 1180 |
+
f"RSM **{sum(x for x, _ in agg)/len(agg):.1f}**, margin **{sum(x-y for x, y in agg)/len(agg):+.1f}**.", ""]
|
| 1181 |
+
L += ["", "For orientation only, the paper's Table I on the same task rows (different data mix and, on the piece "
|
| 1182 |
+
"tasks, a different success criterion, so NOT comparable to the columns above):", "",
|
| 1183 |
+
"| task | BC | BCU | IDQL | RISE |", "|---|---|---|---|---|"]
|
| 1184 |
+
for task, _ in TASKS:
|
| 1185 |
+
q = PAPER[task]
|
| 1186 |
+
L.append(f"| {NAME[task]} | {q[0]} | {q[1]} | {q[2]} | {q[3]} |")
|
| 1187 |
+
L.append("")
|
| 1188 |
+
open("/proj/dmfexp/zwhong/rsm_rise/docs/MASTER_TABLE.md", "w").write("\n".join(L))
|
| 1189 |
+
print("\n".join(L[:22]))
|
gen_q_rsm/rsm_rise/pipeline/scripts/mc_target_spread.py
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""The reference scale for train_rsm.py's `td_tgt_mse_vs_mc` diagnostic (gen_q#268).
|
| 3 |
+
|
| 4 |
+
WHY THIS EXISTS. `td_tgt_mse_vs_mc` is the MSE between the TD-Flow occupancy target and the
|
| 5 |
+
Monte-Carlo target the SAME anchor would have received. It is tempting to read it as a convergence
|
| 6 |
+
measure -- "the bootstrap is learning the MC occupancy" -- and that reading is WRONG, which this
|
| 7 |
+
script demonstrates rather than argues. The occupancy m_beta(.|s,a) is a DISTRIBUTION; the MC target
|
| 8 |
+
is one draw from it and a converged bootstrap is an independent draw from the same distribution, so
|
| 9 |
+
their expected squared difference is 2 * Var(m_beta), not zero. A TD run whose diagnostic fell to
|
| 10 |
+
~0 would be one whose bootstrap had collapsed onto the conditional MEAN.
|
| 11 |
+
|
| 12 |
+
So the reference is the MC-vs-MC spread: draw TWO independent truncated-geometric futures at the same
|
| 13 |
+
anchor and the same beta, and measure the same per-dimension MSE. Any TD value near that number is
|
| 14 |
+
consistent with a correctly-spread bootstrap; a value far above it is a mismatched target, and a
|
| 15 |
+
value far below it is over-smoothing.
|
| 16 |
+
|
| 17 |
+
usage: mc_target_spread.py <task> [<task> ...] [--rows 8192] [--json status/tdflow/mc_spread.json]
|
| 18 |
+
"""
|
| 19 |
+
import argparse
|
| 20 |
+
import json
|
| 21 |
+
import sys
|
| 22 |
+
from pathlib import Path
|
| 23 |
+
|
| 24 |
+
import numpy as np
|
| 25 |
+
|
| 26 |
+
ROOT = Path("/proj/dmfexp/zwhong/rsm_rise")
|
| 27 |
+
sys.path.insert(0, str(ROOT / "code/gen_q/rsm_libero"))
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def main():
|
| 31 |
+
ap = argparse.ArgumentParser()
|
| 32 |
+
ap.add_argument("tasks", nargs="+")
|
| 33 |
+
ap.add_argument("--rows", type=int, default=8192)
|
| 34 |
+
ap.add_argument("--beta-lo", type=float, default=0.90)
|
| 35 |
+
ap.add_argument("--beta-hi", type=float, default=0.995)
|
| 36 |
+
ap.add_argument("--beta-trunc-eps", type=float, default=0.02)
|
| 37 |
+
ap.add_argument("--seed", type=int, default=0)
|
| 38 |
+
ap.add_argument("--json", default=str(ROOT / "status/tdflow/mc_spread.json"))
|
| 39 |
+
a = ap.parse_args()
|
| 40 |
+
from data import LiberoRSMData, truncated_geometric_future
|
| 41 |
+
out = {}
|
| 42 |
+
for task in a.tasks:
|
| 43 |
+
d = LiberoRSMData(str(ROOT / "cache" / task), chunk=8, in_ram=False, reward_mode="dense")
|
| 44 |
+
rng = np.random.default_rng(a.seed)
|
| 45 |
+
eps_pool = d.train_eps
|
| 46 |
+
w = d.ep_len[eps_pool].astype(np.float64); w /= w.sum()
|
| 47 |
+
e = rng.choice(eps_pool, size=a.rows, p=w)
|
| 48 |
+
lo, hi = d.ep_from[e], d.ep_to[e]
|
| 49 |
+
t = lo + (rng.random(a.rows) * (hi - lo)).astype(np.int64)
|
| 50 |
+
# the SAME per-anchor beta cap the trainer applies (gen_q#262)
|
| 51 |
+
L = np.maximum(hi - t, 1).astype(np.float64)
|
| 52 |
+
beta_hi_eff = np.clip(np.power(a.beta_trunc_eps, 1.0 / L), a.beta_lo, a.beta_hi)
|
| 53 |
+
beta = a.beta_lo + rng.random(a.rows) * (beta_hi_eff - a.beta_lo)
|
| 54 |
+
f1 = truncated_geometric_future(t, hi, beta, rng.random(a.rows))
|
| 55 |
+
f2 = truncated_geometric_future(t, hi, beta, rng.random(a.rows))
|
| 56 |
+
x1, x2, x0 = d._feat(f1), d._feat(f2), d._feat(t)
|
| 57 |
+
mc_mc = float(((x1 - x2) ** 2).mean())
|
| 58 |
+
stay = float(((x0 - x1) ** 2).mean())
|
| 59 |
+
out[task] = {"mc_vs_mc": mc_mc, "stay_vs_mc": stay, "rows": int(a.rows),
|
| 60 |
+
"beta_mean": float(beta.mean()), "beta_max": float(beta.max())}
|
| 61 |
+
print(f"[mc_spread] {task}: MC-vs-MC {mc_mc:.3f} | now-vs-MC {stay:.3f} | "
|
| 62 |
+
f"mean beta {beta.mean():.4f} (capped, max {beta.max():.4f})", flush=True)
|
| 63 |
+
Path(a.json).parent.mkdir(parents=True, exist_ok=True)
|
| 64 |
+
Path(a.json).write_text(json.dumps(out, indent=1))
|
| 65 |
+
print(f"[mc_spread] wrote {a.json}")
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
if __name__ == "__main__":
|
| 69 |
+
main()
|
gen_q_rsm/rsm_rise/pipeline/scripts/parity_sweep.py
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Run, under the MEMBERSHIP reward, the recipes that only the DISQUALIFIED progress head ever saw.
|
| 3 |
+
|
| 4 |
+
The progress head (dense privileged shaping) was swept before it was ruled out, and its sweeps did not
|
| 5 |
+
cover the same ground as the membership sweeps that replaced it. Two consequences, both of which make
|
| 6 |
+
the membership numbers look worse than they may be:
|
| 7 |
+
|
| 8 |
+
* beta 0.95 is heavily represented under progress and thin under membership, which matters because
|
| 9 |
+
the progress head's best arm sits at b0.95 on five of six tasks;
|
| 10 |
+
* the RISE-policy proposer at one hop is the progress winner on both two-piece tasks and was never
|
| 11 |
+
tried there under membership. Piece-tip is the extreme case: 9 progress recipes against 4
|
| 12 |
+
membership ones, progress 29.5 % vs membership 1.6 %.
|
| 13 |
+
|
| 14 |
+
Comparing a 4-arm search against a 9-arm search and concluding the reward is worse is a search-budget
|
| 15 |
+
artefact, not a result. This submits the missing recipes at eval seed 0 so the comparison is like for
|
| 16 |
+
like; winners then go through launch_flagship_topup.py as usual.
|
| 17 |
+
|
| 18 |
+
usage: parity_sweep.py [--top 3] [--print-only] [task ...]
|
| 19 |
+
"""
|
| 20 |
+
from __future__ import annotations
|
| 21 |
+
|
| 22 |
+
import argparse
|
| 23 |
+
import glob
|
| 24 |
+
import re
|
| 25 |
+
import subprocess
|
| 26 |
+
import sys
|
| 27 |
+
from pathlib import Path
|
| 28 |
+
|
| 29 |
+
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
| 30 |
+
from verdict_table import cells, pool, rate # noqa: E402
|
| 31 |
+
from launch_flagship_topup import ENVS, POLF, BASE_LABEL, _ck_suffix, ckpt # noqa: E402
|
| 32 |
+
|
| 33 |
+
ROOT = Path("/proj/dmfexp/zwhong/rsm_rise")
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def recipes(c, head):
|
| 37 |
+
out = {}
|
| 38 |
+
for (a, p) in {(a, p) for (a, p, _, _) in c if a[0] == f"rsm:{head}"}:
|
| 39 |
+
m = re.match(r"(\S+)@(\S+) b([\d.]+) L(\d+) N(\d+)", a[1])
|
| 40 |
+
if not m:
|
| 41 |
+
continue
|
| 42 |
+
sr, n = rate(pool(c, lambda x, q, A=a, P=p: x == A and q == P))
|
| 43 |
+
key = (p, float(m.group(3)), int(m.group(4)), int(m.group(5)))
|
| 44 |
+
if key not in out or sr > out[key][0]:
|
| 45 |
+
out[key] = (sr, n, m.group(1), m.group(2))
|
| 46 |
+
return out
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def main():
|
| 50 |
+
ap = argparse.ArgumentParser()
|
| 51 |
+
ap.add_argument("tasks", nargs="*")
|
| 52 |
+
ap.add_argument("--top", type=int, default=3, help="untested recipes per task, best-first by progress score")
|
| 53 |
+
ap.add_argument("--print-only", action="store_true")
|
| 54 |
+
ap.add_argument("--queue", default="preemptable")
|
| 55 |
+
a = ap.parse_args()
|
| 56 |
+
for task in (a.tasks or list(ENVS)):
|
| 57 |
+
if task not in ENVS:
|
| 58 |
+
continue
|
| 59 |
+
c = cells(task)
|
| 60 |
+
pr, me = recipes(c, "progress"), recipes(c, "membership")
|
| 61 |
+
if not pr:
|
| 62 |
+
continue
|
| 63 |
+
gap = sorted(set(pr) - set(me), key=lambda k: -pr[k][0])[:a.top]
|
| 64 |
+
if not gap:
|
| 65 |
+
print(f"### {task}: membership already covers every progress recipe")
|
| 66 |
+
continue
|
| 67 |
+
# a membership successor checkpoint to score with: prefer the one the task's own arms use
|
| 68 |
+
mem_ck = None
|
| 69 |
+
for (p_, b_, l_, n_) in sorted(me, key=lambda k: -me[k][0]):
|
| 70 |
+
mem_ck = (me[(p_, b_, l_, n_)][2], me[(p_, b_, l_, n_)][3])
|
| 71 |
+
break
|
| 72 |
+
if not mem_ck:
|
| 73 |
+
print(f"### {task}: no membership arm to take a successor checkpoint from -- skipped")
|
| 74 |
+
continue
|
| 75 |
+
model, ck = mem_ck
|
| 76 |
+
ckpt_path = ROOT / f"runs/{task}/rsm/{model}/ckpt_{ck}.pt"
|
| 77 |
+
if not ckpt_path.is_file():
|
| 78 |
+
print(f"### {task}: {ckpt_path} missing -- skipped")
|
| 79 |
+
continue
|
| 80 |
+
label = BASE_LABEL.get(model, model) + _ck_suffix(ck)
|
| 81 |
+
print(f"\n### {task} scoring with {label} ({model}@{ck})")
|
| 82 |
+
for (prop, beta, hops, N) in gap:
|
| 83 |
+
fam = POLF.get(prop)
|
| 84 |
+
pol = ckpt(task, fam, 0) if fam else None
|
| 85 |
+
if not pol:
|
| 86 |
+
print(f" SKIP {prop} b{beta} L{hops} N{N}: no {fam}_seed0 checkpoint")
|
| 87 |
+
continue
|
| 88 |
+
mode = "d1" if hops == 1 else "fold"
|
| 89 |
+
print(f" launch {prop:<12} b{beta} L{hops} N{N} (progress scored {pr[(prop,beta,hops,N)][0]:.1f}%)")
|
| 90 |
+
cmd = [sys.executable, str(ROOT / "scripts" / "launch_e1_grid.py"),
|
| 91 |
+
"--task", task, "--env", ENVS[task],
|
| 92 |
+
"--model", f"{label}={ckpt_path}:mlp",
|
| 93 |
+
"--hop", str(ROOT / "runs" / task / "hop" / "gauss" / "policy_r1.pt"),
|
| 94 |
+
"--policy", f"{fam}s0={pol}",
|
| 95 |
+
"--cells", f"{label},{beta},{hops},{mode},{N},argmax,{fam}s0",
|
| 96 |
+
"--num-rollouts", "50", "--horizon", "400", "--eval-seed", "0",
|
| 97 |
+
"--tag", "PARITY-es0",
|
| 98 |
+
"--out-dir", str(ROOT / "runs" / task / "eval_parity"),
|
| 99 |
+
"--pack", "3", "--queue", a.queue]
|
| 100 |
+
if a.print_only:
|
| 101 |
+
cmd.append("--print-only")
|
| 102 |
+
subprocess.run(cmd, check=False, stdout=subprocess.DEVNULL)
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
if __name__ == "__main__":
|
| 106 |
+
main()
|
gen_q_rsm/rsm_rise/pipeline/scripts/problog_table.py
ADDED
|
@@ -0,0 +1,195 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""gen_q#266: the read-out table — `prob` vs `logit` vs `prob_log` on the RISE actor (S0A).
|
| 3 |
+
|
| 4 |
+
One arm = (task, read-out, beta, hops). One cell = (policy seed, eval seed), so a full arm is 3x3 = 9
|
| 5 |
+
cells. ONLY fully-seeded arms are quoted; the rest are counted and excluded, never averaged over what
|
| 6 |
+
happens to have finished.
|
| 7 |
+
|
| 8 |
+
Every score is printed with its health numbers, per the standing rule that a self-implemented scorer is
|
| 9 |
+
not reportable without something a reader can check:
|
| 10 |
+
|
| 11 |
+
ties mean over decision steps of how many of the 128 candidates tie at the arg-max of the RANKING
|
| 12 |
+
array, at the 1e-6 absolute tolerance the other read-outs use. For prob_log this tolerance
|
| 13 |
+
is not meaningful (the quantity spans 40+ orders of magnitude: ~124 where every candidate
|
| 14 |
+
succeeds, ~1e-44 in a hopeless state), so `dist` below is the one to read.
|
| 15 |
+
dist mean number of DISTINCT values in the array -- tolerance-free. 128 = a total order.
|
| 16 |
+
p_ties ties of the PROBABILITY array on the same states, whatever ranks. This is the within-cell
|
| 17 |
+
control: it says what `prob` would have tied on exactly these states.
|
| 18 |
+
sat frac_saturated_mean, the share of candidates with Q >= 0.999.
|
| 19 |
+
|
| 20 |
+
usage: problog_table.py [--md] [task ...]
|
| 21 |
+
"""
|
| 22 |
+
import argparse
|
| 23 |
+
import glob
|
| 24 |
+
import json
|
| 25 |
+
import os
|
| 26 |
+
import re
|
| 27 |
+
import statistics as st
|
| 28 |
+
from collections import defaultdict
|
| 29 |
+
|
| 30 |
+
ROOT = "/proj/dmfexp/zwhong/rsm_rise"
|
| 31 |
+
TASKS = ("threading_expert_play", "mug_expert_suboptimal", "two_piece_expert_play")
|
| 32 |
+
# out-dir -> how to name the read-out of a cell found there
|
| 33 |
+
DIRS = {"eval_readout": None, "eval_problog": "P16 prob_log"}
|
| 34 |
+
CELL = re.compile(r"^E1-(?P<model>[A-Za-z0-9_]+)-R(?P<beta>[0-9.]+)-(?P<L>\d+)-N(?P<n>\d+)-"
|
| 35 |
+
r"(?P<rule>[a-z]+)-(?P<tag>[A-Za-z0-9]+)-es(?P<es>\d+)-s(?P<pol>S0As\d+)$")
|
| 36 |
+
# eval_readout tags: RO16prob / RO16logit / RO256prob
|
| 37 |
+
RO = re.compile(r"^RO(?P<p>\d+)(?P<kind>prob|logit)$")
|
| 38 |
+
PROBLOG = re.compile(r"^PROBLOG(?P<p>\d+)$")
|
| 39 |
+
# the matched `prob` baseline this launcher submits itself, for the tasks the read-out sweep never covered.
|
| 40 |
+
# Kept a SEPARATE row from the archived eval_readout "P16 prob" so the two are never silently merged.
|
| 41 |
+
PROBBASE = re.compile(r"^PROBBASE(?P<p>\d+)$")
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def readout_of(tag):
|
| 45 |
+
m = RO.match(tag)
|
| 46 |
+
if m:
|
| 47 |
+
return f"P{m.group('p')} {m.group('kind')}"
|
| 48 |
+
m = PROBLOG.match(tag)
|
| 49 |
+
if m:
|
| 50 |
+
return f"P{m.group('p')} prob_log"
|
| 51 |
+
m = PROBBASE.match(tag)
|
| 52 |
+
if m:
|
| 53 |
+
return f"P{m.group('p')} prob-matched"
|
| 54 |
+
return None
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def load(task):
|
| 58 |
+
"""-> {(readout, beta, L): {(pol, es): (success, health dict)}}"""
|
| 59 |
+
arms = defaultdict(dict)
|
| 60 |
+
for d in DIRS:
|
| 61 |
+
for f in glob.glob(os.path.join(ROOT, "runs", task, d, "*.json")):
|
| 62 |
+
base = os.path.basename(f)[:-5]
|
| 63 |
+
m = CELL.match(base)
|
| 64 |
+
if not m:
|
| 65 |
+
continue
|
| 66 |
+
ro = readout_of(m.group("tag"))
|
| 67 |
+
if ro is None or m.group("n") != "128" or m.group("rule") != "argmax":
|
| 68 |
+
continue
|
| 69 |
+
try:
|
| 70 |
+
j = json.load(open(f))
|
| 71 |
+
except Exception:
|
| 72 |
+
continue
|
| 73 |
+
if j.get("partial") or j.get("num_episodes", 0) < 50:
|
| 74 |
+
continue
|
| 75 |
+
pl = j.get("planner") or {}
|
| 76 |
+
# guard against a mislabelled directory: the cell's own recorded plan_score must match the
|
| 77 |
+
# read-out the NAME claims. A tag that does not match the fingerprint is dropped, loudly.
|
| 78 |
+
want = ro.split()[1].replace("prob-matched", "prob")
|
| 79 |
+
got = pl.get("plan_score")
|
| 80 |
+
if got != want:
|
| 81 |
+
print(f" !! {task}/{d}/{base}: name says {want}, JSON says {got} -- dropped")
|
| 82 |
+
continue
|
| 83 |
+
pt = j.get("planner_time") or {}
|
| 84 |
+
eps = [e.get("plan") for e in (j.get("episodes") or []) if e.get("plan")]
|
| 85 |
+
|
| 86 |
+
def avg(k):
|
| 87 |
+
# nan is how eval.py's cell-level roll-up spells "this diagnostic did not exist when the
|
| 88 |
+
# cell ran"; treat it as absent rather than letting it poison a mean.
|
| 89 |
+
v = [e[k] for e in eps
|
| 90 |
+
if isinstance(e, dict) and e.get(k) is not None and e[k] == e[k]]
|
| 91 |
+
if v:
|
| 92 |
+
return sum(v) / len(v)
|
| 93 |
+
w = pt.get(k)
|
| 94 |
+
return w if (w is not None and w == w) else None
|
| 95 |
+
h = {k: avg(k) for k in ("ties_at_max_mean", "frac_saturated_mean",
|
| 96 |
+
"prob_ties_at_max_mean", "prob_log_distinct_mean",
|
| 97 |
+
"prob_distinct_mean", "score_std_mean")}
|
| 98 |
+
key = (ro, float(m.group("beta")), int(m.group("L")))
|
| 99 |
+
arms[key][(m.group("pol"), int(m.group("es")))] = (100.0 * j["success_rate"], h)
|
| 100 |
+
return arms
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def fmt(v, nd=1):
|
| 104 |
+
return "--" if v is None else f"{v:.{nd}f}"
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def main():
|
| 108 |
+
ap = argparse.ArgumentParser()
|
| 109 |
+
ap.add_argument("tasks", nargs="*", default=[])
|
| 110 |
+
ap.add_argument("--md", action="store_true", help="markdown table for the issue")
|
| 111 |
+
a = ap.parse_args()
|
| 112 |
+
tasks = a.tasks or list(TASKS)
|
| 113 |
+
rows = []
|
| 114 |
+
for task in tasks:
|
| 115 |
+
arms = load(task)
|
| 116 |
+
by_ro = defaultdict(list)
|
| 117 |
+
incomplete = defaultdict(int)
|
| 118 |
+
for (ro, beta, L), cells in sorted(arms.items()):
|
| 119 |
+
if len(cells) < 9:
|
| 120 |
+
incomplete[ro] += 1
|
| 121 |
+
continue
|
| 122 |
+
sc = [v[0] for v in cells.values()]
|
| 123 |
+
med = st.median(sc)
|
| 124 |
+
hs = [v[1] for v in cells.values()]
|
| 125 |
+
|
| 126 |
+
def hm(k):
|
| 127 |
+
v = [h[k] for h in hs if h.get(k) is not None]
|
| 128 |
+
return sum(v) / len(v) if v else None
|
| 129 |
+
by_ro[ro].append((med, max(sc), hm("ties_at_max_mean"), hm("prob_log_distinct_mean"),
|
| 130 |
+
hm("prob_ties_at_max_mean"), hm("frac_saturated_mean")))
|
| 131 |
+
for ro in sorted(by_ro):
|
| 132 |
+
v = by_ro[ro]
|
| 133 |
+
meds = [x[0] for x in v]
|
| 134 |
+
|
| 135 |
+
def col(i):
|
| 136 |
+
w = [x[i] for x in v if x[i] is not None]
|
| 137 |
+
return sum(w) / len(w) if w else None
|
| 138 |
+
rows.append(dict(task=task, readout=ro, arms=len(v), median=st.median(meds),
|
| 139 |
+
best=max(x[1] for x in v), ties=col(2), dist=col(3),
|
| 140 |
+
p_ties=col(4), sat=col(5), excluded=incomplete.get(ro, 0)))
|
| 141 |
+
for ro in sorted(set(incomplete) - set(by_ro)):
|
| 142 |
+
rows.append(dict(task=task, readout=ro, arms=0, median=None, best=None, ties=None,
|
| 143 |
+
dist=None, p_ties=None, sat=None, excluded=incomplete[ro]))
|
| 144 |
+
hdr = ["task", "read-out", "arms", "median", "max", "ties", "dist", "p_ties", "sat", "excl"]
|
| 145 |
+
if a.md:
|
| 146 |
+
print("| " + " | ".join(hdr) + " |")
|
| 147 |
+
print("|" + "|".join("---" for _ in hdr) + "|")
|
| 148 |
+
else:
|
| 149 |
+
print(("{:<24} {:<14} {:>4} {:>7} {:>6} {:>7} {:>6} {:>7} {:>6} {:>5}").format(*hdr))
|
| 150 |
+
for r in rows:
|
| 151 |
+
cells = [r["task"], r["readout"], str(r["arms"]), fmt(r["median"]), fmt(r["best"]),
|
| 152 |
+
fmt(r["ties"]), fmt(r["dist"]), fmt(r["p_ties"]), fmt(r["sat"], 3),
|
| 153 |
+
str(r["excluded"])]
|
| 154 |
+
if a.md:
|
| 155 |
+
print("| " + " | ".join(cells) + " |")
|
| 156 |
+
else:
|
| 157 |
+
print(("{:<24} {:<14} {:>4} {:>7} {:>6} {:>7} {:>6} {:>7} {:>6} {:>5}").format(*cells))
|
| 158 |
+
tot_excl = sum(r["excluded"] for r in rows)
|
| 159 |
+
print(f"\n{sum(r['arms'] for r in rows)} fully-seeded arm(s) quoted; "
|
| 160 |
+
f"{tot_excl} arm(s) excluded for not having a full 3x3.")
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
if __name__ == "__main__":
|
| 164 |
+
main()
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
# --------------------------------------------------------------------------- #
|
| 168 |
+
# paired comparison: the same (beta, hops, policy seed, eval seed) under two read-outs
|
| 169 |
+
# --------------------------------------------------------------------------- #
|
| 170 |
+
def paired(task, ro_a, ro_b):
|
| 171 |
+
"""[(cell key, score_a, score_b)] over every cell present under BOTH read-outs.
|
| 172 |
+
|
| 173 |
+
This is the comparison that matters. Medians over arms mix 9 arms x 9 cells and hide the pairing;
|
| 174 |
+
here each pair differs in ONE field (plan_score) with the same successor model, checkpoint, beta,
|
| 175 |
+
hops, policy seed, eval seed, episode count and horizon, so the difference is attributable.
|
| 176 |
+
"""
|
| 177 |
+
arms = load(task)
|
| 178 |
+
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()}
|
| 179 |
+
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()}
|
| 180 |
+
keys = sorted(set(a) & set(b), key=str)
|
| 181 |
+
return [(k, a[k], b[k]) for k in keys]
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
def sign_test(pairs):
|
| 185 |
+
"""two-sided exact binomial sign test on the non-tied pairs -> (n, n_a_wins, n_ties, p)."""
|
| 186 |
+
from math import comb
|
| 187 |
+
wins = sum(1 for _, x, y in pairs if x > y)
|
| 188 |
+
loss = sum(1 for _, x, y in pairs if x < y)
|
| 189 |
+
ties = sum(1 for _, x, y in pairs if x == y)
|
| 190 |
+
n = wins + loss
|
| 191 |
+
if n == 0:
|
| 192 |
+
return len(pairs), wins, ties, 1.0
|
| 193 |
+
k = min(wins, loss)
|
| 194 |
+
p = min(1.0, 2.0 * sum(comb(n, i) for i in range(k + 1)) / 2.0 ** n)
|
| 195 |
+
return len(pairs), wins, ties, p
|
gen_q_rsm/rsm_rise/pipeline/scripts/problog_watcher.sh
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
# gen_q#266: babysit the prob_log grid AND its matched `prob` baseline.
|
| 3 |
+
#
|
| 4 |
+
# launch_problog_on_actor.py is idempotent -- launch_e1_grid skips cells whose JSON already exists and
|
| 5 |
+
# cells that are already PEND/RUN -- so re-running it whenever nothing of ours is in flight is exactly
|
| 6 |
+
# "resubmit whatever was preempted or vanished", with no risk of piling duplicates onto a busy queue.
|
| 7 |
+
#
|
| 8 |
+
# Note for whoever restarts this: do NOT `pkill -f problog_watcher.sh`. The pattern matches the shell
|
| 9 |
+
# that is running the kill (the script body appears in its command line), so it kills the caller too --
|
| 10 |
+
# exit 144, and any file rewrite in the same command silently never happens. Kill it by PID:
|
| 11 |
+
# kill $(pgrep -f "bash scripts/problog_watcher.sh")
|
| 12 |
+
ROOT=/proj/dmfexp/zwhong/rsm_rise
|
| 13 |
+
LOG=$ROOT/status/problog_watch.log
|
| 14 |
+
TOTAL=${TOTAL:-324} # 243 prob_log cells + 81 matched-prob cells on two_piece_expert_play
|
| 15 |
+
mkdir -p "$ROOT/status"
|
| 16 |
+
# One instance only. Two watchers can both see a cell as "missing" in the same window and both
|
| 17 |
+
# submit it, which wastes a GPU slot on a duplicate. flock makes a second start a no-op.
|
| 18 |
+
exec 9>"$ROOT/status/.problog_watch.lock"
|
| 19 |
+
flock -n 9 || { echo "$(date -u +%H:%M:%S) another watcher holds the lock; exiting" >> "$LOG"; exit 0; }
|
| 20 |
+
for pass in $(seq 1 "${PASSES:-72}"); do
|
| 21 |
+
done_n=$(ls $ROOT/runs/*/eval_problog/*.json 2>/dev/null | wc -l)
|
| 22 |
+
inflight=$(bjobs -w 2>/dev/null | grep -E "PROBLOG16|PROBBASE16" | grep -cE "PEND|RUN")
|
| 23 |
+
echo "$(date -u +%H:%M:%S) pass=$pass done=$done_n/$TOTAL inflight=$inflight" >> "$LOG"
|
| 24 |
+
if [ "$done_n" -ge "$TOTAL" ]; then
|
| 25 |
+
echo "$(date -u +%H:%M:%S) GRID COMPLETE" >> "$LOG"
|
| 26 |
+
break
|
| 27 |
+
fi
|
| 28 |
+
if [ "$inflight" -eq 0 ]; then
|
| 29 |
+
echo " nothing in flight; resubmitting missing cells" >> "$LOG"
|
| 30 |
+
python3 $ROOT/scripts/launch_problog_on_actor.py >> "$LOG" 2>&1
|
| 31 |
+
python3 $ROOT/scripts/launch_problog_on_actor.py two_piece_expert_play --baseline >> "$LOG" 2>&1
|
| 32 |
+
fi
|
| 33 |
+
sleep 600
|
| 34 |
+
done
|
gen_q_rsm/rsm_rise/pipeline/scripts/real/build_2x2_table.py
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Collect the D3 (stitch-feasibility) numbers for the crossed v5 2x2 and its references into one
|
| 3 |
+
markdown + LaTeX table. Reads only json written by stitch_feasibility.py; no compute."""
|
| 4 |
+
import json, os, sys
|
| 5 |
+
ROOT = "/proj/dmfexp/zwhong/rsm_rise"
|
| 6 |
+
S = f"{ROOT}/status/real"
|
| 7 |
+
DRAWS = [("12345", f"{S}/STITCH_FEASIBILITY_2x2_seed12345.json"),
|
| 8 |
+
("777", f"{S}/STITCH_FEASIBILITY_2x2_seed777.json"),
|
| 9 |
+
("999", f"{S}/STITCH_FEASIBILITY_2x2_seed999.json")]
|
| 10 |
+
ORDER = ["ft_v5", "ft_v5_x10", "ft_v5_x01", "ft_v5_s1", "shipped_R_M", "shipped_R_M_s1", "scratch_v0"]
|
| 11 |
+
LABEL = {"ft_v5": "ft_v5 (trunk s0 x rng s0)", "ft_v5_x10": "ft_v5_x10 (trunk s0 x rng s1)",
|
| 12 |
+
"ft_v5_x01": "ft_v5_x01 (trunk s1 x rng s0)", "ft_v5_s1": "ft_v5_s1 (trunk s1 x rng s1)",
|
| 13 |
+
"shipped_R_M": "R_M shipped (provenance, no ft)", "shipped_R_M_s1": "R_M_s1 shipped",
|
| 14 |
+
"scratch_v0": "R_RW_v0 from scratch (dataset rule)"}
|
| 15 |
+
rows = {}
|
| 16 |
+
for name, path in DRAWS:
|
| 17 |
+
if not os.path.exists(path):
|
| 18 |
+
print(f"[2x2] MISSING {path}", file=sys.stderr); continue
|
| 19 |
+
d = json.load(open(path))
|
| 20 |
+
for h, v in d["heads"].items():
|
| 21 |
+
rows.setdefault(h, {})[name] = v
|
| 22 |
+
present = [h for h in ORDER if h in rows] + [h for h in rows if h not in ORDER]
|
| 23 |
+
def fmt(v, k): return "--" if v is None else f"{v[k]:.3f}"
|
| 24 |
+
md = ["| head | draw | top1-rewarded | per-anchor AUC | frac anchors >0.5 | pooled AUC |",
|
| 25 |
+
"|---|---|---|---|---|---|"]
|
| 26 |
+
for h in present:
|
| 27 |
+
for name, _ in DRAWS:
|
| 28 |
+
v = rows[h].get(name)
|
| 29 |
+
if v is None: continue
|
| 30 |
+
md.append(f"| {LABEL.get(h,h)} | {name} | {fmt(v,'top1_rewarded_frac')} | "
|
| 31 |
+
f"{fmt(v,'auc_per_anchor_mean')} | {fmt(v,'auc_per_anchor_frac_above_0.5')} | "
|
| 32 |
+
f"{fmt(v,'auc_pooled')} |")
|
| 33 |
+
open(f"{S}/D3_2x2_table.md", "w").write("\n".join(md) + "\n")
|
| 34 |
+
tex = [r"\begin{tabular}{lrrrrr}\hline",
|
| 35 |
+
r"head & draw & top1-rew. & per-anchor AUC & frac$>$0.5 & pooled AUC\\\hline"]
|
| 36 |
+
for h in present:
|
| 37 |
+
for name, _ in DRAWS:
|
| 38 |
+
v = rows[h].get(name)
|
| 39 |
+
if v is None: continue
|
| 40 |
+
tex.append(f"{LABEL.get(h,h).replace('_',r'\_')} & {name} & {fmt(v,'top1_rewarded_frac')} & "
|
| 41 |
+
f"{fmt(v,'auc_per_anchor_mean')} & {fmt(v,'auc_per_anchor_frac_above_0.5')} & "
|
| 42 |
+
f"{fmt(v,'auc_pooled')}\\\\")
|
| 43 |
+
tex.append(r"\hline\end{tabular}")
|
| 44 |
+
open(f"{ROOT}/docs/tex/_d3_2x2.tex", "w").write("\n".join(tex) + "\n")
|
| 45 |
+
print("\n".join(md))
|
gen_q_rsm/rsm_rise/pipeline/scripts/real/build_decisive_tables.py
ADDED
|
@@ -0,0 +1,244 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
"""Emit the LaTeX fragments the reward study inputs:
|
| 3 |
+
|
| 4 |
+
docs/tex/_stitch_and_cal.tex reward-head calibration + stitch control per fine-tuned variant
|
| 5 |
+
(status/real/REWARD_FT_NUMBERS.json)
|
| 6 |
+
docs/tex/_decisive.tex THE DECISIVE TEST -- D1 terminal separability, D2 junction ambiguity,
|
| 7 |
+
D3 stitching feasibility, the v5 "RISE reward as shipped" correction,
|
| 8 |
+
and the open-loop screen re-cut by episode provenance
|
| 9 |
+
(status/real/DECISIVE_REWARD.json, STITCH_FEASIBILITY.json,
|
| 10 |
+
V5_REWARD.json, OPENLOOP_BY_PROVENANCE.json)
|
| 11 |
+
|
| 12 |
+
Every table caption names the json it came from. Missing inputs degrade to a one-line "not landed"
|
| 13 |
+
note so the PDF always builds.
|
| 14 |
+
"""
|
| 15 |
+
import json
|
| 16 |
+
from pathlib import Path
|
| 17 |
+
|
| 18 |
+
ROOT = Path("/proj/dmfexp/zwhong/rsm_rise")
|
| 19 |
+
ST = ROOT / "status/real"
|
| 20 |
+
TEX = ROOT / "docs/tex"
|
| 21 |
+
|
| 22 |
+
NICE = {"v0": "v0 provenance", "v1": "v1 goal transition", "v2": "v2 arrival", "v3": "v3 final segment",
|
| 23 |
+
"v4": "v4 success tail", "v5": "v5 RISE provenance"}
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def load(p):
|
| 27 |
+
try:
|
| 28 |
+
return json.loads((ST / p).read_text())
|
| 29 |
+
except Exception as e:
|
| 30 |
+
print(f"[tex] missing {p}: {e}")
|
| 31 |
+
return None
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def esc(s):
|
| 35 |
+
return str(s).replace("_", r"\_").replace("&", r"\&").replace("%", r"\%")
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def f(x, n=3, dash="--"):
|
| 39 |
+
try:
|
| 40 |
+
if x is None:
|
| 41 |
+
return dash
|
| 42 |
+
v = float(x)
|
| 43 |
+
return dash if v != v else f"{v:.{n}f}"
|
| 44 |
+
except Exception:
|
| 45 |
+
return dash
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
# ----------------------------------------------------------------- _stitch_and_cal.tex
|
| 49 |
+
ft = load("REWARD_FT_NUMBERS.json")
|
| 50 |
+
L = []
|
| 51 |
+
if ft and "calibration" in ft:
|
| 52 |
+
cal, st = ft["calibration"], ft.get("stitch", {})
|
| 53 |
+
L += [r"\begin{table}[htbp]\centering\small",
|
| 54 |
+
r"\caption{\textbf{Health of every fine-tuned reward head}, from "
|
| 55 |
+
r"\texttt{status/real/REWARD\_FT\_NUMBERS.json}. \emph{R-head AUC} separates that variant's own "
|
| 56 |
+
r"positive frames from its negatives on the held-out episodes --- it says the head learned the "
|
| 57 |
+
r"labels it was given, nothing more. \emph{CFM} is the flow-matching loss and \emph{nnl1 vs stay} "
|
| 58 |
+
r"the chained-sample distance divided by the hold-still control ($>1$ = worse than standing "
|
| 59 |
+
r"still). The stitch columns are the cross-trajectory control of "
|
| 60 |
+
r"\texttt{scripts/real/stitch\_multihop.py} (\texttt{status/real/stitch\_multihop\_R\_M\_ft\_*.json}): "
|
| 61 |
+
r"\emph{ratio} is the route-2 $\to$ route-3 splice distance over the within-route reference and "
|
| 62 |
+
r"\emph{control} the same quantity for the route-1 splice, which must be worse.}"
|
| 63 |
+
r"\label{tab:rheadcal}",
|
| 64 |
+
r"\begin{tabular}{lrrrrrrr}\toprule",
|
| 65 |
+
r"variant & step & R-head AUC & CFM & nnl1 vs stay & stitch ratio & control & $R$ logit \\\midrule"]
|
| 66 |
+
for k in sorted(cal):
|
| 67 |
+
c = cal[k]; s = st.get(k, {})
|
| 68 |
+
L.append(f"{esc(k)} & {c.get('step','--')} & {f(c.get('rhead_auc_val'),4)} & {f(c.get('cfm_val'))} & "
|
| 69 |
+
f"{f(c.get('nnl1_ratio_vs_stay_val'))} & {f(s.get('ratio_median'))} & "
|
| 70 |
+
f"{f(s.get('route1_control_median'))} & {f(s.get('rhead_logit_mean'),1)} \\\\")
|
| 71 |
+
L += [r"\bottomrule\end{tabular}\end{table}"]
|
| 72 |
+
L += [r"", r"\noindent\textbf{Read the AUC column with care.} An AUC of 1.000 means the head reproduces "
|
| 73 |
+
r"\emph{its own} labels perfectly; for v0 those labels are ``this episode succeeded'', which is "
|
| 74 |
+
r"decidable from provenance alone. v2's AUC is \texttt{NaN} because its 50 positive frames all fall "
|
| 75 |
+
r"in the training split (2 in validation, both in one episode). What the head can actually "
|
| 76 |
+
r"\emph{discriminate} is the subject of the next section.", r""]
|
| 77 |
+
else:
|
| 78 |
+
L = [r"\noindent\emph{(Health table not yet landed: status/real/REWARD\_FT\_NUMBERS.json missing.)}"]
|
| 79 |
+
(TEX / "_stitch_and_cal.tex").write_text("\n".join(L) + "\n")
|
| 80 |
+
print("[tex] wrote _stitch_and_cal.tex")
|
| 81 |
+
|
| 82 |
+
# ----------------------------------------------------------------- _decisive.tex
|
| 83 |
+
D = load("DECISIVE_REWARD.json")
|
| 84 |
+
S3 = load("STITCH_FEASIBILITY.json")
|
| 85 |
+
V5 = load("V5_REWARD.json")
|
| 86 |
+
PR = load("OPENLOOP_BY_PROVENANCE.json")
|
| 87 |
+
L = [r"\clearpage", r"\section{The decisive test: can stitching be shown under this reward?}"
|
| 88 |
+
r"\label{sec:decisive}",
|
| 89 |
+
r"""The corpus has exactly the structure a stitching demonstration needs. State 2 (\emph{pan on stove,
|
| 90 |
+
tomato at its initial position}) is visited by three different routes: route 2 (\texttt{0->2->3}), route 3
|
| 91 |
+
(\texttt{2->3->4}, the \emph{only} rewarded route) and route 4 (\texttt{0->2->6}, a failure). So from one
|
| 92 |
+
junction state the data contains both a rewarded continuation and a failure continuation, and the two
|
| 93 |
+
terminals differ only in where the pan ends up (Fig.~\ref{fig:success} vs Fig.~\ref{fig:stage6}). What was
|
| 94 |
+
never established is whether the \emph{trained reward head} can tell those apart --- and if it cannot, every
|
| 95 |
+
green/red marking in a stitching figure is decoration. Three diagnostics answer that, all on cached features
|
| 96 |
+
with no new training.""", r""]
|
| 97 |
+
|
| 98 |
+
if D:
|
| 99 |
+
L += [r"\subsection{D1 --- can the head separate the two terminals?}",
|
| 100 |
+
r"""$R(z)$ evaluated on every frame whose \texttt{annot.edge\_to} is 4 (rewarded: pan on grate,
|
| 101 |
+
tomato in bowl) versus 6 (failure: pan on the stove, tomato in bowl), and on the last 30 frames of each such
|
| 102 |
+
episode. 0.5 is chance. \texttt{scripts/real/decisive\_reward.py} $\to$
|
| 103 |
+
\texttt{status/real/DECISIVE\_REWARD.json}.""",
|
| 104 |
+
r"\begin{table}[htbp]\centering\small",
|
| 105 |
+
r"\caption{\textbf{D1/D2 --- what each reward head can actually discriminate.} AUC of $R(z)$; "
|
| 106 |
+
r"0.5 is chance. \emph{4 vs 6} is the decisive column: those two states differ only in where the "
|
| 107 |
+
r"pan ends. \emph{4 vs 3} asks whether the head can tell the finished state from the mid-task "
|
| 108 |
+
r"cooking state. \emph{junction} is D2: frames in the first 30 after leaving state 2, rewarded "
|
| 109 |
+
r"continuation (route 3) versus failure continuation (route 4) --- physically the same situation, "
|
| 110 |
+
r"so a provenance head should sit near chance or, worse, be confidently wrong."
|
| 111 |
+
r"}\label{tab:decisive}",
|
| 112 |
+
r"\begin{tabular}{lrrrrr}\toprule",
|
| 113 |
+
r"head & 4 vs 6 (all) & 4 vs 6 (tail 30) & 4 vs 3 (tail) & 4 vs 5 (tail) & junction r3 vs r4 \\\midrule"]
|
| 114 |
+
for k, h in D["heads"].items():
|
| 115 |
+
a = h["auc"]
|
| 116 |
+
L.append(f"{esc(k)} & {f(a['D1_term4_vs_term6_allframes'],4)} & {f(a['D1_term4_vs_term6_tail'],4)} & "
|
| 117 |
+
f"{f(a['D1_term4_vs_term3_tail'],4)} & {f(a['D1_term4_vs_term5_tail'],4)} & "
|
| 118 |
+
f"{f(a['D2_junction_leave_r3_vs_r4'],4)} \\\\")
|
| 119 |
+
L += [r"\bottomrule\end{tabular}\end{table}", r""]
|
| 120 |
+
else:
|
| 121 |
+
L += [r"\noindent\emph{(D1/D2 not yet landed: status/real/DECISIVE\_REWARD.json missing; LSF rr\_decisive.)}", r""]
|
| 122 |
+
|
| 123 |
+
if S3:
|
| 124 |
+
L += [r"\subsection{D3 --- the demonstration number}",
|
| 125 |
+
r"""Standing at a junction state \emph{as it is actually visited on the failure route} (the last 40
|
| 126 |
+
frames before route-4 episodes leave state 2), 128 candidate action chunks are scored: 64 drawn from the
|
| 127 |
+
rewarded continuation (route 3, segment $2\to3$) and 64 from the failure continuation (route 4, segment
|
| 128 |
+
$2\to6$). Logged chunks are used rather than proposer samples precisely so that the label ``this candidate
|
| 129 |
+
continues toward the goal'' is ground truth. The read-out is the flagship one --- \texttt{d1}, $\beta=0.99$,
|
| 130 |
+
16 particles, probability, $T=25$, argmax over 128 --- identical to
|
| 131 |
+
\texttt{status/real/openloop\_*/scorer\_openloop.json}. Chance is 0.5 for both columns.
|
| 132 |
+
\texttt{scripts/real/stitch\_feasibility.py} $\to$ \texttt{status/real/STITCH\_FEASIBILITY.json}.""",
|
| 133 |
+
r"\begin{table}[htbp]\centering\small",
|
| 134 |
+
r"\caption{\textbf{D3 --- does $Q$ separate the rewarded continuation from the failure "
|
| 135 |
+
r"continuation at the shared junction state?} \emph{AUC} pooled over all anchors and averaged "
|
| 136 |
+
r"per anchor; \emph{top-1} is how often the argmax of 128 is a rewarded-continuation chunk "
|
| 137 |
+
r"(chance $0.5$); \emph{spread} is the mean max$-$min of the 128 scores, i.e.\ how much dynamic "
|
| 138 |
+
r"range the ranking has at all.}\label{tab:d3}",
|
| 139 |
+
r"\begin{tabular}{lrrrrr}\toprule",
|
| 140 |
+
r"head & AUC (pooled) & AUC (per anchor) & frac anchors $>0.5$ & top-1 rewarded & score spread \\\midrule"]
|
| 141 |
+
for k, h in S3["heads"].items():
|
| 142 |
+
L.append(f"{esc(k)} & {f(h['auc_pooled'],4)} & {f(h['auc_per_anchor_mean'],4)} & "
|
| 143 |
+
f"{f(h['auc_per_anchor_frac_above_0.5'],3)} & {f(h['top1_rewarded_frac'],3)} & "
|
| 144 |
+
f"{h['score_spread_mean']:.2e} \\\\")
|
| 145 |
+
L += [r"\bottomrule\end{tabular}\end{table}", r""]
|
| 146 |
+
else:
|
| 147 |
+
L += [r"\noindent\emph{(D3 not yet landed: status/real/STITCH\_FEASIBILITY.json missing; LSF rr\_d3stitch.)}", r""]
|
| 148 |
+
|
| 149 |
+
if V5:
|
| 150 |
+
L += [r"\subsection{A correction: the reward RISE trains on is not the reward the dataset defines}",
|
| 151 |
+
r"""The robomimic conversion labels an episode \emph{expert} when its final state is in $\{3,4\}$
|
| 152 |
+
(\texttt{scripts/real/convert\_cooking\_hdf5.py:100}) and writes $+1$ on every frame of those episodes
|
| 153 |
+
(\texttt{:150}), also storing that flag as the hdf5 attribute \texttt{success} (\texttt{:158}). The dataset
|
| 154 |
+
card is narrower: \textbf{``Reward state IDs: [4]''}, with
|
| 155 |
+
\texttt{reward = float(goal\_reached == 1 and reached\_state\_id in reward\_states)}, and its state table
|
| 156 |
+
marks state 3 as \emph{``[Cooking state] Pan on stove, Tomato in the pan --- Terminal in task: False ---
|
| 157 |
+
Rewarded arrival: False''}. State 3 is therefore not a second success terminal; it is the mid-task state
|
| 158 |
+
with the tomato still in the pan, where routes 1 and 2 simply stop.""",
|
| 159 |
+
r"\begin{center}\small\begin{tabular}{rrrcc}\toprule",
|
| 160 |
+
r"terminal & episodes & frames & RISE calls it expert & dataset rewards it \\\midrule"]
|
| 161 |
+
for t, v in sorted(V5["by_terminal_state"].items()):
|
| 162 |
+
L.append(f"{t} & {v['n_eps']} & {v['frames']} & {'yes' if v['rise_expert'] else 'no'} & "
|
| 163 |
+
f"{'yes' if v['dataset_rewarded'] else 'no'} \\\\")
|
| 164 |
+
L += [r"\bottomrule\end{tabular}\end{center}",
|
| 165 |
+
r"\noindent So RISE's critic is trained with $+1$ on every frame of "
|
| 166 |
+
+ str(V5["n_episodes_positive"]) + r" of 248 episodes (" + str(V5["pos_frames"])
|
| 167 |
+
+ r" frames, " + f"{100*V5['frac_frames']:.1f}" + r"\% of the corpus), and "
|
| 168 |
+
+ str(V5["episodes_rise_says_expert_but_dataset_does_not_reward"])
|
| 169 |
+
+ r" of those episodes never put the tomato in the bowl. The successor's own \texttt{v0} uses the "
|
| 170 |
+
r"dataset rule instead (" + str(V5["n_episodes_positive_dataset_rule"])
|
| 171 |
+
+ r" episodes). No successor cell had ever been trained on RISE's labels, so they were added as "
|
| 172 |
+
r"\texttt{v5} (\texttt{scripts/real/make\_v5\_reward.py} $\to$ "
|
| 173 |
+
r"\texttt{cache/real\_cooking\_v5/reward\_v5\_riseprov.f32.npy}, counts in "
|
| 174 |
+
r"\texttt{status/real/V5\_REWARD.json}).", r""]
|
| 175 |
+
|
| 176 |
+
if PR:
|
| 177 |
+
key = next((k for k in PR if PR[k].get("n_decisions", 0) > 100), None)
|
| 178 |
+
if key:
|
| 179 |
+
v = PR[key]
|
| 180 |
+
L += [r"\subsection{The open-loop screen re-cut by episode provenance}",
|
| 181 |
+
r"A natural defence of the open-loop numbers is that only "
|
| 182 |
+
+ str(v["n_rewarded_episodes"]) + r" of the " + str(len(v["episodes"]))
|
| 183 |
+
+ r" held-out episodes reach the goal, so on the rest ``agreeing with the logged chunk'' is "
|
| 184 |
+
r"agreeing with a failure. That defence is testable and it fails: every learned scorer "
|
| 185 |
+
r"ranks \emph{below} chance on the rewarded episodes too. "
|
| 186 |
+
r"\texttt{scripts/real/openloop\_by\_provenance.py} $\to$ "
|
| 187 |
+
r"\texttt{status/real/OPENLOOP\_BY\_PROVENANCE.json}, cell \texttt{"
|
| 188 |
+
+ esc(v.get("tag", key)) + r"}, " + str(v["n_decisions"])
|
| 189 |
+
+ r" paired decisions, nothing re-scored.",
|
| 190 |
+
r"\begin{table}[htbp]\centering\small",
|
| 191 |
+
r"\caption{\textbf{Oracle rank percentile split by whether the episode reaches the goal.} "
|
| 192 |
+
r"$1.0$ = the oracle's own pick, $0.0$ = the worst of 128; a plain sample (\texttt{greedy}) "
|
| 193 |
+
r"and the permutation controls sit at $0.5$ by construction. Lower than $0.5$ means the "
|
| 194 |
+
r"scorer systematically prefers candidates the oracle ranks badly."
|
| 195 |
+
r"}\label{tab:provsplit}",
|
| 196 |
+
r"\begin{tabular}{lrrrr}\toprule",
|
| 197 |
+
r"scorer & all & rewarded eps & failure eps & route 3 only \\\midrule"]
|
| 198 |
+
for k, r in v["scorers"].items():
|
| 199 |
+
L.append(f"{esc(k.replace('score_',''))} & {f(r['all']['rank_pct'],4)} & "
|
| 200 |
+
f"{f(r['rewarded_eps']['rank_pct'],4)} & {f(r['failure_eps']['rank_pct'],4)} & "
|
| 201 |
+
f"{f(r.get('route3',{}).get('rank_pct'),4)} \\\\")
|
| 202 |
+
L += [r"\bottomrule\end{tabular}\end{table}", r""]
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
# ----------------------------------------------------------------- the verdict
|
| 206 |
+
L += [r"\subsection{Verdict, and the smallest fix}",
|
| 207 |
+
r"""\textbf{No head passes.} D1 looks perfect for v0/v1 --- AUC $1.000$ separating state 4 from state 6
|
| 208 |
+
--- but D2 shows what that AUC is made of: the \emph{same} head separates the \emph{junction} frames of
|
| 209 |
+
route 3 from those of route 4 with AUC $1.000$ as well, and route 3's junction frames are its \emph{first}
|
| 210 |
+
frames, before the pan has been touched. The shipped head reads $R(z)=+24.4$ there and $-24.8$ on route 4,
|
| 211 |
+
the same $\pm25$ it reads at the terminals (Table~\ref{tab:decisive}, logit means in
|
| 212 |
+
\texttt{status/real/DECISIVE\_REWARD.json}). Sharper still: routes 2 and 3 both contain the physical edge
|
| 213 |
+
$2\to3$, labelled $0$ in one recording and $+1$ in the other, and the head separates those two copies of the
|
| 214 |
+
same transition with AUC $1.000$. The head has learned \emph{which recording a frame belongs to}.
|
| 215 |
+
And D3, which is the demonstration itself, comes out below chance for every head: the top-ranked of 128
|
| 216 |
+
candidates is a rewarded-continuation chunk $3$--$28\%$ of the time (chance $50\%$), and for the shipped
|
| 217 |
+
head the chain from the \emph{top} candidate retrieves a state-6 failure frame ($0\%$ of particles in the
|
| 218 |
+
goal region) while the chain from the \emph{bottom} candidate retrieves a state-4 goal frame ($100\%$).""",
|
| 219 |
+
r"",
|
| 220 |
+
r"""\textbf{Why this is structural, not a training failure.} Only route 3 is rewarded, and route 3 is
|
| 221 |
+
also the only route that \emph{starts} at state 2 (\texttt{cache/real\_cooking\_v5/SEGMENTS.json}: route 3 is
|
| 222 |
+
\texttt{2->3->4}, two segments, no \texttt{0->2} prefix). So within this corpus ``this state is on the way to
|
| 223 |
+
the goal'' and ``this frame was recorded in a route-3 session'' are the same predicate, and a per-frame label
|
| 224 |
+
that is constant over the recording cannot distinguish them. No amount of relabelling inside the existing
|
| 225 |
+
episodes fixes that; v1, v2 and v3 are three different ways of slicing the same 50 recordings.""",
|
| 226 |
+
r"",
|
| 227 |
+
r"""\textbf{The smallest fix}, in increasing cost:
|
| 228 |
+
\begin{enumerate}\itemsep1pt
|
| 229 |
+
\item \textbf{Record route 5.} The dataset card already declares route 5 $=$ \texttt{1->3->4} with a target
|
| 230 |
+
of 50 episodes and none collected. Route 5 and route 1 (\texttt{0->1->3}) share state 1, and route 5
|
| 231 |
+
reaches the goal --- a second junction with a success and a non-success continuation, recorded in the
|
| 232 |
+
\emph{same} session style. Two junctions instead of one also breaks the ``route 3 is special'' cue.
|
| 233 |
+
\item \textbf{Record a failure continuation out of state 3 in a route-3 session} (pour, then leave the pan on
|
| 234 |
+
the stove $=$ state 6). That puts both terminals inside the \emph{same} recording family, which is the
|
| 235 |
+
only thing that makes the reward a function of the scene rather than of the session.
|
| 236 |
+
\item \textbf{Replace the provenance label with a state-based one:} the dataset's own rule
|
| 237 |
+
\texttt{reward = float(goal\_reached == 1 and reached\_state\_id in [4])} is exactly v2 and is already
|
| 238 |
+
state-based --- but it fires on 50 frames in 181{,}530, and the v2 heads measured here are the worst of
|
| 239 |
+
the set (D1 AUC $0.11$--$0.33$). A detector-style label (``pan on grate'' from the scene, applied to
|
| 240 |
+
every frame of every recording) is the version of v2 that would have enough positives to train on.
|
| 241 |
+
\end{enumerate}""", r""]
|
| 242 |
+
|
| 243 |
+
(TEX / "_decisive.tex").write_text("\n".join(L) + "\n")
|
| 244 |
+
print("[tex] wrote _decisive.tex")
|
gen_q_rsm/rsm_rise/pipeline/scripts/real/build_real_report_tables.py
ADDED
|
@@ -0,0 +1,270 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Emit the LaTeX table fragments for docs/tex/real_proposal_report.tex (owner request 2026-09-22, gen_q #263).
|
| 2 |
+
|
| 3 |
+
Every number is read from a file on disk; nothing is typed in by hand except the hold-still baseline, which is
|
| 4 |
+
quoted from logs/lsf/rr_cpu_actnorm.1836483.out (scripts/tmp/action_norms_real.py, validation split).
|
| 5 |
+
|
| 6 |
+
Sources
|
| 7 |
+
pi0.5 : the `EVAL step N:` lines of logs/lsf/rr_openpi_<run>.*.out (same parser as plot_proposal_curves.py)
|
| 8 |
+
robomimic: <policy>/replay_e<E>/replay_eval.json and runs/real/replay/<tag>/replay_eval.json ->
|
| 9 |
+
pooled_episode_mean.{xyz_l2_first_cm,xyz_l2_chunk_cm,...} (rise_replay_eval.py, stride 10, 25 eps)
|
| 10 |
+
open-loop: status/real/openloop_S0Aidql_*/scorer_openloop.json (scorer_openloop.py, fixed harness)
|
| 11 |
+
W&B : status/real/wandb_runs.json (scripts/tmp/wandb_public_and_list.py) + the per-run wandb_id.txt files
|
| 12 |
+
Writes docs/tex/_real_tables.tex and status/real/report_numbers.json.
|
| 13 |
+
"""
|
| 14 |
+
import glob, json, os, re, collections
|
| 15 |
+
|
| 16 |
+
ROOT = "/proj/dmfexp/zwhong/rsm_rise"
|
| 17 |
+
HOLD_FIRST, HOLD_CHUNK, HOLD_STEP = 0.81, 1.53, 0.22 # rr_cpu_actnorm.1836483.out, validation split
|
| 18 |
+
ENT_PROJ = "richardrl/rsm_rise"
|
| 19 |
+
|
| 20 |
+
def tex(s):
|
| 21 |
+
return s.replace("_", r"\_")
|
| 22 |
+
|
| 23 |
+
def path_tex(p):
|
| 24 |
+
"""A long absolute path typeset so it can break after every separator (\path{} never breaks)."""
|
| 25 |
+
return r"\texttt{%s}" % (tex(p).replace("/", r"/\allowbreak ")
|
| 26 |
+
.replace(r"\_", r"\_\allowbreak "))
|
| 27 |
+
|
| 28 |
+
# ----------------------------------------------------------------- pi0.5 EVAL lines
|
| 29 |
+
PAT = re.compile(r"EVAL step (\d+): val: xyz_first=([0-9.]+)cm xyz_chunk=([0-9.]+)cm loss=([0-9.e-]+) "
|
| 30 |
+
r"grip_acc=([0-9.]+), train_eval: xyz_first=([0-9.]+)cm xyz_chunk=([0-9.]+)cm")
|
| 31 |
+
openpi = {}
|
| 32 |
+
for run in ("stock_s0", "stock_s1", "rise_s0", "rise_s1", "riseadv_s0", "riseadv_s1"):
|
| 33 |
+
pts = {}
|
| 34 |
+
for f in glob.glob(f"{ROOT}/logs/lsf/rr_openpi_{run}.*.out"):
|
| 35 |
+
for m in PAT.finditer(open(f, errors="ignore").read()):
|
| 36 |
+
s = int(m.group(1)); s -= s % 500
|
| 37 |
+
pts[s] = tuple(float(x) for x in m.groups()[1:])
|
| 38 |
+
if pts:
|
| 39 |
+
openpi[run] = sorted(pts.items())
|
| 40 |
+
|
| 41 |
+
# Display names + HF mirror file names. Every checkpoint here is trained on rsm_cooking_v5, this
|
| 42 |
+
# project's own FR3 data; "robomimic" is only the framework RISE ships in (the .pth file format), so the
|
| 43 |
+
# register names the checkpoint by ROLE and DATA, not by library (owner, 2026-09-22).
|
| 44 |
+
HF_REPO = "https://huggingface.co/rli14/rsm_cooking_v5_checkpoints"
|
| 45 |
+
DISPLAY = {"S0Aidql_seed0": r"RISE actor (rsm\_real)", "S0Aidql_seed1": r"RISE actor (rsm\_real)",
|
| 46 |
+
"S0B_seed0": r"BC-union (rsm\_real)", "S0B_seed1": r"BC-union (rsm\_real)"}
|
| 47 |
+
PLAIN = {k: v.replace(r"\_", "_") for k, v in DISPLAY.items()} # for rows that pass through tex()
|
| 48 |
+
HF_NAME = {"S0Aidql_seed0": "rise_actor_rsm_real_s0_e3000.pth",
|
| 49 |
+
"S0Aidql_seed1": "rise_actor_rsm_real_s1_e3000.pth",
|
| 50 |
+
"S0B_seed0": "bc_union_rsm_real_s0_e5000.pth",
|
| 51 |
+
"S0B_seed1": None, # second BC-union seed is not in the mirror
|
| 52 |
+
"stock_s1": "pi05_bc_rsm_real_stock_s1_29999/"}
|
| 53 |
+
|
| 54 |
+
# ----------------------------------------------------------------- robomimic replay evals
|
| 55 |
+
def load_replay(p):
|
| 56 |
+
d = json.load(open(p))
|
| 57 |
+
m = d["pooled_episode_mean"]
|
| 58 |
+
return dict(path=p, ckpt=d["ckpt"], stride=d["stride"], n_episodes=d["n_episodes"],
|
| 59 |
+
first=m["xyz_l2_first_cm"], chunk=m["xyz_l2_chunk_cm"],
|
| 60 |
+
first_max=m.get("xyz_l2_first_max_cm"), grip=m.get("grip_bin_acc"))
|
| 61 |
+
|
| 62 |
+
robo = collections.defaultdict(dict) # robo["S0Aidql_seed1"][3000] = {...}
|
| 63 |
+
for p in glob.glob(f"{ROOT}/runs/cooking_v5_expert_suboptimal/policy/*/replay_e*/replay_eval.json"):
|
| 64 |
+
fam = p.split("/policy/")[1].split("/")[0]
|
| 65 |
+
e = int(re.search(r"replay_e(\d+)/", p).group(1))
|
| 66 |
+
robo[fam][e] = load_replay(p)
|
| 67 |
+
for p in glob.glob(f"{ROOT}/runs/real/replay/*/replay_eval.json"):
|
| 68 |
+
tag = p.split("/replay/")[1].split("/")[0] # e.g. S0Aidql_s1_e2500
|
| 69 |
+
m = re.match(r"(S0Aidql|S0B)_s(\d)_e(\d+)$", tag)
|
| 70 |
+
if not m:
|
| 71 |
+
continue
|
| 72 |
+
fam, e = f"{m.group(1)}_seed{m.group(2)}", int(m.group(3))
|
| 73 |
+
robo[fam].setdefault(e, load_replay(p)) # the replay_e<E> copy wins if both exist
|
| 74 |
+
|
| 75 |
+
# ----------------------------------------------------------------- W&B urls
|
| 76 |
+
wb = {} # display name -> url (the surviving run, see below)
|
| 77 |
+
wb_rows = []
|
| 78 |
+
wbjson = f"{ROOT}/status/real/wandb_runs.json"
|
| 79 |
+
wb_meta = {}
|
| 80 |
+
if os.path.exists(wbjson):
|
| 81 |
+
blob = json.load(open(wbjson))
|
| 82 |
+
wb_meta = {k: v for k, v in blob.items() if k != "runs"}
|
| 83 |
+
wb_rows = blob["runs"]
|
| 84 |
+
# a cell that was preempted and resumed leaves several W&B runs under one display name; the one to link is the
|
| 85 |
+
# newest that is not `crashed`/`failed` (that is the run the current job is still writing to). Sorted so the
|
| 86 |
+
# preferred run is assigned LAST and therefore wins the dict slot.
|
| 87 |
+
for r in sorted(wb_rows, key=lambda d: (d["state"] not in ("crashed", "failed"), d["created"])):
|
| 88 |
+
wb[r["name"]] = r["url"]
|
| 89 |
+
def wb_url_for(sub):
|
| 90 |
+
for n, u in wb.items():
|
| 91 |
+
if sub in n:
|
| 92 |
+
return u
|
| 93 |
+
return None
|
| 94 |
+
openpi_ids = {}
|
| 95 |
+
for f in glob.glob(f"{ROOT}/runs/openpi/checkpoints/*/*/wandb_id.txt"):
|
| 96 |
+
openpi_ids[f.split("/")[-2]] = open(f).read().strip()
|
| 97 |
+
|
| 98 |
+
# ----------------------------------------------------------------- the policy / checkpoint table
|
| 99 |
+
def latest_dir(fam):
|
| 100 |
+
"""Absolute path of the models/ dir holding the highest-epoch checkpoint of a robomimic family."""
|
| 101 |
+
best = (None, -1)
|
| 102 |
+
for p in glob.glob(f"{ROOT}/runs/cooking_v5_expert_suboptimal/policy/{fam}/*/*/models/model_epoch_*.pth"):
|
| 103 |
+
e = int(re.search(r"model_epoch_(\d+)\.pth", p).group(1))
|
| 104 |
+
if e > best[1]:
|
| 105 |
+
best = (p, e)
|
| 106 |
+
return best
|
| 107 |
+
|
| 108 |
+
POLICIES = [] # (role, policy, recipe, seed, steps, abspath, wandb url)
|
| 109 |
+
for run, cfg in (("stock_s0", "pi05_cooking_stock"), ("stock_s1", "pi05_cooking_stock"),
|
| 110 |
+
("rise_s0", "pi05_cooking_rise"), ("rise_s1", "pi05_cooking_rise"),
|
| 111 |
+
("riseadv_s0", "pi05_cooking_riseadv")):
|
| 112 |
+
d = f"{ROOT}/runs/openpi/checkpoints/{cfg}/{run}"
|
| 113 |
+
steps = sorted(int(x) for x in os.listdir(d) if x.isdigit()) if os.path.isdir(d) else []
|
| 114 |
+
last = steps[-1] if steps else None
|
| 115 |
+
rid = openpi_ids.get(run)
|
| 116 |
+
url = f"https://wandb.ai/{ENT_PROJ}/runs/{rid}" if rid else None
|
| 117 |
+
role = "BC" if run.startswith("stock") else "RISE actor"
|
| 118 |
+
POLICIES.append((role, "pi0.5 " + run.rsplit("_s", 1)[0], cfg, run[-1], f"{last} steps",
|
| 119 |
+
f"{d}/{last}", url, HF_NAME.get(run)))
|
| 120 |
+
for fam, role in (("S0B_seed0", "BC"), ("S0B_seed1", "BC"),
|
| 121 |
+
("S0Aidql_seed0", "RISE actor"), ("S0Aidql_seed1", "RISE actor")):
|
| 122 |
+
p, e = latest_dir(fam)
|
| 123 |
+
POLICIES.append((role, DISPLAY[fam], "cooking_v5_expert_suboptimal", fam[-1],
|
| 124 |
+
f"epoch {e}", p, wb_url_for(f"{fam}"), HF_NAME.get(fam)))
|
| 125 |
+
|
| 126 |
+
L = []
|
| 127 |
+
A = L.append
|
| 128 |
+
A(r"% generated by scripts/real/build_real_report_tables.py -- do not edit by hand")
|
| 129 |
+
A(r"\newcommand{\holdfirst}{%.2f}" % HOLD_FIRST)
|
| 130 |
+
A(r"\newcommand{\holdchunk}{%.2f}" % HOLD_CHUNK)
|
| 131 |
+
A(r"\newcommand{\holdstep}{%.2f}" % HOLD_STEP)
|
| 132 |
+
|
| 133 |
+
A(r"\begin{table}[htbp]\centering\small")
|
| 134 |
+
A(r"\caption{Real-world (\texttt{rsm\_cooking\_v5}) proposal policies: role, recipe, seed, training length, "
|
| 135 |
+
r"absolute checkpoint path, W\&B run and the file name in the Hugging Face mirror. Every row is fine-tuned "
|
| 136 |
+
r"on \texttt{rsm\_cooking\_v5}, this project's own FR3 cooking data (\emph{robomimic}, where it appears "
|
| 137 |
+
r"elsewhere, is the training framework RISE ships in --- a file format, not a data source). \emph{BC} rows are plain "
|
| 138 |
+
r"behaviour cloning; \emph{RISE actor} rows carry the RISE/IDQL actor recipe and ship their co-trained IQL "
|
| 139 |
+
r"critic in the same file. Epochs are the latest on disk at the time of writing. The \emph{HF mirror} column "
|
| 140 |
+
r"gives the file name in the public Hugging Face repo (Sec.~\ref{sec:hf}); \emph{--} means that seed was not "
|
| 141 |
+
r"mirrored.}")
|
| 142 |
+
A(r"\label{tab:ckpt}")
|
| 143 |
+
A(r"\begin{tabular}{@{}lllp{13mm}p{46mm}lp{30mm}@{}}\toprule")
|
| 144 |
+
A(r"role & policy & seed & length & checkpoint (absolute) & W\&B & HF mirror name \\ \midrule")
|
| 145 |
+
for role, pol, recipe, seed, steps, p, url, hfn in POLICIES:
|
| 146 |
+
link = r"\href{%s}{run}" % url if url else "--"
|
| 147 |
+
hf = (r"{\tiny \texttt{%s}}" % tex(hfn)) if hfn else "--"
|
| 148 |
+
A(r"%s & %s & %s & %s & {\tiny %s} & %s & %s \\[2pt]"
|
| 149 |
+
% (role, pol, seed, tex(steps), path_tex(p or "--"), link, hf))
|
| 150 |
+
A(r"\bottomrule\end{tabular}\end{table}")
|
| 151 |
+
|
| 152 |
+
# ----------------------------------------------------------------- the fit table (ratios to hold-still)
|
| 153 |
+
A(r"\begin{table}[htbp]\centering\small")
|
| 154 |
+
A(r"\caption{Held-out fit on the 25 validation episodes, quoted as a ratio to the hold-still predictor "
|
| 155 |
+
r"(copy the current end-effector xyz: \holdfirst~cm first action, \holdchunk~cm 8-step chunk mean; per-step "
|
| 156 |
+
r"motion \holdstep~cm). Ratio $>1$ means better than hold-still. pi0.5 rows are the run's own "
|
| 157 |
+
r"\texttt{EVAL step} lines at the last step; RISE-stack rows are "
|
| 158 |
+
r"\texttt{replay\_eval.json:pooled\_episode\_mean} (stride 10, 25 episodes).}")
|
| 159 |
+
A(r"\label{tab:fit}")
|
| 160 |
+
A(r"\begin{tabular}{@{}llrrrrp{38mm}@{}}\toprule")
|
| 161 |
+
A(r"policy & at & first (cm) & chunk (cm) & first ratio & chunk ratio & source \\ \midrule")
|
| 162 |
+
A(r"hold-still & -- & %.2f & %.2f & 1.00 & 1.00 & \texttt{action\_norms\_real.py} \\ \midrule" % (HOLD_FIRST, HOLD_CHUNK))
|
| 163 |
+
fitrows = []
|
| 164 |
+
for run, pts in sorted(openpi.items()):
|
| 165 |
+
s, v = pts[-1]
|
| 166 |
+
fitrows.append((f"pi0.5 {run}", f"{s} steps", v[0], v[1], f"logs/lsf/rr_openpi_{run}.*.out"))
|
| 167 |
+
for fam in ("S0Aidql_seed0", "S0Aidql_seed1", "S0B_seed0", "S0B_seed1"):
|
| 168 |
+
if not robo[fam]:
|
| 169 |
+
continue
|
| 170 |
+
e = max(robo[fam])
|
| 171 |
+
r = robo[fam][e]
|
| 172 |
+
fitrows.append((f"{PLAIN[fam]} s{fam[-1]}", f"epoch {e}", r["first"], r["chunk"],
|
| 173 |
+
r["path"].replace(ROOT + "/", "")))
|
| 174 |
+
for nm, at, f0, c0, src in fitrows:
|
| 175 |
+
A(r"%s & %s & %.2f & %.2f & %.2f$\times$ & %.2f$\times$ & {\tiny %s} \\"
|
| 176 |
+
% (tex(nm), tex(at), f0, c0, HOLD_FIRST / f0, HOLD_CHUNK / c0, path_tex(src)))
|
| 177 |
+
A(r"\bottomrule\end{tabular}\end{table}")
|
| 178 |
+
|
| 179 |
+
# ----------------------------------------------------------------- per-epoch RISE-stack table
|
| 180 |
+
A(r"\begin{table}[htbp]\centering\small")
|
| 181 |
+
A(r"\caption{Per-epoch held-out fit of the RISE-stack actors (\texttt{replay\_eval.json}, stride 10, 25 "
|
| 182 |
+
r"validation episodes). Empty cells have no replay eval on disk.}")
|
| 183 |
+
A(r"\label{tab:perepoch}")
|
| 184 |
+
eps = sorted({e for fam in robo for e in robo[fam] if e >= 500})
|
| 185 |
+
A(r"\begin{tabular}{@{}l" + "r" * len(eps) + r"@{}}\toprule")
|
| 186 |
+
A(r"policy (first / chunk cm) & " + " & ".join(str(e) for e in eps) + r" \\ \midrule")
|
| 187 |
+
for fam in ("S0Aidql_seed0", "S0Aidql_seed1", "S0B_seed0", "S0B_seed1"):
|
| 188 |
+
cells = []
|
| 189 |
+
for e in eps:
|
| 190 |
+
r = robo[fam].get(e)
|
| 191 |
+
cells.append(r"\tiny %.2f/%.2f" % (r["first"], r["chunk"]) if r else "--")
|
| 192 |
+
A(tex(f"{PLAIN[fam]} s{fam[-1]}") + " & " + " & ".join(cells) + r" \\")
|
| 193 |
+
A(r"\bottomrule\end{tabular}\end{table}")
|
| 194 |
+
|
| 195 |
+
# ----------------------------------------------------------------- open-loop scorer comparison
|
| 196 |
+
ol = []
|
| 197 |
+
for d in sorted(glob.glob(f"{ROOT}/status/real/openloop_S0Aidql_*")):
|
| 198 |
+
p = f"{d}/scorer_openloop.json"
|
| 199 |
+
if os.path.exists(p):
|
| 200 |
+
ol.append(json.load(open(p)))
|
| 201 |
+
A(r"\begin{table}[htbp]\centering\small")
|
| 202 |
+
if ol:
|
| 203 |
+
A(r"\caption{Open-loop selection on the \texttt{S0Aidql} proposers' 128 candidates (fixed harness, "
|
| 204 |
+
r"\texttt{scorer\_openloop.py}; stride 25, 25 episodes). \emph{greedy} is the proposer's own first "
|
| 205 |
+
r"sample; \emph{permuted} rows are the score-shuffling controls. Lower is better.}")
|
| 206 |
+
A(r"\label{tab:openloop}")
|
| 207 |
+
A(r"\begin{tabular}{@{}llrrrr@{}}\toprule")
|
| 208 |
+
A(r"cell & scorer & first (cm) & chunk (cm) & $\Delta$ vs greedy & win rate \\ \midrule")
|
| 209 |
+
for d in ol:
|
| 210 |
+
first = True
|
| 211 |
+
for k in ("greedy", "idql", "rsm", "permuted:idql", "permuted:rsm", "random"):
|
| 212 |
+
s = d["scorers"].get(k)
|
| 213 |
+
if not s:
|
| 214 |
+
continue
|
| 215 |
+
A(r"%s & %s & %.3f & %.3f & %+.3f & %.3f \\"
|
| 216 |
+
% (tex(d["tag"]) if first else "", tex(k), s["first_mean_cm"], s["chunk_mean_cm"],
|
| 217 |
+
s["delta_vs_greedy_cm"], s["win_rate_vs_greedy"]))
|
| 218 |
+
first = False
|
| 219 |
+
A(r"\midrule")
|
| 220 |
+
A(r"\bottomrule\end{tabular}")
|
| 221 |
+
else:
|
| 222 |
+
A(r"\caption{Open-loop selection comparison: pending.}\label{tab:openloop}")
|
| 223 |
+
A(r"\begin{tabular}{@{}l@{}}\toprule pending \\ \bottomrule\end{tabular}")
|
| 224 |
+
A(r"\end{table}")
|
| 225 |
+
|
| 226 |
+
|
| 227 |
+
# ----------------------------------------------------------------- the W&B section
|
| 228 |
+
W = []
|
| 229 |
+
if wb_meta:
|
| 230 |
+
W.append(r"The project is \href{%s}{\texttt{%s}}." % (wb_meta["project_url"], tex(wb_meta["project"])))
|
| 231 |
+
ab, aa = wb_meta["access_before"], wb_meta["access_after"]
|
| 232 |
+
W.append(r"The project's \texttt{access} field read back \texttt{%s} \emph{before} this run and \texttt{%s} "
|
| 233 |
+
r"\emph{after}. \texttt{USER\_READ} is W\&B's \emph{public: anyone with the link can view}, so the "
|
| 234 |
+
r"project %s. The reader/mutation script is \texttt{scripts/tmp/wandb\_public\_and\_list.py} "
|
| 235 |
+
r"(run on a CPU node; it issues \texttt{upsertModel(access: USER\_READ)} only when the project is not "
|
| 236 |
+
r"already public, and it was, so no mutation was sent)."
|
| 237 |
+
% (tex(ab), tex(aa),
|
| 238 |
+
r"was \textbf{already public} and needed no change" if ab == "USER_READ"
|
| 239 |
+
else r"was made public by this run"))
|
| 240 |
+
if wb_meta.get("upsert_error"):
|
| 241 |
+
W.append(r"\textbf{The mutation was refused.} The exact API error was:")
|
| 242 |
+
W.append(r"\begin{quote}\ttfamily\small %s \end{quote}" % tex(wb_meta["upsert_error"][:600]))
|
| 243 |
+
W.append(r"The owner can flip it by hand in the project settings "
|
| 244 |
+
r"(\emph{Settings} $\to$ \emph{Privacy} $\to$ \emph{Public}).")
|
| 245 |
+
W.append(r"All %d cooking runs and their URLs are listed in \path{status/real/wandb_runs.json}; the "
|
| 246 |
+
r"per-policy links are in Table~\ref{tab:ckpt}." % len(wb_rows))
|
| 247 |
+
if wb:
|
| 248 |
+
W.append(r"\begin{table}[htbp]\centering\small\caption{Every \texttt{cooking} run in the project.}"
|
| 249 |
+
r"\label{tab:wandb}\begin{tabular}{@{}llll@{}}\toprule")
|
| 250 |
+
W.append(r"run & state & created & URL \\ \midrule")
|
| 251 |
+
for r in sorted(wb_rows, key=lambda d: (d["name"], d["created"])):
|
| 252 |
+
W.append(r"{\tiny %s} & %s & %s & {\tiny \href{%s}{%s}} \\"
|
| 253 |
+
% (tex(r["name"]), tex(r["state"]), tex(r["created"]), r["url"],
|
| 254 |
+
tex(r["url"].split("/runs/")[-1])))
|
| 255 |
+
W.append(r"\bottomrule\end{tabular}\end{table}")
|
| 256 |
+
else:
|
| 257 |
+
W.append(r"\textbf{Pending:} \texttt{scripts/tmp/wandb\_public\_and\_list.py} had not written "
|
| 258 |
+
r"\path{status/real/wandb_runs.json} when this PDF was built.")
|
| 259 |
+
open(f"{ROOT}/docs/tex/_real_wandb.tex", "w").write("\n".join(W) + "\n")
|
| 260 |
+
|
| 261 |
+
open(f"{ROOT}/docs/tex/_real_tables.tex", "w").write("\n".join(L) + "\n")
|
| 262 |
+
json.dump(dict(hold=dict(first=HOLD_FIRST, chunk=HOLD_CHUNK, step=HOLD_STEP),
|
| 263 |
+
openpi={k: v[-1] for k, v in openpi.items()},
|
| 264 |
+
robomimic={f: {str(e): r for e, r in v.items()} for f, v in robo.items()},
|
| 265 |
+
policies=[dict(zip(("role", "policy", "recipe", "seed", "length", "ckpt", "wandb"), p)) for p in POLICIES],
|
| 266 |
+
openloop=[d["tag"] for d in ol], wandb=wb_meta),
|
| 267 |
+
open(f"{ROOT}/status/real/report_numbers.json", "w"), indent=1)
|
| 268 |
+
print("wrote docs/tex/_real_tables.tex and status/real/report_numbers.json")
|
| 269 |
+
print("openpi runs:", sorted(openpi)); print("robomimic epochs:", {f: sorted(v) for f, v in robo.items()})
|
| 270 |
+
print("open-loop cells:", [d["tag"] for d in ol]); print("wandb runs indexed:", len(wb))
|
gen_q_rsm/rsm_rise/pipeline/scripts/real/build_reward_study2.py
ADDED
|
@@ -0,0 +1,199 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
"""LaTeX tables + JSON for the FINE-TUNED reward-head study (gen_q #261).
|
| 3 |
+
|
| 4 |
+
Sources, all named in the PDF:
|
| 5 |
+
status/real/GOAL_REWARD.json label counts v0..v3 (make_goal_reward.py)
|
| 6 |
+
status/real/SUCCESS_TAIL.json label counts v4 (make_v4_reward.py)
|
| 7 |
+
runs/real_cooking_v5/rsm/R_M_ft_v*/history.json reward-head calibration at step 110000
|
| 8 |
+
status/real/stitch_multihop_R_M_ft_v*.json stitch control + reward head on rolled-out states
|
| 9 |
+
status/real/openloop_FT_*/scorer_openloop.json+.npz open-loop screen on identical candidates
|
| 10 |
+
Writes docs/tex/_reward_tables2.tex and status/real/REWARD_FT_NUMBERS.json.
|
| 11 |
+
"""
|
| 12 |
+
import json, glob, os
|
| 13 |
+
from pathlib import Path
|
| 14 |
+
import numpy as np
|
| 15 |
+
|
| 16 |
+
ROOT = Path("/proj/dmfexp/zwhong/rsm_rise")
|
| 17 |
+
RUNS = ROOT / "runs/real_cooking_v5/rsm"
|
| 18 |
+
ST = ROOT / "status/real"
|
| 19 |
+
VERS = ["v0", "v1", "v2", "v3"]
|
| 20 |
+
SEEDS = ["", "_s1"]
|
| 21 |
+
LBL = {"v0": "v0 provenance", "v1": "v1 goal transition", "v2": "v2 arrival", "v3": "v3 final segment"}
|
| 22 |
+
RULE = {
|
| 23 |
+
"v0": "+1 on EVERY frame of a successful episode, 0 on every frame of a failed one",
|
| 24 |
+
"v1": "+1 on every frame of the last run heading into state 4 (the whole 3->4 segment: approach, pour, pan return)",
|
| 25 |
+
"v2": "+1 only on the single frame where the operator declares state 4 (the last frame of the episode)",
|
| 26 |
+
"v3": "+1 on the final segment of EVERY episode, successful or not",
|
| 27 |
+
}
|
| 28 |
+
NPY = {"v0": "reward_v0_provenance.f32.npy", "v1": "reward_v1_goaltrans.f32.npy",
|
| 29 |
+
"v2": "reward_v2_arrival.f32.npy", "v3": "reward_v3_finalseg.f32.npy"}
|
| 30 |
+
KEY = {"v0": "v0_provenance_dense", "v1": "v1_goal_transition", "v2": "v2_arrival_only",
|
| 31 |
+
"v3": "v3_final_segment_all_episodes"}
|
| 32 |
+
OUT = {}
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def esc(s):
|
| 36 |
+
return str(s).replace("_", r"\_").replace("%", r"\%").replace("->", r"$\to$")
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
G = json.load(open(ST / "GOAL_REWARD.json")); by = {v["name"]: v for v in G["versions"]}
|
| 40 |
+
T4 = json.load(open(ST / "SUCCESS_TAIL.json"))
|
| 41 |
+
OUT["labels"] = {v: by[KEY[v]] for v in VERS}; OUT["v4_success_tail"] = T4
|
| 42 |
+
L = []
|
| 43 |
+
|
| 44 |
+
# ---------- 1. the reward table: one row per variant, plain words + counts --------------------
|
| 45 |
+
L.append(r"\begin{table}[htbp]\centering\footnotesize")
|
| 46 |
+
L.append(r"\caption{\textbf{The reward rule, in one sentence per variant.} Counts over the whole cache "
|
| 47 |
+
r"(181{,}530 frames / 248 episodes, of which 50 succeed). \texttt{status/real/GOAL\_REWARD.json}; "
|
| 48 |
+
r"v4 in \texttt{status/real/SUCCESS\_TAIL.json}.}\label{tab:rewardrule}")
|
| 49 |
+
L.append(r"\begin{tabular}{p{0.10\linewidth}p{0.52\linewidth}rrr}\toprule")
|
| 50 |
+
L.append(r"variant & which frames are $+1$ & $+1$ frames & \% & eps.\ with a $+1$ \\\midrule")
|
| 51 |
+
for v in VERS:
|
| 52 |
+
d = by[KEY[v]]
|
| 53 |
+
L.append(f"{esc(LBL[v])} & {esc(RULE[v])} & {d['pos_frames']} & {100*d['frac_frames']:.3f} & "
|
| 54 |
+
f"{d['episodes_with_any_positive']}/248 \\\\")
|
| 55 |
+
L.append(r"v4 success tail & $+1$ from the success marker to the end of a successful episode "
|
| 56 |
+
r"--- \emph{identically equal to v2 here}: the marker IS the last frame in all 50 "
|
| 57 |
+
r"(\texttt{SUCCESS\_TAIL.json}, tail $=1$ frame for every episode) & "
|
| 58 |
+
f"{T4['v4']['pos_frames']} & {100*T4['v4']['frac_frames']:.3f} & "
|
| 59 |
+
f"{T4['v4']['episodes_with_any_positive']}/248 \\\\")
|
| 60 |
+
L.append(r"\bottomrule\end{tabular}\end{table}")
|
| 61 |
+
|
| 62 |
+
# ---------- 2. reward-head calibration after the fine-tune ------------------------------------
|
| 63 |
+
cal = {}
|
| 64 |
+
for v in VERS:
|
| 65 |
+
for s in SEEDS:
|
| 66 |
+
p = RUNS / f"R_M_ft_{v}{s}/history.json"
|
| 67 |
+
if p.exists():
|
| 68 |
+
h = json.load(open(p))[-1]
|
| 69 |
+
cal[v + s] = {k: h.get(k) for k in
|
| 70 |
+
("step", "rhead_auc_val", "rhead_auc_train", "rhead_mae_val",
|
| 71 |
+
"rhead_pred_mean_pos_val", "rhead_pred_mean_neg_val",
|
| 72 |
+
"rhead_pos_rate_val", "cfm_val", "nnl1_ratio_val",
|
| 73 |
+
"nnl1_ratio_vs_stay_val", "q_success_auc")}
|
| 74 |
+
cal[v + s]["success_auc"] = h["per_task"]["0"]["success_auc"]
|
| 75 |
+
OUT["calibration"] = cal
|
| 76 |
+
L.append(r"\begin{table}[htbp]\centering\footnotesize")
|
| 77 |
+
L.append(r"\caption{\textbf{Reward head after the 10k-step warm-start fine-tune} (step 110000; "
|
| 78 |
+
r"\texttt{runs/real\_cooking\_v5/rsm/R\_M\_ft\_<v>[\_s1]/history.json}, last entry). "
|
| 79 |
+
r"\emph{AUC} = held-out separation of $+1$ from $0$ frames by $R(z)$; \emph{pos}/\emph{neg} are its "
|
| 80 |
+
r"mean predictions on those two sets; \emph{succ AUC} is the value's separation of successful from "
|
| 81 |
+
r"failed episodes --- 1.000 for v0 only because v0's label IS episode success.}\label{tab:rheadcal}")
|
| 82 |
+
L.append(r"\begin{tabular}{lrrrrrr}\toprule")
|
| 83 |
+
L.append(r"cell & $R$ AUC (val) & $R$ MAE & mean $R$ on $+1$ & mean $R$ on $0$ & succ AUC & CFM val \\\midrule")
|
| 84 |
+
for v in VERS:
|
| 85 |
+
for s in SEEDS:
|
| 86 |
+
k = v + s
|
| 87 |
+
if k not in cal:
|
| 88 |
+
continue
|
| 89 |
+
c = cal[k]
|
| 90 |
+
L.append(f"R\\_M\\_ft\\_{esc(v+s)} & {c['rhead_auc_val']:.4f} & {c['rhead_mae_val']:.4f} & "
|
| 91 |
+
f"{c['rhead_pred_mean_pos_val']:.4f} & {c['rhead_pred_mean_neg_val']:.4f} & "
|
| 92 |
+
f"{c['success_auc']:.4f} & {c['cfm_val']:.4f} \\\\")
|
| 93 |
+
L.append(r"\bottomrule\end{tabular}\end{table}")
|
| 94 |
+
|
| 95 |
+
# ---------- 3. stitch control + reward head on rolled-out states ------------------------------
|
| 96 |
+
sti = {}
|
| 97 |
+
for v in VERS:
|
| 98 |
+
for s in SEEDS:
|
| 99 |
+
p = ST / f"stitch_multihop_R_M_ft_{v}{s}.json"
|
| 100 |
+
if p.exists():
|
| 101 |
+
d = json.load(open(p))
|
| 102 |
+
h1 = d["multihop"][0]
|
| 103 |
+
sti[v + s] = {"ratio_median": d["splice"]["ratio_median"],
|
| 104 |
+
"route1_control_median": d["splice"]["route1_control_median"],
|
| 105 |
+
"jump_median": d["splice"]["jump_median"],
|
| 106 |
+
"own_future": h1["own_future"], "goal_region": h1["goal_region"],
|
| 107 |
+
"random_pool": h1["random_pool"], "rhead_mean": h1["rhead_mean"],
|
| 108 |
+
"rhead_logit_mean": h1["rhead_logit_mean"],
|
| 109 |
+
"rhead_logit_sat_frac": h1["rhead_logit_sat_frac"]}
|
| 110 |
+
OUT["stitch"] = sti
|
| 111 |
+
if sti:
|
| 112 |
+
L.append(r"\begin{table}[htbp]\centering\footnotesize")
|
| 113 |
+
L.append(r"\caption{\textbf{Stitch control and the reward head on rolled-out states} "
|
| 114 |
+
r"(\texttt{scripts/real/stitch\_multihop.py} $\to$ "
|
| 115 |
+
r"\texttt{status/real/stitch\_multihop\_R\_M\_ft\_<v>.json}). \emph{ratio} = splice jump / one-hop "
|
| 116 |
+
r"motion at the cross-trajectory splice; its control is the same measurement inside a single "
|
| 117 |
+
r"route (\texttt{route1\_control\_median}, $\approx 1$ means the splice is not special. "
|
| 118 |
+
r"Columns 4--6 are one 100-frame hop from held-out states: distance to the model's own future, "
|
| 119 |
+
r"to the goal region, and to a random pool. \emph{sat} = fraction of rolled-out states on which "
|
| 120 |
+
r"the reward logit is saturated.}\label{tab:stitchft}")
|
| 121 |
+
L.append(r"\begin{tabular}{lrrrrrrr}\toprule")
|
| 122 |
+
L.append(r"cell & ratio & control & own fut. & goal reg. & rand.\ pool & mean $R$ & sat \\\midrule")
|
| 123 |
+
for k, c in sti.items():
|
| 124 |
+
L.append(f"R\\_M\\_ft\\_{esc(k)} & {c['ratio_median']:.4f} & {c['route1_control_median']:.4f} & "
|
| 125 |
+
f"{c['own_future']:.3f} & {c['goal_region']:.3f} & {c['random_pool']:.3f} & "
|
| 126 |
+
f"{c['rhead_mean']:.2e} & {c['rhead_logit_sat_frac']:.2f} \\\\")
|
| 127 |
+
L.append(r"\bottomrule\end{tabular}\end{table}")
|
| 128 |
+
|
| 129 |
+
# ---------- 4. the open-loop screen (RISE recipe) ---------------------------------------------
|
| 130 |
+
OL = []
|
| 131 |
+
for tag, pretty in [("FT_S0Aidql_s0_e2000_d1_T25", "S0Aidql seed 0 @ epoch 2000"),
|
| 132 |
+
("FT_S0Aidql_s1_e2500_d1_T25", "S0Aidql seed 1 @ epoch 2500")]:
|
| 133 |
+
p = ST / f"openloop_{tag}/scorer_openloop.json"
|
| 134 |
+
if p.exists():
|
| 135 |
+
OL.append((tag, pretty, json.load(open(p)), ST / f"openloop_{tag}/scores.npz"))
|
| 136 |
+
OUT["openloop"] = {}
|
| 137 |
+
ORDER = ["greedy", "idql", "permuted:idql", "rsm", "permuted:rsm"] + \
|
| 138 |
+
[f"rsm@ft_{v}{s}" for v in VERS for s in SEEDS] + ["oracle"]
|
| 139 |
+
PRETTY = {"greedy": "greedy (plain sample)", "idql": "IDQL critic",
|
| 140 |
+
"permuted:idql": "\\quad permuted control", "rsm": "RSM flagship R\\_M (100k, v0 labels)",
|
| 141 |
+
"permuted:rsm": "\\quad permuted control", "oracle": "oracle (best of the 128)"}
|
| 142 |
+
for v in VERS:
|
| 143 |
+
for s in SEEDS:
|
| 144 |
+
PRETTY[f"rsm@ft_{v}{s}"] = f"RSM ft {esc(v+s)}"
|
| 145 |
+
for tag, pretty, d, npz in OL:
|
| 146 |
+
sc = d["scorers"]
|
| 147 |
+
# paired per-decision comparison against the v0 fine-tune control
|
| 148 |
+
paired = {}
|
| 149 |
+
if npz.exists():
|
| 150 |
+
z = np.load(npz, allow_pickle=True)
|
| 151 |
+
err = z["err_first"] # (n_dec, n_cand) cm
|
| 152 |
+
def pick(name):
|
| 153 |
+
key = "score_" + name.replace(":", "_")
|
| 154 |
+
return err[np.arange(err.shape[0]), z[key].argmax(1)] if key in z.files else None
|
| 155 |
+
base = pick("rsm@ft_v0")
|
| 156 |
+
for k in sc:
|
| 157 |
+
if k == "oracle":
|
| 158 |
+
continue
|
| 159 |
+
e = pick(k) if k != "greedy" else err[:, 0]
|
| 160 |
+
if e is None or base is None:
|
| 161 |
+
continue
|
| 162 |
+
dd = e - base
|
| 163 |
+
paired[k] = {"mean_cm": float(e.mean()), "delta_vs_ftv0_cm": float(dd.mean()),
|
| 164 |
+
"se_cm": float(dd.std(ddof=1) / np.sqrt(len(dd))),
|
| 165 |
+
"win_vs_ftv0": float((e < base).mean()), "n": int(len(dd))}
|
| 166 |
+
OUT["openloop"][tag] = {"n_episodes": d["n_episodes"], "n_decisions": d["n_decisions"],
|
| 167 |
+
"valid_for_results": d["valid_for_results"], "scorers": sc, "paired": paired}
|
| 168 |
+
L.append(r"\begin{table}[htbp]\centering\footnotesize")
|
| 169 |
+
L.append(r"\caption{\textbf{Open-loop best-of-128 screen, " + esc(pretty) + r"} "
|
| 170 |
+
r"(\texttt{scripts/real/scorer\_openloop.py}, N=128 diffusion candidates, argmax, prob read-out, "
|
| 171 |
+
r"$T{=}25$, d1, $\beta{=}0.99$; " + f"{d['n_episodes']} held-out episodes, {d['n_decisions']} decisions"
|
| 172 |
+
r"). Every scorer ranks the SAME 128 candidates at the SAME state, so the comparison is paired. "
|
| 173 |
+
r"\emph{first} = cm between the chosen first action and the logged expert action (lower is closer "
|
| 174 |
+
r"to the demonstrator); \emph{$\Delta$ vs ft\_v0} is the paired mean difference $\pm$ s.e.; "
|
| 175 |
+
r"\emph{rank} is the chosen candidate's percentile in the oracle ordering (0.5 = chance). Source: "
|
| 176 |
+
r"\texttt{status/real/openloop\_" + esc(tag) + r"/}.}\label{tab:ol" + tag.replace("_", "") + "}")
|
| 177 |
+
L.append(r"\begin{tabular}{lrrrrr}\toprule")
|
| 178 |
+
L.append(r"scorer & first (cm) & $\Delta$ vs ft\_v0 (cm) & win vs ft\_v0 & win vs greedy & rank pct \\\midrule")
|
| 179 |
+
for k in ORDER:
|
| 180 |
+
if k not in sc:
|
| 181 |
+
continue
|
| 182 |
+
v_ = sc[k]; p_ = paired.get(k)
|
| 183 |
+
dcol = f"{p_['delta_vs_ftv0_cm']:+.4f} $\\pm$ {p_['se_cm']:.4f}" if p_ else "---"
|
| 184 |
+
wcol = f"{p_['win_vs_ftv0']:.3f}" if p_ else "---"
|
| 185 |
+
L.append(f"{PRETTY.get(k, esc(k))} & {v_['first_mean_cm']:.4f} & {dcol} & {wcol} & "
|
| 186 |
+
f"{v_['win_rate_vs_greedy']:.3f} & {v_['oracle_rank_pct_mean']:.4f} \\\\")
|
| 187 |
+
if k == "permuted:rsm":
|
| 188 |
+
L.append(r"\midrule")
|
| 189 |
+
L.append(r"\bottomrule\end{tabular}\end{table}")
|
| 190 |
+
|
| 191 |
+
Path(ROOT / "docs/tex/_reward_tables2.tex").write_text("\n".join(L) + "\n")
|
| 192 |
+
(ST / "REWARD_FT_NUMBERS.json").write_text(json.dumps(OUT, indent=2, default=float))
|
| 193 |
+
print("[rw2] wrote docs/tex/_reward_tables2.tex", len(L), "lines; open-loop tags:", [t for t, _, _, _ in OL])
|
| 194 |
+
for tag in OUT["openloop"]:
|
| 195 |
+
pr = OUT["openloop"][tag]["paired"]
|
| 196 |
+
for k in ORDER:
|
| 197 |
+
if k in pr:
|
| 198 |
+
print(f" {tag} {k:20s} mean={pr[k]['mean_cm']:.4f} d_vs_ftv0={pr[k]['delta_vs_ftv0_cm']:+.4f}"
|
| 199 |
+
f" +-{pr[k]['se_cm']:.4f} win={pr[k]['win_vs_ftv0']:.3f}")
|
gen_q_rsm/rsm_rise/pipeline/scripts/real/build_reward_tables.py
ADDED
|
@@ -0,0 +1,276 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
"""LaTeX fragments for the reward-head study (gen_q #261): docs/tex/_reward_tables.tex.
|
| 3 |
+
|
| 4 |
+
Sources: status/real/GOAL_REWARD.json (label counts, written by scripts/real/make_goal_reward.py),
|
| 5 |
+
runs/real_cooking_v5/rsm/R_RW_v*/{ckpt.pt,history.json} (training + health),
|
| 6 |
+
status/real/stitch_multihop_R_RW_v*.json (chaining control),
|
| 7 |
+
status/real/openloop_RW_*/scorer_openloop.json (open-loop selection on identical candidates).
|
| 8 |
+
"""
|
| 9 |
+
import json, glob
|
| 10 |
+
from pathlib import Path
|
| 11 |
+
import numpy as np
|
| 12 |
+
|
| 13 |
+
ROOT = Path("/proj/dmfexp/zwhong/rsm_rise")
|
| 14 |
+
RUNS = ROOT / "runs/real_cooking_v5/rsm"
|
| 15 |
+
TEX = ROOT / "docs/tex/_reward_tables.tex"
|
| 16 |
+
VERS = [("R_RW_v0", "v0 provenance (dense)", "reward_v0_provenance.f32.npy"),
|
| 17 |
+
("R_RW_v1", "v1 goal transition", "reward_v1_goaltrans.f32.npy"),
|
| 18 |
+
("R_RW_v2", "v2 arrival only", "reward_v2_arrival.f32.npy"),
|
| 19 |
+
("R_RW_v3", "v3 final segment (all eps)", "reward_v3_finalseg.f32.npy")]
|
| 20 |
+
NAME2KEY = {"R_RW_v0": "v0_provenance_dense", "R_RW_v1": "v1_goal_transition",
|
| 21 |
+
"R_RW_v2": "v2_arrival_only", "R_RW_v3": "v3_final_segment_all_episodes"}
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def esc(s):
|
| 25 |
+
return str(s).replace("_", "\\_").replace("%", "\\%")
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
G = json.load(open(ROOT / "status/real/GOAL_REWARD.json"))
|
| 29 |
+
by = {v["name"]: v for v in G["versions"]}
|
| 30 |
+
L = []
|
| 31 |
+
|
| 32 |
+
# ---- label counts -------------------------------------------------------------------------
|
| 33 |
+
L.append(r"\begin{table}[htbp]\centering\small")
|
| 34 |
+
L.append(r"\caption{The four reward labels, counted on \texttt{cache/real\_cooking\_v5} "
|
| 35 |
+
r"(181{,}530 frames, 248 episodes). \emph{train}/\emph{val} use the SAME split every cell "
|
| 36 |
+
r"trains on (\texttt{LiberoRSMData} seed 0, \texttt{val\_frac} 0.1, unstratified: 24 validation "
|
| 37 |
+
r"episodes, of which %d are rewarded). Source: \texttt{status/real/GOAL\_REWARD.json}, produced by "
|
| 38 |
+
r"\texttt{scripts/real/make\_goal\_reward.py}.}" % by["v0_provenance_dense"]["val_episodes_expert"])
|
| 39 |
+
L.append(r"\label{tab:labels}")
|
| 40 |
+
L.append(r"\begin{tabular}{lrrrrrr}\toprule")
|
| 41 |
+
L.append(r"label & pos.\ frames & \% of frames & train & val & eps.\ with a pos. & of which suboptimal \\\midrule")
|
| 42 |
+
for cell, lbl, _ in VERS:
|
| 43 |
+
v = by[NAME2KEY[cell]]
|
| 44 |
+
L.append(f"{esc(lbl)} & {v['pos_frames']} & {100*v['frac_frames']:.3f} & {v['pos_frames_train']} & "
|
| 45 |
+
f"{v['pos_frames_val']} & {v['episodes_with_any_positive']}/248 & "
|
| 46 |
+
f"{v['episodes_with_any_positive_suboptimal']} \\\\")
|
| 47 |
+
L.append(r"\bottomrule\end{tabular}\end{table}")
|
| 48 |
+
|
| 49 |
+
# ---- per-route breakdown -----------------------------------------------------------------
|
| 50 |
+
L.append(r"\begin{table}[htbp]\centering\small")
|
| 51 |
+
L.append(r"\caption{Positive frames by route. Route 3 (\texttt{2->3->4}) is the ONLY route that reaches the "
|
| 52 |
+
r"goal state 4, and it is exactly the set of 50 episodes the cache marks \texttt{ep\_success}. "
|
| 53 |
+
r"Source: \texttt{status/real/GOAL\_REWARD.json}, \texttt{by\_route}.}")
|
| 54 |
+
L.append(r"\label{tab:byroute}")
|
| 55 |
+
routes = sorted(by["v0_provenance_dense"]["by_route"], key=int)
|
| 56 |
+
L.append(r"\begin{tabular}{lll" + "r" * len(VERS) + r"}\toprule")
|
| 57 |
+
L.append(r"route & path & eps & " + " & ".join(esc(l) for _, l, _ in VERS) + r" \\\midrule")
|
| 58 |
+
for rt in routes:
|
| 59 |
+
row = by["v0_provenance_dense"]["by_route"][rt]
|
| 60 |
+
cells = []
|
| 61 |
+
for cell, _, _ in VERS:
|
| 62 |
+
b = by[NAME2KEY[cell]]["by_route"][rt]
|
| 63 |
+
cells.append(f"{b['pos_frames']}")
|
| 64 |
+
L.append(f"{rt} & \\texttt{{{esc(row['path'])}}} & {row['n_eps']} & " + " & ".join(cells) + r" \\")
|
| 65 |
+
L.append(r"\bottomrule\end{tabular}\end{table}")
|
| 66 |
+
|
| 67 |
+
# ---- FINE-TUNED cells (run 2: the owner's correction -- finetune, do not retrain) ---------
|
| 68 |
+
# Every ft cell starts from the flagship successor's own step-100000 checkpoint (R_M for seed 0,
|
| 69 |
+
# R_M_s1 for seed 1), swaps in the new per-frame reward labels and runs 10k further steps at the
|
| 70 |
+
# checkpoint's final learning rate (3e-4; train_rsm.py has no LR schedule). Mechanics and the
|
| 71 |
+
# guard that stops a preempted cell rewinding: scripts/rr_rsm.sh, cells R_M_ft_v*.
|
| 72 |
+
FT = [("R_M_ft_v0", "v0 provenance (control)"), ("R_M_ft_v1", "v1 goal transition"),
|
| 73 |
+
("R_M_ft_v2", "v2 arrival only"), ("R_M_ft_v3", "v3 final segment (all eps)"),
|
| 74 |
+
("R_M_ft_v0_s1", "v0 provenance (control), seed 1"), ("R_M_ft_v1_s1", "v1 goal transition, seed 1"),
|
| 75 |
+
("R_M_ft_v2_s1", "v2 arrival only, seed 1"), ("R_M_ft_v3_s1", "v3 final segment, seed 1")]
|
| 76 |
+
BASE = [("R_M", "flagship, provenance label (not fine-tuned)"), ("R_M_s1", "flagship seed 1 (not fine-tuned)")]
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def read_cell(cell, label, stitch_prefix="stitch_multihop_"):
|
| 80 |
+
d = RUNS / cell
|
| 81 |
+
rec = {"cell": cell, "label": label, "step": None, "hist": {}, "ckpt": None}
|
| 82 |
+
ck = sorted(glob.glob(str(d / "ckpt_s*.pt")), key=lambda f: int(f.split("_s")[-1].split(".")[0]))
|
| 83 |
+
rec["ckpt"] = ck[-1] if ck else (str(d / "ckpt.pt") if (d / "ckpt.pt").exists() else None)
|
| 84 |
+
if (d / "history.json").exists():
|
| 85 |
+
h = json.load(open(d / "history.json"))
|
| 86 |
+
if h:
|
| 87 |
+
rec["hist"] = h[-1]; rec["step"] = h[-1].get("step")
|
| 88 |
+
sm = ROOT / f"status/real/{stitch_prefix}{cell}.json"
|
| 89 |
+
rec["stitch"] = json.load(open(sm)) if sm.exists() else None
|
| 90 |
+
return rec
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def health_table(rows, caption, label):
|
| 94 |
+
out = [r"\begin{table}[htbp]\centering\small", r"\caption{%s}" % caption, r"\label{%s}" % label,
|
| 95 |
+
r"\begin{tabular}{llrrrrrr}\toprule",
|
| 96 |
+
r"cell & label & step & r-auc val & r-mae val & pos rate & nnl1 ratio & vs stay \\\midrule"]
|
| 97 |
+
for r_ in rows:
|
| 98 |
+
h = r_["hist"]
|
| 99 |
+
def g(k, f="{:.4f}"):
|
| 100 |
+
v = h.get(k)
|
| 101 |
+
return f.format(v) if isinstance(v, (int, float)) and np.isfinite(v) else "---"
|
| 102 |
+
out.append(f"\\texttt{{{esc(r_['cell'])}}} & {esc(r_['label'])} & "
|
| 103 |
+
f"{r_['step'] if r_['step'] is not None else '---'} & {g('rhead_auc_val')} & "
|
| 104 |
+
f"{g('rhead_mae_val','{:.2e}')} & {g('rhead_pos_rate_val')} & {g('nnl1_ratio_val')} & "
|
| 105 |
+
f"{g('nnl1_ratio_vs_stay_val')} \\\\")
|
| 106 |
+
out.append(r"\bottomrule\end{tabular}\end{table}")
|
| 107 |
+
return out
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def chain_table(rows, caption, label):
|
| 111 |
+
if not any(r_["stitch"] for r_ in rows):
|
| 112 |
+
return []
|
| 113 |
+
out = [r"\begin{table}[htbp]\centering\small", r"\caption{%s}" % caption, r"\label{%s}" % label,
|
| 114 |
+
r"\begin{tabular}{lrrrrr}\toprule",
|
| 115 |
+
r"cell & splice ratio & rhead @1 hop & @2 & @4 & @8 \\\midrule"]
|
| 116 |
+
for r_ in rows:
|
| 117 |
+
s_ = r_["stitch"]
|
| 118 |
+
if not s_:
|
| 119 |
+
continue
|
| 120 |
+
mh = {int(x["hops"]): x for x in s_["multihop"]}
|
| 121 |
+
def rh(k):
|
| 122 |
+
return f"{mh[k]['rhead_mean']:.2e}" if k in mh else "---"
|
| 123 |
+
out.append(f"\\texttt{{{esc(r_['cell'])}}} & {s_['splice']['ratio_median']:.4f} & {rh(1)} & "
|
| 124 |
+
f"{rh(2)} & {rh(4)} & {rh(8)} \\\\")
|
| 125 |
+
out.append(r"\bottomrule\end{tabular}\end{table}")
|
| 126 |
+
return out
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
ft_rows = [read_cell(c, l) for c, l in FT if (RUNS / c).exists()]
|
| 130 |
+
base_rows = [read_cell(c, l) for c, l in BASE if (RUNS / c).exists()]
|
| 131 |
+
L += health_table(base_rows + ft_rows,
|
| 132 |
+
r"FINE-TUNED reward heads (the run-2 recipe) and the two un-fine-tuned flagship successors "
|
| 133 |
+
r"they start from. Each \texttt{R\_M\_ft\_v*} cell loads \texttt{R\_M}'s (resp.\ "
|
| 134 |
+
r"\texttt{R\_M\_s1}'s) step-100000 checkpoint -- weights, EMA target and optimiser state -- "
|
| 135 |
+
r"swaps in the new per-frame label and runs 10{,}000 further steps at the same learning rate "
|
| 136 |
+
r"($3\times10^{-4}$; \texttt{train\_rsm.py} has no LR schedule, so `the checkpoint's final "
|
| 137 |
+
r"learning rate' and `the training learning rate' are the same number). Seed is matched to the "
|
| 138 |
+
r"source cell, so the validation split is the source's. Numbers read from each cell's own "
|
| 139 |
+
r"\texttt{runs/real\_cooking\_v5/rsm/<cell>/history.json}.", "tab:fthealth")
|
| 140 |
+
L += chain_table(ft_rows,
|
| 141 |
+
r"Chained-hop / stitch control re-measured on every fine-tuned checkpoint "
|
| 142 |
+
r"(\texttt{scripts/real/stitch\_multihop.py}, $\beta_{hi}{=}0.99$, hop $=100$ frames, 256 "
|
| 143 |
+
r"anchors). The reward changed, so this control cannot be inherited from \texttt{R\_M}. "
|
| 144 |
+
r"Sources: \texttt{status/real/stitch\_multihop\_R\_M\_ft\_*.json}.", "tab:ftchain")
|
| 145 |
+
|
| 146 |
+
# ---- FINE-TUNED open-loop: all variants scored on ONE candidate set ------------------------
|
| 147 |
+
olft = sorted(glob.glob(str(ROOT / "status/real/openloop_FT_*/scorer_openloop.json")))
|
| 148 |
+
if olft:
|
| 149 |
+
L.append(r"\begin{table}[htbp]\centering\small")
|
| 150 |
+
L.append(r"\caption{Open-loop best-of-128 selection with the RISE recipe, fine-tuned reward heads. "
|
| 151 |
+
r"Every column in a block ranks the SAME 128 candidate chunks at the SAME state (one proposal "
|
| 152 |
+
r"pass per proposer; \texttt{scorer\_openloop.py --rsm-ckpt-extra}), so the comparison is paired "
|
| 153 |
+
r"decision by decision. Settings are exactly the flagship read-out of "
|
| 154 |
+
r"\texttt{status/real/openloop\_S0Aidql\_*}: $N{=}128$, argmax, prob read-out, $T{=}25$, mode d1 "
|
| 155 |
+
r"depth 1, $\beta{=}0.99$, 16 particles, stride 25, horizon 8, the 25 held-out episodes. "
|
| 156 |
+
r"\texttt{rsm} is the un-fine-tuned flagship \texttt{R\_M}, i.e. the tie-back control. Errors are "
|
| 157 |
+
r"the first-action xyz error in cm (lower is better); $\Delta$ is against greedy; \emph{rank pct} "
|
| 158 |
+
r"is where the pick lands in the oracle's ordering (0.5 = the sampling null). Sources: "
|
| 159 |
+
r"\texttt{status/real/openloop\_FT\_*/scorer\_openloop.json}.}")
|
| 160 |
+
L.append(r"\label{tab:ftopenloop}")
|
| 161 |
+
L.append(r"\begin{tabular}{llrrrr}\toprule")
|
| 162 |
+
L.append(r"proposer & scorer & first (cm) & $\Delta$ (cm) & win vs greedy & rank pct \\\midrule")
|
| 163 |
+
for f in olft:
|
| 164 |
+
d = json.load(open(f))
|
| 165 |
+
order = ["greedy", "idql", "permuted:idql", "rsm", "permuted:rsm"] + \
|
| 166 |
+
sorted(k for k in d["scorers"] if k.startswith("rsm@")) + ["oracle"]
|
| 167 |
+
first = True
|
| 168 |
+
for s_ in order:
|
| 169 |
+
v = d["scorers"].get(s_)
|
| 170 |
+
if not v:
|
| 171 |
+
continue
|
| 172 |
+
L.append(f"{esc(d['tag']) if first else ''} & {esc(s_)} & {v['first_mean_cm']:.4f} & "
|
| 173 |
+
f"{v['delta_vs_greedy_cm']:+.4f} & {v['win_rate_vs_greedy']:.3f} & "
|
| 174 |
+
f"{v['oracle_rank_pct_mean']:.3f} \\\\")
|
| 175 |
+
first = False
|
| 176 |
+
L.append(r"\midrule")
|
| 177 |
+
L[-1] = r"\bottomrule\end{tabular}\end{table}"
|
| 178 |
+
else:
|
| 179 |
+
L.append(r"\emph{The fine-tuned open-loop cells had not landed when this PDF was built; their job ids are "
|
| 180 |
+
r"in Sec.~\ref{sec:rwstatus}.}")
|
| 181 |
+
|
| 182 |
+
# ---- training / health -------------------------------------------------------------------
|
| 183 |
+
rows = []
|
| 184 |
+
for cell, lbl, _ in VERS:
|
| 185 |
+
d = RUNS / cell
|
| 186 |
+
rec = {"cell": cell, "label": lbl, "step": None, "hist": {}, "ckpt": None}
|
| 187 |
+
ck = sorted(glob.glob(str(d / "ckpt_s*.pt")), key=lambda f: int(f.split("_s")[-1].split(".")[0]))
|
| 188 |
+
rec["ckpt"] = ck[-1] if ck else (str(d / "ckpt.pt") if (d / "ckpt.pt").exists() else None)
|
| 189 |
+
if (d / "history.json").exists():
|
| 190 |
+
h = json.load(open(d / "history.json"))
|
| 191 |
+
if h:
|
| 192 |
+
rec["hist"] = h[-1]; rec["step"] = h[-1].get("step")
|
| 193 |
+
sm = ROOT / f"status/real/stitch_multihop_{cell}.json"
|
| 194 |
+
rec["stitch"] = json.load(open(sm)) if sm.exists() else None
|
| 195 |
+
rows.append(rec)
|
| 196 |
+
|
| 197 |
+
L.append(r"\begin{table}[htbp]\centering\small")
|
| 198 |
+
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 "
|
| 199 |
+
r"\texttt{runs/real\_cooking\_v5/rsm/R\_RW\_v*/history.json}. Architecture, cache, optimiser, "
|
| 200 |
+
r"$\beta$ band, chunk, seed and step budget are identical to \texttt{R\_M}; ONLY the per-frame "
|
| 201 |
+
r"reward label differs. \texttt{pos rate} is the fraction of validation anchors the label marks "
|
| 202 |
+
r"positive, and is the denominator the AUC has to be read against.}")
|
| 203 |
+
L.append(r"\label{tab:rwhealth}")
|
| 204 |
+
L.append(r"\begin{tabular}{llrrrrrr}\toprule")
|
| 205 |
+
L.append(r"cell & label & step & r-auc val & r-mae val & pos rate & nnl1 ratio & vs stay \\\midrule")
|
| 206 |
+
for r_ in rows:
|
| 207 |
+
h = r_["hist"]
|
| 208 |
+
def g(k, f="{:.4f}"):
|
| 209 |
+
v = h.get(k)
|
| 210 |
+
return f.format(v) if isinstance(v, (int, float)) and np.isfinite(v) else "---"
|
| 211 |
+
L.append(f"\\texttt{{{esc(r_['cell'])}}} & {esc(r_['label'])} & "
|
| 212 |
+
f"{r_['step'] if r_['step'] is not None else '---'} & {g('rhead_auc_val')} & "
|
| 213 |
+
f"{g('rhead_mae_val','{:.2e}')} & {g('rhead_pos_rate_val')} & {g('nnl1_ratio_val')} & "
|
| 214 |
+
f"{g('nnl1_ratio_vs_stay_val')} \\\\")
|
| 215 |
+
L.append(r"\bottomrule\end{tabular}\end{table}")
|
| 216 |
+
|
| 217 |
+
# ---- chaining control --------------------------------------------------------------------
|
| 218 |
+
if any(r_["stitch"] for r_ in rows):
|
| 219 |
+
L.append(r"\begin{table}[htbp]\centering\small")
|
| 220 |
+
L.append(r"\caption{Chained-hop control per reward version (\texttt{scripts/real/stitch\_multihop.py}, "
|
| 221 |
+
r"$\beta_{hi}{=}0.99$, hop $=100$ frames, 256 anchors). \texttt{rhead} is the mean reward-head "
|
| 222 |
+
r"read-out at the end of the chain: under the provenance label it underflows within a few hops, "
|
| 223 |
+
r"which is what leaves a planner with no gradient. Sources: "
|
| 224 |
+
r"\texttt{status/real/stitch\_multihop\_R\_RW\_v*.json}.}")
|
| 225 |
+
L.append(r"\label{tab:rwchain}")
|
| 226 |
+
L.append(r"\begin{tabular}{lrrrrr}\toprule")
|
| 227 |
+
L.append(r"cell & splice ratio & rhead @1 hop & @2 & @4 & @8 \\\midrule")
|
| 228 |
+
for r_ in rows:
|
| 229 |
+
s = r_["stitch"]
|
| 230 |
+
if not s:
|
| 231 |
+
continue
|
| 232 |
+
mh = {int(x["hops"]): x for x in s["multihop"]}
|
| 233 |
+
def rh(k):
|
| 234 |
+
return f"{mh[k]['rhead_mean']:.2e}" if k in mh else "---"
|
| 235 |
+
L.append(f"\\texttt{{{esc(r_['cell'])}}} & {s['splice']['ratio_median']:.4f} & {rh(1)} & "
|
| 236 |
+
f"{rh(2)} & {rh(4)} & {rh(8)} \\\\")
|
| 237 |
+
L.append(r"\bottomrule\end{tabular}\end{table}")
|
| 238 |
+
|
| 239 |
+
# ---- open loop ---------------------------------------------------------------------------
|
| 240 |
+
ol = sorted(glob.glob(str(ROOT / "status/real/openloop_RW_*/scorer_openloop.json")))
|
| 241 |
+
if ol:
|
| 242 |
+
L.append(r"\begin{table}[htbp]\centering\small")
|
| 243 |
+
L.append(r"\caption{Open-loop selection, one row block per reward version, run with "
|
| 244 |
+
r"\texttt{scripts/real/scorer\_openloop.py} at the SAME proposer checkpoints, seed, stride, "
|
| 245 |
+
r"candidate count and read-out settings as the \texttt{R\_M} cells of the successor report, so "
|
| 246 |
+
r"the versions are compared on identical candidate sets. Errors in cm; $\Delta$ against greedy "
|
| 247 |
+
r"(negative = better). Sources: \texttt{status/real/openloop\_RW\_*/scorer\_openloop.json}.}")
|
| 248 |
+
L.append(r"\label{tab:rwopenloop}")
|
| 249 |
+
L.append(r"\begin{tabular}{llrrrr}\toprule")
|
| 250 |
+
L.append(r"cell & scorer & first (cm) & $\Delta$ (cm) & win vs greedy & rank pct \\\midrule")
|
| 251 |
+
for f in ol:
|
| 252 |
+
d = json.load(open(f))
|
| 253 |
+
first = True
|
| 254 |
+
for s in ["greedy", "rsm", "permuted:rsm", "oracle"]:
|
| 255 |
+
v = d["scorers"].get(s)
|
| 256 |
+
if not v:
|
| 257 |
+
continue
|
| 258 |
+
L.append(f"{esc(d['tag']) if first else ''} & {esc(s)} & {v['first_mean_cm']:.4f} & "
|
| 259 |
+
f"{v['delta_vs_greedy_cm']:+.4f} & {v['win_rate_vs_greedy']:.3f} & "
|
| 260 |
+
f"{v['oracle_rank_pct_mean']:.3f} \\\\")
|
| 261 |
+
first = False
|
| 262 |
+
L.append(r"\midrule")
|
| 263 |
+
L[-1] = r"\bottomrule\end{tabular}\end{table}"
|
| 264 |
+
else:
|
| 265 |
+
L.append(r"\emph{The open-loop selection comparison had not landed when this PDF was built; the cells "
|
| 266 |
+
r"are listed in Sec.~\ref{sec:rwstatus}.}")
|
| 267 |
+
|
| 268 |
+
TEX.write_text("\n".join(L) + "\n")
|
| 269 |
+
print("wrote", TEX)
|
| 270 |
+
json.dump({"rows": [{k: v for k, v in r_.items() if k != "stitch"} for r_ in rows],
|
| 271 |
+
"ft_rows": [{k: v for k, v in r_.items() if k != "stitch"} for r_ in ft_rows],
|
| 272 |
+
"base_rows": [{k: v for k, v in r_.items() if k != "stitch"} for r_ in base_rows],
|
| 273 |
+
"ft_openloop": {Path(f).parent.name: json.load(open(f))["scorers"] for f in olft},
|
| 274 |
+
"labels": G["versions"]},
|
| 275 |
+
open(ROOT / "status/real/REWARD_STUDY_NUMBERS.json", "w"), indent=2, default=str)
|
| 276 |
+
print("wrote", ROOT / "status/real/REWARD_STUDY_NUMBERS.json")
|
gen_q_rsm/rsm_rise/pipeline/scripts/real/build_successor_tables.py
ADDED
|
@@ -0,0 +1,232 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
"""Collect every number the successor report (gen_q #261) quotes, from files on disk, and emit
|
| 3 |
+
LaTeX fragments + a machine-readable status/real/SUCCESSOR_NUMBERS.json.
|
| 4 |
+
|
| 5 |
+
Sources, all named in the PDF next to the number they produce:
|
| 6 |
+
runs/real_cooking_v5/rsm/<cell>/ckpt.pt ["config"], ["step"] -- the knobs and the final step
|
| 7 |
+
runs/real_cooking_v5/rsm/<cell>/history.json -- the training/eval curve the trainer wrote
|
| 8 |
+
status/real/wandb_runs.json -- W&B ids/urls (written by the REAL_REPORT stream)
|
| 9 |
+
status/real_cooking_stitch_arrivals.json -- cross-trajectory stitch control (feature space)
|
| 10 |
+
status/real_cooking_stitch_multihop.json -- chained-hop control on R_M
|
| 11 |
+
status/real_cooking_beta.json -- the beta band derivation
|
| 12 |
+
status/real/GOAL_REWARD.json -- reward-version label counts
|
| 13 |
+
status/real/openloop_S0Aidql_*/scorer_openloop.json + scores.npz -- open-loop selection + ties
|
| 14 |
+
"""
|
| 15 |
+
import json, glob, os, sys
|
| 16 |
+
from pathlib import Path
|
| 17 |
+
import numpy as np
|
| 18 |
+
|
| 19 |
+
ROOT = Path("/proj/dmfexp/zwhong/rsm_rise")
|
| 20 |
+
RUNS = ROOT / "runs/real_cooking_v5/rsm"
|
| 21 |
+
OUT = ROOT / "status/real/SUCCESSOR_NUMBERS.json"
|
| 22 |
+
TEX = ROOT / "docs/tex"
|
| 23 |
+
|
| 24 |
+
ORDER = ["R_M", "R_M_s1", "R_M_notrunc", "R_M_notrunc_s1", "R_M_chunk20",
|
| 25 |
+
"R_M_rterm40", "R_M_rterm40st", "R_M_rterm120",
|
| 26 |
+
"R_L40", "R_L40_notrunc", "R_XL", "R_XL_notrunc",
|
| 27 |
+
"R_RW_v0", "R_RW_v1", "R_RW_v2", "R_RW_v3"]
|
| 28 |
+
KNOB = {
|
| 29 |
+
"R_M": "flagship: width 1024, depth 4, seed 0, beta [0.95,0.99], trunc eps 0.02, chunk 8, dense reward",
|
| 30 |
+
"R_M_s1": "R\\_M at training seed 1 (also reseeds the episode split)",
|
| 31 |
+
"R_M_notrunc": "R\\_M with --beta-trunc-eps 0.99: the per-anchor beta cap never binds (pre-fix behaviour)",
|
| 32 |
+
"R_M_notrunc_s1": "R\\_M\\_notrunc at seed 1",
|
| 33 |
+
"R_M_chunk20": "R\\_M with --chunk 20 (0.40\\,s of motion at 50\\,Hz instead of 0.16\\,s)",
|
| 34 |
+
"R_M_rterm40": "reward-mode terminal, k=40 frames (0.8\\,s, 2000 positives)",
|
| 35 |
+
"R_M_rterm40st": "rterm40 with --stratify-success 1 (different val split; new baseline, not a drop-in)",
|
| 36 |
+
"R_M_rterm120": "reward-mode terminal, k=120 frames (2.4\\,s, 6000 positives)",
|
| 37 |
+
"R_L40": "width 1536, R\\_M otherwise",
|
| 38 |
+
"R_L40_notrunc": "width 1536, cap disabled",
|
| 39 |
+
"R_XL": "width 2048, R\\_M otherwise",
|
| 40 |
+
"R_XL_notrunc": "width 2048, cap disabled",
|
| 41 |
+
"R_RW_v0": "reward study v0: provenance label supplied as an array (must reproduce R\\_M)",
|
| 42 |
+
"R_RW_v1": "reward study v1: goal-transition label (last contiguous edge\\_to==4 run)",
|
| 43 |
+
"R_RW_v2": "reward study v2: arrival frames only (50 positives)",
|
| 44 |
+
"R_RW_v3": "reward study v3: final segment of EVERY episode (provenance-free)",
|
| 45 |
+
}
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def esc(s):
|
| 49 |
+
return str(s).replace("_", "\\_").replace("%", "\\%")
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
wb = {}
|
| 53 |
+
p = ROOT / "status/real/wandb_runs.json"
|
| 54 |
+
if p.exists():
|
| 55 |
+
for r in json.load(open(p))["runs"]:
|
| 56 |
+
wb[r["name"]] = r
|
| 57 |
+
|
| 58 |
+
cells = []
|
| 59 |
+
for name in ORDER:
|
| 60 |
+
d = RUNS / name
|
| 61 |
+
if not (d / "history.json").exists() and not (d / "ckpt.pt").exists():
|
| 62 |
+
continue
|
| 63 |
+
rec = {"cell": name, "dir": str(d), "knob": KNOB.get(name, "")}
|
| 64 |
+
try:
|
| 65 |
+
import torch
|
| 66 |
+
c = torch.load(d / "ckpt.pt", map_location="cpu", weights_only=False)
|
| 67 |
+
rec["step"] = int(c["step"]); rec["config"] = c["config"]
|
| 68 |
+
except Exception as e:
|
| 69 |
+
rec["step"] = None; rec["config"] = {}; rec["ckpt_error"] = str(e)
|
| 70 |
+
ck = sorted(glob.glob(str(d / "ckpt_s*.pt")),
|
| 71 |
+
key=lambda f: int(f.split("_s")[-1].split(".")[0]))
|
| 72 |
+
rec["ckpt_final"] = ck[-1] if ck else str(d / "ckpt.pt")
|
| 73 |
+
rec["ckpt_all"] = ck
|
| 74 |
+
h = []
|
| 75 |
+
if (d / "history.json").exists():
|
| 76 |
+
h = json.load(open(d / "history.json"))
|
| 77 |
+
rec["n_evals"] = len(h)
|
| 78 |
+
rec["history_last"] = h[-1] if h else {}
|
| 79 |
+
rec["curve"] = [{k: e.get(k) for k in
|
| 80 |
+
["step", "cfm_val", "reward_auc", "rhead_auc_val", "rhead_mae_val",
|
| 81 |
+
"q_action_winrate", "nnl1_ratio_val", "nnl1_ratio_vs_stay_val",
|
| 82 |
+
"minmse_val", "q_mean"]} for e in h]
|
| 83 |
+
r = wb.get(f"real_cooking_v5/rsm/{name}")
|
| 84 |
+
rec["wandb"] = {"id": r["id"], "url": r["url"], "state": r["state"]} if r else None
|
| 85 |
+
cells.append(rec)
|
| 86 |
+
|
| 87 |
+
# ---- open-loop selection cells ------------------------------------------------------------
|
| 88 |
+
ol = []
|
| 89 |
+
# report A quotes ONLY the flagship S0Aidql re-runs (the harness-fixed cells of #263 comment 5769487243).
|
| 90 |
+
# openloop_FT_* belongs to the reward-head study (report B) and openloop_SMOKE_* is a 1-episode patch test.
|
| 91 |
+
for f in sorted(glob.glob(str(ROOT / "status/real/openloop_S0Aidql_*/scorer_openloop.json"))):
|
| 92 |
+
d = json.load(open(f))
|
| 93 |
+
rec = {k: d[k] for k in ("tag", "policy", "rsm_ckpt", "rsm_hop_ckpt", "rsm_mode", "rsm_depth",
|
| 94 |
+
"rsm_beta", "rsm_score_kind", "rsm_temperature", "n_cand", "stride",
|
| 95 |
+
"n_episodes", "n_decisions", "candidate_spread_xyz_cm",
|
| 96 |
+
"valid_for_results") if k in d}
|
| 97 |
+
rec["file"] = f
|
| 98 |
+
rec["scorers"] = {k: {kk: vv for kk, vv in v.items()} for k, v in d["scorers"].items()}
|
| 99 |
+
sp = Path(f).with_name("scores.npz")
|
| 100 |
+
if sp.exists():
|
| 101 |
+
z = np.load(sp)
|
| 102 |
+
for key, lbl in (("score_rsm", "rsm"), ("score_idql", "idql")):
|
| 103 |
+
if key not in z.files:
|
| 104 |
+
continue
|
| 105 |
+
s = z[key]
|
| 106 |
+
# TIE COUNT of the read-out: how often the argmax is not unique, and how much of the
|
| 107 |
+
# 128-candidate array collapses to one value (float32 equality on the ranking array).
|
| 108 |
+
mx = s.max(1, keepdims=True)
|
| 109 |
+
n_at_max = (s == mx).sum(1)
|
| 110 |
+
uniq = np.array([len(np.unique(row)) for row in s])
|
| 111 |
+
rec.setdefault("ties", {})[lbl] = {
|
| 112 |
+
"decisions": int(s.shape[0]), "n_cand": int(s.shape[1]),
|
| 113 |
+
"frac_decisions_with_tied_argmax": float((n_at_max > 1).mean()),
|
| 114 |
+
"mean_n_at_max": float(n_at_max.mean()),
|
| 115 |
+
"max_n_at_max": int(n_at_max.max()),
|
| 116 |
+
"mean_unique_scores": float(uniq.mean()),
|
| 117 |
+
"frac_decisions_all_identical": float((uniq == 1).mean()),
|
| 118 |
+
"score_range_mean": float((s.max(1) - s.min(1)).mean()),
|
| 119 |
+
}
|
| 120 |
+
ol.append(rec)
|
| 121 |
+
|
| 122 |
+
rep = {
|
| 123 |
+
"generated_by": "scripts/real/build_successor_tables.py",
|
| 124 |
+
"cache": "cache/real_cooking_v5",
|
| 125 |
+
"cells": cells,
|
| 126 |
+
"openloop": ol,
|
| 127 |
+
"stitch_arrivals": json.load(open(ROOT / "status/real_cooking_stitch_arrivals.json")),
|
| 128 |
+
"stitch_multihop": json.load(open(ROOT / "status/real_cooking_stitch_multihop.json")),
|
| 129 |
+
"beta_band": {k: v for k, v in json.load(open(ROOT / "status/real_cooking_beta.json")).items()
|
| 130 |
+
if k != "lens"},
|
| 131 |
+
"goal_reward": (json.load(open(ROOT / "status/real/GOAL_REWARD.json"))
|
| 132 |
+
if (ROOT / "status/real/GOAL_REWARD.json").exists() else None),
|
| 133 |
+
}
|
| 134 |
+
# per-variant stitch/chaining re-runs, if they exist
|
| 135 |
+
rep["stitch_per_cell"] = {}
|
| 136 |
+
for f in sorted(glob.glob(str(ROOT / "status/real/stitch_multihop_*.json"))):
|
| 137 |
+
rep["stitch_per_cell"][Path(f).stem.replace("stitch_multihop_", "")] = json.load(open(f))
|
| 138 |
+
OUT.write_text(json.dumps(rep, indent=2, default=str))
|
| 139 |
+
print("wrote", OUT)
|
| 140 |
+
|
| 141 |
+
# ---------------- LaTeX: register table ----------------------------------------------------
|
| 142 |
+
L = []
|
| 143 |
+
L.append(r"\begin{table}[htbp]\centering\small")
|
| 144 |
+
L.append(r"\caption{Successor-model register on \texttt{cache/real\_cooking\_v5}. Every cell is "
|
| 145 |
+
r"\texttt{rsm\_libero/train\_rsm.py} launched through \texttt{scripts/rr\_rsm.sh}; the knobs are read "
|
| 146 |
+
r"back from each checkpoint's own \texttt{config} blob, not from the launcher. "
|
| 147 |
+
r"Checkpoint paths are absolute. Source: \texttt{status/real/SUCCESSOR\_NUMBERS.json}.}")
|
| 148 |
+
L.append(r"\label{tab:cells}")
|
| 149 |
+
L.append(r"\begin{tabular}{llrrrrrl}\toprule")
|
| 150 |
+
L.append(r"cell & reward & width & chunk & trunc & seed & step & W\&B \\\midrule")
|
| 151 |
+
for c in cells:
|
| 152 |
+
cf = c["config"] or {}
|
| 153 |
+
rw = cf.get("reward_mode", "?")
|
| 154 |
+
if cf.get("reward_npy"):
|
| 155 |
+
rw = Path(cf["reward_npy"]).stem.replace("reward_", "").replace(".f32", "")
|
| 156 |
+
elif rw == "terminal":
|
| 157 |
+
rw = f"terminal k={cf.get('k_success')}"
|
| 158 |
+
wbs = (r"\href{%s}{%s}" % (c["wandb"]["url"], c["wandb"]["id"][:8])) if c["wandb"] else "---"
|
| 159 |
+
L.append(f"\\texttt{{{esc(c['cell'])}}} & {esc(rw)} & {cf.get('flow_width','?')} & "
|
| 160 |
+
f"{cf.get('chunk','?')} & {cf.get('beta_trunc_eps','?')} & {cf.get('seed','?')} & "
|
| 161 |
+
f"{c['step'] if c['step'] is not None else '---'} & {wbs} \\\\")
|
| 162 |
+
L.append(r"\bottomrule\end{tabular}\end{table}")
|
| 163 |
+
|
| 164 |
+
# ---------------- LaTeX: health table ------------------------------------------------------
|
| 165 |
+
L.append(r"\begin{table}[htbp]\centering\small")
|
| 166 |
+
L.append(r"\caption{Health numbers at the final step of each cell, all read from that cell's own "
|
| 167 |
+
r"\texttt{history.json} (the trainer's held-out evaluation). \texttt{cfm} is the flow "
|
| 168 |
+
r"matching validation loss; \texttt{r-auc}/\texttt{r-mae} the reward head on the validation "
|
| 169 |
+
r"episodes; \texttt{nnl1 ratio} the successor sample's nearest-neighbour $L_1$ to the episode's "
|
| 170 |
+
r"own future divided by the same distance to a random pool (lower is better, $1.0$ = no better "
|
| 171 |
+
r"than random); \texttt{vs stay} the same ratio against the hold-still predictor (>1 means the "
|
| 172 |
+
r"sample is FARTHER from the future than simply staying put); \texttt{win} the fraction of "
|
| 173 |
+
r"validation anchors where the logged action outranks a random one.}")
|
| 174 |
+
L.append(r"\label{tab:health}")
|
| 175 |
+
L.append(r"\begin{tabular}{lrrrrrrr}\toprule")
|
| 176 |
+
L.append(r"cell & cfm val & r-auc val & r-mae val & nnl1 ratio & vs stay & minmse & win \\\midrule")
|
| 177 |
+
for c in cells:
|
| 178 |
+
h = c["history_last"] or {}
|
| 179 |
+
def g(k, f="{:.4f}"):
|
| 180 |
+
v = h.get(k)
|
| 181 |
+
return f.format(v) if isinstance(v, (int, float)) else "---"
|
| 182 |
+
L.append(f"\\texttt{{{esc(c['cell'])}}} & {g('cfm_val')} & {g('rhead_auc_val')} & "
|
| 183 |
+
f"{g('rhead_mae_val','{:.2e}')} & {g('nnl1_ratio_val')} & {g('nnl1_ratio_vs_stay_val')} & "
|
| 184 |
+
f"{g('minmse_val')} & {g('q_action_winrate')} \\\\")
|
| 185 |
+
L.append(r"\bottomrule\end{tabular}\end{table}")
|
| 186 |
+
|
| 187 |
+
# ---------------- LaTeX: open-loop table ---------------------------------------------------
|
| 188 |
+
L.append(r"\begin{table}[htbp]\centering\small")
|
| 189 |
+
L.append(r"\caption{Open-loop selection on the \texttt{S0Aidql} proposers, 128 candidates per decision, "
|
| 190 |
+
r"705 decisions over the 25 validation episodes, \emph{after} the frame-history fix "
|
| 191 |
+
r"(\#263 comment 5769487243). Errors are the xyz $L_2$ of the chosen first action against the "
|
| 192 |
+
r"logged one, in cm. $\Delta$ is against greedy (negative = better). "
|
| 193 |
+
r"\texttt{rank} is the mean oracle-rank percentile of the chosen candidate (0.5 = blind). "
|
| 194 |
+
r"Source files: \texttt{status/real/openloop\_*/scorer\_openloop.json}.}")
|
| 195 |
+
L.append(r"\label{tab:openloop}")
|
| 196 |
+
L.append(r"\begin{tabular}{llrrrr}\toprule")
|
| 197 |
+
L.append(r"cell & scorer & first (cm) & $\Delta$ (cm) & win vs greedy & rank pct \\\midrule")
|
| 198 |
+
for r_ in ol:
|
| 199 |
+
if not r_.get("valid_for_results"):
|
| 200 |
+
continue
|
| 201 |
+
first = True
|
| 202 |
+
for s in ["greedy", "idql", "permuted:idql", "rsm", "permuted:rsm", "oracle"]:
|
| 203 |
+
v = r_["scorers"].get(s)
|
| 204 |
+
if not v:
|
| 205 |
+
continue
|
| 206 |
+
L.append(f"{esc(r_['tag']) if first else ''} & {esc(s)} & {v['first_mean_cm']:.4f} & "
|
| 207 |
+
f"{v['delta_vs_greedy_cm']:+.4f} & {v['win_rate_vs_greedy']:.3f} & "
|
| 208 |
+
f"{v['oracle_rank_pct_mean']:.3f} \\\\")
|
| 209 |
+
first = False
|
| 210 |
+
L.append(r"\midrule")
|
| 211 |
+
L[-1] = r"\bottomrule\end{tabular}\end{table}"
|
| 212 |
+
|
| 213 |
+
# ---------------- LaTeX: tie table ---------------------------------------------------------
|
| 214 |
+
L.append(r"\begin{table}[htbp]\centering\small")
|
| 215 |
+
L.append(r"\caption{Ties in the ranking array, computed here from the per-decision score matrices "
|
| 216 |
+
r"\texttt{status/real/openloop\_*/scores.npz} ($705\times128$ float32). "
|
| 217 |
+
r"\emph{tied argmax} is the fraction of decisions where more than one candidate attains the "
|
| 218 |
+
r"maximum; \emph{unique} the mean number of distinct score values among the 128 candidates; "
|
| 219 |
+
r"\emph{range} the mean max$-$min of the score array. A saturated \texttt{prob} read-out shows "
|
| 220 |
+
r"itself as a small unique count and a near-zero range.}")
|
| 221 |
+
L.append(r"\label{tab:ties}")
|
| 222 |
+
L.append(r"\begin{tabular}{llrrrr}\toprule")
|
| 223 |
+
L.append(r"cell & scorer & tied argmax & mean at max & unique / 128 & range \\\midrule")
|
| 224 |
+
for r_ in ol:
|
| 225 |
+
for s, t in (r_.get("ties") or {}).items():
|
| 226 |
+
L.append(f"{esc(r_['tag'])} & {esc(s)} & {t['frac_decisions_with_tied_argmax']:.3f} & "
|
| 227 |
+
f"{t['mean_n_at_max']:.2f} & {t['mean_unique_scores']:.1f} & "
|
| 228 |
+
f"{t['score_range_mean']:.3e} \\\\")
|
| 229 |
+
L.append(r"\bottomrule\end{tabular}\end{table}")
|
| 230 |
+
|
| 231 |
+
(TEX / "_succ_tables.tex").write_text("\n".join(L) + "\n")
|
| 232 |
+
print("wrote", TEX / "_succ_tables.tex")
|
gen_q_rsm/rsm_rise/pipeline/scripts/real/cam_dlt.py
ADDED
|
@@ -0,0 +1,307 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""gen_q#278 FIGURE B step 1 -- solve the global camera from the data, and report its error.
|
| 3 |
+
|
| 4 |
+
Owner, 2026-09-23 12:30Z: "we have the robot urdf and the training images. we can counterfactually do
|
| 5 |
+
forward kinematics and render directions of the actions" -- and the camera pose does NOT have to come from
|
| 6 |
+
real/config/calibration.yaml (which holds only resolution / serial / exposure, no intrinsics or extrinsics).
|
| 7 |
+
Solve it from thousands of logged correspondences instead.
|
| 8 |
+
|
| 9 |
+
CORRESPONDENCES
|
| 10 |
+
3D data/raw/cooking_v5_expert_suboptimal.hdf5 obs/robot0_eef_pos -- absolute EE xyz, robot base frame.
|
| 11 |
+
(obs/ee_state[:3] is the same array; eef_pos is used because it is unambiguously the position block.)
|
| 12 |
+
2D data/real/rsm_cooking_v5/videos/chunk-000/observation.images.global/episode_%06d.mp4 at 640x480.
|
| 13 |
+
NOTE the owner's note pointed at data/real/lerobot_home -- that tree is EMPTY on this filesystem; the
|
| 14 |
+
full-res LeRobot frames live under data/real/rsm_cooking_v5. hdf5 demo_N.attrs['episode_index'] == N
|
| 15 |
+
and annot/frame_index is 0..T-1, so the pairing is by index with no interpolation.
|
| 16 |
+
|
| 17 |
+
PIXEL DETECTOR (the arm is the only thing that moves)
|
| 18 |
+
background = per-episode median over the sampled frames; diff = |frame - background| in grayscale;
|
| 19 |
+
threshold = max(--abs-thresh, Otsu); morphological open/close; connected components.
|
| 20 |
+
REJECT a frame when: no blob above --min-area; the second largest blob exceeds --split-frac of the
|
| 21 |
+
largest (a split silhouette); the blob exceeds --max-area-frac of the image; or the blob spans
|
| 22 |
+
--frame-span-frac of BOTH image dimensions (a lighting change rather than the arm).
|
| 23 |
+
There is deliberately NO "touches the border" rule: the FR3 is anchored off-frame so its silhouette
|
| 24 |
+
reaches the image edge in almost every frame -- the first smoke run (LSF 1886290) rejected 172 of 200
|
| 25 |
+
frames on exactly that rule, which is why it is not used.
|
| 26 |
+
Two pixel estimators are reported side by side, because the centroid of the whole arm silhouette is NOT a
|
| 27 |
+
fixed 3D point and that bias is the main thing that can wreck this fit:
|
| 28 |
+
centroid -- centroid of the largest moving blob (the owner's recipe);
|
| 29 |
+
tipmotion -- centroid of the top --tip-pct percentile of |frame[t]-frame[t-k]| inside that blob, i.e.
|
| 30 |
+
the fastest-moving pixels;
|
| 31 |
+
distaltip -- mean of the blob pixels in the top --distal-pct percentile of distance from the blob's
|
| 32 |
+
own border-touching pixels (the arm's off-frame base), i.e. the distal end of the arm.
|
| 33 |
+
Smoke LSF 1886310 (8 eps, 194 correspondences): centroid held-out 65.4 px, tipmotion 102.5 px -- the
|
| 34 |
+
whole-silhouette centroid is NOT a fixed 3D point and the fastest-moving pixels track the elbow as often
|
| 35 |
+
as the gripper, which is why distaltip was added.
|
| 36 |
+
|
| 37 |
+
FIT
|
| 38 |
+
Hartley-normalised DLT for the full 3x4 P (11 dof) inside a RANSAC loop, then a least-squares refit on the
|
| 39 |
+
inliers. Episodes are split by EPISODE (never by frame) into fit / held-out, so the reported residual is
|
| 40 |
+
on frames from episodes the fit never saw. Median and p90 reprojection error in pixels at 640x480.
|
| 41 |
+
|
| 42 |
+
The gate the owner set: median held-out residual < ~10 px -> the overlay is trustworthy for arrow
|
| 43 |
+
directions. Worse than that and we publish the base-frame panels only and say so.
|
| 44 |
+
"""
|
| 45 |
+
import argparse, json, os, sys
|
| 46 |
+
import numpy as np
|
| 47 |
+
|
| 48 |
+
ROOT = "/proj/dmfexp/zwhong/rsm_rise"
|
| 49 |
+
VID = ROOT + "/data/real/rsm_cooking_v5/videos/chunk-000/observation.images.global/episode_%06d.mp4"
|
| 50 |
+
H5 = ROOT + "/data/raw/cooking_v5_expert_suboptimal.hdf5"
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def decode(path, idxs):
|
| 54 |
+
"""Return {frame_index: HxWx3 uint8} for the requested indices, decoding the file once."""
|
| 55 |
+
import av
|
| 56 |
+
want = set(int(i) for i in idxs)
|
| 57 |
+
out = {}
|
| 58 |
+
with av.open(path) as c:
|
| 59 |
+
st = c.streams.video[0]
|
| 60 |
+
st.thread_type = "AUTO"
|
| 61 |
+
for n, fr in enumerate(c.decode(st)):
|
| 62 |
+
if n in want:
|
| 63 |
+
out[n] = fr.to_ndarray(format="rgb24")
|
| 64 |
+
if len(out) == len(want):
|
| 65 |
+
break
|
| 66 |
+
return out
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def detect(frames, idxs, a):
|
| 70 |
+
"""frames: {i: rgb}. Returns list of (frame_index, px_centroid, px_tipmotion) for accepted frames."""
|
| 71 |
+
import cv2
|
| 72 |
+
ks = sorted(frames)
|
| 73 |
+
if len(ks) < 5:
|
| 74 |
+
return [], {"too_few_frames": len(ks)}
|
| 75 |
+
stack = np.stack([cv2.cvtColor(frames[k], cv2.COLOR_RGB2GRAY) for k in ks])
|
| 76 |
+
bg = np.median(stack, axis=0).astype(np.uint8)
|
| 77 |
+
Himg, Wimg = bg.shape
|
| 78 |
+
area_img = float(Himg * Wimg)
|
| 79 |
+
kern = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))
|
| 80 |
+
acc, rej = [], {"no_blob": 0, "frame_spanning": 0, "split": 0, "too_big": 0}
|
| 81 |
+
for pos, k in enumerate(ks):
|
| 82 |
+
g = stack[pos]
|
| 83 |
+
d = cv2.absdiff(g, bg)
|
| 84 |
+
thr_otsu, _ = cv2.threshold(d, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
|
| 85 |
+
thr = max(a.abs_thresh, float(thr_otsu))
|
| 86 |
+
m = (d >= thr).astype(np.uint8)
|
| 87 |
+
m = cv2.morphologyEx(m, cv2.MORPH_OPEN, kern)
|
| 88 |
+
m = cv2.morphologyEx(m, cv2.MORPH_CLOSE, kern)
|
| 89 |
+
n, lab, stats, cent = cv2.connectedComponentsWithStats(m, 8)
|
| 90 |
+
if n <= 1:
|
| 91 |
+
rej["no_blob"] += 1
|
| 92 |
+
continue
|
| 93 |
+
areas = stats[1:, cv2.CC_STAT_AREA]
|
| 94 |
+
order = np.argsort(areas)[::-1]
|
| 95 |
+
big = order[0] + 1
|
| 96 |
+
if areas[order[0]] < a.min_area:
|
| 97 |
+
rej["no_blob"] += 1
|
| 98 |
+
continue
|
| 99 |
+
if areas[order[0]] > a.max_area_frac * area_img:
|
| 100 |
+
rej["too_big"] += 1
|
| 101 |
+
continue
|
| 102 |
+
if len(order) > 1 and areas[order[1]] > a.split_frac * areas[order[0]]:
|
| 103 |
+
rej["split"] += 1
|
| 104 |
+
continue
|
| 105 |
+
x, y, w, h = (stats[big, cv2.CC_STAT_LEFT], stats[big, cv2.CC_STAT_TOP],
|
| 106 |
+
stats[big, cv2.CC_STAT_WIDTH], stats[big, cv2.CC_STAT_HEIGHT])
|
| 107 |
+
# NOT a border rejection: the FR3 arm is anchored off-frame, so its silhouette touches the image
|
| 108 |
+
# edge in ~86% of frames (smoke LSF 1886290: 172/200 rejected on that rule). What must be rejected
|
| 109 |
+
# is a blob that fills the frame -- a lighting change, not the arm.
|
| 110 |
+
if w >= a.frame_span_frac * Wimg and h >= a.frame_span_frac * Himg:
|
| 111 |
+
rej["frame_spanning"] += 1
|
| 112 |
+
continue
|
| 113 |
+
blob = (lab == big)
|
| 114 |
+
c_cent = np.array([cent[big][0], cent[big][1]], float)
|
| 115 |
+
ys_b, xs_b = np.nonzero(blob)
|
| 116 |
+
# distaltip: the arm is anchored off-frame, so the blob pixels ON the image border are its base.
|
| 117 |
+
# The gripper is the distal end -- the blob pixels farthest from that base. Taking the mean of the
|
| 118 |
+
# top --distal-pct percentile (not the single extreme pixel) keeps it robust to speckle.
|
| 119 |
+
onb = (xs_b <= 1) | (ys_b <= 1) | (xs_b >= Wimg - 2) | (ys_b >= Himg - 2)
|
| 120 |
+
c_dist = c_cent
|
| 121 |
+
if onb.sum() >= 5:
|
| 122 |
+
base = np.array([xs_b[onb].mean(), ys_b[onb].mean()], float)
|
| 123 |
+
dd_ = np.hypot(xs_b - base[0], ys_b - base[1])
|
| 124 |
+
q = np.percentile(dd_, a.distal_pct)
|
| 125 |
+
sel = dd_ >= q
|
| 126 |
+
if sel.sum() >= 5:
|
| 127 |
+
c_dist = np.array([xs_b[sel].mean(), ys_b[sel].mean()], float)
|
| 128 |
+
# tip estimator: fastest-moving pixels inside the blob, vs a frame --tip-lag back in the sample
|
| 129 |
+
ref = stack[max(0, pos - a.tip_lag)]
|
| 130 |
+
mot = cv2.absdiff(g, ref).astype(np.float32) * blob
|
| 131 |
+
v = mot[blob]
|
| 132 |
+
c_tip = c_cent
|
| 133 |
+
if v.size > 20:
|
| 134 |
+
q = np.percentile(v, a.tip_pct)
|
| 135 |
+
sel = blob & (mot >= max(q, 1.0))
|
| 136 |
+
if sel.sum() >= 10:
|
| 137 |
+
ys, xs = np.nonzero(sel)
|
| 138 |
+
c_tip = np.array([xs.mean(), ys.mean()], float)
|
| 139 |
+
acc.append((k, c_cent, c_tip, c_dist))
|
| 140 |
+
return acc, rej
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
def dlt(X, x):
|
| 144 |
+
"""Hartley-normalised DLT. X (n,3) world, x (n,2) pixels -> P (3,4)."""
|
| 145 |
+
n = len(X)
|
| 146 |
+
cX, cx = X.mean(0), x.mean(0)
|
| 147 |
+
sX = np.sqrt(3) / max(np.linalg.norm(X - cX, axis=1).mean(), 1e-9)
|
| 148 |
+
sx = np.sqrt(2) / max(np.linalg.norm(x - cx, axis=1).mean(), 1e-9)
|
| 149 |
+
T = np.array([[sx, 0, -sx * cx[0]], [0, sx, -sx * cx[1]], [0, 0, 1]])
|
| 150 |
+
U = np.eye(4) * sX
|
| 151 |
+
U[:3, 3] = -sX * cX
|
| 152 |
+
U[3, 3] = 1
|
| 153 |
+
Xn = (X - cX) * sX
|
| 154 |
+
xn = (x - cx) * sx
|
| 155 |
+
A = np.zeros((2 * n, 12))
|
| 156 |
+
for i in range(n):
|
| 157 |
+
Xi = np.append(Xn[i], 1.0)
|
| 158 |
+
A[2 * i, 4:8] = -Xi
|
| 159 |
+
A[2 * i, 8:12] = xn[i, 1] * Xi
|
| 160 |
+
A[2 * i + 1, 0:4] = Xi
|
| 161 |
+
A[2 * i + 1, 8:12] = -xn[i, 0] * Xi
|
| 162 |
+
_, _, Vt = np.linalg.svd(A)
|
| 163 |
+
Pn = Vt[-1].reshape(3, 4)
|
| 164 |
+
return np.linalg.inv(T) @ Pn @ U
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
def project(P, X):
|
| 168 |
+
Xh = np.concatenate([X, np.ones((len(X), 1))], 1)
|
| 169 |
+
p = Xh @ P.T
|
| 170 |
+
z = p[:, 2:3]
|
| 171 |
+
z = np.where(np.abs(z) < 1e-9, 1e-9, z)
|
| 172 |
+
return p[:, :2] / z
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
def ransac_dlt(X, x, rng, iters=400, thr=12.0, minset=8):
|
| 176 |
+
n = len(X)
|
| 177 |
+
best = (None, -1, None)
|
| 178 |
+
for _ in range(iters):
|
| 179 |
+
idx = rng.choice(n, size=minset, replace=False)
|
| 180 |
+
try:
|
| 181 |
+
P = dlt(X[idx], x[idx])
|
| 182 |
+
except np.linalg.LinAlgError:
|
| 183 |
+
continue
|
| 184 |
+
e = np.linalg.norm(project(P, X) - x, axis=1)
|
| 185 |
+
inl = e < thr
|
| 186 |
+
if inl.sum() > best[1]:
|
| 187 |
+
best = (P, int(inl.sum()), inl)
|
| 188 |
+
P, ninl, inl = best
|
| 189 |
+
if P is None or ninl < 12:
|
| 190 |
+
return None, None
|
| 191 |
+
for _ in range(3): # least-squares refit on the inliers, twice re-thresholded
|
| 192 |
+
P = dlt(X[inl], x[inl])
|
| 193 |
+
e = np.linalg.norm(project(P, X) - x, axis=1)
|
| 194 |
+
inl = e < thr
|
| 195 |
+
if inl.sum() < 12:
|
| 196 |
+
break
|
| 197 |
+
return P, inl
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
def main():
|
| 201 |
+
ap = argparse.ArgumentParser()
|
| 202 |
+
ap.add_argument("--n-episodes", type=int, default=60)
|
| 203 |
+
ap.add_argument("--frame-stride", type=int, default=10)
|
| 204 |
+
ap.add_argument("--max-frames-per-ep", type=int, default=40)
|
| 205 |
+
ap.add_argument("--abs-thresh", type=float, default=18.0)
|
| 206 |
+
ap.add_argument("--min-area", type=int, default=400)
|
| 207 |
+
ap.add_argument("--max-area-frac", type=float, default=0.35)
|
| 208 |
+
ap.add_argument("--split-frac", type=float, default=0.55)
|
| 209 |
+
ap.add_argument("--frame-span-frac", type=float, default=0.92)
|
| 210 |
+
ap.add_argument("--tip-pct", type=float, default=95.0)
|
| 211 |
+
ap.add_argument("--tip-lag", type=int, default=2)
|
| 212 |
+
ap.add_argument("--distal-pct", type=float, default=99.0)
|
| 213 |
+
ap.add_argument("--ransac-thr", type=float, default=12.0)
|
| 214 |
+
ap.add_argument("--holdout-frac", type=float, default=0.20)
|
| 215 |
+
ap.add_argument("--seed", type=int, default=0)
|
| 216 |
+
ap.add_argument("--out", default=ROOT + "/status/real/CAM_DLT.json")
|
| 217 |
+
a = ap.parse_args()
|
| 218 |
+
import h5py
|
| 219 |
+
rng = np.random.default_rng(a.seed)
|
| 220 |
+
|
| 221 |
+
f = h5py.File(H5, "r")
|
| 222 |
+
dd = f["data"]
|
| 223 |
+
eps = sorted(int(k.split("_")[1]) for k in dd.keys())
|
| 224 |
+
rng.shuffle(eps)
|
| 225 |
+
eps = sorted(eps[: a.n_episodes])
|
| 226 |
+
print(f"[cam_dlt] {len(eps)} episodes: {eps[:8]}...", flush=True)
|
| 227 |
+
|
| 228 |
+
rows = [] # (ep, frame, X(3), px_cent(2), px_tip(2))
|
| 229 |
+
rej_tot, n_seen = {}, 0
|
| 230 |
+
for e in eps:
|
| 231 |
+
vp = VID % e
|
| 232 |
+
if not os.path.exists(vp):
|
| 233 |
+
print(f"[cam_dlt] ep {e}: no video", flush=True)
|
| 234 |
+
continue
|
| 235 |
+
pos = dd[f"demo_{e}"]["obs/robot0_eef_pos"][:]
|
| 236 |
+
idxs = list(range(0, len(pos), a.frame_stride))[: a.max_frames_per_ep]
|
| 237 |
+
try:
|
| 238 |
+
frames = decode(vp, idxs)
|
| 239 |
+
except Exception as ex:
|
| 240 |
+
print(f"[cam_dlt] ep {e}: decode failed {type(ex).__name__}: {ex}", flush=True)
|
| 241 |
+
continue
|
| 242 |
+
acc, rej = detect(frames, idxs, a)
|
| 243 |
+
n_seen += len(frames)
|
| 244 |
+
for k, v in rej.items():
|
| 245 |
+
rej_tot[k] = rej_tot.get(k, 0) + v
|
| 246 |
+
for k, c, t, dtip in acc:
|
| 247 |
+
if k < len(pos):
|
| 248 |
+
rows.append((e, k, pos[k].astype(float), c, t, dtip))
|
| 249 |
+
print(f"[cam_dlt] ep {e}: {len(frames)} decoded, {len(acc)} accepted", flush=True)
|
| 250 |
+
|
| 251 |
+
if len(rows) < 100:
|
| 252 |
+
json.dump({"error": "too few correspondences", "n": len(rows), "rejected": rej_tot},
|
| 253 |
+
open(a.out, "w"), indent=1)
|
| 254 |
+
raise SystemExit(f"only {len(rows)} correspondences")
|
| 255 |
+
|
| 256 |
+
ep_arr = np.array([r[0] for r in rows])
|
| 257 |
+
fr_arr = np.array([r[1] for r in rows])
|
| 258 |
+
X = np.stack([r[2] for r in rows])
|
| 259 |
+
PX = {"centroid": np.stack([r[3] for r in rows]),
|
| 260 |
+
"tipmotion": np.stack([r[4] for r in rows]),
|
| 261 |
+
"distaltip": np.stack([r[5] for r in rows])}
|
| 262 |
+
|
| 263 |
+
uep = np.unique(ep_arr)
|
| 264 |
+
rng2 = np.random.default_rng(a.seed + 1)
|
| 265 |
+
ho = set(rng2.choice(uep, size=max(2, int(round(a.holdout_frac * len(uep)))), replace=False).tolist())
|
| 266 |
+
is_ho = np.array([e in ho for e in ep_arr])
|
| 267 |
+
print(f"[cam_dlt] {len(rows)} correspondences, {len(uep)} episodes, "
|
| 268 |
+
f"{is_ho.sum()} held-out rows from {len(ho)} episodes", flush=True)
|
| 269 |
+
|
| 270 |
+
out = {"n_correspondences": int(len(rows)), "n_frames_decoded": int(n_seen),
|
| 271 |
+
"n_episodes": int(len(uep)), "rejected": rej_tot,
|
| 272 |
+
"holdout_episodes": sorted(int(e) for e in ho),
|
| 273 |
+
"image_size": [640, 480], "video_root": VID % 0,
|
| 274 |
+
"note_lerobot_home_empty": "data/real/lerobot_home is EMPTY; full-res frames come from "
|
| 275 |
+
"data/real/rsm_cooking_v5/videos/chunk-000/observation.images.global",
|
| 276 |
+
"estimators": {}}
|
| 277 |
+
for name, x in PX.items():
|
| 278 |
+
P, inl = ransac_dlt(X[~is_ho], x[~is_ho], np.random.default_rng(a.seed + 2),
|
| 279 |
+
thr=a.ransac_thr)
|
| 280 |
+
if P is None:
|
| 281 |
+
out["estimators"][name] = {"error": "RANSAC found no consensus"}
|
| 282 |
+
continue
|
| 283 |
+
e_fit = np.linalg.norm(project(P, X[~is_ho]) - x[~is_ho], axis=1)
|
| 284 |
+
e_ho = np.linalg.norm(project(P, X[is_ho]) - x[is_ho], axis=1)
|
| 285 |
+
out["estimators"][name] = {
|
| 286 |
+
"P": P.tolist(),
|
| 287 |
+
"n_fit_rows": int((~is_ho).sum()), "n_inliers": int(inl.sum()),
|
| 288 |
+
"inlier_frac": float(inl.mean()),
|
| 289 |
+
"fit_median_px": float(np.median(e_fit)), "fit_p90_px": float(np.percentile(e_fit, 90)),
|
| 290 |
+
"heldout_n": int(is_ho.sum()),
|
| 291 |
+
"heldout_median_px": float(np.median(e_ho)),
|
| 292 |
+
"heldout_p90_px": float(np.percentile(e_ho, 90)),
|
| 293 |
+
"heldout_mean_px": float(e_ho.mean()),
|
| 294 |
+
"gate_lt_10px": bool(np.median(e_ho) < 10.0),
|
| 295 |
+
}
|
| 296 |
+
print(f"[cam_dlt] {name}: held-out median {np.median(e_ho):.2f} px, "
|
| 297 |
+
f"p90 {np.percentile(e_ho,90):.2f} px, inliers {inl.mean():.2f}", flush=True)
|
| 298 |
+
|
| 299 |
+
np.savez(a.out.replace(".json", "_corr.npz"), ep=ep_arr, frame=fr_arr, X=X,
|
| 300 |
+
px_centroid=PX["centroid"], px_tipmotion=PX["tipmotion"],
|
| 301 |
+
px_distaltip=PX["distaltip"], is_heldout=is_ho)
|
| 302 |
+
json.dump(out, open(a.out, "w"), indent=1)
|
| 303 |
+
print("[cam_dlt] wrote", a.out, flush=True)
|
| 304 |
+
|
| 305 |
+
|
| 306 |
+
if __name__ == "__main__":
|
| 307 |
+
main()
|
gen_q_rsm/rsm_rise/pipeline/scripts/real/cam_dump_frames.py
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""gen_q#278 FIGURE B -- dump global-camera frames with a pixel grid, for hand-labelling the gripper.
|
| 3 |
+
|
| 4 |
+
The motion-blob detectors all failed the camera fit (smoke LSF 1886310/1886313: centroid 65 px,
|
| 5 |
+
tipmotion 102 px, distaltip 211 px held-out, against a ~10 px gate) because the moving mask contains the
|
| 6 |
+
whole arm AND the manipulated objects. A DLT needs only >=6 good correspondences, so the standard fallback
|
| 7 |
+
is a small hand-labelled set. This dumps frames chosen to SPREAD the EE in 3D (greedy farthest-point over
|
| 8 |
+
obs/robot0_eef_pos) with a 40-px grid burned in so a pixel can be read off the picture.
|
| 9 |
+
"""
|
| 10 |
+
import argparse, json, os
|
| 11 |
+
import numpy as np
|
| 12 |
+
|
| 13 |
+
ROOT = "/proj/dmfexp/zwhong/rsm_rise"
|
| 14 |
+
VID = ROOT + "/data/real/rsm_cooking_v5/videos/chunk-000/observation.images.global/episode_%06d.mp4"
|
| 15 |
+
H5 = ROOT + "/data/raw/cooking_v5_expert_suboptimal.hdf5"
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def main():
|
| 19 |
+
ap = argparse.ArgumentParser()
|
| 20 |
+
ap.add_argument("--n", type=int, default=12)
|
| 21 |
+
ap.add_argument("--pool-episodes", type=int, default=40)
|
| 22 |
+
ap.add_argument("--stride", type=int, default=25)
|
| 23 |
+
ap.add_argument("--grid", type=int, default=40)
|
| 24 |
+
ap.add_argument("--out", default=ROOT + "/status/real/cam_label")
|
| 25 |
+
a = ap.parse_args()
|
| 26 |
+
import cv2, h5py, av
|
| 27 |
+
os.makedirs(a.out, exist_ok=True)
|
| 28 |
+
f = h5py.File(H5, "r")
|
| 29 |
+
dd = f["data"]
|
| 30 |
+
eps = sorted(int(k.split("_")[1]) for k in dd.keys())
|
| 31 |
+
rng = np.random.default_rng(0)
|
| 32 |
+
rng.shuffle(eps)
|
| 33 |
+
eps = sorted(eps[: a.pool_episodes])
|
| 34 |
+
cand = []
|
| 35 |
+
for e in eps:
|
| 36 |
+
if not os.path.exists(VID % e):
|
| 37 |
+
continue
|
| 38 |
+
pos = dd[f"demo_{e}"]["obs/robot0_eef_pos"][:]
|
| 39 |
+
for k in range(0, len(pos), a.stride):
|
| 40 |
+
cand.append((e, k, pos[k].astype(float)))
|
| 41 |
+
P = np.stack([c[2] for c in cand])
|
| 42 |
+
# greedy farthest-point sampling so the labels span the workspace
|
| 43 |
+
sel = [int(np.argmax(np.linalg.norm(P - P.mean(0), axis=1)))]
|
| 44 |
+
for _ in range(a.n - 1):
|
| 45 |
+
d = np.min(np.linalg.norm(P[:, None] - P[sel][None], axis=2), axis=1)
|
| 46 |
+
sel.append(int(np.argmax(d)))
|
| 47 |
+
meta = []
|
| 48 |
+
for j, i in enumerate(sel):
|
| 49 |
+
e, k, xyz = cand[i]
|
| 50 |
+
with av.open(VID % e) as c:
|
| 51 |
+
st = c.streams.video[0]
|
| 52 |
+
st.thread_type = "AUTO"
|
| 53 |
+
img = None
|
| 54 |
+
for n, fr in enumerate(c.decode(st)):
|
| 55 |
+
if n == k:
|
| 56 |
+
img = fr.to_ndarray(format="bgr24")
|
| 57 |
+
break
|
| 58 |
+
if img is None:
|
| 59 |
+
continue
|
| 60 |
+
g = img.copy()
|
| 61 |
+
for x in range(0, g.shape[1], a.grid):
|
| 62 |
+
cv2.line(g, (x, 0), (x, g.shape[0]), (0, 255, 0), 1)
|
| 63 |
+
cv2.putText(g, str(x), (x + 2, 12), cv2.FONT_HERSHEY_PLAIN, 0.7, (0, 255, 255), 1)
|
| 64 |
+
for y in range(0, g.shape[0], a.grid):
|
| 65 |
+
cv2.line(g, (0, y), (g.shape[1], y), (0, 255, 0), 1)
|
| 66 |
+
cv2.putText(g, str(y), (2, y + 12), cv2.FONT_HERSHEY_PLAIN, 0.7, (0, 255, 255), 1)
|
| 67 |
+
name = f"{j:02d}_ep{e}_f{k}.png"
|
| 68 |
+
cv2.imwrite(os.path.join(a.out, name), g)
|
| 69 |
+
cv2.imwrite(os.path.join(a.out, "raw_" + name), img)
|
| 70 |
+
meta.append({"file": name, "episode": int(e), "frame": int(k), "xyz_m": xyz.tolist()})
|
| 71 |
+
print("[dump]", name, xyz, flush=True)
|
| 72 |
+
json.dump(meta, open(os.path.join(a.out, "frames.json"), "w"), indent=1)
|
| 73 |
+
print("[dump] wrote", len(meta), "frames to", a.out, flush=True)
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
if __name__ == "__main__":
|
| 77 |
+
main()
|
gen_q_rsm/rsm_rise/pipeline/scripts/real/decisive_reward.py
ADDED
|
@@ -0,0 +1,197 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
"""DECISIVE TEST for the successor's reward head (gen_q #261 / #270, owner ask 2026-09-22 05:40 UTC).
|
| 3 |
+
|
| 4 |
+
"How can we show STITCHING across trajectories? Under the reward given, can it be shown?"
|
| 5 |
+
|
| 6 |
+
The corpus structure that would make a stitching demo possible (cache/real_cooking_v5/meta.npz,
|
| 7 |
+
SEGMENTS.json, and the dataset card data/real/rsm_cooking_v5/README.md):
|
| 8 |
+
|
| 9 |
+
route 0 0->5 50 eps terminal 5 = FAILURE (pan at start, tomato on stove)
|
| 10 |
+
route 1 0->1->3 50 eps terminal 3 = "cooking state", pan on stove + tomato IN THE PAN -- NOT a success
|
| 11 |
+
route 2 0->2->3 48 eps terminal 3 = same non-terminal cooking state
|
| 12 |
+
route 3 2->3->4 50 eps terminal 4 = THE ONLY REWARDED STATE (pan on grate, tomato in the bowl)
|
| 13 |
+
route 4 0->2->6 50 eps terminal 6 = FAILURE (pan on the STOVE, tomato in bowl)
|
| 14 |
+
|
| 15 |
+
State 2 ("pan on stove, tomato at initial state") is shared by routes 2, 3 and 4, so from ONE junction
|
| 16 |
+
state the data holds a rewarded continuation (route 3) and a failure continuation (route 4). That is
|
| 17 |
+
the stitch. What is NOT established is whether the trained reward head can support it. Three
|
| 18 |
+
diagnostics, all on cached features, no training:
|
| 19 |
+
|
| 20 |
+
D1 SEPARABILITY OF THE TWO TERMINALS. State 4 (rewarded) and state 6 (failure) differ ONLY in where
|
| 21 |
+
the pan ends (dataset card, states table). R(z) is evaluated on every frame whose edge_to is 4 vs
|
| 22 |
+
6, and on the last --tail frames of each such episode. AUC + score histograms. A head that
|
| 23 |
+
cannot separate 4 from 6 cannot colour a stitching figure.
|
| 24 |
+
|
| 25 |
+
D2 JUNCTION AMBIGUITY. Frames at/near state 2, split by the route the episode continued on (2, 3, 4).
|
| 26 |
+
Under the provenance reward the SAME physical state carries label 1 (route 3) and 0 (routes 2, 4),
|
| 27 |
+
so the head must be ~chance there. Measured, not assumed.
|
| 28 |
+
|
| 29 |
+
D3 lives in scripts/real/stitch_feasibility.py (it needs the flow).
|
| 30 |
+
|
| 31 |
+
Outputs status/real/DECISIVE_REWARD.json + raw logits in DECISIVE_REWARD_scores.npz.
|
| 32 |
+
"""
|
| 33 |
+
from __future__ import annotations
|
| 34 |
+
import argparse, json, sys
|
| 35 |
+
from pathlib import Path
|
| 36 |
+
import numpy as np
|
| 37 |
+
import torch
|
| 38 |
+
|
| 39 |
+
sys.path.insert(0, "/proj/dmfexp/zwhong/projs/issue_resolver_richardrl/gen_q_rsm/rsm_libero")
|
| 40 |
+
from data import LiberoRSMData # noqa: E402
|
| 41 |
+
from model import RewardHead, IdentityEncoder # noqa: E402
|
| 42 |
+
|
| 43 |
+
ROOT = "/proj/dmfexp/zwhong/rsm_rise"
|
| 44 |
+
CACHE = f"{ROOT}/cache/real_cooking_v5"
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def auc(pos, neg):
|
| 48 |
+
"""Mann-Whitney AUC of pos over neg (ties count 0.5). No sklearn dependency."""
|
| 49 |
+
pos = np.asarray(pos, np.float64); neg = np.asarray(neg, np.float64)
|
| 50 |
+
if len(pos) == 0 or len(neg) == 0:
|
| 51 |
+
return float("nan")
|
| 52 |
+
x = np.concatenate([pos, neg])
|
| 53 |
+
r = np.empty(len(x), np.float64)
|
| 54 |
+
o = np.argsort(x, kind="mergesort")
|
| 55 |
+
xs = x[o]
|
| 56 |
+
i = 0
|
| 57 |
+
while i < len(xs): # average ranks within ties
|
| 58 |
+
j = i
|
| 59 |
+
while j + 1 < len(xs) and xs[j + 1] == xs[i]:
|
| 60 |
+
j += 1
|
| 61 |
+
r[o[i:j + 1]] = 0.5 * (i + j) + 1.0
|
| 62 |
+
i = j + 1
|
| 63 |
+
n1 = len(pos)
|
| 64 |
+
return float((r[:n1].sum() - n1 * (n1 + 1) / 2.0) / (n1 * len(neg)))
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def stats(v):
|
| 68 |
+
v = np.asarray(v, np.float64)
|
| 69 |
+
if len(v) == 0:
|
| 70 |
+
return {"n": 0}
|
| 71 |
+
return {"n": int(len(v)), "mean": float(v.mean()), "std": float(v.std()),
|
| 72 |
+
"p05": float(np.percentile(v, 5)), "median": float(np.median(v)),
|
| 73 |
+
"p95": float(np.percentile(v, 95)), "min": float(v.min()), "max": float(v.max())}
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def main():
|
| 77 |
+
ap = argparse.ArgumentParser()
|
| 78 |
+
ap.add_argument("--ckpt", action="append", default=[], metavar="NAME=PATH",
|
| 79 |
+
help="repeatable; every head is scored on the identical frame sets")
|
| 80 |
+
ap.add_argument("--cache", default=CACHE)
|
| 81 |
+
ap.add_argument("--tail", type=int, default=30, help="last-N-frames subset of each episode (D1)")
|
| 82 |
+
ap.add_argument("--junction", type=int, default=30,
|
| 83 |
+
help="D2 window: the last J frames BEFORE leaving state 2 and the first J after")
|
| 84 |
+
ap.add_argument("--out", default=f"{ROOT}/status/real/DECISIVE_REWARD.json")
|
| 85 |
+
a = ap.parse_args()
|
| 86 |
+
dev = "cuda" if torch.cuda.is_available() else "cpu"
|
| 87 |
+
heads = dict(kv.split("=", 1) for kv in a.ckpt)
|
| 88 |
+
print(f"[dec] dev={dev} heads={list(heads)}", flush=True)
|
| 89 |
+
|
| 90 |
+
C = Path(a.cache)
|
| 91 |
+
m = np.load(C / "meta.npz", allow_pickle=True)
|
| 92 |
+
ep_from, ep_to = m["ep_from"].astype(int), m["ep_to"].astype(int)
|
| 93 |
+
route = np.asarray(m["ep_route"], int)
|
| 94 |
+
succ = np.asarray(m["ep_success"], bool)
|
| 95 |
+
et = np.load(C / "edge_to.i16.npy").astype(int)
|
| 96 |
+
ef = np.load(C / "edge_from.i16.npy").astype(int)
|
| 97 |
+
seg = np.load(C / "seg.i16.npy").astype(int)
|
| 98 |
+
n_ep = len(ep_from)
|
| 99 |
+
|
| 100 |
+
# ------------------------------------------------------------------ frame sets
|
| 101 |
+
sets: dict[str, np.ndarray] = {}
|
| 102 |
+
# D1: every frame heading into each terminal, and the last --tail frames of those episodes
|
| 103 |
+
for s in (3, 4, 5, 6):
|
| 104 |
+
sets[f"edge_to_{s}"] = np.nonzero(et == s)[0]
|
| 105 |
+
for s, rts in [(4, [3]), (6, [4]), (5, [0]), (3, [1, 2])]:
|
| 106 |
+
rows = np.concatenate([np.arange(ep_to[e] - a.tail, ep_to[e])
|
| 107 |
+
for e in np.nonzero(np.isin(route, rts))[0]])
|
| 108 |
+
sets[f"tail{a.tail}_term{s}"] = rows
|
| 109 |
+
# D2: the junction at state 2. "arriving" = last J frames of the segment whose edge_to == 2
|
| 110 |
+
# (routes 2 and 4 only -- route 3 episodes START at state 2, frame 0).
|
| 111 |
+
# "leaving" = first J frames of the segment whose edge_from == 2 (routes 2, 3, 4).
|
| 112 |
+
for rt in (2, 3, 4):
|
| 113 |
+
arr, lea = [], []
|
| 114 |
+
for e in np.nonzero(route == rt)[0]:
|
| 115 |
+
lo, hi = ep_from[e], ep_to[e]
|
| 116 |
+
i_arr = np.nonzero(et[lo:hi] == 2)[0]
|
| 117 |
+
if len(i_arr):
|
| 118 |
+
arr.append(np.arange(lo + max(0, i_arr[-1] + 1 - a.junction), lo + i_arr[-1] + 1))
|
| 119 |
+
i_lea = np.nonzero(ef[lo:hi] == 2)[0]
|
| 120 |
+
if len(i_lea):
|
| 121 |
+
lea.append(np.arange(lo + i_lea[0], lo + min(i_lea[0] + a.junction, hi - lo)))
|
| 122 |
+
if arr:
|
| 123 |
+
sets[f"junction_arrive_route{rt}"] = np.concatenate(arr)
|
| 124 |
+
if lea:
|
| 125 |
+
sets[f"junction_leave_route{rt}"] = np.concatenate(lea)
|
| 126 |
+
# whole-route reference pools
|
| 127 |
+
for rt in range(5):
|
| 128 |
+
rows = np.concatenate([np.arange(ep_from[e], ep_to[e]) for e in np.nonzero(route == rt)[0]])
|
| 129 |
+
sets[f"route{rt}_all"] = rows[::7] # subsample: these are 30-60k rows each
|
| 130 |
+
|
| 131 |
+
for k, v in sets.items():
|
| 132 |
+
print(f"[dec] set {k:28s} n={len(v)}", flush=True)
|
| 133 |
+
|
| 134 |
+
# ------------------------------------------------------------------ score every head
|
| 135 |
+
out = {"cache": str(C), "tail": a.tail, "junction": a.junction,
|
| 136 |
+
"set_sizes": {k: int(len(v)) for k, v in sets.items()},
|
| 137 |
+
"route_table": {str(rt): {"n_eps": int((route == rt).sum()),
|
| 138 |
+
"cache_success": bool(succ[route == rt][0])} for rt in range(5)},
|
| 139 |
+
"heads": {}}
|
| 140 |
+
raw = {}
|
| 141 |
+
# the feature table is identical for every head (same cache, same chunk/seed) -- build it once
|
| 142 |
+
c0 = torch.load(list(heads.values())[0], map_location="cpu", weights_only=False)["config"]
|
| 143 |
+
d = LiberoRSMData(a.cache, chunk=int(c0["chunk"]), k_success=int(c0["k_success"]),
|
| 144 |
+
seed=int(c0["seed"]), in_ram=True, val_frac=0.1, reward_mode=c0["reward_mode"])
|
| 145 |
+
F = lambda idx: d._feat(np.asarray(idx, np.int64))
|
| 146 |
+
for name, path in heads.items():
|
| 147 |
+
c = torch.load(path, map_location=dev, weights_only=False)
|
| 148 |
+
cfg = c["config"]
|
| 149 |
+
rew = RewardHead(int(c["d_lat"]), len(c["tasks"])).to(dev).eval()
|
| 150 |
+
rew.load_state_dict(c["rew"])
|
| 151 |
+
L = {}
|
| 152 |
+
with torch.no_grad():
|
| 153 |
+
for k, rows in sets.items():
|
| 154 |
+
lg = []
|
| 155 |
+
for i in range(0, len(rows), 8192):
|
| 156 |
+
z = torch.from_numpy(F(rows[i:i + 8192])).to(dev)
|
| 157 |
+
t = torch.zeros(len(z), dtype=torch.long, device=dev)
|
| 158 |
+
lg.append(rew(z, t).float().cpu().numpy())
|
| 159 |
+
L[k] = np.concatenate(lg) if lg else np.zeros(0, np.float32)
|
| 160 |
+
h = {"ckpt": path, "step": int(c.get("step", -1)), "reward_mode": cfg["reward_mode"],
|
| 161 |
+
"reward_npy": cfg.get("reward_npy", ""), "logit": {k: stats(v) for k, v in L.items()},
|
| 162 |
+
"prob": {k: stats(1.0 / (1.0 + np.exp(-np.clip(v, -60, 60)))) for k, v in L.items()},
|
| 163 |
+
"sat_frac": {k: float((np.abs(v) > 15).mean()) for k, v in L.items()}}
|
| 164 |
+
# the decisive AUCs
|
| 165 |
+
h["auc"] = {
|
| 166 |
+
"D1_term4_vs_term6_allframes": auc(L["edge_to_4"], L["edge_to_6"]),
|
| 167 |
+
"D1_term4_vs_term6_tail": auc(L[f"tail{a.tail}_term4"], L[f"tail{a.tail}_term6"]),
|
| 168 |
+
"D1_term4_vs_term3_tail": auc(L[f"tail{a.tail}_term4"], L[f"tail{a.tail}_term3"]),
|
| 169 |
+
"D1_term4_vs_term5_tail": auc(L[f"tail{a.tail}_term4"], L[f"tail{a.tail}_term5"]),
|
| 170 |
+
"D2_junction_leave_r3_vs_r4": auc(L["junction_leave_route3"], L["junction_leave_route4"]),
|
| 171 |
+
"D2_junction_leave_r3_vs_r2": auc(L["junction_leave_route3"], L["junction_leave_route2"]),
|
| 172 |
+
"D2_junction_arrive_r2_vs_r4": auc(L["junction_arrive_route2"], L["junction_arrive_route4"]),
|
| 173 |
+
"route3_vs_route4_allframes": auc(L["route3_all"], L["route4_all"]),
|
| 174 |
+
}
|
| 175 |
+
# 12-bin histogram of the logit on the two terminals, for the PDF
|
| 176 |
+
lo = float(min(L["edge_to_4"].min(), L["edge_to_6"].min()))
|
| 177 |
+
hi = float(max(L["edge_to_4"].max(), L["edge_to_6"].max()))
|
| 178 |
+
edges = np.linspace(lo, hi, 13)
|
| 179 |
+
h["hist"] = {"edges": edges.tolist(),
|
| 180 |
+
"term4": np.histogram(L["edge_to_4"], edges)[0].tolist(),
|
| 181 |
+
"term6": np.histogram(L["edge_to_6"], edges)[0].tolist()}
|
| 182 |
+
out["heads"][name] = h
|
| 183 |
+
for k, v in L.items():
|
| 184 |
+
raw[f"{name}|{k}"] = v.astype(np.float32)
|
| 185 |
+
print(f"[dec] {name:12s} step={h['step']:>7} "
|
| 186 |
+
f"AUC(4vs6)={h['auc']['D1_term4_vs_term6_allframes']:.4f} "
|
| 187 |
+
f"tail={h['auc']['D1_term4_vs_term6_tail']:.4f} "
|
| 188 |
+
f"AUC(4vs3)={h['auc']['D1_term4_vs_term3_tail']:.4f} "
|
| 189 |
+
f"junction(r3vsr4)={h['auc']['D2_junction_leave_r3_vs_r4']:.4f}", flush=True)
|
| 190 |
+
|
| 191 |
+
Path(a.out).write_text(json.dumps(out, indent=1))
|
| 192 |
+
np.savez_compressed(a.out.replace(".json", "_scores.npz"), **raw)
|
| 193 |
+
print(f"[dec] wrote {a.out}", flush=True)
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
if __name__ == "__main__":
|
| 197 |
+
main()
|
gen_q_rsm/rsm_rise/pipeline/scripts/real/destiny_route_split.py
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Split a DESTINY_*.json/_scores.npz result by the EPISODE ROUTE of each arm.
|
| 3 |
+
|
| 4 |
+
Motivation (gen_q#277): the pooled S0 contrast mixes a SHARED-PREFIX pair
|
| 5 |
+
(0->2->3 goal vs 0->2->6 failure -- identical 0->2 prefix, so appearance and the
|
| 6 |
+
immediate action cannot separate them) with a DISJOINT pair (0->1->3 vs 0->5,
|
| 7 |
+
which differ from the first edge and are therefore confoundable by episode
|
| 8 |
+
appearance). Reporting them separately says whether a separating read-out is
|
| 9 |
+
predicting the future or recognising the trajectory.
|
| 10 |
+
|
| 11 |
+
Reads only the artifacts the destiny run already wrote; no model calls.
|
| 12 |
+
"""
|
| 13 |
+
import argparse, json, sys
|
| 14 |
+
import numpy as np
|
| 15 |
+
sys.path.insert(0, __file__.rsplit("/", 1)[0])
|
| 16 |
+
from destiny_test import cluster_boot # same estimator, same bootstrap
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def main():
|
| 20 |
+
ap = argparse.ArgumentParser()
|
| 21 |
+
ap.add_argument("--json", required=True)
|
| 22 |
+
ap.add_argument("--cache", default="/proj/dmfexp/zwhong/rsm_rise/cache/real_cooking_v5")
|
| 23 |
+
ap.add_argument("--n-boot", type=int, default=2000)
|
| 24 |
+
ap.add_argument("--seed", type=int, default=0)
|
| 25 |
+
ap.add_argument("--out", required=True)
|
| 26 |
+
a = ap.parse_args()
|
| 27 |
+
|
| 28 |
+
d = json.load(open(a.json))
|
| 29 |
+
z = np.load(a.json.replace(".json", "_scores.npz"), allow_pickle=True)
|
| 30 |
+
ep = np.asarray(d["anchor_ep"], np.int64)
|
| 31 |
+
lab = np.asarray(d["anchor_is_goal"], bool)
|
| 32 |
+
path = np.load(a.cache + "/meta.npz", allow_pickle=True)["ep_path"]
|
| 33 |
+
route = np.array([str(path[e]) for e in ep])
|
| 34 |
+
|
| 35 |
+
goal_routes = sorted(set(route[lab]))
|
| 36 |
+
fail_routes = sorted(set(route[~lab]))
|
| 37 |
+
pairs = {"POOLED": (goal_routes, fail_routes)}
|
| 38 |
+
for g in goal_routes:
|
| 39 |
+
for f in fail_routes:
|
| 40 |
+
# shared prefix = same first edge
|
| 41 |
+
tag = "shared-prefix" if g.split("->")[1] == f.split("->")[1] else "disjoint"
|
| 42 |
+
pairs["%s vs %s [%s]" % (g, f, tag)] = ([g], [f])
|
| 43 |
+
|
| 44 |
+
out = {"source": a.json, "contrast": d["contrast"],
|
| 45 |
+
"routes_goal": {r: int((route[lab] == r).sum()) for r in goal_routes},
|
| 46 |
+
"routes_failure": {r: int((route[~lab] == r).sum()) for r in fail_routes},
|
| 47 |
+
"n_ep_per_route": {r: int(len(np.unique(ep[route == r]))) for r in goal_routes + fail_routes},
|
| 48 |
+
"pairs": {}}
|
| 49 |
+
for name, (gs, fs) in pairs.items():
|
| 50 |
+
sel = np.isin(route, gs + fs)
|
| 51 |
+
cells = {}
|
| 52 |
+
for key in z.files:
|
| 53 |
+
head, ro = key.split("|", 1)
|
| 54 |
+
S = np.asarray(z[key], np.float64)
|
| 55 |
+
if len(S) != len(ep):
|
| 56 |
+
continue
|
| 57 |
+
cells.setdefault(head, {})[ro] = cluster_boot(S[sel], lab[sel], ep[sel], a.n_boot, a.seed)
|
| 58 |
+
out["pairs"][name] = {"n_pos": int((lab & sel).sum()), "n_neg": int((~lab & sel).sum()),
|
| 59 |
+
"n_ep": int(len(np.unique(ep[sel]))), "heads": cells}
|
| 60 |
+
json.dump(out, open(a.out, "w"), indent=1)
|
| 61 |
+
print("wrote", a.out)
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
if __name__ == "__main__":
|
| 65 |
+
main()
|
gen_q_rsm/rsm_rise/pipeline/scripts/real/destiny_test.py
ADDED
|
@@ -0,0 +1,324 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
"""DESTINY TEST -- gen_q#276 (owner 2026-09-23 11:45Z, corrected 11:55Z and 12:05Z).
|
| 3 |
+
|
| 4 |
+
Same state, different future. Does the VALUE at an anchor predict where the episode ends up, or is it a
|
| 5 |
+
state classifier? Eval-only on the cached DINOv2 features; no proposer, no roll-out.
|
| 6 |
+
|
| 7 |
+
CONTRASTS (--contrast)
|
| 8 |
+
S2 HEADLINE. Anchors in the 2->3 segment of route 3 (2->3->4, GOAL) vs anchors in the 2->6 segment of
|
| 9 |
+
route 4 (0->2->6, FAILURE). Both are "pan on stove, tomato at initial state"; only the future differs.
|
| 10 |
+
S3 SCHEME-DISCRIMINATING. Anchors just after arrival at S3 that go on to pour (route 3, first W frames of
|
| 11 |
+
the 3->4 segment) vs anchors just after arrival at S3 in an episode that STOPS at cooking (routes 1/2,
|
| 12 |
+
last W frames). Under EXPERT_EPISODE both arms are positive, so that head should be unable to separate
|
| 13 |
+
them; under GOAL_SEGMENT only the first is.
|
| 14 |
+
S0 THE STITCHING TEST. Anchors in the segment leaving S0, by eventual destiny: routes 1/2 (0->1->3,
|
| 15 |
+
0->2->3, reach cooking) vs routes 0/4 (0->5, 0->2->6, fail). NOTE, and it is the point of the test:
|
| 16 |
+
NO logged episode contains both S0 and S4, so no S0 anchor's own episode holds a GOAL_SEGMENT or
|
| 17 |
+
GOAL_EPISODE positive at all -- the value can only separate these by composing across episodes.
|
| 18 |
+
|
| 19 |
+
READ-OUTS, on the SAME anchors (--readout, repeatable)
|
| 20 |
+
rew the reward head alone, sigma(R(z)/T). Under GOAL_SEGMENT an S2 anchor is labelled 0 on BOTH
|
| 21 |
+
arms by construction, so a null here is EXPECTED; separation would mean the head is leaking
|
| 22 |
+
trajectory identity, which is a defect (owner 11:55Z).
|
| 23 |
+
d1 one beta-occupancy read (the read-out the twin shipped). No composition.
|
| 24 |
+
chain:B:G the coin-terminated beta chain at beta B, gamma G. Needs B < G; the cap comes from the 1e-3
|
| 25 |
+
tail. beta must be inside the checkpoint's trained [beta_lo, beta_hi] (R_M: 0.95..0.99).
|
| 26 |
+
perm:<r> the permuted null for read-out r: the same score vector shuffled across anchors, so the
|
| 27 |
+
contrast label carries no information. Reported beside every cell.
|
| 28 |
+
The action handed to the value is the anchor's own LOGGED chunk, so this is V^behaviour(s), not a max over
|
| 29 |
+
proposals -- the destiny question is about the state's value, not about ranking draws.
|
| 30 |
+
|
| 31 |
+
REACHABILITY (owner 11:55Z). Every cell is bucketed by the anchor's distance in frames to the first frame of
|
| 32 |
+
the 3->4 segment of ITS OWN episode (inf when that episode has none, which is every failure anchor and every
|
| 33 |
+
S0 anchor). The horizon is 1/(1-gamma) frames, so the reachable fraction per bucket is printed beside the
|
| 34 |
+
cell; a pooled number would hide the horizon limit as a model failure. The distance to the episode's own
|
| 35 |
+
TERMINAL is reported too, because route 0->2->6's segments are much shorter than route 2->3->4's and a pooled
|
| 36 |
+
comparison would favour the failure arm on distance alone.
|
| 37 |
+
|
| 38 |
+
Reported per (head, read-out, contrast, bucket): AUC, median value gap, and a CLUSTER bootstrap over
|
| 39 |
+
EPISODES (n=50 goal episodes is the cluster count on the goal arm, never the frame count).
|
| 40 |
+
Output: <out>.json (+ <out>_scores.npz with every raw score vector).
|
| 41 |
+
"""
|
| 42 |
+
from __future__ import annotations
|
| 43 |
+
import argparse, json, sys
|
| 44 |
+
from pathlib import Path
|
| 45 |
+
import numpy as np
|
| 46 |
+
import torch
|
| 47 |
+
|
| 48 |
+
sys.path.insert(0, "/proj/dmfexp/zwhong/projs/issue_resolver_richardrl/gen_q_rsm/rsm_libero")
|
| 49 |
+
from data import LiberoRSMData # noqa: E402
|
| 50 |
+
|
| 51 |
+
ROOT = "/proj/dmfexp/zwhong/rsm_rise"
|
| 52 |
+
CACHE = f"{ROOT}/cache/real_cooking_v5"
|
| 53 |
+
# route id -> the planned sequence it was collected for (real/config/task/tabletop.yaml edge_combinations)
|
| 54 |
+
ROUTE_TXT = {0: "0->5", 1: "0->1->3", 2: "0->2->3", 3: "2->3->4", 4: "0->2->6"}
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def auc(pos, neg):
|
| 58 |
+
pos = np.asarray(pos, np.float64); neg = np.asarray(neg, np.float64)
|
| 59 |
+
if len(pos) == 0 or len(neg) == 0:
|
| 60 |
+
return float("nan")
|
| 61 |
+
x = np.concatenate([pos, neg]); o = np.argsort(x, kind="mergesort"); xs = x[o]
|
| 62 |
+
r = np.empty(len(x), np.float64); i = 0
|
| 63 |
+
while i < len(xs):
|
| 64 |
+
j = i
|
| 65 |
+
while j + 1 < len(xs) and xs[j + 1] == xs[i]:
|
| 66 |
+
j += 1
|
| 67 |
+
r[o[i:j + 1]] = 0.5 * (i + j) + 1.0; i = j + 1
|
| 68 |
+
n1 = len(pos)
|
| 69 |
+
return float((r[:n1].sum() - n1 * (n1 + 1) / 2.0) / (n1 * len(neg)))
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def cluster_boot(score, lab, ep, n_boot=2000, seed=0):
|
| 73 |
+
"""AUC + median gap with a bootstrap over EPISODES (the cluster), not frames."""
|
| 74 |
+
rng = np.random.default_rng(seed)
|
| 75 |
+
eps = np.unique(ep)
|
| 76 |
+
a0 = auc(score[lab], score[~lab]); g0 = float(np.median(score[lab]) - np.median(score[~lab])) \
|
| 77 |
+
if lab.any() and (~lab).any() else float("nan")
|
| 78 |
+
out = []
|
| 79 |
+
for _ in range(n_boot):
|
| 80 |
+
take = rng.choice(eps, size=len(eps), replace=True)
|
| 81 |
+
idx = np.concatenate([np.nonzero(ep == e)[0] for e in take])
|
| 82 |
+
l = lab[idx]
|
| 83 |
+
if not l.any() or l.all():
|
| 84 |
+
continue
|
| 85 |
+
out.append(auc(score[idx][l], score[idx][~l]))
|
| 86 |
+
out = np.array(out) if out else np.array([np.nan])
|
| 87 |
+
return dict(auc=a0, auc_lo=float(np.nanpercentile(out, 2.5)), auc_hi=float(np.nanpercentile(out, 97.5)),
|
| 88 |
+
median_gap=g0, n_pos=int(lab.sum()), n_neg=int((~lab).sum()),
|
| 89 |
+
n_ep_pos=int(len(np.unique(ep[lab]))), n_ep_neg=int(len(np.unique(ep[~lab]))))
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
BUCKETS = [(0, 50), (50, 100), (100, 200), (200, 400), (400, 10 ** 9)]
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def main():
|
| 96 |
+
ap = argparse.ArgumentParser()
|
| 97 |
+
ap.add_argument("--ckpt", action="append", default=[], metavar="NAME=PATH", required=True)
|
| 98 |
+
ap.add_argument("--cache", default=CACHE)
|
| 99 |
+
ap.add_argument("--contrast", default="S2", choices=["S0", "S2", "S3"])
|
| 100 |
+
ap.add_argument("--readout", action="append", default=[],
|
| 101 |
+
help="rew | d1 | chain:<beta>:<gamma> (the permuted null of each is added automatically)")
|
| 102 |
+
ap.add_argument("--anchors-per-ep", type=int, default=8, help="uniformly spaced inside the anchor segment")
|
| 103 |
+
ap.add_argument("--s3-win", type=int, default=100, help="S3 contrast: frames either side of the arrival at S3")
|
| 104 |
+
ap.add_argument("--hop-ckpt", default=f"{ROOT}/runs/real_cooking_v5/hop/flow/policy_r1.pt",
|
| 105 |
+
help="Stage-2 hop head. The coin chain re-decides the action at every hop, so at cap>1 "
|
| 106 |
+
"it is REQUIRED (rsm_scorer.py:622). Unused by rew / d1.")
|
| 107 |
+
ap.add_argument("--particles", type=int, default=16)
|
| 108 |
+
ap.add_argument("--temperature", type=float, default=25.0)
|
| 109 |
+
ap.add_argument("--score-kind", default="prob")
|
| 110 |
+
ap.add_argument("--held-out-only", type=int, default=1)
|
| 111 |
+
ap.add_argument("--split", default=f"{ROOT}/data/derived/cooking_v5_split.json")
|
| 112 |
+
ap.add_argument("--n-boot", type=int, default=2000)
|
| 113 |
+
ap.add_argument("--seed", type=int, default=0)
|
| 114 |
+
ap.add_argument("--out", required=True)
|
| 115 |
+
a = ap.parse_args()
|
| 116 |
+
readouts = a.readout or ["rew", "d1", "chain:0.99:0.999"]
|
| 117 |
+
dev = "cuda" if torch.cuda.is_available() else "cpu"
|
| 118 |
+
heads = dict(kv.split("=", 1) for kv in a.ckpt)
|
| 119 |
+
rng = np.random.default_rng(a.seed)
|
| 120 |
+
|
| 121 |
+
C = Path(a.cache)
|
| 122 |
+
m = np.load(C / "meta.npz", allow_pickle=True)
|
| 123 |
+
ep_from, ep_to = m["ep_from"].astype(int), m["ep_to"].astype(int)
|
| 124 |
+
route = np.asarray(m["ep_route"], int)
|
| 125 |
+
et = np.load(C / "edge_to.i16.npy").astype(int)
|
| 126 |
+
ef = np.load(C / "edge_from.i16.npy").astype(int)
|
| 127 |
+
n_ep = len(ep_from)
|
| 128 |
+
|
| 129 |
+
held = None
|
| 130 |
+
if a.held_out_only:
|
| 131 |
+
# same held-out list the edge harness uses (scorer_openloop.py:278)
|
| 132 |
+
sp = json.loads(Path(a.split).read_text())
|
| 133 |
+
held = {int(k) for k, v in sp["episodes"].items() if v["split"] == "valid"}
|
| 134 |
+
|
| 135 |
+
# ---- the first frame of the 3->4 segment of each episode (inf when it has none): the GOAL_SEGMENT
|
| 136 |
+
# positive the value has to reach. Reachability is measured against THIS.
|
| 137 |
+
goal_seg_start = np.full(n_ep, np.inf)
|
| 138 |
+
for e in range(n_ep):
|
| 139 |
+
lo, hi = ep_from[e], ep_to[e]
|
| 140 |
+
i = np.nonzero((ef[lo:hi] == 3) & (et[lo:hi] == 4))[0]
|
| 141 |
+
if len(i):
|
| 142 |
+
goal_seg_start[e] = lo + i[0]
|
| 143 |
+
|
| 144 |
+
def seg_rows(e, a_from, a_to):
|
| 145 |
+
lo, hi = ep_from[e], ep_to[e]
|
| 146 |
+
i = np.nonzero((ef[lo:hi] == a_from) & (et[lo:hi] == a_to))[0]
|
| 147 |
+
return (lo + i) if len(i) else np.array([], int)
|
| 148 |
+
|
| 149 |
+
# ---- anchors per contrast: (rows, is_goal_arm, episode)
|
| 150 |
+
rows, lab, aep, note = [], [], [], {}
|
| 151 |
+
def add(e, r, is_goal):
|
| 152 |
+
if len(r) == 0:
|
| 153 |
+
return
|
| 154 |
+
k = min(a.anchors_per_ep, len(r))
|
| 155 |
+
sel = r[np.linspace(0, len(r) - 1, k).astype(int)]
|
| 156 |
+
rows.append(sel); lab.append(np.full(k, is_goal, bool)); aep.append(np.full(k, e, int))
|
| 157 |
+
|
| 158 |
+
for e in range(n_ep):
|
| 159 |
+
if held is not None and e not in held:
|
| 160 |
+
continue
|
| 161 |
+
rt = int(route[e])
|
| 162 |
+
if a.contrast == "S2":
|
| 163 |
+
if rt == 3:
|
| 164 |
+
add(e, seg_rows(e, 2, 3), True) # 2->3->4, the goal continuation
|
| 165 |
+
elif rt == 4:
|
| 166 |
+
add(e, seg_rows(e, 2, 6), False) # 0->2->6, the failure continuation
|
| 167 |
+
elif a.contrast == "S3":
|
| 168 |
+
if rt == 3:
|
| 169 |
+
r = seg_rows(e, 3, 4)
|
| 170 |
+
add(e, r[:a.s3_win], True) # just poured-bound
|
| 171 |
+
elif rt in (1, 2):
|
| 172 |
+
lo, hi = ep_from[e], ep_to[e]
|
| 173 |
+
add(e, np.arange(max(lo, hi - a.s3_win), hi), False) # arrived at S3 and stopped
|
| 174 |
+
elif a.contrast == "S0":
|
| 175 |
+
if rt == 1:
|
| 176 |
+
add(e, seg_rows(e, 0, 1), True)
|
| 177 |
+
elif rt == 2:
|
| 178 |
+
add(e, seg_rows(e, 0, 2), True)
|
| 179 |
+
elif rt == 0:
|
| 180 |
+
add(e, seg_rows(e, 0, 5), False)
|
| 181 |
+
elif rt == 4:
|
| 182 |
+
add(e, seg_rows(e, 0, 2), False)
|
| 183 |
+
if not rows:
|
| 184 |
+
raise SystemExit(f"no anchors for contrast {a.contrast}")
|
| 185 |
+
rows = np.concatenate(rows); lab = np.concatenate(lab); aep = np.concatenate(aep)
|
| 186 |
+
order = np.argsort(rows); rows, lab, aep = rows[order], lab[order], aep[order]
|
| 187 |
+
|
| 188 |
+
# distance to the 3->4 boundary of the anchor's OWN episode, and to its own terminal
|
| 189 |
+
d_goal = np.array([goal_seg_start[e] - r for e, r in zip(aep, rows)], float)
|
| 190 |
+
d_goal[d_goal < 0] = np.inf
|
| 191 |
+
d_term = np.array([ep_to[e] - r for e, r in zip(aep, rows)], float)
|
| 192 |
+
note["anchor_arms"] = {
|
| 193 |
+
"goal": sorted({ROUTE_TXT[int(route[e])] for e in np.unique(aep[lab])}),
|
| 194 |
+
"failure": sorted({ROUTE_TXT[int(route[e])] for e in np.unique(aep[~lab])}),
|
| 195 |
+
}
|
| 196 |
+
note["frac_anchors_whose_own_episode_has_a_3to4_segment"] = float(np.mean(np.isfinite(d_goal)))
|
| 197 |
+
note["frac_goal_arm_anchors_needing_a_DIFFERENT_episode_for_the_goal"] = float(
|
| 198 |
+
np.mean(~np.isfinite(d_goal[lab])))
|
| 199 |
+
print(f"[destiny] contrast {a.contrast}: {len(rows)} anchors "
|
| 200 |
+
f"({lab.sum()} goal from {len(np.unique(aep[lab]))} eps, {(~lab).sum()} failure from "
|
| 201 |
+
f"{len(np.unique(aep[~lab]))} eps); held-out only={bool(a.held_out_only)}\n"
|
| 202 |
+
f"[destiny] goal arm routes {note['anchor_arms']['goal']} | failure arm "
|
| 203 |
+
f"{note['anchor_arms']['failure']}\n"
|
| 204 |
+
f"[destiny] own episode contains a 3->4 segment for {note['frac_anchors_whose_own_episode_has_a_3to4_segment']:.3f} "
|
| 205 |
+
f"of anchors; {note['frac_goal_arm_anchors_needing_a_DIFFERENT_episode_for_the_goal']:.3f} of the GOAL arm "
|
| 206 |
+
f"must compose across episodes", flush=True)
|
| 207 |
+
|
| 208 |
+
# ---- features + the anchor's own logged chunk
|
| 209 |
+
c0 = torch.load(list(heads.values())[0], map_location="cpu", weights_only=False)
|
| 210 |
+
cfg0 = c0["config"]; chunk = int(cfg0["chunk"])
|
| 211 |
+
d = LiberoRSMData(a.cache, chunk=chunk, k_success=int(cfg0["k_success"]), seed=int(cfg0["seed"]),
|
| 212 |
+
in_ram=True, val_frac=0.1, reward_mode=cfg0["reward_mode"])
|
| 213 |
+
F = lambda idx: d._feat(np.asarray(idx, np.int64))
|
| 214 |
+
epi = np.searchsorted(ep_to, rows, "right")
|
| 215 |
+
A = np.asarray(d._chunk_at(rows.astype(np.int64), epi.astype(np.int64)), np.float32)
|
| 216 |
+
A = A.reshape(len(rows), chunk, -1)
|
| 217 |
+
|
| 218 |
+
from types import SimpleNamespace
|
| 219 |
+
from robomimic.algo.rsm_scorer import RSMScorer, chain_continuation_p, chain_cap as chain_cap_fn
|
| 220 |
+
|
| 221 |
+
out = {"contrast": a.contrast, "cache": str(C), "n_anchors": int(len(rows)),
|
| 222 |
+
"readouts": readouts, "heads": {}, "notes": note,
|
| 223 |
+
"anchor_rows": rows.tolist(), "anchor_is_goal": lab.tolist(), "anchor_ep": aep.tolist(),
|
| 224 |
+
"dist_to_3to4_frames": [None if not np.isfinite(x) else float(x) for x in d_goal],
|
| 225 |
+
"dist_to_own_terminal_frames": d_term.tolist(),
|
| 226 |
+
"readout_spec": {}}
|
| 227 |
+
raw = {}
|
| 228 |
+
|
| 229 |
+
for hname, path in heads.items():
|
| 230 |
+
ck = torch.load(path, map_location="cpu", weights_only=False)
|
| 231 |
+
din = int(ck["d_in"]); bl, bh = ck["config"].get("beta_lo"), ck["config"].get("beta_hi")
|
| 232 |
+
stub = SimpleNamespace(d=din, sd=torch.ones(din), normalize=None)
|
| 233 |
+
hres = {"ckpt": path, "beta_lo": bl, "beta_hi": bh, "cells": {}}
|
| 234 |
+
for ro in readouts:
|
| 235 |
+
if ro == "rew":
|
| 236 |
+
sc = RSMScorer(backend="mlp", ckpt=path, hop_ckpt="", state=stub, mode="d1", depth=1,
|
| 237 |
+
beta=0.99, gamma=0.999, n_particles=1, score_kind=a.score_kind,
|
| 238 |
+
temperature=a.temperature, device=dev)
|
| 239 |
+
bk = sc.backend
|
| 240 |
+
with torch.no_grad():
|
| 241 |
+
S = []
|
| 242 |
+
for i in range(0, len(rows), 256):
|
| 243 |
+
x = torch.as_tensor(F(rows[i:i + 256]), dtype=torch.float32, device=dev)
|
| 244 |
+
z = bk.latent(x)
|
| 245 |
+
tk = torch.zeros(z.shape[0], dtype=torch.long, device=z.device)
|
| 246 |
+
r = bk.rew(z, tk) # R(z, task) -> logit (rsm_libero model.py:156)
|
| 247 |
+
r = r[0] if isinstance(r, (tuple, list)) else r
|
| 248 |
+
S.append(torch.sigmoid(r.reshape(len(z), -1)[:, 0] / a.temperature).cpu().numpy())
|
| 249 |
+
S = np.concatenate(S)
|
| 250 |
+
spec = {"kind": "reward head alone, sigma(R(z)/T)", "T": a.temperature}
|
| 251 |
+
else:
|
| 252 |
+
if ro == "d1":
|
| 253 |
+
mode, beta, gamma = "d1", 0.99, 0.99
|
| 254 |
+
else:
|
| 255 |
+
_, b, g = ro.split(":"); mode, beta, gamma = "chain", float(b), float(g)
|
| 256 |
+
if bl is not None and not (float(bl) <= beta <= float(bh)):
|
| 257 |
+
print(f"[destiny] SKIP {hname} {ro}: beta {beta} OUTSIDE the trained range "
|
| 258 |
+
f"[{bl},{bh}] -- an out-of-range beta is a defect, not a data point", flush=True)
|
| 259 |
+
continue
|
| 260 |
+
sc = RSMScorer(backend="mlp", ckpt=path,
|
| 261 |
+
hop_ckpt=(a.hop_ckpt if mode in ("chain", "chain_rb") else ""),
|
| 262 |
+
state=stub, mode=mode, depth=1,
|
| 263 |
+
beta=beta, gamma=gamma, n_particles=a.particles, score_kind=a.score_kind,
|
| 264 |
+
temperature=a.temperature, device=dev)
|
| 265 |
+
p = chain_continuation_p(beta, gamma) if mode == "chain" else 0.0
|
| 266 |
+
spec = {"kind": mode, "beta": beta, "gamma": gamma, "p": float(p),
|
| 267 |
+
"E_extra_hops": float(p / (1 - p)) if p < 1 else None,
|
| 268 |
+
"E_model_reads": float(1 / (1 - p)) if p < 1 else None,
|
| 269 |
+
"cap": int(chain_cap_fn(beta, gamma)) if mode == "chain" else 1,
|
| 270 |
+
"horizon_frames_1_over_1_minus_gamma": float(1 / (1 - gamma)),
|
| 271 |
+
"particles": a.particles}
|
| 272 |
+
import time as _t
|
| 273 |
+
t0 = _t.time()
|
| 274 |
+
with torch.no_grad():
|
| 275 |
+
S = np.empty(len(rows), np.float32)
|
| 276 |
+
for i in range(len(rows)):
|
| 277 |
+
x = torch.as_tensor(F([rows[i]]), dtype=torch.float32, device=dev)
|
| 278 |
+
S[i] = float(sc.score(x, A[i:i + 1, :sc.chunk])[0])
|
| 279 |
+
spec["s_per_decision"] = (_t.time() - t0) / max(1, len(rows))
|
| 280 |
+
if mode_needs_hop := (ro not in ("rew", "d1")):
|
| 281 |
+
spec["hop_ckpt"] = a.hop_ckpt
|
| 282 |
+
out["readout_spec"][ro] = spec
|
| 283 |
+
raw[f"{hname}|{ro}"] = S
|
| 284 |
+
perm = S[rng.permutation(len(S))]
|
| 285 |
+
raw[f"{hname}|perm:{ro}"] = perm
|
| 286 |
+
cell = {"pooled": cluster_boot(S, lab, aep, a.n_boot, a.seed),
|
| 287 |
+
"pooled_permuted": cluster_boot(perm, lab, aep, a.n_boot, a.seed),
|
| 288 |
+
"buckets": {}}
|
| 289 |
+
H = spec.get("horizon_frames_1_over_1_minus_gamma", float("nan"))
|
| 290 |
+
for lo_b, hi_b in BUCKETS:
|
| 291 |
+
sel = (d_goal >= lo_b) & (d_goal < hi_b)
|
| 292 |
+
key = f"{lo_b}-{'inf' if hi_b > 10 ** 8 else hi_b}"
|
| 293 |
+
if sel.sum() < 4 or not lab[sel].any() or lab[sel].all():
|
| 294 |
+
cell["buckets"][key] = {"n": int(sel.sum()), "skipped": "one arm empty or n<4"}
|
| 295 |
+
continue
|
| 296 |
+
c = cluster_boot(S[sel], lab[sel], aep[sel], a.n_boot, a.seed)
|
| 297 |
+
c["reachable_frac"] = float(np.mean(d_goal[sel] <= H)) if np.isfinite(H) else None
|
| 298 |
+
cell["buckets"][key] = c
|
| 299 |
+
sel = ~np.isfinite(d_goal)
|
| 300 |
+
if sel.sum() >= 4 and lab[sel].any() and not lab[sel].all():
|
| 301 |
+
cell["buckets"]["no-3to4-in-own-episode"] = cluster_boot(S[sel], lab[sel], aep[sel],
|
| 302 |
+
a.n_boot, a.seed)
|
| 303 |
+
else:
|
| 304 |
+
cell["buckets"]["no-3to4-in-own-episode"] = {
|
| 305 |
+
"n": int(sel.sum()),
|
| 306 |
+
"skipped": "one arm empty -- the goal must come from a DIFFERENT episode"}
|
| 307 |
+
hres["cells"][ro] = cell
|
| 308 |
+
pb = cell["pooled"]; pp = cell["pooled_permuted"]
|
| 309 |
+
print(f"[destiny] {hname:16s} {ro:16s} AUC {pb['auc']:.3f} [{pb['auc_lo']:.3f},{pb['auc_hi']:.3f}] "
|
| 310 |
+
f"gap {pb['median_gap']:+.4f} | permuted {pp['auc']:.3f} "
|
| 311 |
+
f"[{pp['auc_lo']:.3f},{pp['auc_hi']:.3f}] | n {pb['n_pos']}+{pb['n_neg']} "
|
| 312 |
+
f"({pb['n_ep_pos']}+{pb['n_ep_neg']} eps)"
|
| 313 |
+
+ (f" | {spec['s_per_decision']:.3f} s/decision" if "s_per_decision" in spec else ""),
|
| 314 |
+
flush=True)
|
| 315 |
+
out["heads"][hname] = hres
|
| 316 |
+
|
| 317 |
+
Path(a.out).parent.mkdir(parents=True, exist_ok=True)
|
| 318 |
+
Path(a.out).write_text(json.dumps(out, indent=1))
|
| 319 |
+
np.savez_compressed(a.out.replace(".json", "_scores.npz"), **raw)
|
| 320 |
+
print(f"[destiny] wrote {a.out}", flush=True)
|
| 321 |
+
|
| 322 |
+
|
| 323 |
+
if __name__ == "__main__":
|
| 324 |
+
main()
|
gen_q_rsm/rsm_rise/pipeline/scripts/real/dirdump_screen.sh
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
# gen_q#278 -- DIRECTION DUMP for the S0/S2 diversity figure the owner asked for ("visualize all the 3D
|
| 3 |
+
# directions the end effector goes at the initial state anchors ... I want to see if it is actually diverse").
|
| 4 |
+
#
|
| 5 |
+
# SAME anchor grid, SAME proposer settings and the SAME edge classification as edge_screen.sh; the ONLY
|
| 6 |
+
# difference is that NO scorer checkpoint is passed, so scorer_openloop.py builds modes = ["greedy"] alone
|
| 7 |
+
# (scorer_openloop.py:170) and the run costs proposer sampling only. The per-episode edge_parts/*.npz
|
| 8 |
+
# therefore carry cand_disp_mm [n_anchor,N,3] / logged_disp_mm / ee_xyz_mm for an actor WITHOUT paying for a
|
| 9 |
+
# chain, which is what makes the actor-by-actor diversity table affordable.
|
| 10 |
+
#
|
| 11 |
+
# usage: EDGE_NAME=<tag> EDGE_POLICY=<openpi:cfg:ckpt> dirdump_screen.sh <shard-i> <shard-n>
|
| 12 |
+
set -uo pipefail
|
| 13 |
+
ROOT=/proj/dmfexp/zwhong/rsm_rise
|
| 14 |
+
I=${1:-0}; K=${2:-1}
|
| 15 |
+
NAME=${EDGE_NAME:?set EDGE_NAME}
|
| 16 |
+
POLICY=${EDGE_POLICY:?set EDGE_POLICY}
|
| 17 |
+
NCAND=${EDGE_NCAND:-128}
|
| 18 |
+
OUT=$ROOT/status/real/dir_$NAME
|
| 19 |
+
mkdir -p "$OUT"
|
| 20 |
+
exec $ROOT/scripts/real/run_env_openpi.sh $ROOT/scripts/real/scorer_openloop.py \
|
| 21 |
+
--policy "$POLICY" \
|
| 22 |
+
--n-cand "$NCAND" --horizon 8 --stride 25 \
|
| 23 |
+
--edge-test --edge-horizon 8 --edge-min-sep-deg 20 --edge-anchor-stride 5 \
|
| 24 |
+
--edge-anchor-radius-mm 30 --edge-anchor-min-support 20 \
|
| 25 |
+
--ep-shard "$I/$K" --tag "dir_$NAME" --out "$OUT"
|
gen_q_rsm/rsm_rise/pipeline/scripts/real/edge_AD_read.py
ADDED
|
@@ -0,0 +1,337 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
r"""#278 RUNG AD -- THE READER FOR THE GOAL-BOUND REPLICATION WAVE (SLURM 42197 ctrl / 42198 aug).
|
| 2 |
+
|
| 3 |
+
PUSHED BEFORE ANY SHARD OF THE `AD_aug` ARM EXISTED (the aug job was still PENDING on SLURM with an
|
| 4 |
+
empty output directory when this file was committed), so the statistic, the grouping and the
|
| 5 |
+
(a)/(b)/(c) reading below are fixed independently of the numbers they will be applied to. The reading
|
| 6 |
+
itself is NOT new: it is copied verbatim from the payload headers
|
| 7 |
+
scripts/real/payloads/edgeAD_{ctrl,aug}_s{0..3}.sh, which were pushed at run 36 (gen_q rsm_rise_data
|
| 8 |
+
7b3d2184) while both jobs were queued and zero shards existed. This file only mechanises it.
|
| 9 |
+
|
| 10 |
+
THE NUMBER THAT CHOSE THE WAVE (status/real/EDGE_GOALBOUND_AUC.json, LSF 1903087, 114 arms screened at
|
| 11 |
+
the common held-out S0 anchor set, leverage-free unweighted per-anchor Mann-Whitney AUC):
|
| 12 |
+
edge_U_aug AUG_invariant_t0p02_s0/ckpt_s100000.pt gb 0.740 [.676,.843] fail 0.561
|
| 13 |
+
edge_T_rise R_XL/ckpt_s100000.pt (CONTROL) gb 0.517 [.464,.578] fail 0.594
|
| 14 |
+
i.e. the augmented successor INVERTS the control's cell ordering -- but on EIGHT held-out goal-bound
|
| 15 |
+
episodes, whose exact paired p-floor 2/2^8 = 0.0078 sits above the screen's Bonferroni 0.05/114 =
|
| 16 |
+
0.00044. It is a SCREEN HIT. This wave re-measures the same one factor (the successor checkpoint,
|
| 17 |
+
everything else pinned to edge_T_rise) on 40 goal-bound TRAIN-split clusters, 5x the screen's 8.
|
| 18 |
+
|
| 19 |
+
CONTRACT: rise_stack/EDGE_TEST.md reserves held-out episodes for headline numbers and train-split
|
| 20 |
+
anchors for DEBUGGING. These 60 episodes are all train-split, so WHATEVER THIS PRINTS, the #278
|
| 21 |
+
verdict stays FAIL / CLOSED and the pre-registered bar is untouched. scorer_openloop.py excludes each
|
| 22 |
+
anchor episode from its own direction field (--ep-ids -> ep_excl), so a train episode cannot label
|
| 23 |
+
itself.
|
| 24 |
+
|
| 25 |
+
PRE-REGISTERED READING (from the payload headers, verbatim):
|
| 26 |
+
(a) REPLICATES: AUG goal-bound AUC_u > 0.5 with its 95 % cluster interval excluding 0.5 AND the paired
|
| 27 |
+
(rsm - permuted) interval excluding 0, on >= 25 goal-bound episodes.
|
| 28 |
+
(b) SPECIFIC: additionally (AUG - control) at goal-bound > (AUG - control) at the failure anchors,
|
| 29 |
+
intervals reported. If AUG beats the control in BOTH cells it is simply a better scorer and the
|
| 30 |
+
goal-bound framing is wrong; say so.
|
| 31 |
+
(c) DOES NOT REPLICATE: AUG goal-bound AUC_u falls to ~0.5 or its interval covers chance -> the run-35
|
| 32 |
+
hit was multiplicity over 114 arms at 8 clusters and the augmentation option is spent.
|
| 33 |
+
|
| 34 |
+
CAVEATS THAT TRAVEL WITH EVERY NUMBER HERE:
|
| 35 |
+
* run 33's candidate gate: the anchors are identical across arms but 45-99 % of the 128 candidates are
|
| 36 |
+
redrawn per arm, so a BETWEEN-ARM difference contains candidate sampling noise. Each arm's own
|
| 37 |
+
AUC vs its own greedy / permuted column is within-arm and unaffected. The paired between-arm cells
|
| 38 |
+
below are printed with that caveat attached and matched anchor-by-anchor (episode, anchor index,
|
| 39 |
+
verified on ee_xyz_mm) so at least the anchor set is common.
|
| 40 |
+
* "goal-bound" here means destiny = COOKING (routes 0->1->3, 0->2->3). No S0 episode reaches S4 --
|
| 41 |
+
route 2->3->4 does not start at S0 -- which is the owner's stitching point itself.
|
| 42 |
+
"""
|
| 43 |
+
import sys, os, json, glob
|
| 44 |
+
import numpy as np
|
| 45 |
+
|
| 46 |
+
sys.path.insert(0, "/proj/dmfexp/zwhong/rsm_rise/scripts/real")
|
| 47 |
+
from edge_ceiling2 import arm as ceiling_arm, auc as mw_auc
|
| 48 |
+
|
| 49 |
+
ROOT = "/proj/dmfexp/zwhong/rsm_rise/status/real"
|
| 50 |
+
SPLIT = json.load(open("/proj/dmfexp/zwhong/rsm_rise/data/derived/cooking_v5_split.json"))["episodes"]
|
| 51 |
+
# ---- run 39: the SAME reduction, pointable at a second arm pair by environment only. ----------------
|
| 52 |
+
# The statistic, the grouping, the bootstrap, the anchor matching and the (a)/(b)/(c) text below are
|
| 53 |
+
# UNTOUCHED. Only WHICH two arms and WHICH episode list are read can be overridden, so that the
|
| 54 |
+
# held-out re-read proposed on #278 (comment 5822434834, posted BEFORE this edit) uses byte-identical
|
| 55 |
+
# code to the train-split read it is compared against. With no environment set, every default is the
|
| 56 |
+
# rung-AD one and the published train-split verdict reproduces exactly.
|
| 57 |
+
EPS_FILE = os.environ.get("AD_EPS_FILE", f"{ROOT}/edge_gbrep_eps.txt")
|
| 58 |
+
EPS = [int(x) for x in open(EPS_FILE).read().replace(",", " ").split()]
|
| 59 |
+
CTRL = os.environ.get("AD_CTRL", "edge_AD_ctrl")
|
| 60 |
+
AUG = os.environ.get("AD_AUG", "edge_AD_aug")
|
| 61 |
+
SPLIT_LABEL = os.environ.get("AD_SPLIT_LABEL", "train (DEBUGGING)")
|
| 62 |
+
OUT_NAME = os.environ.get("AD_OUT", "EDGE_AD_GBREP.json")
|
| 63 |
+
NB, SEED = 20000, 0
|
| 64 |
+
MIN_GB_EPISODES = int(os.environ.get("AD_MIN_GB", "25")) # the rule's power gate, from the payload headers
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def sign_test(vals):
|
| 68 |
+
"""Two-sided exact paired sign test over episode-level differences. Pre-registered on #278
|
| 69 |
+
comment 5822434834 before this function existed, because a bootstrap percentile interval on ten
|
| 70 |
+
clusters is not a certification and the exact test's p-floor (2/2**n) must be printed beside it."""
|
| 71 |
+
v = np.asarray([x for x in vals if x == x and x != 0.0], float)
|
| 72 |
+
n = v.size
|
| 73 |
+
if n == 0:
|
| 74 |
+
return dict(n=0, n_pos=0, p=float("nan"), p_floor=float("nan"))
|
| 75 |
+
k = int((v > 0).sum())
|
| 76 |
+
from math import comb
|
| 77 |
+
tail = sum(comb(n, i) for i in range(0, min(k, n - k) + 1))
|
| 78 |
+
p = min(1.0, 2.0 * tail / (2.0 ** n))
|
| 79 |
+
return dict(n=n, n_pos=k, p=float(p), p_floor=float(2.0 / 2.0 ** n))
|
| 80 |
+
COLS = {"rsm": "score_rsm", "perm": "score_permuted__rsm",
|
| 81 |
+
"idql": "score_idql", "permi": "score_permuted__idql"}
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def destiny_of(e):
|
| 85 |
+
return "goalbound" if SPLIT[str(int(e))]["final_state"] in (3, 4) else "failure"
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
GB = [e for e in EPS if destiny_of(e) == "goalbound"]
|
| 89 |
+
FA = [e for e in EPS if destiny_of(e) == "failure"]
|
| 90 |
+
GROUPS = [("DEST_goalbound", GB), ("DEST_failure", FA), ("ALL", EPS)]
|
| 91 |
+
|
| 92 |
+
# --- rung AG (#278, pushed at zero shards): the S2 anchor set splits the "goalbound" label that S0
|
| 93 |
+
# forced on us. destiny_of() calls final_state in (3,4) goal-bound, but at S0 that can only ever mean
|
| 94 |
+
# COOKING -- no S0 episode reaches S4 (see the header). At S2 the two are genuinely different
|
| 95 |
+
# destinies, so AD_EXTRA_DESTINY=1 adds them as SEPARATE groups. It is a GROUPING, not a statistic:
|
| 96 |
+
# the AUC, the cluster bootstrap, the pairing and the sign test below are untouched, and with the
|
| 97 |
+
# variable unset GROUPS is byte-identical to the list that produced every published cell.
|
| 98 |
+
if os.environ.get("AD_EXTRA_DESTINY", "") not in ("", "0"):
|
| 99 |
+
G4 = [e for e in EPS if SPLIT[str(int(e))]["final_state"] == 4]
|
| 100 |
+
C3 = [e for e in EPS if SPLIT[str(int(e))]["final_state"] == 3]
|
| 101 |
+
GROUPS = ([("DEST_goal4", G4), ("DEST_cook3", C3)] + GROUPS)
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
# --- per_anchor / boot_matrix / ci are byte-identical to edge_goalbound_auc.py's (run 35, published) --
|
| 105 |
+
def per_anchor(d, keep):
|
| 106 |
+
"""Per-anchor Mann-Whitney AUC of on-route vs off-route candidates, per scorer.
|
| 107 |
+
Same loop, same filters, same `auc` as edge_ceiling2.arm -- only the aggregation differs."""
|
| 108 |
+
out = {k: [] for k in COLS}
|
| 109 |
+
out["greedy"] = []
|
| 110 |
+
EP, IDX, W, XYZ = [], [], [], []
|
| 111 |
+
for f in sorted(glob.glob(f"{d}/edge_parts/*.npz")):
|
| 112 |
+
e = int(f.split("/")[-1][2:-4])
|
| 113 |
+
if e not in keep:
|
| 114 |
+
continue
|
| 115 |
+
z = np.load(f, allow_pickle=True)
|
| 116 |
+
if "onroute" not in z.files:
|
| 117 |
+
continue
|
| 118 |
+
onr = np.asarray(z["onroute"], bool)
|
| 119 |
+
xyz = np.asarray(z["ee_xyz_mm"], np.float64) if "ee_xyz_mm" in z.files else None
|
| 120 |
+
for i in range(onr.shape[0]):
|
| 121 |
+
o = onr[i]
|
| 122 |
+
n = o.size
|
| 123 |
+
n_on = int(o.sum())
|
| 124 |
+
if not (0 < n_on < n):
|
| 125 |
+
continue
|
| 126 |
+
EP.append(e)
|
| 127 |
+
IDX.append(i)
|
| 128 |
+
XYZ.append(xyz[i] if xyz is not None else np.full(3, np.nan))
|
| 129 |
+
W.append((n - n_on) / (n - 1.0))
|
| 130 |
+
out["greedy"].append(mw_auc(-np.arange(n, dtype=float), o))
|
| 131 |
+
for k, key in COLS.items():
|
| 132 |
+
out[k].append(mw_auc(z[key][i].astype(np.float64), o) if key in z.files else np.nan)
|
| 133 |
+
return ({k: np.asarray(v) for k, v in out.items()}, np.asarray(EP, int),
|
| 134 |
+
np.asarray(IDX, int), np.asarray(W, float), np.asarray(XYZ, float))
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
def boot_matrix(EP, nb=NB, seed=SEED):
|
| 138 |
+
"""Cluster (episode) bootstrap as an exact count matrix: B[b,i] = times anchor i's episode drawn."""
|
| 139 |
+
u = np.unique(EP)
|
| 140 |
+
rng = np.random.default_rng(seed)
|
| 141 |
+
draw = rng.choice(u.size, (nb, u.size), replace=True)
|
| 142 |
+
cnt = np.zeros((nb, u.size), np.int32)
|
| 143 |
+
np.add.at(cnt, (np.repeat(np.arange(nb), u.size), draw.ravel()), 1)
|
| 144 |
+
idx = np.searchsorted(u, EP)
|
| 145 |
+
return cnt[:, idx].astype(np.float64), u.size
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
def ci(v, B, alpha=0.05):
|
| 149 |
+
"""Mean of v with a cluster-bootstrap percentile interval at level alpha (two-sided)."""
|
| 150 |
+
m = float(np.mean(v))
|
| 151 |
+
bm = (B @ v) / B.sum(1)
|
| 152 |
+
return m, float(np.percentile(bm, 100 * alpha / 2)), float(np.percentile(bm, 100 * (1 - alpha / 2)))
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
def eps_on_disk(a):
|
| 156 |
+
return {int(f.split("/")[-1][2:-4]) for f in glob.glob(f"{ROOT}/{a}/edge_parts/*.npz")}
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
# ---------------- what is on disk ----------------
|
| 160 |
+
have = {a: eps_on_disk(a) & set(EPS) for a in (CTRL, AUG)}
|
| 161 |
+
both = sorted(have[CTRL] & have[AUG])
|
| 162 |
+
gb_both = [e for e in both if destiny_of(e) == "goalbound"]
|
| 163 |
+
fa_both = [e for e in both if destiny_of(e) == "failure"]
|
| 164 |
+
print(f"RUNG AD reader -- anchor list {EPS_FILE}, {len(EPS)} {SPLIT_LABEL} episodes "
|
| 165 |
+
f"({len(GB)} goal-bound / {len(FA)} failure)")
|
| 166 |
+
for a in (CTRL, AUG):
|
| 167 |
+
g = len([e for e in have[a] if destiny_of(e) == "goalbound"])
|
| 168 |
+
print(f" {a:16s} {len(have[a]):3d}/{len(EPS)} episodes on disk ({g} goal-bound)")
|
| 169 |
+
print(f" common to BOTH arms: {len(both)} episodes ({len(gb_both)} goal-bound, {len(fa_both)} failure)")
|
| 170 |
+
COMPLETE = len(both) == len(EPS)
|
| 171 |
+
READABLE = len(gb_both) >= MIN_GB_EPISODES
|
| 172 |
+
if not COMPLETE:
|
| 173 |
+
print(f" ** PARTIAL: the wave is not finished. Every cell below is over the {len(both)} common "
|
| 174 |
+
f"episodes only and is a progress read, not the rung. **")
|
| 175 |
+
if not READABLE:
|
| 176 |
+
print(f" ** the rule's power gate (>= {MIN_GB_EPISODES} goal-bound episodes) is NOT met: "
|
| 177 |
+
f"{len(gb_both)}. NO VERDICT WILL BE PRINTED. **")
|
| 178 |
+
|
| 179 |
+
# ---------------- SELF-TEST, printed before any new number ----------------
|
| 180 |
+
print("\nSELF-TEST -- per-anchor AUCs must reproduce edge_ceiling2.arm() exactly (it produced every")
|
| 181 |
+
print("published ceiling/%ceil number), on the CONTROL arm of this wave, for every group:")
|
| 182 |
+
ok, ran = True, 0
|
| 183 |
+
for g, eps in GROUPS:
|
| 184 |
+
keep = set(eps) & have[CTRL]
|
| 185 |
+
if not keep:
|
| 186 |
+
print(f" {g:16s} no episodes on disk yet -- skipped")
|
| 187 |
+
continue
|
| 188 |
+
A, EP, IDX, W, XYZ = per_anchor(f"{ROOT}/{CTRL}", keep)
|
| 189 |
+
r = ceiling_arm(f"{ROOT}/{CTRL}", keep=keep)
|
| 190 |
+
w_rsm = float((W * A["rsm"]).sum() / W.sum())
|
| 191 |
+
d_rsm = float((W * (A["rsm"] - A["greedy"])).mean())
|
| 192 |
+
e1 = abs(w_rsm - r["auc_rsm"]["weighted"])
|
| 193 |
+
e2 = abs(d_rsm - r["d_vs_greedy_rsm"])
|
| 194 |
+
e3 = abs(len(W) - r["n_anchors"])
|
| 195 |
+
ok &= (e1 < 1e-12 and e2 < 1e-12 and e3 == 0)
|
| 196 |
+
ran += 1
|
| 197 |
+
print(f" {g:16s} n={len(W):4d} (harness {r['n_anchors']:4d}) AUCw err {e1:.2e} "
|
| 198 |
+
f"d_vs_greedy err {e2:.2e} [harness d_rsm {r['d_vs_greedy_rsm']:+.4f}]")
|
| 199 |
+
assert ran and ok, "self-test FAILED -- no number printed"
|
| 200 |
+
print(" PASS -- the reduction reads the same anchors and the same scores as every published cell.\n")
|
| 201 |
+
|
| 202 |
+
# ---------------- the table ----------------
|
| 203 |
+
res = {"_meta": dict(arms=[CTRL, AUG], nb=NB, seed=SEED, episodes=EPS, split=SPLIT_LABEL,
|
| 204 |
+
goalbound_episodes=GB, failure_episodes=FA,
|
| 205 |
+
on_disk={a: sorted(have[a]) for a in (CTRL, AUG)},
|
| 206 |
+
common_episodes=both, complete=bool(COMPLETE), readable=bool(READABLE),
|
| 207 |
+
min_gb_episodes=MIN_GB_EPISODES,
|
| 208 |
+
note="UNWEIGHTED per-anchor Mann-Whitney AUC, on-route vs off-route candidates; "
|
| 209 |
+
"chance 0.5; TRAIN-split debugging read, NOT the pre-registered bar")}
|
| 210 |
+
PAIR = {}
|
| 211 |
+
for g, eps in GROUPS:
|
| 212 |
+
keep = set(eps) & set(both)
|
| 213 |
+
print(f"\n### GROUP {g} ({len(keep)} episodes common to both arms)")
|
| 214 |
+
if not keep:
|
| 215 |
+
print(" (nothing on disk for both arms yet)")
|
| 216 |
+
continue
|
| 217 |
+
hdr = (f"{'arm':16s} {'ep':>2s} {'anc':>4s} {'w_bar':>6s} | {'AUCu_rsm':>8s} {'raw95':>17s} | "
|
| 218 |
+
f"{'greedy':>6s} {'perm':>6s} {'idql':>6s} | {'rsm-perm':>9s} {'raw95':>17s}")
|
| 219 |
+
print(hdr)
|
| 220 |
+
print("-" * len(hdr))
|
| 221 |
+
res[g] = {}
|
| 222 |
+
store = {}
|
| 223 |
+
for a in (CTRL, AUG):
|
| 224 |
+
A, EP, IDX, W, XYZ = per_anchor(f"{ROOT}/{a}", keep)
|
| 225 |
+
store[a] = (A, EP, IDX, W, XYZ)
|
| 226 |
+
B, nep = boot_matrix(EP)
|
| 227 |
+
m, lo, hi = ci(A["rsm"], B)
|
| 228 |
+
dp, dplo, dphi = ci(A["rsm"] - A["perm"], B)
|
| 229 |
+
dg, dglo, dghi = ci(A["rsm"] - A["greedy"], B)
|
| 230 |
+
res[g][a] = dict(n_episodes=int(nep), n_anchors=int(len(W)), w_bar=float(W.mean()),
|
| 231 |
+
auc_rsm=m, auc_rsm_raw95=[lo, hi],
|
| 232 |
+
auc_greedy=float(A["greedy"].mean()),
|
| 233 |
+
auc_perm=float(np.nanmean(A["perm"])),
|
| 234 |
+
auc_idql=float(np.nanmean(A["idql"])),
|
| 235 |
+
d_rsm_perm=dp, d_rsm_perm_raw95=[dplo, dphi],
|
| 236 |
+
d_rsm_greedy=dg, d_rsm_greedy_raw95=[dglo, dghi],
|
| 237 |
+
clears=bool(lo > 0.5 and dplo > 0.0))
|
| 238 |
+
star = " *" if res[g][a]["clears"] else " "
|
| 239 |
+
print(f"{a:16s} {nep:2d} {len(W):4d} {W.mean():6.3f} | {m:8.3f} [{lo:+.3f},{hi:+.3f}] | "
|
| 240 |
+
f"{A['greedy'].mean():6.3f} {np.nanmean(A['perm']):6.3f} {np.nanmean(A['idql']):6.3f} | "
|
| 241 |
+
f"{dp:+9.4f} [{dplo:+.3f},{dphi:+.3f}]{star}")
|
| 242 |
+
|
| 243 |
+
# ---- paired AUG - CTRL at matched anchors (same episode, same anchor index, ee_xyz verified) ----
|
| 244 |
+
(Ac, EPc, IXc, Wc, Xc), (Aa, EPa, IXa, Wa, Xa) = store[CTRL], store[AUG]
|
| 245 |
+
kc = {(e, i): j for j, (e, i) in enumerate(zip(EPc, IXc))}
|
| 246 |
+
ja, jc = [], []
|
| 247 |
+
for j, (e, i) in enumerate(zip(EPa, IXa)):
|
| 248 |
+
if (e, i) in kc:
|
| 249 |
+
ja.append(j)
|
| 250 |
+
jc.append(kc[(e, i)])
|
| 251 |
+
ja, jc = np.asarray(ja, int), np.asarray(jc, int)
|
| 252 |
+
if len(ja):
|
| 253 |
+
dxyz = float(np.nanmax(np.abs(Xa[ja] - Xc[jc]))) if len(ja) else float("nan")
|
| 254 |
+
assert not (dxyz > 1e-3), f"matched anchors disagree on ee_xyz_mm by {dxyz:.4g} mm"
|
| 255 |
+
Bp, nepp = boot_matrix(EPa[ja])
|
| 256 |
+
d, dlo, dhi = ci(Aa["rsm"][ja] - Ac["rsm"][jc], Bp)
|
| 257 |
+
PAIR[g] = dict(n_anchors=int(len(ja)), n_episodes=int(nepp), d=d, raw95=[dlo, dhi],
|
| 258 |
+
max_ee_xyz_mismatch_mm=dxyz,
|
| 259 |
+
per_ep=[float(x) for x in
|
| 260 |
+
[np.mean((Aa["rsm"][ja] - Ac["rsm"][jc])[EPa[ja] == e])
|
| 261 |
+
for e in np.unique(EPa[ja])]],
|
| 262 |
+
eps=[int(e) for e in np.unique(EPa[ja])])
|
| 263 |
+
PAIR[g]["sign_test"] = sign_test(PAIR[g]["per_ep"])
|
| 264 |
+
res[g]["_paired_aug_minus_ctrl"] = PAIR[g]
|
| 265 |
+
st = PAIR[g]["sign_test"]
|
| 266 |
+
print(f" exact paired sign test: {st['n_pos']}/{st['n']} episodes positive, "
|
| 267 |
+
f"p={st['p']:.2e} (floor 2/2**{st['n']} = {st['p_floor']:.2e})")
|
| 268 |
+
print(f"{'AUG - CTRL (paired)':16s} {nepp:2d} {len(ja):4d} {'':6s} | {d:+8.4f} "
|
| 269 |
+
f"[{dlo:+.3f},{dhi:+.3f}] | anchors matched exactly (max ee_xyz gap {dxyz:.1e} mm); "
|
| 270 |
+
f"CANDIDATES ARE REDRAWN PER ARM (run 33 gate)")
|
| 271 |
+
|
| 272 |
+
# ---------------- specificity: difference-in-differences ----------------
|
| 273 |
+
DID = None
|
| 274 |
+
if "DEST_goalbound" in PAIR and "DEST_failure" in PAIR:
|
| 275 |
+
dg_, dgl, dgh = PAIR["DEST_goalbound"]["d"], *PAIR["DEST_goalbound"]["raw95"]
|
| 276 |
+
df_, dfl, dfh = PAIR["DEST_failure"]["d"], *PAIR["DEST_failure"]["raw95"]
|
| 277 |
+
# cluster bootstrap of the contrast itself: resample episodes WITHIN each cell independently
|
| 278 |
+
pg = np.asarray(PAIR["DEST_goalbound"]["per_ep"])
|
| 279 |
+
pf = np.asarray(PAIR["DEST_failure"]["per_ep"])
|
| 280 |
+
rng = np.random.default_rng(SEED)
|
| 281 |
+
bg = pg[rng.integers(0, pg.size, (NB, pg.size))].mean(1)
|
| 282 |
+
bf = pf[rng.integers(0, pf.size, (NB, pf.size))].mean(1)
|
| 283 |
+
did = float(pg.mean() - pf.mean())
|
| 284 |
+
dlo, dhi = (float(np.percentile(bg - bf, 2.5)), float(np.percentile(bg - bf, 97.5)))
|
| 285 |
+
DID = dict(did=did, raw95=[dlo, dhi], gb=float(pg.mean()), fail=float(pf.mean()),
|
| 286 |
+
n_gb_eps=int(pg.size), n_fail_eps=int(pf.size))
|
| 287 |
+
res["_specificity_did"] = DID
|
| 288 |
+
print(f"\nSPECIFICITY (rule (b)): (AUG-CTRL)|goal-bound - (AUG-CTRL)|failure = {did:+.4f} "
|
| 289 |
+
f"[{dlo:+.3f},{dhi:+.3f}] (gb {pg.mean():+.4f} on {pg.size} eps, "
|
| 290 |
+
f"fail {pf.mean():+.4f} on {pf.size} eps; episode-level cluster bootstrap)")
|
| 291 |
+
|
| 292 |
+
# ---------------- the mechanical reading ----------------
|
| 293 |
+
print("\n" + "=" * 100)
|
| 294 |
+
if not READABLE:
|
| 295 |
+
print(f"NO VERDICT: the rule needs >= {MIN_GB_EPISODES} goal-bound episodes common to both arms; "
|
| 296 |
+
f"{len(gb_both)} are on disk. Re-run when the wave finishes.")
|
| 297 |
+
else:
|
| 298 |
+
G = res["DEST_goalbound"]
|
| 299 |
+
a = G[AUG]
|
| 300 |
+
rep = bool(a["auc_rsm_raw95"][0] > 0.5 and a["d_rsm_perm_raw95"][0] > 0.0)
|
| 301 |
+
if rep:
|
| 302 |
+
spec = bool(DID and DID["raw95"][0] > 0.0)
|
| 303 |
+
both_cells = bool(res["DEST_failure"][AUG]["auc_rsm_raw95"][0] > 0.5)
|
| 304 |
+
print(f"READING (a) FIRES -- REPLICATES: AUG goal-bound AUC_u {a['auc_rsm']:.3f} "
|
| 305 |
+
f"raw95 {['%+.3f' % x for x in a['auc_rsm_raw95']]} (chance 0.5) and paired rsm-permuted "
|
| 306 |
+
f"{a['d_rsm_perm']:+.4f} {['%+.3f' % x for x in a['d_rsm_perm_raw95']]} on "
|
| 307 |
+
f"{a['n_episodes']} goal-bound clusters; control {G[CTRL]['auc_rsm']:.3f} "
|
| 308 |
+
f"{['%+.3f' % x for x in G[CTRL]['auc_rsm_raw95']]}.")
|
| 309 |
+
if spec and not both_cells:
|
| 310 |
+
print(" (b) SPECIFIC: the gain is larger at the goal-bound anchors than at the failure "
|
| 311 |
+
f"anchors, DiD {DID['did']:+.4f} {['%+.3f' % x for x in DID['raw95']]} -- "
|
| 312 |
+
"augmentation acts exactly where the pooled leverage-weighted metric cannot see it.")
|
| 313 |
+
elif both_cells:
|
| 314 |
+
print(" (b) NOT SPECIFIC: AUG also clears chance at the FAILURE anchors "
|
| 315 |
+
f"({res['DEST_failure'][AUG]['auc_rsm']:.3f}) -- it is simply a better scorer and the "
|
| 316 |
+
"goal-bound framing is WRONG; say so.")
|
| 317 |
+
else:
|
| 318 |
+
print(f" (b) SPECIFICITY NOT ESTABLISHED: DiD {DID['did'] if DID else float('nan'):+.4f} "
|
| 319 |
+
f"{(['%+.3f' % x for x in DID['raw95']]) if DID else 'n/a'} covers 0.")
|
| 320 |
+
print(f" SPLIT = {SPLIT_LABEL}. It cannot move the #278 verdict, which is the "
|
| 321 |
+
"LEVERAGE-WEIGHTED clause-2 number on the S0 held-out set (+0.0135 [-0.0249,+0.0612], "
|
| 322 |
+
"rung U).")
|
| 323 |
+
else:
|
| 324 |
+
print(f"READING (c) FIRES -- DOES NOT REPLICATE: AUG goal-bound AUC_u {a['auc_rsm']:.3f} "
|
| 325 |
+
f"raw95 {['%+.3f' % x for x in a['auc_rsm_raw95']]}, paired rsm-permuted "
|
| 326 |
+
f"{a['d_rsm_perm']:+.4f} {['%+.3f' % x for x in a['d_rsm_perm_raw95']]}, on "
|
| 327 |
+
f"{a['n_episodes']} goal-bound clusters (5x the screen's 8). The run-35 hit "
|
| 328 |
+
"(0.740 [.676,.843] at 8 clusters) was multiplicity over 114 arms. The closed negative "
|
| 329 |
+
"is untouched and the augmentation lead is SPENT.")
|
| 330 |
+
print("=" * 100)
|
| 331 |
+
print("\nThe pre-registered #278 verdict is UNCHANGED and is not a function of anything above:")
|
| 332 |
+
print(" clause 1 coverage 0.904 PASS | clause 2 +0.0909 [+0.0373,+0.1480] vs +0.10 FAIL | "
|
| 333 |
+
"clause 3 flip 0.745 vs greedy 0.519 PASS -> CONJUNCTION FAIL, #278 stays CLOSED.")
|
| 334 |
+
|
| 335 |
+
out = f"{ROOT}/{OUT_NAME}"
|
| 336 |
+
json.dump(res, open(out, "w"), indent=1, default=float)
|
| 337 |
+
print("\nwrote", out)
|
gen_q_rsm/rsm_rise/pipeline/scripts/real/edge_AH_read.py
ADDED
|
@@ -0,0 +1,256 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
r"""#278 RUNG AH -- IS THE S2 RESULT A *CONSTANT* DIRECTION PREFERENCE?
|
| 2 |
+
|
| 3 |
+
WHY THIS MEASUREMENT, WITH THE NUMBER THAT CHOSE IT (rung AG, SLURM 42623 -> 43081,
|
| 4 |
+
status/real/EDGE_AG_SEED0.json, logs/slurm/rr_cpu_edgeAG_read.43081.out):
|
| 5 |
+
|
| 6 |
+
S2 held-out anchors, CONTROL arm (shipped successor R_XL), unweighted per-anchor AUC of the
|
| 7 |
+
on-route candidates vs the off-route ones:
|
| 8 |
+
DEST_goal4 (route 2->3->4, on-route edge 2->3) AUC_u 0.246 [+0.159,+0.334] 45 anchors / 5 eps
|
| 9 |
+
DEST_cook3 (route 0->2->3, on-route edge 2->3) AUC_u 0.319 [+0.260,+0.567] 23 anchors / 4 eps
|
| 10 |
+
DEST_failure (route 0->2->6, on-route edge 2->6) AUC_u 0.690 [+0.633,+0.754] 65 anchors / 5 eps
|
| 11 |
+
The four augmented seeds show the same split (goal4 0.194/0.20/0.27/0.29, failure 0.54/../..).
|
| 12 |
+
|
| 13 |
+
Those two cells are NOT independent claims. At S2 there are exactly two available edges, 2->3 and
|
| 14 |
+
2->6, and "on-route" is defined relative to the EPISODE'S OWN route: it is 2->3 in the goal-bound
|
| 15 |
+
groups and 2->6 in the failure group. So a scorer with a SINGLE FIXED preference for the 2->6
|
| 16 |
+
direction -- one that ignores the anchor state entirely -- scores AUC ~ 0.25 in the goal-bound cells
|
| 17 |
+
and ~ 0.75 in the failure cell BY ARITHMETIC, without conditioning on anything. 0.246 and 0.690 are
|
| 18 |
+
very close to exactly that pattern.
|
| 19 |
+
|
| 20 |
+
If that is what is happening, then the failure-cell positives this project has published (rung AG
|
| 21 |
+
ctrl d_rsm +0.170 at DEST_failure, and the pooled +0.0434 that is positive only because of it) are
|
| 22 |
+
NOT evidence of planning, and the negative on #278 is localised much more sharply than "the scorer
|
| 23 |
+
ranks at chance": the scorer has NO state-conditional direction preference at the branch at all.
|
| 24 |
+
|
| 25 |
+
THIS FILE MEASURES THAT DIRECTLY, WITH ONE FIXED EDGE NAME. For every contrastive S2 anchor it
|
| 26 |
+
computes the scorer's preference for the edge literally named "2->6" -- the SAME edge in every group,
|
| 27 |
+
so the quantity no longer moves when the episode's destiny changes:
|
| 28 |
+
rp26 = mean rank percentile (edge_field.rank_pct, the published function) of the candidates
|
| 29 |
+
classified into "2->6", among that anchor's 128 candidates;
|
| 30 |
+
top1_26 = 1 if the top-scored candidate is classified into "2->6", else 0.
|
| 31 |
+
Both are aggregated per destiny group with the SAME episode-level cluster bootstrap used by
|
| 32 |
+
edge_AD_read.py (boot_matrix / ci imported from it, not reimplemented).
|
| 33 |
+
|
| 34 |
+
PRE-REGISTERED READING (fixed before this file was run; the rule is on rp26 under the `rsm` scorer,
|
| 35 |
+
the others are reported as nulls and context):
|
| 36 |
+
(A) CONSTANT DIRECTION PREFERENCE -- rp26 is on the same side of 0.5 in the goal-bound groups and in
|
| 37 |
+
the failure group, AND the difference rp26(failure) - rp26(goal-bound) has its 95 % cluster
|
| 38 |
+
interval COVERING 0. Reading: the S2 AUC split is arithmetic, the scorer does not condition on
|
| 39 |
+
the anchor, and every failure-cell positive published on this test is an artefact of the
|
| 40 |
+
on-route label tracking the episode's route. Say that plainly.
|
| 41 |
+
(B) DESTINY-CONDITIONED -- rp26(failure) - rp26(goal-bound) > 0 with its interval EXCLUDING 0. The
|
| 42 |
+
scorer does condition on the state; the #278 negative is then about the SIZE of the effect, not
|
| 43 |
+
about the absence of conditioning, and the next rung stays on the scorer's capacity.
|
| 44 |
+
(C) INVERTED -- the difference is < 0 with its interval excluding 0. That is a sign defect in the
|
| 45 |
+
labels or the fields and must be hunted before any further scorer work.
|
| 46 |
+
Ceiling/floor context printed beside every cell: `greedy_idx` (the proposer's own order, an unbiased
|
| 47 |
+
draw -> 0.5) and `random`. A null that is itself off 0.5 means the CANDIDATE POOL is imbalanced and
|
| 48 |
+
is reported as such.
|
| 49 |
+
|
| 50 |
+
SCOPE. This is a READ of arrays already on disk (status/real/edge_AG_*/edge_parts/*.npz, written by
|
| 51 |
+
SLURM 42623). No model runs, no checkpoint is loaded, nothing is retrained and no pre-registered
|
| 52 |
+
quantity is altered. The #278 verdict is a function of clause 2 (the leverage-weighted held-out S0
|
| 53 |
+
d_vs_greedy, +0.0135 [-0.0249,+0.0612] at rung U) and CANNOT be changed by anything printed here --
|
| 54 |
+
#278 stays CLOSED whichever clause fires.
|
| 55 |
+
|
| 56 |
+
CAVEATS THAT TRAVEL WITH THESE NUMBERS:
|
| 57 |
+
* the anchors are the harness's own contrastive anchors (0 < onroute.sum() < n_cand), the same gate
|
| 58 |
+
behind every published cell, so these rows are the same anchors as rung AG's;
|
| 59 |
+
* candidates are REDRAWN per arm (run 33), so between-ARM comparisons carry sampling noise; the
|
| 60 |
+
rule above is a WITHIN-ARM comparison between destiny groups and is not affected by that;
|
| 61 |
+
* DEST_goal4 has at most 5 held-out clusters and DEST_cook3 at most 5, so intervals are wide by
|
| 62 |
+
construction; the rule is written to be readable at that power because (A) is the hypothesis that
|
| 63 |
+
the two cells MOVE TOGETHER, which the pooled goal-bound group (up to 9 clusters) can support.
|
| 64 |
+
"""
|
| 65 |
+
import os, sys, json, glob
|
| 66 |
+
import numpy as np
|
| 67 |
+
|
| 68 |
+
sys.path.insert(0, "/proj/dmfexp/zwhong/rsm_rise/scripts/real")
|
| 69 |
+
from edge_field import rank_pct # the published rank-percentile, unmodified
|
| 70 |
+
|
| 71 |
+
# The cluster bootstrap and the interval are NOT reimplemented here: the two functions are LIFTED
|
| 72 |
+
# VERBATIM out of scripts/real/edge_AD_read.py (the file that produced every published rung
|
| 73 |
+
# AD/AE/AF/AG cell) by source extraction, so they are byte-identical by construction rather than by
|
| 74 |
+
# inspection. edge_AD_read.py cannot simply be imported -- it runs its whole analysis at module
|
| 75 |
+
# level -- so the two function definitions are located with `ast` and exec'd on their own.
|
| 76 |
+
import ast as _ast
|
| 77 |
+
_SRC = open("/proj/dmfexp/zwhong/rsm_rise/scripts/real/edge_AD_read.py").read()
|
| 78 |
+
_TREE = _ast.parse(_SRC)
|
| 79 |
+
_LIFT = {n.name: _ast.get_source_segment(_SRC, n) for n in _TREE.body
|
| 80 |
+
if isinstance(n, _ast.FunctionDef) and n.name in ("boot_matrix", "ci")}
|
| 81 |
+
assert set(_LIFT) == {"boot_matrix", "ci"}, _LIFT.keys()
|
| 82 |
+
# NB/SEED must exist before the exec: boot_matrix's signature is `def boot_matrix(EP, nb=NB,
|
| 83 |
+
# seed=SEED)` and Python binds those defaults at definition time. 20000/0 are edge_AD_read.py's own
|
| 84 |
+
# values, asserted against its source below so a drift there cannot pass silently.
|
| 85 |
+
assert "NB, SEED = 20000, 0" in _SRC, "edge_AD_read.py changed its bootstrap constants"
|
| 86 |
+
_NS = {"np": np, "NB": 20000, "SEED": 0}
|
| 87 |
+
for _n in ("boot_matrix", "ci"):
|
| 88 |
+
exec(compile(_LIFT[_n], "edge_AD_read.py::" + _n, "exec"), _NS)
|
| 89 |
+
boot_matrix, ci = _NS["boot_matrix"], _NS["ci"]
|
| 90 |
+
SPLIT = json.load(open("/proj/dmfexp/zwhong/rsm_rise/data/derived/cooking_v5_split.json"))["episodes"]
|
| 91 |
+
|
| 92 |
+
ROOT = "/proj/dmfexp/zwhong/rsm_rise/status/real"
|
| 93 |
+
EPS_FILE = os.environ.get("AH_EPS_FILE", f"{ROOT}/edge_heldout_eps.txt")
|
| 94 |
+
EPS = [int(x) for x in open(EPS_FILE).read().replace(",", " ").split()]
|
| 95 |
+
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(",")
|
| 96 |
+
EDGE = os.environ.get("AH_EDGE", "2->6") # the ONE fixed edge name the rule is written on
|
| 97 |
+
OUT_NAME = os.environ.get("AH_OUT", "EDGE_AH_CONSTPREF.json")
|
| 98 |
+
NB, SEED = 20000, 0
|
| 99 |
+
|
| 100 |
+
COLS = {"rsm": "score_rsm", "perm": "score_permuted__rsm",
|
| 101 |
+
"idql": "score_idql", "permi": "score_permuted__idql"}
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def destiny3(e):
|
| 105 |
+
fs = SPLIT[str(int(e))]["final_state"]
|
| 106 |
+
return "DEST_goal4" if fs == 4 else ("DEST_cook3" if fs == 3 else "DEST_failure")
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def read_arm(d, keep, edge):
|
| 110 |
+
"""per contrastive anchor: rank-pct and top-1 indicator for the FIXED edge name `edge`."""
|
| 111 |
+
rp = {k: [] for k in COLS}
|
| 112 |
+
t1 = {k: [] for k in COLS}
|
| 113 |
+
rp["greedy_idx"], t1["greedy_idx"], rp["random"], t1["random"] = [], [], [], []
|
| 114 |
+
EP, IDX, AVAIL_OK, NSEL = [], [], [], []
|
| 115 |
+
rng = np.random.default_rng(SEED)
|
| 116 |
+
for f in sorted(glob.glob(f"{d}/edge_parts/*.npz")):
|
| 117 |
+
e = int(f.split("/")[-1][2:-4])
|
| 118 |
+
if e not in keep:
|
| 119 |
+
continue
|
| 120 |
+
z = np.load(f, allow_pickle=True)
|
| 121 |
+
if "onroute" not in z.files:
|
| 122 |
+
continue
|
| 123 |
+
meta = json.loads(bytes(z["__meta__"]).decode())
|
| 124 |
+
onr = np.asarray(z["onroute"], bool)
|
| 125 |
+
cls = np.asarray(z["cls"], int)
|
| 126 |
+
for i in range(onr.shape[0]):
|
| 127 |
+
o, c = onr[i], cls[i]
|
| 128 |
+
n = o.size
|
| 129 |
+
if not (0 < int(o.sum()) < n): # the harness's own contrastive gate
|
| 130 |
+
continue
|
| 131 |
+
av = meta[i]["avail"]
|
| 132 |
+
# rung AI (#278): AH_EDGE=__TRUE__ selects the edge THIS EPISODE ACTUALLY TOOK, so the
|
| 133 |
+
# quantity is "how does the scorer rank the expert's own direction" and is comparable
|
| 134 |
+
# across destiny groups without the global-ON_ROUTE confusion that rung AH's prose had.
|
| 135 |
+
e_here = meta[i]["true_edge"] if edge == "__TRUE__" else edge
|
| 136 |
+
if e_here not in av:
|
| 137 |
+
AVAIL_OK.append(False)
|
| 138 |
+
continue
|
| 139 |
+
sel = (c == av.index(e_here))
|
| 140 |
+
if not (0 < int(sel.sum()) < n): # the fixed edge must also be contrastive here
|
| 141 |
+
continue
|
| 142 |
+
AVAIL_OK.append(True)
|
| 143 |
+
EP.append(e); IDX.append(i); NSEL.append(int(sel.sum()))
|
| 144 |
+
for k, key in COLS.items():
|
| 145 |
+
if key not in z.files:
|
| 146 |
+
rp[k].append(np.nan); t1[k].append(np.nan); continue
|
| 147 |
+
s = z[key][i].astype(np.float64)
|
| 148 |
+
rp[k].append(float(rank_pct(s)[sel].mean()))
|
| 149 |
+
t1[k].append(float(sel[int(np.argmax(s))]))
|
| 150 |
+
s = -np.arange(n, dtype=float) # greedy_idx: candidate 0 wins -> unbiased draw
|
| 151 |
+
rp["greedy_idx"].append(float(rank_pct(s)[sel].mean()))
|
| 152 |
+
t1["greedy_idx"].append(float(sel[int(np.argmax(s))]))
|
| 153 |
+
s = rng.permutation(n).astype(float)
|
| 154 |
+
rp["random"].append(float(rank_pct(s)[sel].mean()))
|
| 155 |
+
t1["random"].append(float(sel[int(np.argmax(s))]))
|
| 156 |
+
return ({k: np.asarray(v, float) for k, v in rp.items()},
|
| 157 |
+
{k: np.asarray(v, float) for k, v in t1.items()},
|
| 158 |
+
np.asarray(EP, int), np.asarray(IDX, int), np.asarray(NSEL, float),
|
| 159 |
+
int(len(AVAIL_OK) - sum(AVAIL_OK)))
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
def cell(v, EP):
|
| 163 |
+
B, nclu = boot_matrix(EP, NB, SEED)
|
| 164 |
+
m, lo, hi = ci(v, B)
|
| 165 |
+
return dict(mean=m, lo=lo, hi=hi, n=int(v.size), n_clusters=int(nclu))
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
def diff_cell(v, EP, mask_a, mask_b):
|
| 169 |
+
"""mean(v[a]) - mean(v[b]) with ONE cluster bootstrap over the union of episodes (paired by
|
| 170 |
+
episode resample, the same construction edge_AD_read.py uses for its DiD)."""
|
| 171 |
+
EPu = EP
|
| 172 |
+
B, nclu = boot_matrix(EPu, NB, SEED)
|
| 173 |
+
wa, wb = mask_a.astype(float), mask_b.astype(float)
|
| 174 |
+
num_a, den_a = (B * (v * wa)).sum(1), (B * wa).sum(1)
|
| 175 |
+
num_b, den_b = (B * (v * wb)).sum(1), (B * wb).sum(1)
|
| 176 |
+
ok = (den_a > 0) & (den_b > 0)
|
| 177 |
+
d = num_a[ok] / den_a[ok] - num_b[ok] / den_b[ok]
|
| 178 |
+
m = float(v[mask_a].mean() - v[mask_b].mean())
|
| 179 |
+
return dict(mean=m, lo=float(np.percentile(d, 2.5)), hi=float(np.percentile(d, 97.5)),
|
| 180 |
+
n_a=int(mask_a.sum()), n_b=int(mask_b.sum()), n_boot_ok=int(ok.sum()))
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
def fmt(c):
|
| 184 |
+
return f"{c['mean']:+.4f} [{c['lo']:+.4f},{c['hi']:+.4f}]"
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
def main():
|
| 188 |
+
print(__doc__.split("PRE-REGISTERED READING")[0].strip()[:0] or "", end="")
|
| 189 |
+
print(f"RUNG AH -- constant-direction-preference diagnostic on the FIXED edge '{EDGE}'")
|
| 190 |
+
print(f" anchors: {EPS_FILE} ({len(EPS)} episodes) arms: {', '.join(ARMS)}")
|
| 191 |
+
print(f" rp{EDGE} = mean rank percentile of the candidates classified into '{EDGE}';"
|
| 192 |
+
f" top1 = the top-scored candidate is in '{EDGE}'.")
|
| 193 |
+
print(" A scorer with a single fixed preference for this edge gives the SAME rp in every"
|
| 194 |
+
" destiny group.\n")
|
| 195 |
+
out = {"edge": EDGE, "eps_file": EPS_FILE, "arms": {}}
|
| 196 |
+
for arm in ARMS:
|
| 197 |
+
rp, t1, EP, IDX, NSEL, n_skip = read_arm(f"{ROOT}/{arm}", set(EPS), EDGE)
|
| 198 |
+
if EP.size == 0:
|
| 199 |
+
print(f"### {arm}: no anchors\n"); continue
|
| 200 |
+
dst = np.array([destiny3(e) for e in EP])
|
| 201 |
+
gb = (dst == "DEST_goal4") | (dst == "DEST_cook3")
|
| 202 |
+
fa = (dst == "DEST_failure")
|
| 203 |
+
print(f"### ARM {arm} {EP.size} contrastive anchors / {len(set(EP.tolist()))} episodes "
|
| 204 |
+
f"(skipped {n_skip} anchors where '{EDGE}' was unavailable); "
|
| 205 |
+
f"mean candidates in '{EDGE}' {NSEL.mean():.1f} of 128")
|
| 206 |
+
print(f"{'scorer':<12} {'DEST_goal4':<26} {'DEST_cook3':<26} {'goal-bound pooled':<26} "
|
| 207 |
+
f"{'DEST_failure':<26} {'fail - goalbound':<26}")
|
| 208 |
+
arec = {}
|
| 209 |
+
for k in ["rsm", "perm", "idql", "permi", "greedy_idx", "random"]:
|
| 210 |
+
v = rp[k]
|
| 211 |
+
if not np.isfinite(v).any():
|
| 212 |
+
continue
|
| 213 |
+
cells = {g: cell(v[dst == g], EP[dst == g]) for g in ("DEST_goal4", "DEST_cook3", "DEST_failure")}
|
| 214 |
+
cells["GOALBOUND"] = cell(v[gb], EP[gb])
|
| 215 |
+
dif = diff_cell(v, EP, fa, gb)
|
| 216 |
+
arec[k] = {"rp": {g: cells[g] for g in cells}, "rp_diff_fail_minus_goalbound": dif,
|
| 217 |
+
"top1": {g: cell(t1[k][dst == g], EP[dst == g]) for g in
|
| 218 |
+
("DEST_goal4", "DEST_cook3", "DEST_failure")}}
|
| 219 |
+
print(f"{k:<12} {fmt(cells['DEST_goal4']):<26} {fmt(cells['DEST_cook3']):<26} "
|
| 220 |
+
f"{fmt(cells['GOALBOUND']):<26} {fmt(cells['DEST_failure']):<26} {fmt(dif):<26}")
|
| 221 |
+
print(f"{'top1 rsm':<12} "
|
| 222 |
+
+ " ".join(f"{g.split('_')[1]} {arec['rsm']['top1'][g]['mean']:.3f}"
|
| 223 |
+
for g in ('DEST_goal4', 'DEST_cook3', 'DEST_failure')))
|
| 224 |
+
d = arec["rsm"]["rp_diff_fail_minus_goalbound"]
|
| 225 |
+
gbm, fam = arec["rsm"]["rp"]["GOALBOUND"]["mean"], arec["rsm"]["rp"]["DEST_failure"]["mean"]
|
| 226 |
+
same_side = (gbm - 0.5) * (fam - 0.5) > 0
|
| 227 |
+
if d["lo"] <= 0.0 <= d["hi"] and same_side:
|
| 228 |
+
verdict = ("(A) CONSTANT DIRECTION PREFERENCE -- rp is on the same side of 0.5 in both "
|
| 229 |
+
f"destinies (goal-bound {gbm:.3f}, failure {fam:.3f}) and their difference "
|
| 230 |
+
f"{fmt(d)} covers 0. The S2 AUC split is arithmetic: the scorer does not "
|
| 231 |
+
"condition on the anchor, and the failure-cell positives are an artefact of "
|
| 232 |
+
"the on-route label tracking the episode's route.")
|
| 233 |
+
elif d["lo"] > 0.0:
|
| 234 |
+
verdict = ("(B) DESTINY-CONDITIONED -- rp is higher on the failure route "
|
| 235 |
+
f"{fmt(d)}, interval excludes 0. The scorer DOES condition on the state; "
|
| 236 |
+
"the #278 negative is about the size of the effect, not its absence.")
|
| 237 |
+
elif d["hi"] < 0.0:
|
| 238 |
+
verdict = ("(C) INVERTED -- rp is LOWER on the failure route " + fmt(d) +
|
| 239 |
+
", interval excludes 0. A sign defect in the labels or the fields; hunt it "
|
| 240 |
+
"before any further scorer work.")
|
| 241 |
+
else:
|
| 242 |
+
verdict = ("(A-partial) the difference " + fmt(d) + " covers 0 but the two destinies are "
|
| 243 |
+
f"NOT on the same side of 0.5 (goal-bound {gbm:.3f}, failure {fam:.3f}): "
|
| 244 |
+
"consistent with a constant preference too weak to place, not with conditioning.")
|
| 245 |
+
print(" READING " + verdict + "\n")
|
| 246 |
+
arec["verdict"] = verdict
|
| 247 |
+
out["arms"][arm] = arec
|
| 248 |
+
out["note"] = ("#278 stays CLOSED: its clause 2 is the leverage-weighted held-out S0 d_vs_greedy "
|
| 249 |
+
"(+0.0135 [-0.0249,+0.0612], rung U) and is not a function of anything here.")
|
| 250 |
+
p = f"{ROOT}/{OUT_NAME}"
|
| 251 |
+
json.dump(out, open(p, "w"), indent=1, default=float)
|
| 252 |
+
print("wrote", p)
|
| 253 |
+
|
| 254 |
+
|
| 255 |
+
if __name__ == "__main__":
|
| 256 |
+
main()
|
gen_q_rsm/rsm_rise/pipeline/scripts/real/edge_AJ_read.py
ADDED
|
@@ -0,0 +1,222 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
r"""#278 RUNG AJ -- IS THE S2 INVERSION A DIRECTION PREFERENCE OR A MAGNITUDE PREFERENCE?
|
| 2 |
+
|
| 3 |
+
THE NUMBERS THAT CHOSE IT (all measured this run, all on the held-out S2 anchors):
|
| 4 |
+
|
| 5 |
+
1. RUNG AI (SLURM 43088, status/real/EDGE_AI_TAKEN_S2.json) -- rp_taken, the mean rank percentile
|
| 6 |
+
the scorer gives the candidates classified into THE EDGE THE EXPERT ACTUALLY TOOK:
|
| 7 |
+
arm goal-bound pooled DEST_failure top1_taken (goal4/cook3/fail)
|
| 8 |
+
AG ctrl (R_XL) 0.4183 [.3951,.4497] 0.4532 [.4157,.4784] 0.222 / 0.348 / 0.415
|
| 9 |
+
AG aug s0 0.3949 [.3651,.4354] 0.5112 [.4877,.5321] 0.239 / 0.208 / 0.631
|
| 10 |
+
AG aug s1 0.3896 [.3575,.4320] 0.4684 [.4331,.4910] 0.289 / 0.348 / 0.354
|
| 11 |
+
AG aug s2 0.4167 [.3902,.4481] 0.5043 [.4732,.5258] 0.244 / 0.417 / 0.523
|
| 12 |
+
AG aug s3 0.4311 [.3969,.4599] 0.4607 [.4285,.4857] 0.311 / 0.542 / 0.415
|
| 13 |
+
nulls (permuted:rsm, permuted:idql, random, greedy_idx) 0.49-0.52 in every cell
|
| 14 |
+
All five arms are BELOW 0.5 at the goal-bound anchors with intervals excluding it, and never
|
| 15 |
+
above it anywhere. The scorer is not at chance at S2: it reliably prefers the direction the
|
| 16 |
+
expert did NOT take, and the nulls show the candidate pool itself is balanced.
|
| 17 |
+
|
| 18 |
+
2. THE LABELS ARE NOT THE CAUSE (status/real/EDGE_FIELD_VALIDATE_h16.json, already on disk, the
|
| 19 |
+
same min-sep 20 deg setting every wave used): at S2 the HELD-OUT LOGGED ACTION is classified
|
| 20 |
+
into its own true edge with accuracy 0.688 (chance 0.5, n = 1281, 15 episodes; recall 2->3
|
| 21 |
+
0.611, 2->6 0.864), the two fields are separated by a median 69.0 deg with none below 20, and
|
| 22 |
+
2->6 is the most concentrated field in the graph (leave-one-out median 18.2 deg, R 0.526).
|
| 23 |
+
An inverted or unusable field would not classify the expert's own action correctly. So the
|
| 24 |
+
sign lives in the SCORER, and rung AH's option (C) "sign defect in the labels" is answered NO.
|
| 25 |
+
|
| 26 |
+
3. WHAT IS STILL OPEN, AND IS WHAT THIS FILE MEASURES. The edge classes are not magnitude-neutral:
|
| 27 |
+
a candidate is assigned to the edge whose field its DISPLACEMENT best matches, and the two S2
|
| 28 |
+
edges differ in how far the gripper travels. If the scorer simply prefers BIG (or small) moves,
|
| 29 |
+
it produces exactly the observed pattern without any directional opinion at all.
|
| 30 |
+
|
| 31 |
+
THE MEASUREMENT, per arm, on the same contrastive anchors:
|
| 32 |
+
(a) MAG_RHO -- the per-anchor Spearman correlation between the scorer's score and cand_mag_mm,
|
| 33 |
+
aggregated with the episode cluster bootstrap. How much of the ordering is magnitude.
|
| 34 |
+
(b) MAG_GAP -- mean cand_mag_mm of the true-edge candidates minus that of the others (mm), so the
|
| 35 |
+
size of the confound is visible in physical units.
|
| 36 |
+
(c) rp_taken_STRAT -- rp_taken recomputed WITHIN magnitude quartiles: each anchor's 128 candidates
|
| 37 |
+
are split into 4 equal bins by cand_mag_mm, the rank percentile is taken inside each bin, and
|
| 38 |
+
the true-edge candidates' within-bin percentiles are averaged. If magnitude is the whole
|
| 39 |
+
story this returns to 0.5; if the preference is directional it survives.
|
| 40 |
+
rp_taken (unstratified) is reprinted beside it from the same code path so the attenuation is read
|
| 41 |
+
off one row.
|
| 42 |
+
|
| 43 |
+
PRE-REGISTERED READING (fixed before the job was submitted; on the `rsm` scorer, goal-bound cell):
|
| 44 |
+
(J1) MAGNITUDE CONFOUND -- rp_taken_STRAT's interval COVERS 0.5 while rp_taken's excludes it. The
|
| 45 |
+
S2 inversion is then a preference over how far the arm moves, not over where it goes, and the
|
| 46 |
+
edge test at S2 has been reading a magnitude preference. The fix is to control magnitude in
|
| 47 |
+
the candidate set, which is standard practice and already has a harness knob (cand_shrink).
|
| 48 |
+
(J2) DIRECTIONAL -- rp_taken_STRAT stays below 0.5 with its interval excluding it. The inversion
|
| 49 |
+
is genuinely about direction; magnitude does not explain it, and the next work is the scorer's
|
| 50 |
+
own polarity (the value/reward it maximises at these states), not the candidate set.
|
| 51 |
+
(J3) PARTIAL -- the point estimate moves toward 0.5 by more than half the gap but the interval
|
| 52 |
+
still excludes it. Both mechanisms are present; report both sizes and say which dominates.
|
| 53 |
+
MAG_RHO and MAG_GAP are printed for every arm whichever clause fires, because a large rho with an
|
| 54 |
+
unattenuated rp_taken_STRAT is itself a finding: it means the scorer's ordering is mostly magnitude
|
| 55 |
+
AND still anti-correlated with the expert's direction.
|
| 56 |
+
|
| 57 |
+
Reads arrays already on disk (SLURM 42623). No model is loaded, nothing is retrained, and no
|
| 58 |
+
pre-registered quantity is altered. #278 stays CLOSED: its clause 2 is the leverage-weighted
|
| 59 |
+
held-out S0 d_vs_greedy, +0.0135 [-0.0249,+0.0612] at rung U, and is not a function of anything here.
|
| 60 |
+
"""
|
| 61 |
+
import os, sys, json, glob
|
| 62 |
+
import numpy as np
|
| 63 |
+
|
| 64 |
+
sys.path.insert(0, "/proj/dmfexp/zwhong/rsm_rise/scripts/real")
|
| 65 |
+
from edge_field import rank_pct
|
| 66 |
+
|
| 67 |
+
# same verbatim lift as rung AH/AI: the bootstrap is edge_AD_read.py's, by source extraction
|
| 68 |
+
import ast as _ast
|
| 69 |
+
_SRC = open("/proj/dmfexp/zwhong/rsm_rise/scripts/real/edge_AD_read.py").read()
|
| 70 |
+
_TREE = _ast.parse(_SRC)
|
| 71 |
+
_LIFT = {n.name: _ast.get_source_segment(_SRC, n) for n in _TREE.body
|
| 72 |
+
if isinstance(n, _ast.FunctionDef) and n.name in ("boot_matrix", "ci")}
|
| 73 |
+
assert set(_LIFT) == {"boot_matrix", "ci"}
|
| 74 |
+
assert "NB, SEED = 20000, 0" in _SRC, "edge_AD_read.py changed its bootstrap constants"
|
| 75 |
+
_NS = {"np": np, "NB": 20000, "SEED": 0}
|
| 76 |
+
for _n in ("boot_matrix", "ci"):
|
| 77 |
+
exec(compile(_LIFT[_n], "edge_AD_read.py::" + _n, "exec"), _NS)
|
| 78 |
+
boot_matrix, ci = _NS["boot_matrix"], _NS["ci"]
|
| 79 |
+
|
| 80 |
+
ROOT = "/proj/dmfexp/zwhong/rsm_rise/status/real"
|
| 81 |
+
SPLIT = json.load(open("/proj/dmfexp/zwhong/rsm_rise/data/derived/cooking_v5_split.json"))["episodes"]
|
| 82 |
+
EPS = [int(x) for x in open(os.environ.get("AJ_EPS_FILE", f"{ROOT}/edge_heldout_eps.txt")
|
| 83 |
+
).read().replace(",", " ").split()]
|
| 84 |
+
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(",")
|
| 85 |
+
OUT_NAME = os.environ.get("AJ_OUT", "EDGE_AJ_MAGNITUDE.json")
|
| 86 |
+
NQ = int(os.environ.get("AJ_QUANTILES", "4"))
|
| 87 |
+
COLS = {"rsm": "score_rsm", "perm": "score_permuted__rsm", "idql": "score_idql"}
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def destiny3(e):
|
| 91 |
+
fs = SPLIT[str(int(e))]["final_state"]
|
| 92 |
+
return "DEST_goal4" if fs == 4 else ("DEST_cook3" if fs == 3 else "DEST_failure")
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def spearman(a, b):
|
| 96 |
+
ra = np.argsort(np.argsort(np.asarray(a, float))).astype(float)
|
| 97 |
+
rb = np.argsort(np.argsort(np.asarray(b, float))).astype(float)
|
| 98 |
+
ra -= ra.mean(); rb -= rb.mean()
|
| 99 |
+
d = np.sqrt((ra * ra).sum() * (rb * rb).sum())
|
| 100 |
+
return float((ra * rb).sum() / d) if d > 0 else np.nan
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def strat_rank_pct(s, mag, nq):
|
| 104 |
+
"""rank percentile computed WITHIN magnitude quantile bins (ties in mag broken by order)."""
|
| 105 |
+
n = len(s)
|
| 106 |
+
order = np.argsort(np.asarray(mag, float), kind="stable")
|
| 107 |
+
out = np.full(n, np.nan)
|
| 108 |
+
bins = np.array_split(order, nq)
|
| 109 |
+
for b in bins:
|
| 110 |
+
if b.size < 2:
|
| 111 |
+
out[b] = 0.5
|
| 112 |
+
continue
|
| 113 |
+
out[b] = rank_pct(np.asarray(s, float)[b])
|
| 114 |
+
return out
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
def read_arm(d, keep):
|
| 118 |
+
rows = {k: {"rp": [], "rps": [], "rho": []} for k in COLS}
|
| 119 |
+
EP, GAP, NSEL = [], [], []
|
| 120 |
+
for f in sorted(glob.glob(f"{d}/edge_parts/*.npz")):
|
| 121 |
+
e = int(f.split("/")[-1][2:-4])
|
| 122 |
+
if e not in keep:
|
| 123 |
+
continue
|
| 124 |
+
z = np.load(f, allow_pickle=True)
|
| 125 |
+
if "onroute" not in z.files:
|
| 126 |
+
continue
|
| 127 |
+
meta = json.loads(bytes(z["__meta__"]).decode())
|
| 128 |
+
onr, cls, mag = np.asarray(z["onroute"], bool), np.asarray(z["cls"], int), np.asarray(z["cand_mag_mm"], float)
|
| 129 |
+
for i in range(onr.shape[0]):
|
| 130 |
+
o, c, m = onr[i], cls[i], mag[i]
|
| 131 |
+
n = o.size
|
| 132 |
+
if not (0 < int(o.sum()) < n):
|
| 133 |
+
continue
|
| 134 |
+
av = meta[i]["avail"]
|
| 135 |
+
te = meta[i]["true_edge"]
|
| 136 |
+
if te not in av:
|
| 137 |
+
continue
|
| 138 |
+
sel = (c == av.index(te))
|
| 139 |
+
if not (0 < int(sel.sum()) < n):
|
| 140 |
+
continue
|
| 141 |
+
EP.append(e); NSEL.append(int(sel.sum()))
|
| 142 |
+
GAP.append(float(m[sel].mean() - m[~sel].mean()))
|
| 143 |
+
for k, key in COLS.items():
|
| 144 |
+
if key not in z.files:
|
| 145 |
+
for q in ("rp", "rps", "rho"):
|
| 146 |
+
rows[k][q].append(np.nan)
|
| 147 |
+
continue
|
| 148 |
+
s = z[key][i].astype(np.float64)
|
| 149 |
+
rows[k]["rp"].append(float(rank_pct(s)[sel].mean()))
|
| 150 |
+
rows[k]["rps"].append(float(strat_rank_pct(s, m, NQ)[sel].mean()))
|
| 151 |
+
rows[k]["rho"].append(spearman(s, m))
|
| 152 |
+
return ({k: {q: np.asarray(v, float) for q, v in r.items()} for k, r in rows.items()},
|
| 153 |
+
np.asarray(EP, int), np.asarray(GAP, float), np.asarray(NSEL, float))
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
def cell(v, EP):
|
| 157 |
+
B, nclu = boot_matrix(EP, 20000, 0)
|
| 158 |
+
m, lo, hi = ci(v, B)
|
| 159 |
+
return dict(mean=m, lo=lo, hi=hi, n=int(v.size), n_clusters=int(nclu))
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
def fmt(c):
|
| 163 |
+
return f"{c['mean']:+.4f} [{c['lo']:+.4f},{c['hi']:+.4f}]"
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
def main():
|
| 167 |
+
print(f"RUNG AJ -- direction or magnitude? {NQ} magnitude quantile bins per anchor, "
|
| 168 |
+
f"{len(EPS)} held-out episodes, arms: {', '.join(ARMS)}")
|
| 169 |
+
print(" rp_taken = rank percentile of the EXPERT'S OWN edge's candidates (rung AI's quantity)")
|
| 170 |
+
print(" rp_STRAT = the same, ranked WITHIN magnitude quantile bins")
|
| 171 |
+
print(" MAG_RHO = per-anchor Spearman(score, candidate displacement magnitude)")
|
| 172 |
+
print(" MAG_GAP = mean magnitude of the expert-edge candidates minus the others, mm\n")
|
| 173 |
+
out = {"n_quantiles": NQ, "arms": {}}
|
| 174 |
+
for arm in ARMS:
|
| 175 |
+
R, EP, GAP, NSEL = read_arm(f"{ROOT}/{arm}", set(EPS))
|
| 176 |
+
if EP.size == 0:
|
| 177 |
+
print(f"### {arm}: no anchors\n"); continue
|
| 178 |
+
dst = np.array([destiny3(e) for e in EP])
|
| 179 |
+
gb = (dst == "DEST_goal4") | (dst == "DEST_cook3")
|
| 180 |
+
fa = (dst == "DEST_failure")
|
| 181 |
+
print(f"### ARM {arm} {EP.size} anchors / {len(set(EP.tolist()))} episodes; "
|
| 182 |
+
f"expert-edge candidates {NSEL.mean():.1f} of 128; "
|
| 183 |
+
f"MAG_GAP goal-bound {fmt(cell(GAP[gb], EP[gb]))} mm, failure {fmt(cell(GAP[fa], EP[fa]))} mm")
|
| 184 |
+
print(f"{'scorer':<8} {'group':<12} {'rp_taken':<26} {'rp_STRAT':<26} {'MAG_RHO':<26}")
|
| 185 |
+
rec = {"mag_gap": {"goalbound": cell(GAP[gb], EP[gb]), "failure": cell(GAP[fa], EP[fa])}}
|
| 186 |
+
for k in COLS:
|
| 187 |
+
if not np.isfinite(R[k]["rp"]).any():
|
| 188 |
+
continue
|
| 189 |
+
rec[k] = {}
|
| 190 |
+
for gname, msk in (("goal-bound", gb), ("failure", fa)):
|
| 191 |
+
c_rp, c_rs, c_rh = (cell(R[k]["rp"][msk], EP[msk]), cell(R[k]["rps"][msk], EP[msk]),
|
| 192 |
+
cell(R[k]["rho"][msk], EP[msk]))
|
| 193 |
+
rec[k][gname] = {"rp_taken": c_rp, "rp_strat": c_rs, "mag_rho": c_rh}
|
| 194 |
+
print(f"{k:<8} {gname:<12} {fmt(c_rp):<26} {fmt(c_rs):<26} {fmt(c_rh):<26}")
|
| 195 |
+
g = rec["rsm"]["goal-bound"]
|
| 196 |
+
rp, rs = g["rp_taken"], g["rp_strat"]
|
| 197 |
+
below_rp, below_rs = rp["hi"] < 0.5, rs["hi"] < 0.5
|
| 198 |
+
moved = (rs["mean"] - rp["mean"]) / max(0.5 - rp["mean"], 1e-9)
|
| 199 |
+
if below_rp and not below_rs:
|
| 200 |
+
v = (f"(J1) MAGNITUDE CONFOUND -- rp_taken {fmt(rp)} excludes 0.5 but stratified "
|
| 201 |
+
f"{fmt(rs)} covers it (closed {100*moved:.0f} % of the gap). The S2 inversion is a "
|
| 202 |
+
"preference over how far the arm moves, not over where it goes.")
|
| 203 |
+
elif below_rp and below_rs and moved <= 0.5:
|
| 204 |
+
v = (f"(J2) DIRECTIONAL -- stratified {fmt(rs)} still excludes 0.5 (only "
|
| 205 |
+
f"{100*moved:.0f} % of the gap closed). Magnitude does not explain the inversion; "
|
| 206 |
+
"the scorer's own polarity at these states does.")
|
| 207 |
+
elif below_rp and below_rs:
|
| 208 |
+
v = (f"(J3) PARTIAL -- stratified {fmt(rs)} still excludes 0.5 but closed "
|
| 209 |
+
f"{100*moved:.0f} % of the gap: both mechanisms are present, magnitude the larger.")
|
| 210 |
+
else:
|
| 211 |
+
v = (f"NOT INVERTED IN THIS ARM -- rp_taken {fmt(rp)} does not exclude 0.5; the "
|
| 212 |
+
"(J1)/(J2)/(J3) rule does not apply and the cell is reported as is.")
|
| 213 |
+
print(" READING " + v + "\n")
|
| 214 |
+
rec["verdict"] = v
|
| 215 |
+
out["arms"][arm] = rec
|
| 216 |
+
p = f"{ROOT}/{OUT_NAME}"
|
| 217 |
+
json.dump(out, open(p, "w"), indent=1, default=float)
|
| 218 |
+
print("wrote", p)
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
if __name__ == "__main__":
|
| 222 |
+
main()
|
gen_q_rsm/rsm_rise/pipeline/scripts/real/edge_arrival_check.py
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
"""gen_q#276 STEP 1 (label validation) -- are the per-EPISODE edge labels consistent with where the
|
| 3 |
+
arm actually ended up?
|
| 4 |
+
|
| 5 |
+
The rendered stage frames say two things the yaml does not: `end_stage2_global.png` (episode 100, the
|
| 6 |
+
LAST frame annotated edge_to==2 on route 0->2->3) shows the pan at its STARTING position with the
|
| 7 |
+
tomato in it -- i.e. state 1 -- while episode 101 on the same route shows the pan on the stove with the
|
| 8 |
+
tomato untouched, which is state 2 exactly. So at least one episode's segment label does not match its
|
| 9 |
+
scene. A mislabelled episode pollutes that edge's direction field, so count them.
|
| 10 |
+
|
| 11 |
+
Proxy, no vision needed: at the ARRIVAL frame of a segment (its last frame) the gripper has just
|
| 12 |
+
released whatever it carried, so the ee position is a signature of the edge. Per edge we take the
|
| 13 |
+
median arrival position over its episodes and report each episode's distance to it; an episode far from
|
| 14 |
+
its own edge's centre, and CLOSER to a sibling edge's centre, is flagged. CPU only.
|
| 15 |
+
"""
|
| 16 |
+
from __future__ import annotations
|
| 17 |
+
import argparse, json, sys
|
| 18 |
+
from collections import defaultdict
|
| 19 |
+
import numpy as np
|
| 20 |
+
|
| 21 |
+
sys.path.insert(0, "/proj/dmfexp/zwhong/rsm_rise/scripts/real")
|
| 22 |
+
from edge_field import ROOT, HDF5, SPLIT
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def main():
|
| 26 |
+
ap = argparse.ArgumentParser()
|
| 27 |
+
ap.add_argument("--hdf5", default=str(HDF5))
|
| 28 |
+
ap.add_argument("--split", default=str(SPLIT))
|
| 29 |
+
ap.add_argument("--out", required=True)
|
| 30 |
+
a = ap.parse_args()
|
| 31 |
+
import h5py
|
| 32 |
+
meta = json.load(open(a.split))["episodes"]
|
| 33 |
+
arr = defaultdict(list) # edge -> [(ep, xyz_at_arrival)]
|
| 34 |
+
with h5py.File(a.hdf5, "r") as f:
|
| 35 |
+
for ep in sorted(int(k) for k in meta):
|
| 36 |
+
g = f["data"][f"demo_{ep}"]
|
| 37 |
+
P = g["obs"]["robot0_eef_pos"][()].astype(np.float64)
|
| 38 |
+
ef = g["annot"]["edge_from"][()].astype(int)
|
| 39 |
+
et = g["annot"]["edge_to"][()].astype(int)
|
| 40 |
+
for e in sorted(set(zip(ef.tolist(), et.tolist()))):
|
| 41 |
+
m = np.nonzero((ef == e[0]) & (et == e[1]))[0]
|
| 42 |
+
if len(m):
|
| 43 |
+
arr[e].append((ep, P[m[-1]]))
|
| 44 |
+
res = {"hdf5": a.hdf5, "edges": {}, "flagged": []}
|
| 45 |
+
cen = {e: np.median(np.stack([x for _, x in v]), 0) for e, v in arr.items()}
|
| 46 |
+
for e, v in sorted(arr.items()):
|
| 47 |
+
key = f"{e[0]}->{e[1]}"
|
| 48 |
+
d = np.array([np.linalg.norm(x - cen[e]) for _, x in v]) * 1000.0
|
| 49 |
+
sib = [s for s in arr if s[0] == e[0] and s != e]
|
| 50 |
+
res["edges"][key] = {
|
| 51 |
+
"n_episodes": len(v), "centre_xyz_m": [float(x) for x in cen[e]],
|
| 52 |
+
"dist_to_own_centre_mm": {"median": float(np.median(d)), "p90": float(np.percentile(d, 90)),
|
| 53 |
+
"max": float(d.max())},
|
| 54 |
+
"siblings": [f"{s[0]}->{s[1]}" for s in sib],
|
| 55 |
+
"sibling_centre_sep_mm": {f"{s[0]}->{s[1]}": float(1000 * np.linalg.norm(cen[e] - cen[s])) for s in sib},
|
| 56 |
+
}
|
| 57 |
+
# an episode is FLAGGED when its arrival is closer to a sibling edge's centre than to its own
|
| 58 |
+
for (ep, x) in v:
|
| 59 |
+
own = np.linalg.norm(x - cen[e])
|
| 60 |
+
for s in sib:
|
| 61 |
+
if np.linalg.norm(x - cen[s]) < own:
|
| 62 |
+
res["flagged"].append({"episode": int(ep), "labelled_edge": key,
|
| 63 |
+
"closer_to": f"{s[0]}->{s[1]}",
|
| 64 |
+
"dist_own_mm": float(1000 * own),
|
| 65 |
+
"dist_other_mm": float(1000 * np.linalg.norm(x - cen[s])),
|
| 66 |
+
"split": meta[str(ep)]["split"],
|
| 67 |
+
"path": meta[str(ep)]["path"]})
|
| 68 |
+
break
|
| 69 |
+
n_by = defaultdict(int)
|
| 70 |
+
for r in res["flagged"]:
|
| 71 |
+
n_by[r["labelled_edge"]] += 1
|
| 72 |
+
res["flagged_count_by_edge"] = dict(n_by)
|
| 73 |
+
res["flagged_total"] = len(res["flagged"])
|
| 74 |
+
res["n_episodes"] = len(meta)
|
| 75 |
+
json.dump(res, open(a.out, "w"), indent=1)
|
| 76 |
+
print("[arr] wrote", a.out)
|
| 77 |
+
for k, v in res["edges"].items():
|
| 78 |
+
print(f"[arr] {k:<6} n={v['n_episodes']:3d} own-centre dist med {v['dist_to_own_centre_mm']['median']:6.1f} "
|
| 79 |
+
f"p90 {v['dist_to_own_centre_mm']['p90']:6.1f} mm sibling sep {v['sibling_centre_sep_mm']}")
|
| 80 |
+
print(f"[arr] FLAGGED {res['flagged_total']} of {sum(len(v) for v in arr.values())} segments: {dict(n_by)}")
|
| 81 |
+
for r in res["flagged"][:40]:
|
| 82 |
+
print("[arr] ep %d labelled %s but closer to %s (%.0f vs %.0f mm) path=%s split=%s"
|
| 83 |
+
% (r["episode"], r["labelled_edge"], r["closer_to"], r["dist_own_mm"], r["dist_other_mm"],
|
| 84 |
+
r["path"], r["split"]))
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
if __name__ == "__main__":
|
| 88 |
+
main()
|
gen_q_rsm/rsm_rise/pipeline/scripts/real/edge_candidate_gate.py
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
r"""#278 run 33 addendum: HOW DIFFERENT are the candidate sets across arms?
|
| 2 |
+
|
| 3 |
+
edge_route_decomp.py's GATE A (onroute classification, elementwise) FAILED on 7/7 non-control arms
|
| 4 |
+
with 27-75 of 291 anchors mismatched. The anchors themselves match (same episode/frame), so what
|
| 5 |
+
differs is the PROPOSER's 128 draws. Every cross-arm comparison in this ladder -- rungs V, Z, AA,
|
| 6 |
+
AB, AC -- reads arms through DIFFERENT candidate sets at the same anchors, so the size of that
|
| 7 |
+
difference is a property of the whole study, not of this run. Quantify it from the shards:
|
| 8 |
+
per anchor, the fraction of the 128 candidate displacement vectors that are not bitwise equal to
|
| 9 |
+
the control's, and the fraction of anchors that are fully identical.
|
| 10 |
+
"""
|
| 11 |
+
import json, sys
|
| 12 |
+
import numpy as np
|
| 13 |
+
from pathlib import Path
|
| 14 |
+
|
| 15 |
+
ROOT = Path("/proj/dmfexp/zwhong/rsm_rise/status/real")
|
| 16 |
+
CTRL = "edge_T_rise"
|
| 17 |
+
ARMS = ["edge_V_goalep", "edge_V_goalseg", "edge_V_win400", "edge_V_win100",
|
| 18 |
+
"edge_AC_rise_flow4", "edge_AC_rise_flow16", "edge_AC_rise_flow32"]
|
| 19 |
+
COMMON = set(json.load(open(ROOT / "EDGE_ROUTE_DECOMP.json"))["_meta"]["common_episodes"])
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def load(arm):
|
| 23 |
+
out = {}
|
| 24 |
+
for f in sorted((ROOT / arm / "edge_parts").glob("ep*.npz")):
|
| 25 |
+
if f.name.endswith(".tmp.npz"):
|
| 26 |
+
continue
|
| 27 |
+
z = np.load(f, allow_pickle=False)
|
| 28 |
+
meta = json.loads(bytes(z["__meta__"]).decode())
|
| 29 |
+
if not meta:
|
| 30 |
+
continue
|
| 31 |
+
for i, m in enumerate(meta):
|
| 32 |
+
if int(m["episode"]) not in COMMON:
|
| 33 |
+
continue
|
| 34 |
+
out[(int(m["episode"]), int(m["frame"]))] = dict(
|
| 35 |
+
disp=np.asarray(z["cand_disp_mm"][i], np.float32),
|
| 36 |
+
logged=np.asarray(z["logged_disp_mm"][i], np.float32),
|
| 37 |
+
ee=np.asarray(z["ee_xyz_mm"][i], np.float32),
|
| 38 |
+
onroute=np.asarray(z["onroute"][i], bool),
|
| 39 |
+
cls=np.asarray(z["cls"][i], np.int8))
|
| 40 |
+
return out
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
C = load(CTRL)
|
| 44 |
+
print(f"control {CTRL}: {len(C)} anchors on the common episode set\n")
|
| 45 |
+
hdr = (f"{'arm':22s} {'anchors':>8s} {'ee match':>9s} {'logged match':>13s} "
|
| 46 |
+
f"{'anchors w/ identical cands':>27s} {'mean frac cands differing':>26s} "
|
| 47 |
+
f"{'onroute mismatched anchors':>27s}")
|
| 48 |
+
print(hdr); print("-" * len(hdr))
|
| 49 |
+
out = {"control": CTRL, "n_anchors": len(C), "arms": {}}
|
| 50 |
+
for a in ARMS:
|
| 51 |
+
A = load(a)
|
| 52 |
+
keys = [k for k in C if k in A]
|
| 53 |
+
ee = sum(1 for k in keys if np.array_equal(A[k]["ee"], C[k]["ee"]))
|
| 54 |
+
lg = sum(1 for k in keys if np.array_equal(A[k]["logged"], C[k]["logged"]))
|
| 55 |
+
frac, ident, onr = [], 0, 0
|
| 56 |
+
for k in keys:
|
| 57 |
+
d1, d2 = A[k]["disp"], C[k]["disp"]
|
| 58 |
+
if d1.shape != d2.shape:
|
| 59 |
+
frac.append(1.0); continue
|
| 60 |
+
same = np.all(np.isclose(d1, d2, rtol=0, atol=1e-6), axis=-1)
|
| 61 |
+
frac.append(float(1.0 - same.mean()))
|
| 62 |
+
ident += int(same.all())
|
| 63 |
+
onr += int(not np.array_equal(A[k]["onroute"], C[k]["onroute"]))
|
| 64 |
+
r = dict(n_anchors=len(keys), ee_match=ee, logged_match=lg,
|
| 65 |
+
anchors_identical_candidates=ident,
|
| 66 |
+
mean_frac_candidates_differing=float(np.mean(frac)) if frac else float("nan"),
|
| 67 |
+
median_frac_candidates_differing=float(np.median(frac)) if frac else float("nan"),
|
| 68 |
+
onroute_mismatched_anchors=onr)
|
| 69 |
+
out["arms"][a] = r
|
| 70 |
+
print(f"{a:22s} {len(keys):8d} {ee:4d}/{len(keys):<4d} {lg:6d}/{len(keys):<6d} "
|
| 71 |
+
f"{ident:12d}/{len(keys):<4d} {r['mean_frac_candidates_differing']:26.4f} "
|
| 72 |
+
f"{onr:22d}/{len(keys):<4d}")
|
| 73 |
+
json.dump(out, open(ROOT / "EDGE_CANDIDATE_GATE.json", "w"), indent=1, default=float)
|
| 74 |
+
print("\n-> status/real/EDGE_CANDIDATE_GATE.json")
|
| 75 |
+
print("READING: ee_xyz and the logged action match everywhere -> the ANCHORS are the same physical\n"
|
| 76 |
+
"states (that is the gate RANK_CTRL and every earlier rung checked). What differs is the\n"
|
| 77 |
+
"PROPOSER DRAW. A between-arm delta is therefore measured through resampled candidates, and\n"
|
| 78 |
+
"the ordering that survives that resampling (the flow arms reproduce the route decomposition\n"
|
| 79 |
+
"with freshly drawn candidates) is the stronger claim, not the weaker one.")
|
gen_q_rsm/rsm_rise/pipeline/scripts/real/edge_ceiling2.py
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""gen_q#278 -- what the on-route rank-pct metric can MAXIMALLY show, and what it is really measuring.
|
| 3 |
+
|
| 4 |
+
Two exact facts about the headline metric, both derived from edge_field.rank_pct and verified
|
| 5 |
+
against the shipped edge_test.json to 4 decimal places:
|
| 6 |
+
|
| 7 |
+
1. IDENTITY (holds per anchor, exactly, no approximation):
|
| 8 |
+
mean rank_pct over on-route = [ (n_on-1)/2 + n_off * AUC ] / (n-1)
|
| 9 |
+
where AUC is the Mann-Whitney separation of on-route from off-route candidates at that anchor.
|
| 10 |
+
The within-on-route term is a complete round robin and is therefore SCORER-INDEPENDENT. So the
|
| 11 |
+
only thing any scorer can move is n_off*AUC/(n-1), and
|
| 12 |
+
|
| 13 |
+
2. CEILING: AUC <= 1 gives ceiling = (n_off + (n_on-1)/2)/(n-1) ~= 1 - f_onroute/2.
|
| 14 |
+
d_vs_greedy therefore has a hard upper bound set by the PROPOSER's on-route fraction, not by
|
| 15 |
+
the scorer. The pre-registered +0.10 bar is a fraction of THAT, not of 1.0.
|
| 16 |
+
|
| 17 |
+
3. LEVERAGE: the per-anchor weight is w = n_off/(n-1). It varies from 1/127 to ~30/127 across
|
| 18 |
+
anchors, so a plain average of per-anchor AUC is NOT what the metric reports; the metric is the
|
| 19 |
+
LEVERAGE-WEIGHTED AUC. Both are printed, because the gap between them says how concentrated
|
| 20 |
+
the test's power is.
|
| 21 |
+
"""
|
| 22 |
+
import sys, json, glob
|
| 23 |
+
import numpy as np
|
| 24 |
+
|
| 25 |
+
sys.path.insert(0, __file__.rsplit("/", 1)[0])
|
| 26 |
+
from edge_field import rank_pct
|
| 27 |
+
|
| 28 |
+
NB, SEED = 2000, 0
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def auc(sc, o):
|
| 32 |
+
a, b = sc[o], sc[~o]
|
| 33 |
+
return float(((a[:, None] > b[None, :]).sum() + 0.5 * (a[:, None] == b[None, :]).sum())
|
| 34 |
+
/ (a.size * b.size))
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def arm(d, keep=None):
|
| 38 |
+
cols = {"rsm": "score_rsm", "idql": "score_idql", "perm": "score_permuted__rsm",
|
| 39 |
+
"permi": "score_permuted__idql"}
|
| 40 |
+
W, EP, A = [], [], {k: [] for k in cols}
|
| 41 |
+
A["greedy"] = []
|
| 42 |
+
RP = {k: [] for k in list(cols) + ["greedy"]}
|
| 43 |
+
CEIL = []
|
| 44 |
+
for f in sorted(glob.glob(f"{d}/edge_parts/*.npz")):
|
| 45 |
+
z = np.load(f, allow_pickle=True)
|
| 46 |
+
if "onroute" not in z.files:
|
| 47 |
+
continue
|
| 48 |
+
e = int(f.split("/")[-1][2:-4])
|
| 49 |
+
if keep is not None and e not in keep:
|
| 50 |
+
continue
|
| 51 |
+
onr = np.asarray(z["onroute"], bool)
|
| 52 |
+
for i in range(onr.shape[0]):
|
| 53 |
+
o = onr[i]; n = o.size; n_on = int(o.sum()); n_off = n - n_on
|
| 54 |
+
if not (0 < n_on < n):
|
| 55 |
+
continue
|
| 56 |
+
w = n_off / (n - 1.0)
|
| 57 |
+
W.append(w); EP.append(e)
|
| 58 |
+
CEIL.append((n_off + (n_on - 1) / 2.0) / (n - 1))
|
| 59 |
+
g = -np.arange(n, dtype=float)
|
| 60 |
+
A["greedy"].append(auc(g, o)); RP["greedy"].append(float(rank_pct(g)[o].mean()))
|
| 61 |
+
for k, key in cols.items():
|
| 62 |
+
if key in z.files:
|
| 63 |
+
sc = z[key][i].astype(np.float64)
|
| 64 |
+
A[k].append(auc(sc, o)); RP[k].append(float(rank_pct(sc)[o].mean()))
|
| 65 |
+
W = np.asarray(W); EP = np.asarray(EP)
|
| 66 |
+
u = np.unique(EP)
|
| 67 |
+
rng = np.random.default_rng(SEED)
|
| 68 |
+
boots = [np.concatenate([np.flatnonzero(EP == q) for q in rng.choice(u, u.size, True)])
|
| 69 |
+
for _ in range(NB)]
|
| 70 |
+
|
| 71 |
+
def wm(v, idx=None):
|
| 72 |
+
v = np.asarray(v)
|
| 73 |
+
if idx is None:
|
| 74 |
+
return float((W * v).sum() / W.sum())
|
| 75 |
+
return float((W[idx] * v[idx]).sum() / W[idx].sum())
|
| 76 |
+
|
| 77 |
+
out = {"n_anchors": len(W), "n_episodes": int(u.size),
|
| 78 |
+
"onroute_frac": float(1 - (W * (len(W) / len(W))).mean() * 0), # filled below
|
| 79 |
+
"w_mean": float(W.mean()), "w_p50": float(np.median(W)), "w_p90": float(np.percentile(W, 90)),
|
| 80 |
+
"leverage_top20pct_share": float(np.sort(W)[::-1][:max(1, len(W) // 5)].sum() / W.sum()),
|
| 81 |
+
"ceiling_rankpct": float(np.mean(CEIL))}
|
| 82 |
+
for k, v in A.items():
|
| 83 |
+
if not v:
|
| 84 |
+
continue
|
| 85 |
+
v = np.asarray(v)
|
| 86 |
+
bw = [wm(v, b) for b in boots]
|
| 87 |
+
bu = [v[b].mean() for b in boots]
|
| 88 |
+
out["auc_" + k] = {"weighted": wm(v), "w_lo": float(np.percentile(bw, 2.5)),
|
| 89 |
+
"w_hi": float(np.percentile(bw, 97.5)),
|
| 90 |
+
"unweighted": float(v.mean()), "u_lo": float(np.percentile(bu, 2.5)),
|
| 91 |
+
"u_hi": float(np.percentile(bu, 97.5))}
|
| 92 |
+
out["rankpct_" + k] = float(np.mean(RP[k]))
|
| 93 |
+
# exact reconstruction check: d_vs_greedy must equal mean_a[ w_a*(AUC_a - AUCg_a) ]
|
| 94 |
+
g = np.asarray(A["greedy"])
|
| 95 |
+
for k in A:
|
| 96 |
+
if k == "greedy":
|
| 97 |
+
continue
|
| 98 |
+
out["d_vs_greedy_" + k] = float((W * (np.asarray(A[k]) - g)).mean())
|
| 99 |
+
out["d_ceiling"] = out["ceiling_rankpct"] - out["rankpct_greedy"]
|
| 100 |
+
# AUC the +0.10 bar demands, in the SAME leverage-weighted units the metric reports
|
| 101 |
+
out["auc_needed_for_bar"] = out["auc_greedy"]["weighted"] + 0.10 / float(W.mean())
|
| 102 |
+
return out
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
if __name__ == "__main__":
|
| 106 |
+
o = {}
|
| 107 |
+
for d in sys.argv[1:]:
|
| 108 |
+
t = d.rstrip("/").split("/")[-1]
|
| 109 |
+
try:
|
| 110 |
+
o[t] = arm(d)
|
| 111 |
+
except Exception as e:
|
| 112 |
+
o[t] = {"error": repr(e)}
|
| 113 |
+
print(f"{'arm':20s} {'eps':>3s} {'anc':>4s} {'wbar':>5s} {'d_ceil':>7s} {'d_rsm':>7s} {'%ceil':>6s} "
|
| 114 |
+
f"| {'AUCw_rsm':>22s} {'AUCw_grd':>8s} {'AUCw_prm':>8s} {'AUC_need':>8s} | {'AUCu_rsm':>8s}")
|
| 115 |
+
for t, r in o.items():
|
| 116 |
+
if "error" in r:
|
| 117 |
+
print(f"{t:20s} {r['error'][:70]}"); continue
|
| 118 |
+
a = r["auc_rsm"]
|
| 119 |
+
print(f"{t:20s} {r['n_episodes']:3d} {r['n_anchors']:4d} {r['w_mean']:5.3f} "
|
| 120 |
+
f"{r['d_ceiling']:+7.4f} {r['d_vs_greedy_rsm']:+7.4f} "
|
| 121 |
+
f"{100*r['d_vs_greedy_rsm']/r['d_ceiling']:5.1f}% | "
|
| 122 |
+
f"{a['weighted']:.3f}[{a['w_lo']:.3f},{a['w_hi']:.3f}] "
|
| 123 |
+
f"{r['auc_greedy']['weighted']:8.3f} {r['auc_perm']['weighted']:8.3f} "
|
| 124 |
+
f"{r['auc_needed_for_bar']:8.3f} | {a['unweighted']:8.3f}")
|
| 125 |
+
import os
|
| 126 |
+
op = os.environ.get("RR_CEIL_OUT", "status/real/EDGE_CEILING.json")
|
| 127 |
+
json.dump(o, open(op, "w"), indent=1)
|
| 128 |
+
print("->", op)
|
gen_q_rsm/rsm_rise/pipeline/scripts/real/edge_ceiling_route.py
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
r"""#278 run 34 (second reduction): IS RUN 33'S ROUTE HETEROGENEITY A SCORER DEFICIT OR HEADROOM?
|
| 2 |
+
|
| 3 |
+
Run 33 measured d_vs_greedy +0.1340 on the 0->5 route against +0.0448 on the on-route-edge routes
|
| 4 |
+
and +0.0032 at the cooking cell of the same first edge. That was read as "the pooled number is
|
| 5 |
+
carried by the failure route". There is an alternative reading with a measurable signature, and the
|
| 6 |
+
artefacts on disk already contain it: at a failure anchor the LOGGED action heads off-route, so the
|
| 7 |
+
greedy/BC baseline is bad by construction and the headroom is large; at an on-route anchor the logged
|
| 8 |
+
action is already on-route and there is little room above it. The metric's own ceiling identity
|
| 9 |
+
(edge_ceiling2.py, verified to 4 dp against edge_field.rank_pct) gives the headroom per anchor:
|
| 10 |
+
d_ceiling = ceiling_rankpct - rankpct_greedy, ceiling = (n_off + (n_on-1)/2)/(n-1)
|
| 11 |
+
so %ceil = d_rsm / d_ceiling is the scorer's share of what was AVAILABLE in that group.
|
| 12 |
+
|
| 13 |
+
PRE-REGISTERED READING (written before the per-group numbers were computed; the pooled cell
|
| 14 |
+
%ceil 47.9 % is already published, the per-group split is not):
|
| 15 |
+
(i) %ceil approximately FLAT across the four routes (spread <= ~10 points) -> the absolute
|
| 16 |
+
heterogeneity run 33 reported is a HEADROOM effect. The scorer converts the same share of
|
| 17 |
+
the available signal everywhere, and the correct statement is that the TEST has little power
|
| 18 |
+
at on-route anchors, not that the scorer fails there.
|
| 19 |
+
(ii) %ceil MUCH LOWER on the goal-bound routes (0->1->3, 0->2->3) than on 0->5 -> the deficit is
|
| 20 |
+
the scorer, exactly as run 33 read it, and the goal-bound cell is a genuine failure.
|
| 21 |
+
(iii) %ceil HIGHER on the goal-bound routes -> the pooled number understates the scorer at the
|
| 22 |
+
states a planner needs, and the on-route cells are power-limited.
|
| 23 |
+
Either way the verdict on #278 is untouched: this is a decomposition of a fired rule, not a new arm.
|
| 24 |
+
|
| 25 |
+
No new model call, no new harness: edge_ceiling2.arm() called per route group via its own `keep`
|
| 26 |
+
argument, on the SAME edge_parts/*.npz as every published number.
|
| 27 |
+
"""
|
| 28 |
+
import sys, json, os
|
| 29 |
+
import numpy as np
|
| 30 |
+
sys.path.insert(0, "/proj/dmfexp/zwhong/rsm_rise/scripts/real")
|
| 31 |
+
from edge_ceiling2 import arm
|
| 32 |
+
|
| 33 |
+
ROOT = "/proj/dmfexp/zwhong/rsm_rise/status/real"
|
| 34 |
+
SPLIT = json.load(open("/proj/dmfexp/zwhong/rsm_rise/data/derived/cooking_v5_split.json"))["episodes"]
|
| 35 |
+
COMMON = [7, 9, 12, 22, 46, 52, 54, 68, 73, 86, 105, 107, 120, 131, 137, 204, 223, 224, 230, 231]
|
| 36 |
+
ARMS = [("edge_T_rise", "CONTROL, shipped best cell (GOAL_EPISODE, flow 8, p16)"),
|
| 37 |
+
("edge_AC_rise_flow32", "replicate at flow 32"),
|
| 38 |
+
("edge_V_goalseg", "GOAL_SEGMENT label (pooled-negative arm)")]
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def route_of(e):
|
| 42 |
+
return "->".join(str(x) for x in SPLIT[str(int(e))]["path"])
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def destiny_of(e):
|
| 46 |
+
return "goalbound" if SPLIT[str(int(e))]["final_state"] in (3, 4) else "failure"
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
by_route = {}
|
| 50 |
+
for e in COMMON:
|
| 51 |
+
by_route.setdefault(route_of(e), []).append(e)
|
| 52 |
+
GROUPS = [("ALL", COMMON)] + [(f"R_{k}", v) for k, v in sorted(by_route.items())]
|
| 53 |
+
GROUPS += [("ONROUTE_EDGE", [e for e in COMMON if route_of(e) != "0->5"]),
|
| 54 |
+
("DEST_goalbound", [e for e in COMMON if destiny_of(e) == "goalbound"]),
|
| 55 |
+
("DEST_failure", [e for e in COMMON if destiny_of(e) == "failure"])]
|
| 56 |
+
|
| 57 |
+
print("route census of the common 20 held-out episodes (printed before any number):")
|
| 58 |
+
for k, v in sorted(by_route.items()):
|
| 59 |
+
print(f" {k:10s} {len(v)} episodes {v} destiny={destiny_of(v[0])}")
|
| 60 |
+
|
| 61 |
+
out = {"_meta": dict(common_episodes=COMMON, groups={k: v for k, v in GROUPS},
|
| 62 |
+
note="edge_ceiling2.arm() per group; contrastive anchors only, as the metric")}
|
| 63 |
+
for a, lab in ARMS:
|
| 64 |
+
d = f"{ROOT}/{a}"
|
| 65 |
+
if not os.path.isdir(d + "/edge_parts"):
|
| 66 |
+
print(f"\n{a}: no parts on disk -- skipped"); continue
|
| 67 |
+
print(f"\n### {a} -- {lab}")
|
| 68 |
+
hdr = (f"{'group':16s} {'eps':>3s} {'anc':>4s} {'wbar':>5s} {'d_ceil':>8s} {'d_rsm':>8s} "
|
| 69 |
+
f"{'%ceil':>7s} | {'AUCw_rsm':>8s} {'AUCw_grd':>8s} {'AUC_need':>8s} {'rp_grd':>7s}")
|
| 70 |
+
print(hdr); print("-" * len(hdr))
|
| 71 |
+
out[a] = {"_label": lab}
|
| 72 |
+
for g, eps in GROUPS:
|
| 73 |
+
try:
|
| 74 |
+
r = arm(d, keep=set(eps))
|
| 75 |
+
except Exception as ex: # a group with no contrastive anchor
|
| 76 |
+
print(f"{g:16s} error {ex!r}"); continue
|
| 77 |
+
if not r.get("n_anchors"):
|
| 78 |
+
print(f"{g:16s} no contrastive anchors"); continue
|
| 79 |
+
pc = 100 * r["d_vs_greedy_rsm"] / r["d_ceiling"] if r["d_ceiling"] else float("nan")
|
| 80 |
+
r["pct_of_ceiling"] = pc
|
| 81 |
+
out[a][g] = r
|
| 82 |
+
print(f"{g:16s} {r['n_episodes']:3d} {r['n_anchors']:4d} {r['w_mean']:5.3f} "
|
| 83 |
+
f"{r['d_ceiling']:+8.4f} {r['d_vs_greedy_rsm']:+8.4f} {pc:6.1f}% | "
|
| 84 |
+
f"{r['auc_rsm']['weighted']:8.3f} {r['auc_greedy']['weighted']:8.3f} "
|
| 85 |
+
f"{r['auc_needed_for_bar']:8.3f} {r['rankpct_greedy']:7.3f}")
|
| 86 |
+
|
| 87 |
+
# ---- the mechanical reading, on the CONTROL ----
|
| 88 |
+
c = out.get("edge_T_rise", {})
|
| 89 |
+
keys = ["R_0->5", "R_0->1->3", "R_0->2->3", "R_0->2->6"]
|
| 90 |
+
pcs = {k: c[k]["pct_of_ceiling"] for k in keys if k in c}
|
| 91 |
+
if len(pcs) == 4:
|
| 92 |
+
spread = max(pcs.values()) - min(pcs.values())
|
| 93 |
+
gb = np.mean([pcs["R_0->1->3"], pcs["R_0->2->3"]])
|
| 94 |
+
fe = pcs["R_0->5"]
|
| 95 |
+
if spread <= 10.0:
|
| 96 |
+
verd = ("(i) %ceil is FLAT across routes -> run 33's absolute heterogeneity is a HEADROOM "
|
| 97 |
+
"effect; the test has little power at on-route anchors rather than the scorer "
|
| 98 |
+
"failing there")
|
| 99 |
+
elif gb < fe - 10.0:
|
| 100 |
+
verd = ("(ii) %ceil is MUCH LOWER on the goal-bound routes -> the deficit is the scorer at "
|
| 101 |
+
"exactly the states a planner needs, as run 33 read it")
|
| 102 |
+
elif gb > fe + 10.0:
|
| 103 |
+
verd = ("(iii) %ceil is HIGHER on the goal-bound routes -> the pooled number UNDERSTATES "
|
| 104 |
+
"the scorer where a planner needs it and the on-route cells are power-limited")
|
| 105 |
+
else:
|
| 106 |
+
verd = ("between the pre-registered cases: spread > 10 points but the goal-bound mean is "
|
| 107 |
+
"within 10 points of the failure route -- report the numbers, claim neither")
|
| 108 |
+
print(f"\n%ceil per route (control): " + " ".join(f"{k}={v:.1f}%" for k, v in pcs.items()))
|
| 109 |
+
print(f"spread {spread:.1f} points; goal-bound mean {gb:.1f}% vs failure edge {fe:.1f}%")
|
| 110 |
+
print("READING: " + verd)
|
| 111 |
+
out["_reading"] = dict(pct_of_ceiling=pcs, spread=spread, goalbound_mean=float(gb),
|
| 112 |
+
failure_edge=float(fe), verdict=verd)
|
| 113 |
+
print("\nThe #278 verdict is UNCHANGED either way: the bar is on the pooled clause-2 number "
|
| 114 |
+
"(+0.0909 < +0.10) and this is a decomposition of it, not a new arm.")
|
| 115 |
+
|
| 116 |
+
p = f"{ROOT}/EDGE_CEILING_ROUTE.json"
|
| 117 |
+
json.dump(out, open(p, "w"), indent=1, default=float)
|
| 118 |
+
print("\nwrote", p)
|
gen_q_rsm/rsm_rise/pipeline/scripts/real/edge_dirfig.py
ADDED
|
@@ -0,0 +1,204 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""gen_q#278 -- FIGURE A and the DIVERSITY TABLE for the proposer's first-action directions.
|
| 3 |
+
|
| 4 |
+
Owner, 2026-09-23: "visualize all the 3D directions the end effector goes at the initial state anchors ...
|
| 5 |
+
for every anchor give a 3D direction ... I want to see if it is actually diverse, the pi.5".
|
| 6 |
+
|
| 7 |
+
Reads the RAW 3-vectors the edge writer stores per anchor (scorer_openloop.py: cand_disp_mm [n_anchor,N,3],
|
| 8 |
+
logged_disp_mm [n_anchor,3], ee_xyz_mm [n_anchor,3], all base-frame mm) -- directions are NEVER inferred from
|
| 9 |
+
the class labels. No camera model is needed for any number or panel here; the image overlay (FIGURE B) is a
|
| 10 |
+
separate step that only ships if its held-out reprojection residual is small.
|
| 11 |
+
|
| 12 |
+
Per anchor, over candidates whose displacement exceeds --min-mag-mm:
|
| 13 |
+
mean_pair_angle_deg mean pairwise angle between unit directions (spread of the fan)
|
| 14 |
+
sphere_cov fraction of a 4096-point Fibonacci sphere within --cap-deg of SOME candidate
|
| 15 |
+
(a solid-angle estimate: 1.0 = the whole sphere is within one cap of a sample)
|
| 16 |
+
n_clusters greedy leader clustering of the unit directions at --cluster-deg
|
| 17 |
+
logged_min_angle_deg angle from the LOGGED direction to the nearest candidate -- can this proposer
|
| 18 |
+
produce the action the demonstrator actually took?
|
| 19 |
+
Aggregated per branch state with a CLUSTER bootstrap over EPISODES (the anchors within an episode are not
|
| 20 |
+
independent), matching the edge test's own convention.
|
| 21 |
+
"""
|
| 22 |
+
import argparse, glob, json, os
|
| 23 |
+
import numpy as np
|
| 24 |
+
|
| 25 |
+
ROOT = "/proj/dmfexp/zwhong/rsm_rise"
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def unit(v):
|
| 29 |
+
n = np.linalg.norm(v, axis=-1, keepdims=True)
|
| 30 |
+
return np.where(n > 0, v / np.maximum(n, 1e-9), 0.0)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def fib_sphere(n=4096):
|
| 34 |
+
i = np.arange(n) + 0.5
|
| 35 |
+
phi = np.arccos(1 - 2 * i / n)
|
| 36 |
+
theta = np.pi * (1 + 5 ** 0.5) * i
|
| 37 |
+
return np.stack([np.cos(theta) * np.sin(phi), np.sin(theta) * np.sin(phi), np.cos(phi)], 1)
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def leader_clusters(u, deg):
|
| 41 |
+
c = np.cos(np.deg2rad(deg))
|
| 42 |
+
heads = []
|
| 43 |
+
for d in u:
|
| 44 |
+
if not heads or max(float(d @ h) for h in heads) < c:
|
| 45 |
+
heads.append(d)
|
| 46 |
+
return len(heads)
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def boot_ci(vals, groups, n_boot=2000, seed=0):
|
| 50 |
+
vals, groups = np.asarray(vals, float), np.asarray(groups)
|
| 51 |
+
if len(vals) == 0:
|
| 52 |
+
return (float("nan"),) * 3
|
| 53 |
+
gs = np.unique(groups)
|
| 54 |
+
idx = {g: np.where(groups == g)[0] for g in gs}
|
| 55 |
+
rng = np.random.default_rng(seed)
|
| 56 |
+
out = np.empty(n_boot)
|
| 57 |
+
for b in range(n_boot):
|
| 58 |
+
pick = rng.choice(gs, len(gs), replace=True)
|
| 59 |
+
out[b] = np.mean(np.concatenate([vals[idx[g]] for g in pick]))
|
| 60 |
+
return float(vals.mean()), float(np.percentile(out, 2.5)), float(np.percentile(out, 97.5))
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def load_arm(d, state, min_mag, cap_deg, cluster_deg, sphere):
|
| 64 |
+
"""-> per-anchor rows + the pooled unit directions for the figures."""
|
| 65 |
+
rows, pool = [], []
|
| 66 |
+
for f in sorted(glob.glob(os.path.join(d, "edge_parts", "*.npz"))):
|
| 67 |
+
z = np.load(f)
|
| 68 |
+
if "cand_disp_mm" not in z.files:
|
| 69 |
+
continue # written before the raw-vector instrumentation landed
|
| 70 |
+
meta = json.loads(bytes(z["__meta__"]).decode())
|
| 71 |
+
disp, logd, cls = z["cand_disp_mm"], z["logged_disp_mm"], z["cls"]
|
| 72 |
+
for i, m in enumerate(meta):
|
| 73 |
+
if int(m["state"]) != state:
|
| 74 |
+
continue
|
| 75 |
+
dd = disp[i]
|
| 76 |
+
keep = np.linalg.norm(dd, axis=-1) >= min_mag
|
| 77 |
+
if keep.sum() < 2:
|
| 78 |
+
continue
|
| 79 |
+
u = unit(dd[keep])
|
| 80 |
+
cosm = np.clip(u @ u.T, -1, 1)
|
| 81 |
+
iu = np.triu_indices(len(u), 1)
|
| 82 |
+
mean_pair = float(np.degrees(np.arccos(cosm[iu])).mean())
|
| 83 |
+
cov = float((np.max(sphere @ u.T, axis=1) >= np.cos(np.deg2rad(cap_deg))).mean())
|
| 84 |
+
lu = unit(logd[i])
|
| 85 |
+
lmin = float(np.degrees(np.arccos(np.clip((u @ lu).max(), -1, 1)))) if np.linalg.norm(logd[i]) > 0 else float("nan")
|
| 86 |
+
rows.append(dict(episode=int(m["episode"]), frame=int(m["frame"]), state=state,
|
| 87 |
+
n_used=int(keep.sum()), mean_pair_angle_deg=mean_pair, sphere_cov=cov,
|
| 88 |
+
n_clusters=leader_clusters(u, cluster_deg),
|
| 89 |
+
logged_min_angle_deg=lmin,
|
| 90 |
+
median_mag_mm=float(np.median(np.linalg.norm(dd, axis=-1))),
|
| 91 |
+
disp_spread_mm=float(m.get("disp_spread_mm", float("nan")))))
|
| 92 |
+
pool.append((int(m["episode"]), int(m["frame"]), u, unit(logd[i]), cls[i][keep],
|
| 93 |
+
[str(e) for e in m["avail"]]))
|
| 94 |
+
return rows, pool
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def summarise(rows, seed=0):
|
| 98 |
+
if not rows:
|
| 99 |
+
return {"n_anchor": 0}
|
| 100 |
+
g = [r["episode"] for r in rows]
|
| 101 |
+
out = {"n_anchor": len(rows), "n_episode": len(set(g))}
|
| 102 |
+
for k in ("mean_pair_angle_deg", "sphere_cov", "n_clusters", "logged_min_angle_deg",
|
| 103 |
+
"median_mag_mm", "disp_spread_mm"):
|
| 104 |
+
v = [r[k] for r in rows]
|
| 105 |
+
v = [x for x in v if np.isfinite(x)]
|
| 106 |
+
gg = [r["episode"] for r in rows if np.isfinite(r[k])]
|
| 107 |
+
m, lo, hi = boot_ci(v, gg, seed=seed)
|
| 108 |
+
out[k] = {"mean": m, "lo": lo, "hi": hi}
|
| 109 |
+
return out
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
def figure_a(pool, name, state, png, max_anchors=24):
|
| 113 |
+
import matplotlib
|
| 114 |
+
matplotlib.use("Agg")
|
| 115 |
+
import matplotlib.pyplot as plt
|
| 116 |
+
if not pool:
|
| 117 |
+
return None
|
| 118 |
+
# panel 1-3: ALL anchors pooled, the three base-frame projections; panel 4+: small multiples
|
| 119 |
+
planes = [(0, 1, "X (mm, base frame)", "Y"), (0, 2, "X", "Z"), (1, 2, "Y", "Z")]
|
| 120 |
+
fig = plt.figure(figsize=(16, 5.2))
|
| 121 |
+
for p, (a, b, xl, yl) in enumerate(planes):
|
| 122 |
+
ax = fig.add_subplot(1, 3, p + 1)
|
| 123 |
+
for ep, fr, u, lu, cls, avail in pool:
|
| 124 |
+
for c in np.unique(cls):
|
| 125 |
+
s = cls == c
|
| 126 |
+
lab = avail[c] if 0 <= c < len(avail) else "undef"
|
| 127 |
+
ax.scatter(u[s][:, a], u[s][:, b], s=2, alpha=0.25,
|
| 128 |
+
color=plt.cm.tab10(int(c) % 10), label=lab)
|
| 129 |
+
ax.arrow(0, 0, lu[a] * 0.9, lu[b] * 0.9, color="k", width=0.004, alpha=0.30,
|
| 130 |
+
length_includes_head=True)
|
| 131 |
+
ax.set_xlim(-1.1, 1.1); ax.set_ylim(-1.1, 1.1); ax.set_aspect("equal")
|
| 132 |
+
ax.set_xlabel(xl); ax.set_ylabel(yl)
|
| 133 |
+
h, l = ax.get_legend_handles_labels()
|
| 134 |
+
seen = dict(zip(l, h))
|
| 135 |
+
if p == 0:
|
| 136 |
+
ax.legend(seen.values(), seen.keys(), fontsize=7, loc="upper right", markerscale=4)
|
| 137 |
+
fig.suptitle(f"FIGURE A -- {name}: unit first-action directions at S{state} anchors, all anchors pooled "
|
| 138 |
+
f"(black = the LOGGED action, colour = edge class)")
|
| 139 |
+
fig.tight_layout(); fig.savefig(png, dpi=130); plt.close(fig)
|
| 140 |
+
|
| 141 |
+
# small multiples, XY view, one panel per anchor -- "is it diverse" at a glance
|
| 142 |
+
sm = png.replace(".png", "_anchors.png")
|
| 143 |
+
k = min(max_anchors, len(pool))
|
| 144 |
+
cols, rowsn = 6, int(np.ceil(k / 6))
|
| 145 |
+
fig, axes = plt.subplots(rowsn, cols, figsize=(2.1 * cols, 2.1 * rowsn), squeeze=False)
|
| 146 |
+
step = max(1, len(pool) // k)
|
| 147 |
+
for j in range(rowsn * cols):
|
| 148 |
+
ax = axes[j // cols][j % cols]; ax.set_xticks([]); ax.set_yticks([])
|
| 149 |
+
if j >= k:
|
| 150 |
+
ax.axis("off"); continue
|
| 151 |
+
ep, fr, u, lu, cls, avail = pool[j * step]
|
| 152 |
+
ax.scatter(u[:, 0], u[:, 1], s=4, c=[plt.cm.tab10(int(c) % 10) for c in cls], alpha=0.7)
|
| 153 |
+
ax.arrow(0, 0, lu[0] * 0.9, lu[1] * 0.9, color="k", width=0.03, length_includes_head=True)
|
| 154 |
+
ax.set_xlim(-1.15, 1.15); ax.set_ylim(-1.15, 1.15); ax.set_aspect("equal")
|
| 155 |
+
ax.set_title(f"ep{ep} f{fr}", fontsize=6)
|
| 156 |
+
fig.suptitle(f"FIGURE A (small multiples) -- {name}, S{state}: XY top view, one panel per anchor")
|
| 157 |
+
fig.tight_layout(); fig.savefig(sm, dpi=130); plt.close(fig)
|
| 158 |
+
return sm
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
def main():
|
| 162 |
+
ap = argparse.ArgumentParser()
|
| 163 |
+
ap.add_argument("--arm", action="append", required=True, metavar="NAME=DIR",
|
| 164 |
+
help="a run directory containing edge_parts/ with cand_disp_mm")
|
| 165 |
+
ap.add_argument("--state", type=int, action="append", default=None)
|
| 166 |
+
ap.add_argument("--min-mag-mm", type=float, default=1.0)
|
| 167 |
+
ap.add_argument("--cap-deg", type=float, default=20.0)
|
| 168 |
+
ap.add_argument("--cluster-deg", type=float, default=20.0)
|
| 169 |
+
ap.add_argument("--figdir", default=f"{ROOT}/docs/figs/real_dirs")
|
| 170 |
+
ap.add_argument("--out", required=True)
|
| 171 |
+
a = ap.parse_args()
|
| 172 |
+
states = a.state or [0, 2]
|
| 173 |
+
sphere = fib_sphere(4096)
|
| 174 |
+
os.makedirs(a.figdir, exist_ok=True)
|
| 175 |
+
res, md = {}, []
|
| 176 |
+
md.append("| arm | state | anchors (eps) | mean pairwise angle (deg) [CI] | sphere coverage @20deg [CI] "
|
| 177 |
+
"| clusters @20deg [CI] | angle to LOGGED (deg) [CI] | median |disp| mm |")
|
| 178 |
+
md.append("|---|---|---|---|---|---|---|---|")
|
| 179 |
+
for spec in a.arm:
|
| 180 |
+
name, d = spec.split("=", 1)
|
| 181 |
+
for st in states:
|
| 182 |
+
rows, pool = load_arm(d, st, a.min_mag_mm, a.cap_deg, a.cluster_deg, sphere)
|
| 183 |
+
s = summarise(rows)
|
| 184 |
+
res[f"{name}|S{st}"] = {"dir": d, "summary": s,
|
| 185 |
+
"params": {"min_mag_mm": a.min_mag_mm, "cap_deg": a.cap_deg,
|
| 186 |
+
"cluster_deg": a.cluster_deg}}
|
| 187 |
+
if s["n_anchor"]:
|
| 188 |
+
png = os.path.join(a.figdir, f"figA_{name}_S{st}.png")
|
| 189 |
+
figure_a(pool, name, st, png)
|
| 190 |
+
res[f"{name}|S{st}"]["figures"] = [png, png.replace(".png", "_anchors.png")]
|
| 191 |
+
f = lambda k, p=1: (f"{s[k]['mean']:.{p}f} [{s[k]['lo']:.{p}f},{s[k]['hi']:.{p}f}]")
|
| 192 |
+
md.append(f"| {name} | S{st} | {s['n_anchor']} ({s['n_episode']}) | {f('mean_pair_angle_deg')} "
|
| 193 |
+
f"| {f('sphere_cov',3)} | {f('n_clusters')} | {f('logged_min_angle_deg')} "
|
| 194 |
+
f"| {s['median_mag_mm']['mean']:.1f} |")
|
| 195 |
+
else:
|
| 196 |
+
md.append(f"| {name} | S{st} | 0 | -- (no edge_parts with cand_disp_mm) | | | | |")
|
| 197 |
+
print(f"[dirfig] {name} S{st}: {json.dumps(s)}", flush=True)
|
| 198 |
+
json.dump(res, open(a.out, "w"), indent=1)
|
| 199 |
+
open(a.out.replace(".json", ".md"), "w").write("\n".join(md) + "\n")
|
| 200 |
+
print("wrote", a.out, "and", a.out.replace(".json", ".md"))
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
if __name__ == "__main__":
|
| 204 |
+
main()
|
gen_q_rsm/rsm_rise/pipeline/scripts/real/edge_field.py
ADDED
|
@@ -0,0 +1,283 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
"""gen_q#276 STEP 1 -- the edge-direction field, and its validation.
|
| 3 |
+
|
| 4 |
+
The rig has no simulator, so a candidate action cannot be rolled out. But `actions_raw` is an ABSOLUTE
|
| 5 |
+
end-effector target (data attr action_type='absolute'), so a candidate chunk at frame t proposes a
|
| 6 |
+
DISPLACEMENT d = a[H-1,:3] - p_t from the current ee position p_t. The task graph's edges each have a
|
| 7 |
+
characteristic displacement direction at a given place on the table (edge 0->2 = "to the pan handle",
|
| 8 |
+
0->1/0->5 = "to the tomato", then apart), so `d` classifies which edge a candidate is taking.
|
| 9 |
+
|
| 10 |
+
Direction is a FIELD, not a constant: "to the tomato" points differently from the left of the table than
|
| 11 |
+
from the right. So the field of edge e is estimated by k-nearest-neighbours in ee-xyz over the logged
|
| 12 |
+
frames that carry annot.edge_from/edge_to == e, on the TRAIN split only.
|
| 13 |
+
|
| 14 |
+
field_e(p) = normalise( sum_{i in kNN_e(p)} w_i u_i ), u_i = normalise(a_i[H-1,:3] - p_i)
|
| 15 |
+
|
| 16 |
+
and a candidate with displacement d at p is classified argmax_e cos(d, field_e(p)).
|
| 17 |
+
|
| 18 |
+
Validation (EDGE_TEST.md step 1, "a mislabelled edge silently inverts the whole test"):
|
| 19 |
+
* angular spread of each edge's field, globally and after conditioning on position (leave-one-EPISODE-out);
|
| 20 |
+
* pairwise separation of the fields that are available at the same anchor -- two edges whose fields are
|
| 21 |
+
parallel at an anchor cannot be told apart there, however clean each one is on its own;
|
| 22 |
+
* the decisive one: classify the LOGGED action of HELD-OUT episodes at the anchors. If the true expert
|
| 23 |
+
displacement is not recovered, no candidate's can be.
|
| 24 |
+
|
| 25 |
+
Everything here reads only annot/, obs/robot0_eef_pos and actions_raw -- no images, no model: CPU only.
|
| 26 |
+
"""
|
| 27 |
+
from __future__ import annotations
|
| 28 |
+
import json
|
| 29 |
+
from pathlib import Path
|
| 30 |
+
import numpy as np
|
| 31 |
+
|
| 32 |
+
ROOT = Path("/proj/dmfexp/zwhong/rsm_rise")
|
| 33 |
+
HDF5 = ROOT / "data/raw/cooking_v5_expert_suboptimal.hdf5"
|
| 34 |
+
SPLIT = ROOT / "data/derived/cooking_v5_split.json"
|
| 35 |
+
|
| 36 |
+
# real/config/task/tabletop.yaml, transcribed in rise_stack/EDGE_TEST.md. on-route = lies on some route to
|
| 37 |
+
# the single rewarded state 4; the two terminals 5 and 6 are failures.
|
| 38 |
+
ON_ROUTE = {(0, 1), (0, 2), (1, 3), (2, 3), (3, 4)}
|
| 39 |
+
FAILURE = {(0, 5), (2, 6)}
|
| 40 |
+
BRANCH_STATES = (0, 2) # the shared-prefix states: 3 edges leave 0, 2 leave 2
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def unit(v, axis=-1, eps=1e-9):
|
| 44 |
+
n = np.linalg.norm(v, axis=axis, keepdims=True)
|
| 45 |
+
return v / np.maximum(n, eps)
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def ang_deg(a, b):
|
| 49 |
+
"""angle between unit-ish vectors, degrees, elementwise over the leading axes."""
|
| 50 |
+
c = np.clip((unit(a) * unit(b)).sum(-1), -1.0, 1.0)
|
| 51 |
+
return np.degrees(np.arccos(c))
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def load_frames(horizon=8, hdf5=HDF5, split=SPLIT, max_eps=0):
|
| 55 |
+
"""Per-frame table over every episode: ee position, chunk displacement, edge label, split.
|
| 56 |
+
|
| 57 |
+
Displacement uses the LOGGED ACTION at the end of the chunk (a[t+H-1]) minus the CURRENT ee position,
|
| 58 |
+
which is exactly the quantity a candidate chunk supplies -- not p[t+H]-p[t], which carries the
|
| 59 |
+
controller's tracking lag and would bias the field against the candidates.
|
| 60 |
+
"""
|
| 61 |
+
import h5py
|
| 62 |
+
meta = json.load(open(split))["episodes"]
|
| 63 |
+
eps = sorted(int(k) for k in meta)
|
| 64 |
+
if max_eps:
|
| 65 |
+
eps = eps[:max_eps]
|
| 66 |
+
rec = []
|
| 67 |
+
with h5py.File(hdf5, "r") as f:
|
| 68 |
+
for ep in eps:
|
| 69 |
+
g = f["data"][f"demo_{ep}"]
|
| 70 |
+
P = g["obs"]["robot0_eef_pos"][()].astype(np.float64)
|
| 71 |
+
A = (g["actions_raw"] if "actions_raw" in g else g["actions"])[()].astype(np.float64)[:, :3]
|
| 72 |
+
ef = g["annot"]["edge_from"][()].astype(int)
|
| 73 |
+
et = g["annot"]["edge_to"][()].astype(int)
|
| 74 |
+
T = len(P)
|
| 75 |
+
t = np.arange(0, T - horizon)
|
| 76 |
+
d = A[t + horizon - 1] - P[t]
|
| 77 |
+
rec.append(dict(ep=ep, t=t, p=P[t], d=d, ef=ef[t], et=et[t],
|
| 78 |
+
split=meta[str(ep)]["split"], path=tuple(meta[str(ep)]["path"])))
|
| 79 |
+
return rec
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def stack(rec, which=None):
|
| 83 |
+
sel = [r for r in rec if which is None or r["split"] == which]
|
| 84 |
+
if not sel:
|
| 85 |
+
return dict(ep=np.zeros(0, int), t=np.zeros(0, int), p=np.zeros((0, 3)), d=np.zeros((0, 3)),
|
| 86 |
+
ef=np.zeros(0, int), et=np.zeros(0, int))
|
| 87 |
+
return dict(ep=np.concatenate([np.full(len(r["t"]), r["ep"]) for r in sel]),
|
| 88 |
+
t=np.concatenate([r["t"] for r in sel]),
|
| 89 |
+
p=np.concatenate([r["p"] for r in sel]),
|
| 90 |
+
d=np.concatenate([r["d"] for r in sel]),
|
| 91 |
+
ef=np.concatenate([r["ef"] for r in sel]),
|
| 92 |
+
et=np.concatenate([r["et"] for r in sel]))
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
class EdgeField:
|
| 96 |
+
"""kNN direction field of one edge, fitted on the train split."""
|
| 97 |
+
|
| 98 |
+
def __init__(self, p, u, ep, k=64, min_move_m=2e-3):
|
| 99 |
+
from scipy.spatial import cKDTree
|
| 100 |
+
self.k = k
|
| 101 |
+
self.p, self.u, self.ep = p, u, ep
|
| 102 |
+
self.tree = cKDTree(p) if len(p) else None
|
| 103 |
+
self.min_move_m = min_move_m
|
| 104 |
+
|
| 105 |
+
def __len__(self):
|
| 106 |
+
return len(self.p)
|
| 107 |
+
|
| 108 |
+
def __call__(self, q, exclude_ep=None):
|
| 109 |
+
"""field direction(s) at query position(s) q [.,3] -> unit [.,3] (zeros where no support)."""
|
| 110 |
+
q = np.atleast_2d(np.asarray(q, float))
|
| 111 |
+
out = np.zeros((len(q), 3))
|
| 112 |
+
if self.tree is None:
|
| 113 |
+
return out
|
| 114 |
+
kk = min(self.k if exclude_ep is None else self.k * 4, len(self.p))
|
| 115 |
+
dist, idx = self.tree.query(q, k=kk)
|
| 116 |
+
dist = np.atleast_2d(dist); idx = np.atleast_2d(idx)
|
| 117 |
+
for i in range(len(q)):
|
| 118 |
+
j = idx[i]
|
| 119 |
+
m = np.ones(len(j), bool)
|
| 120 |
+
if exclude_ep is not None:
|
| 121 |
+
m &= (self.ep[j] != exclude_ep[i])
|
| 122 |
+
j = j[m][: self.k]
|
| 123 |
+
if len(j) == 0:
|
| 124 |
+
continue
|
| 125 |
+
out[i] = unit(self.u[j].mean(0))
|
| 126 |
+
return out
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
def fit_fields(tr, k=64, min_move_m=2e-3):
|
| 130 |
+
"""one EdgeField per (from,to) present in the train split."""
|
| 131 |
+
fields, counts = {}, {}
|
| 132 |
+
mag = np.linalg.norm(tr["d"], axis=1)
|
| 133 |
+
keys = sorted(set(zip(tr["ef"].tolist(), tr["et"].tolist())))
|
| 134 |
+
for e in keys:
|
| 135 |
+
m = (tr["ef"] == e[0]) & (tr["et"] == e[1]) & (mag >= min_move_m)
|
| 136 |
+
counts[e] = dict(n_frames=int(m.sum()), n_frames_all=int(((tr["ef"] == e[0]) & (tr["et"] == e[1])).sum()),
|
| 137 |
+
n_episodes=int(len(set(tr["ep"][m].tolist()))))
|
| 138 |
+
fields[e] = EdgeField(tr["p"][m], unit(tr["d"][m]), tr["ep"][m], k=k, min_move_m=min_move_m)
|
| 139 |
+
return fields, counts
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
def edges_from(fields, s):
|
| 143 |
+
return [e for e in fields if e[0] == s]
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
def classify(d, p, fields, avail):
|
| 147 |
+
"""argmax_e cos(d, field_e(p)). d,p are [N,3]; avail is the list of candidate edges.
|
| 148 |
+
Returns (idx into avail [N], cos matrix [N,len(avail)])."""
|
| 149 |
+
F = np.stack([fields[e](p) for e in avail], 1) # [N,E,3]
|
| 150 |
+
c = (unit(d)[:, None, :] * F).sum(-1)
|
| 151 |
+
c[np.isnan(c)] = -1.0
|
| 152 |
+
return c.argmax(1), c
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
# ================================================================================================
|
| 156 |
+
# gen_q#276 STEP 2 -- the five numbers. This is the ONLY place the metric is defined; both
|
| 157 |
+
# scorer_openloop.py (at the end of a run) and edge_report.py (merging shards) call it, so a
|
| 158 |
+
# sharded screen and an unsharded one produce the identical summary.
|
| 159 |
+
# ================================================================================================
|
| 160 |
+
|
| 161 |
+
def rank_pct(s):
|
| 162 |
+
"""for every candidate, the fraction of the OTHER candidates it strictly beats. 1.0 = top.
|
| 163 |
+
|
| 164 |
+
Strictly-lower counting (not average-rank) is deliberate: the reward head saturates on this
|
| 165 |
+
cache and ties at the max are the failure mode we must be able to SEE, so a tied block gets
|
| 166 |
+
the pessimistic percentile and `ties_at_max` is reported beside every number."""
|
| 167 |
+
s = np.asarray(s, np.float64)
|
| 168 |
+
n = len(s)
|
| 169 |
+
if n < 2:
|
| 170 |
+
return np.zeros(n)
|
| 171 |
+
order = np.argsort(s, kind="stable")
|
| 172 |
+
ss = s[order]
|
| 173 |
+
# number of entries strictly below each sorted position
|
| 174 |
+
lower = np.searchsorted(ss, ss, side="left").astype(np.float64)
|
| 175 |
+
out = np.empty(n)
|
| 176 |
+
out[order] = lower / (n - 1)
|
| 177 |
+
return out
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
def _boot_ci(vals, groups, n_boot=2000, seed=0, alpha=0.05):
|
| 181 |
+
"""cluster bootstrap over EPISODES (anchors inside one episode are not independent)."""
|
| 182 |
+
vals = np.asarray(vals, float); groups = np.asarray(groups)
|
| 183 |
+
m = np.isfinite(vals)
|
| 184 |
+
vals, groups = vals[m], groups[m]
|
| 185 |
+
if len(vals) == 0:
|
| 186 |
+
return dict(mean=float("nan"), lo=float("nan"), hi=float("nan"), n=0, n_episodes=0)
|
| 187 |
+
g = np.unique(groups)
|
| 188 |
+
idx = {gg: np.where(groups == gg)[0] for gg in g}
|
| 189 |
+
rng = np.random.default_rng(seed)
|
| 190 |
+
bs = np.empty(n_boot)
|
| 191 |
+
for b in range(n_boot):
|
| 192 |
+
pick = rng.choice(len(g), len(g), replace=True)
|
| 193 |
+
take = np.concatenate([idx[g[p]] for p in pick])
|
| 194 |
+
bs[b] = vals[take].mean()
|
| 195 |
+
return dict(mean=float(vals.mean()), lo=float(np.percentile(bs, 100 * alpha / 2)),
|
| 196 |
+
hi=float(np.percentile(bs, 100 * (1 - alpha / 2))), n=int(len(vals)),
|
| 197 |
+
n_episodes=int(len(g)))
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
def summarise_anchors(recs, modes, seed=0, n_boot=2000):
|
| 201 |
+
"""recs: the per-anchor dicts written by scorer_openloop.py --edge-test.
|
| 202 |
+
|
| 203 |
+
Returns the EDGE_TEST.md numbers per branch state:
|
| 204 |
+
coverage (gate), on-route rank percentile per scorer with the paired delta vs greedy and a
|
| 205 |
+
cluster-bootstrap CI, the permuted control, the counterfactual flip rate, and beside them the
|
| 206 |
+
candidate spread and ties-at-max that say whether the candidate set could carry any signal.
|
| 207 |
+
"""
|
| 208 |
+
cols = list(modes) + ["greedy_idx", "random"]
|
| 209 |
+
res = {"n_anchors_total": len(recs), "states": {}}
|
| 210 |
+
rng = np.random.default_rng(seed)
|
| 211 |
+
for s_ in sorted({int(r["state"]) for r in recs}):
|
| 212 |
+
R = [r for r in recs if int(r["state"]) == s_]
|
| 213 |
+
eps = np.array([int(r["episode"]) for r in R])
|
| 214 |
+
cov = np.array([bool(np.any(r["onroute"])) for r in R])
|
| 215 |
+
nN = np.array([int(r["n_cand"]) for r in R])
|
| 216 |
+
non = np.array([int(np.sum(r["onroute"])) for r in R])
|
| 217 |
+
nundef = np.array([int(np.sum(np.asarray(r["cls"]) < 0)) for r in R])
|
| 218 |
+
d = {"n_anchors": len(R), "n_episodes": int(len(set(eps.tolist()))),
|
| 219 |
+
"avail": R[0]["avail"], "n_cand": int(nN[0]) if len(nN) else 0,
|
| 220 |
+
"coverage": float(cov.mean()),
|
| 221 |
+
"coverage_ci": _boot_ci(cov.astype(float), eps, n_boot, seed),
|
| 222 |
+
"onroute_frac_of_candidates": float((non / np.maximum(nN, 1)).mean()),
|
| 223 |
+
"undirected_frac_of_candidates": float((nundef / np.maximum(nN, 1)).mean()),
|
| 224 |
+
"cand_disp_spread_mm": float(np.mean([r["disp_spread_mm"] for r in R])),
|
| 225 |
+
"cand_disp_mag_mm_mean": float(np.mean([np.mean(r["cand_mag_mm"]) for r in R])),
|
| 226 |
+
"true_edge_counts": {}, "scorers": {}, "flip": {}}
|
| 227 |
+
for r in R:
|
| 228 |
+
d["true_edge_counts"][r["true_edge"]] = d["true_edge_counts"].get(r["true_edge"], 0) + 1
|
| 229 |
+
|
| 230 |
+
# ---- ranking: only anchors where BOTH classes are present can order anything ----------
|
| 231 |
+
contrast = np.array([0 < int(np.sum(r["onroute"])) < int(r["n_cand"]) for r in R])
|
| 232 |
+
d["n_anchors_contrastive"] = int(contrast.sum())
|
| 233 |
+
fail = np.array([bool(r["true_is_failure"]) for r in R])
|
| 234 |
+
d["n_anchors_failure_edge"] = int(fail.sum())
|
| 235 |
+
|
| 236 |
+
def scores_of(r, m):
|
| 237 |
+
n = int(r["n_cand"])
|
| 238 |
+
if m == "greedy_idx":
|
| 239 |
+
return -np.arange(n, dtype=float) # candidate 0 wins; an unbiased draw -> null 0.5
|
| 240 |
+
if m == "random":
|
| 241 |
+
return rng.permutation(n).astype(float)
|
| 242 |
+
sc = r["scores"].get(m)
|
| 243 |
+
return None if sc is None else np.asarray(sc, np.float64)
|
| 244 |
+
|
| 245 |
+
per = {}
|
| 246 |
+
for m in cols:
|
| 247 |
+
rk, tie, flip_c, flip_all, ok = [], [], [], [], []
|
| 248 |
+
for r, c_ in zip(R, contrast):
|
| 249 |
+
sc = scores_of(r, m)
|
| 250 |
+
if sc is None:
|
| 251 |
+
rk.append(np.nan); tie.append(np.nan); ok.append(False); continue
|
| 252 |
+
ok.append(True)
|
| 253 |
+
orr = np.asarray(r["onroute"], bool)
|
| 254 |
+
tie.append(float((sc == sc.max()).sum()))
|
| 255 |
+
rk.append(float(rank_pct(sc)[orr].mean()) if (c_ and orr.any()) else np.nan)
|
| 256 |
+
if r["true_is_failure"]:
|
| 257 |
+
hit = bool(orr[int(np.argmax(sc))])
|
| 258 |
+
flip_all.append(float(hit))
|
| 259 |
+
if orr.any():
|
| 260 |
+
flip_c.append(float(hit))
|
| 261 |
+
if not any(ok):
|
| 262 |
+
continue
|
| 263 |
+
per[m] = np.array(rk)
|
| 264 |
+
d["scorers"][m] = {"onroute_rank_pct": _boot_ci(rk, eps, n_boot, seed),
|
| 265 |
+
"ties_at_max_mean": float(np.nanmean(tie)),
|
| 266 |
+
"ties_at_max_frac_all_tied": float(np.nanmean(np.asarray(tie) >= np.asarray(nN, float)))}
|
| 267 |
+
d["flip"][m] = {"rate_covered_anchors": (float(np.mean(flip_c)) if flip_c else float("nan")),
|
| 268 |
+
"n_covered": len(flip_c),
|
| 269 |
+
"rate_all_failure_anchors": (float(np.mean(flip_all)) if flip_all else float("nan")),
|
| 270 |
+
"n_all": len(flip_all)}
|
| 271 |
+
# ---- paired deltas: same anchors, same candidates, only the ranking rule differs ------
|
| 272 |
+
if "greedy_idx" in per:
|
| 273 |
+
for m in per:
|
| 274 |
+
if m == "greedy_idx":
|
| 275 |
+
continue
|
| 276 |
+
dv = per[m] - per["greedy_idx"]
|
| 277 |
+
d["scorers"][m]["delta_vs_greedy"] = _boot_ci(dv, eps, n_boot, seed)
|
| 278 |
+
for m in [x for x in per if not x.startswith("permuted:")]:
|
| 279 |
+
pm = f"permuted:{m}"
|
| 280 |
+
if pm in per:
|
| 281 |
+
d["scorers"][m]["delta_vs_permuted"] = _boot_ci(per[m] - per[pm], eps, n_boot, seed)
|
| 282 |
+
res["states"][f"S{s_}"] = d
|
| 283 |
+
return res
|
gen_q_rsm/rsm_rise/pipeline/scripts/real/edge_field_validate.py
ADDED
|
@@ -0,0 +1,173 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
"""gen_q#276 STEP 1 validation of the edge-direction estimator. CPU only (annot + eef_pos + actions_raw).
|
| 3 |
+
|
| 4 |
+
Writes one JSON with, per edge: the angular spread of its direction field (global and after conditioning on
|
| 5 |
+
position, leave-one-EPISODE-out); per branch state: the anchor count under the shared-prefix filter, the
|
| 6 |
+
pairwise separation of the fields available there, and the accuracy of classifying the HELD-OUT logged
|
| 7 |
+
action. An edge whose directions do not concentrate cannot classify anything and is reported for exclusion.
|
| 8 |
+
"""
|
| 9 |
+
from __future__ import annotations
|
| 10 |
+
import argparse, json, sys, time
|
| 11 |
+
from pathlib import Path
|
| 12 |
+
import numpy as np
|
| 13 |
+
|
| 14 |
+
sys.path.insert(0, "/proj/dmfexp/zwhong/rsm_rise/scripts/real")
|
| 15 |
+
from edge_field import (ROOT, load_frames, stack, fit_fields, unit, ang_deg, edges_from,
|
| 16 |
+
ON_ROUTE, FAILURE, BRANCH_STATES)
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def main():
|
| 20 |
+
ap = argparse.ArgumentParser()
|
| 21 |
+
ap.add_argument("--horizon", type=int, default=8)
|
| 22 |
+
ap.add_argument("--knn", type=int, default=64)
|
| 23 |
+
ap.add_argument("--min-move-mm", type=float, default=2.0)
|
| 24 |
+
ap.add_argument("--anchor-radius-mm", type=float, default=30.0)
|
| 25 |
+
ap.add_argument("--anchor-min-support", type=int, default=20)
|
| 26 |
+
ap.add_argument("--min-sep-deg", default="0,20,30,45",
|
| 27 |
+
help="admissibility sweep: an anchor is kept only if EVERY pair of edges available "
|
| 28 |
+
"there has fields at least this far apart. 0 = the position-support filter only. "
|
| 29 |
+
"This is a property of the LABELS and the geometry, not of any scorer: at S0 the "
|
| 30 |
+
"on-route edge 0->1 and the failure edge 0->5 both start by reaching for the "
|
| 31 |
+
"tomato, so before the grasp no direction can separate them and an anchor there "
|
| 32 |
+
"carries no information for ANY ranking rule.")
|
| 33 |
+
ap.add_argument("--stride", type=int, default=5, help="subsample frames for the spread stats")
|
| 34 |
+
ap.add_argument("--max-eps", type=int, default=0)
|
| 35 |
+
ap.add_argument("--out", required=True)
|
| 36 |
+
a = ap.parse_args()
|
| 37 |
+
t0 = time.time()
|
| 38 |
+
mm = a.min_move_mm / 1000.0
|
| 39 |
+
rec = load_frames(horizon=a.horizon, max_eps=a.max_eps)
|
| 40 |
+
print(f"[ef] loaded {len(rec)} episodes {time.time()-t0:.0f}s", flush=True)
|
| 41 |
+
tr, va = stack(rec, "train"), stack(rec, "valid")
|
| 42 |
+
fields, counts = fit_fields(tr, k=a.knn, min_move_m=mm)
|
| 43 |
+
print(f"[ef] fields: {sorted(fields)} {time.time()-t0:.0f}s", flush=True)
|
| 44 |
+
|
| 45 |
+
res = {"horizon": a.horizon, "knn": a.knn, "min_move_mm": a.min_move_mm,
|
| 46 |
+
"anchor_radius_mm": a.anchor_radius_mm, "anchor_min_support": a.anchor_min_support,
|
| 47 |
+
"n_episodes": len(rec), "n_frames_train": int(len(tr["t"])), "n_frames_valid": int(len(va["t"])),
|
| 48 |
+
"edges": {}, "branch_states": {}}
|
| 49 |
+
|
| 50 |
+
# ---- per-edge angular spread -------------------------------------------------------------
|
| 51 |
+
for e, F in sorted(fields.items()):
|
| 52 |
+
key = f"{e[0]}->{e[1]}"
|
| 53 |
+
d = {"n_frames_moving": counts[e]["n_frames"], "n_frames_all": counts[e]["n_frames_all"],
|
| 54 |
+
"n_episodes": counts[e]["n_episodes"],
|
| 55 |
+
"on_route": e in ON_ROUTE, "failure": e in FAILURE}
|
| 56 |
+
if len(F) < 50:
|
| 57 |
+
d["status"] = "too few frames"; res["edges"][key] = d; continue
|
| 58 |
+
u = F.u
|
| 59 |
+
gmean = unit(u.mean(0))
|
| 60 |
+
d["global_resultant_R"] = float(np.linalg.norm(u.mean(0)))
|
| 61 |
+
ga = ang_deg(u, gmean[None, :])
|
| 62 |
+
d["global_angle_to_mean_deg"] = {"median": float(np.median(ga)), "p90": float(np.percentile(ga, 90)),
|
| 63 |
+
"mean": float(ga.mean())}
|
| 64 |
+
# conditional (the field actually used): predict each train frame from OTHER episodes' neighbours
|
| 65 |
+
sub = np.arange(0, len(F), max(1, a.stride))
|
| 66 |
+
pred = F(F.p[sub], exclude_ep=F.ep[sub])
|
| 67 |
+
ok = np.linalg.norm(pred, axis=1) > 0.5
|
| 68 |
+
la = ang_deg(u[sub][ok], pred[ok])
|
| 69 |
+
d["conditional_loo_angle_deg"] = {"n": int(ok.sum()), "median": float(np.median(la)),
|
| 70 |
+
"p90": float(np.percentile(la, 90)), "mean": float(la.mean()),
|
| 71 |
+
"frac_within_45deg": float((la < 45).mean()),
|
| 72 |
+
"frac_within_90deg": float((la < 90).mean())}
|
| 73 |
+
# concentration of the conditional residual: R of the residual directions
|
| 74 |
+
d["conditional_resultant_R"] = float(np.linalg.norm(unit(u[sub][ok]).mean(0)))
|
| 75 |
+
d["usable"] = bool(d["conditional_loo_angle_deg"]["median"] < 45.0)
|
| 76 |
+
res["edges"][key] = d
|
| 77 |
+
print(f"[ef] {key:7s} n={len(F):6d} eps={d['n_episodes']:3d} globalR={d['global_resultant_R']:.3f} "
|
| 78 |
+
f"medang={d['global_angle_to_mean_deg']['median']:5.1f} loo_med={np.median(la):5.1f} "
|
| 79 |
+
f"usable={d['usable']}", flush=True)
|
| 80 |
+
|
| 81 |
+
# ---- anchors, separation, held-out logged-action classification ---------------------------
|
| 82 |
+
r = a.anchor_radius_mm / 1000.0
|
| 83 |
+
for s in BRANCH_STATES:
|
| 84 |
+
avail = sorted(edges_from(fields, s))
|
| 85 |
+
key = f"S{s}"
|
| 86 |
+
info = {"available_edges": [f"{u}->{v}" for u, v in avail], "n_edges": len(avail)}
|
| 87 |
+
if len(avail) < 2:
|
| 88 |
+
info["status"] = "not a branch"; res["branch_states"][key] = info; continue
|
| 89 |
+
|
| 90 |
+
def anchors(tab):
|
| 91 |
+
m = tab["ef"] == s
|
| 92 |
+
idx = np.where(m)[0]
|
| 93 |
+
if len(idx) == 0:
|
| 94 |
+
return idx, np.zeros(0, bool)
|
| 95 |
+
p = tab["p"][idx]
|
| 96 |
+
sup = np.ones(len(idx), bool)
|
| 97 |
+
for e in avail:
|
| 98 |
+
F = fields[e]
|
| 99 |
+
cnt = np.array([len(x) for x in F.tree.query_ball_point(p, r)])
|
| 100 |
+
sup &= cnt >= a.anchor_min_support
|
| 101 |
+
return idx, sup
|
| 102 |
+
|
| 103 |
+
thetas = [float(x) for x in a.min_sep_deg.split(",")]
|
| 104 |
+
|
| 105 |
+
def sep_mask(P, theta):
|
| 106 |
+
"""pairwise field separation at each position >= theta (deg)."""
|
| 107 |
+
Fv = {e: fields[e](P) for e in avail}
|
| 108 |
+
m = np.ones(len(P), bool)
|
| 109 |
+
for i in range(len(avail)):
|
| 110 |
+
for j in range(i + 1, len(avail)):
|
| 111 |
+
m &= ang_deg(Fv[avail[i]], Fv[avail[j]]) >= theta
|
| 112 |
+
return m, Fv
|
| 113 |
+
|
| 114 |
+
sweep = {}
|
| 115 |
+
for theta in thetas:
|
| 116 |
+
ent = {}
|
| 117 |
+
for name, tab in (("train", tr), ("valid", va)):
|
| 118 |
+
idx, sup = anchors(tab)
|
| 119 |
+
keep = idx[sup]
|
| 120 |
+
if len(keep):
|
| 121 |
+
ms, Fv = sep_mask(tab["p"][keep], theta)
|
| 122 |
+
keep = keep[ms]
|
| 123 |
+
ent[f"n_frames_at_{name}"] = int(len(idx))
|
| 124 |
+
ent[f"n_anchors_{name}"] = int(len(keep))
|
| 125 |
+
ent[f"anchor_frac_{name}"] = float(len(keep) / max(len(idx), 1))
|
| 126 |
+
if name == "valid":
|
| 127 |
+
vi = keep
|
| 128 |
+
if len(vi):
|
| 129 |
+
P = va["p"][vi]
|
| 130 |
+
Fv = {e: fields[e](P) for e in avail}
|
| 131 |
+
s_ = {}
|
| 132 |
+
for i in range(len(avail)):
|
| 133 |
+
for j in range(i + 1, len(avail)):
|
| 134 |
+
e1, e2 = avail[i], avail[j]
|
| 135 |
+
ang = ang_deg(Fv[e1], Fv[e2])
|
| 136 |
+
s_[f"{e1[0]}->{e1[1]} vs {e2[0]}->{e2[1]}"] = {
|
| 137 |
+
"median_deg": float(np.median(ang)), "p10_deg": float(np.percentile(ang, 10)),
|
| 138 |
+
"frac_below_20deg": float((ang < 20).mean())}
|
| 139 |
+
ent["field_separation_at_valid_anchors"] = s_
|
| 140 |
+
D = va["d"][vi]
|
| 141 |
+
keepm = np.linalg.norm(D, axis=1) >= mm
|
| 142 |
+
true_e = list(zip(va["ef"][vi].tolist(), va["et"][vi].tolist()))
|
| 143 |
+
C = np.stack([Fv[e] for e in avail], 1)
|
| 144 |
+
cos = (unit(D)[:, None, :] * C).sum(-1)
|
| 145 |
+
pred = cos.argmax(1)
|
| 146 |
+
tru = np.array([avail.index(t) for t in true_e])
|
| 147 |
+
ent["heldout_logged_action_classification"] = {
|
| 148 |
+
"n": int(keepm.sum()),
|
| 149 |
+
"accuracy": float((pred[keepm] == tru[keepm]).mean()) if keepm.any() else None,
|
| 150 |
+
"chance": 1.0 / len(avail),
|
| 151 |
+
"n_valid_episodes": int(len(set(va["ep"][vi].tolist()))),
|
| 152 |
+
"per_true_edge": {f"{avail[i][0]}->{avail[i][1]}":
|
| 153 |
+
{"n": int(((tru == i) & keepm).sum()),
|
| 154 |
+
"recall": float((pred[keepm & (tru == i)] == i).mean())
|
| 155 |
+
if (keepm & (tru == i)).any() else None}
|
| 156 |
+
for i in range(len(avail))},
|
| 157 |
+
"confusion": [[int(((tru == i) & (pred == j) & keepm).sum()) for j in range(len(avail))]
|
| 158 |
+
for i in range(len(avail))]}
|
| 159 |
+
acc = ent.get("heldout_logged_action_classification", {}).get("accuracy")
|
| 160 |
+
print(f"[ef] {key} theta={theta:5.1f} anchors valid={ent['n_anchors_valid']:6d}"
|
| 161 |
+
f"/{ent['n_frames_at_valid']} train={ent['n_anchors_train']:6d} "
|
| 162 |
+
f"acc={acc if acc is None else round(acc,4)} chance={1.0/len(avail):.3f}", flush=True)
|
| 163 |
+
sweep[f"{theta:g}"] = ent
|
| 164 |
+
info["min_sep_sweep"] = sweep
|
| 165 |
+
res["branch_states"][key] = info
|
| 166 |
+
|
| 167 |
+
Path(a.out).parent.mkdir(parents=True, exist_ok=True)
|
| 168 |
+
json.dump(res, open(a.out, "w"), indent=1)
|
| 169 |
+
print(f"[ef] wrote {a.out} {time.time()-t0:.0f}s", flush=True)
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
if __name__ == "__main__":
|
| 173 |
+
main()
|
gen_q_rsm/rsm_rise/pipeline/scripts/real/edge_flip_audit.py
ADDED
|
@@ -0,0 +1,306 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
r"""#278 run 34: THE PRE-REGISTERED BAR HAS THREE CLAUSES AND ONLY ONE OF THEM HAS BEEN REPORTED
|
| 2 |
+
AT THE BEST CELL. This applies clause 3 -- the COUNTERFACTUAL FLIP RATE, which rise_stack/EDGE_TEST.md
|
| 3 |
+
(b89c430, unchanged) calls "the sharpest number" -- to the arms already on disk.
|
| 4 |
+
|
| 5 |
+
THE HOLE (why this is a reading, not a new rung). EDGE_TEST.md "Pass bar (pre-registered)" is a
|
| 6 |
+
CONJUNCTION of three clauses:
|
| 7 |
+
(1) proposer coverage of the on-route cluster >= 0.8 of anchors;
|
| 8 |
+
(2) RSM on-route rank percentile > greedy by >= 0.10 and > its permuted control, interval excluding 0;
|
| 9 |
+
(3) counterfactual flip rate at failure anchors >= 0.5 for RSM and STRICTLY GREATER than BC/greedy's.
|
| 10 |
+
Runs 31/32/33 reported (1) and (2) in every table and CLOSED #278 on (2). Clause (3) has been computed
|
| 11 |
+
by edge_field.summarise_anchors into every arm's own edge_test.json since the arm ran -- it was simply
|
| 12 |
+
never carried into the matched tables, so the closing negative quoted one clause of a three-clause bar.
|
| 13 |
+
This run carries all three, on the COMMON episode set, with the episode-cluster interval clause (3)
|
| 14 |
+
never had, and states the OVERLAP: at S0 the only logged failure first edge is 0->5, so clause (3) is
|
| 15 |
+
measured on a SUBSET of the very route that run 33 showed carries the pooled clause-(2) number.
|
| 16 |
+
|
| 17 |
+
NO NEW RULE IS PRE-REGISTERED HERE, AND NONE COULD BE: the flip numbers were already on disk. The
|
| 18 |
+
rule applied is the contract's own clause text, quoted verbatim below, pre-registered at b89c430
|
| 19 |
+
before any arm ran. Nothing is retrained and no model is called: this is a re-read of the existing
|
| 20 |
+
edge_parts/*.npz through edge_field.summarise_anchors, the one place the metric is defined.
|
| 21 |
+
|
| 22 |
+
NO SECOND HARNESS: coverage / rank / flip all come from edge_field.summarise_anchors via
|
| 23 |
+
edge_report.load_dir; the per-anchor recomputation exists ONLY as a self-test that must agree with it
|
| 24 |
+
to 0.00e+00 before any number is printed.
|
| 25 |
+
"""
|
| 26 |
+
import sys, json
|
| 27 |
+
import numpy as np
|
| 28 |
+
sys.path.insert(0, "/proj/dmfexp/zwhong/rsm_rise/scripts/real")
|
| 29 |
+
from pathlib import Path
|
| 30 |
+
from edge_report import load_dir
|
| 31 |
+
from edge_field import summarise_anchors, rank_pct
|
| 32 |
+
|
| 33 |
+
ROOT = Path("/proj/dmfexp/zwhong/rsm_rise/status/real")
|
| 34 |
+
SPLIT = json.load(open("/proj/dmfexp/zwhong/rsm_rise/data/derived/cooking_v5_split.json"))["episodes"]
|
| 35 |
+
N_BOOT = 2000
|
| 36 |
+
BAR = 0.10
|
| 37 |
+
FLIP_BAR = 0.50
|
| 38 |
+
CTRL = "edge_T_rise"
|
| 39 |
+
|
| 40 |
+
# the arms that pin the SAME cell (proposer pi05_cooking_rise/rise_s0/29999, R_XL, beta 0.99 /
|
| 41 |
+
# gamma 0.995) and therefore share an anchor set. T = shipped best cell; AC = flow replicates;
|
| 42 |
+
# AB = particle replicates; V = the trained reward LABELS at this cell.
|
| 43 |
+
ARMS = [("edge_T_rise", "GOAL_EPISODE R_XL s100000 flow 8 p16 (CONTROL = shipped best cell)"),
|
| 44 |
+
("edge_AC_rise_flow4", "GOAL_EPISODE flow 4 (replicate)"),
|
| 45 |
+
("edge_AC_rise_flow16", "GOAL_EPISODE flow 16 (replicate)"),
|
| 46 |
+
("edge_AC_rise_flow32", "GOAL_EPISODE flow 32 (replicate)"),
|
| 47 |
+
("edge_AB_rise_p16_s202", "GOAL_EPISODE p16 seed 202 (replicate)"),
|
| 48 |
+
("edge_AB_rise_p64", "GOAL_EPISODE p64 (replicate)"),
|
| 49 |
+
("edge_AB_rise_p256", "GOAL_EPISODE p256 (replicate)"),
|
| 50 |
+
("edge_V_goalep", "GOAL_EPISODE R_XL_ft_v0 pos share 0.294"),
|
| 51 |
+
("edge_V_goalseg", "GOAL_SEGMENT R_XL_ft_v1 pos share 0.167"),
|
| 52 |
+
("edge_V_win400", "GOAL_WINDOW_400 R_XL_ft_B400 pos share 0.111"),
|
| 53 |
+
("edge_V_win100", "GOAL_WINDOW_100 R_XL_ft_B pos share 0.028")]
|
| 54 |
+
|
| 55 |
+
CLAUSES = {
|
| 56 |
+
1: 'Proposer coverage of the on-route cluster **>= 0.8** of anchors at both branch states.',
|
| 57 |
+
2: ('RSM on-route rank percentile **> greedy by >= 0.10** and **> its permuted control** with a '
|
| 58 |
+
'paired interval that excludes zero, at both S0 and S2, on held-out episodes.'),
|
| 59 |
+
3: ('Counterfactual flip rate at failure anchors **>= 0.5** for RSM and **strictly greater than** '
|
| 60 |
+
"BC/greedy's."),
|
| 61 |
+
}
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def route_of(ep):
|
| 65 |
+
return "->".join(str(x) for x in SPLIT[str(int(ep))]["path"])
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def boot_ci(vals, eps, seed=0, alpha=0.05):
|
| 69 |
+
"""the harness's episode-cluster bootstrap, applied to a per-anchor vector."""
|
| 70 |
+
vals = np.asarray(vals, float); eps = np.asarray(eps)
|
| 71 |
+
m = np.isfinite(vals); vals, eps = vals[m], eps[m]
|
| 72 |
+
if not len(vals):
|
| 73 |
+
return dict(mean=float("nan"), lo=float("nan"), hi=float("nan"), n=0, n_episodes=0)
|
| 74 |
+
g = np.unique(eps); idx = {x: np.where(eps == x)[0] for x in g}
|
| 75 |
+
rng = np.random.default_rng(seed); bs = np.empty(N_BOOT)
|
| 76 |
+
for b in range(N_BOOT):
|
| 77 |
+
take = np.concatenate([idx[g[p]] for p in rng.choice(len(g), len(g), replace=True)])
|
| 78 |
+
bs[b] = vals[take].mean()
|
| 79 |
+
return dict(mean=float(vals.mean()), lo=float(np.percentile(bs, 100 * alpha / 2)),
|
| 80 |
+
hi=float(np.percentile(bs, 100 * (1 - alpha / 2))), n=int(len(vals)),
|
| 81 |
+
n_episodes=int(len(g)))
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def f(d, w=24):
|
| 85 |
+
if not d or not np.isfinite(d.get("mean", float("nan"))):
|
| 86 |
+
return f"{'--':>{w}s}"
|
| 87 |
+
return f"{d['mean']:+.4f}[{d['lo']:+.4f},{d['hi']:+.4f}]".rjust(w)
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def fr(d, w=22):
|
| 91 |
+
if not d or not np.isfinite(d.get("mean", float("nan"))):
|
| 92 |
+
return f"{'--':>{w}s}"
|
| 93 |
+
return f"{d['mean']:.3f}[{d['lo']:.3f},{d['hi']:.3f}]".rjust(w)
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
# ---------------------------------------------------------------- per-anchor flip, recomputed ------
|
| 97 |
+
def flip_vectors(recs, keep, modes):
|
| 98 |
+
"""Per-anchor flip indicator for each scorer, on the CLAUSE-3 anchor set: anchors whose LOGGED
|
| 99 |
+
edge is a failure edge (true_is_failure) AND where the proposer covered the on-route cluster
|
| 100 |
+
(otherwise there is nothing for the argmax to flip TO). Exactly edge_field's own definition."""
|
| 101 |
+
out = {m: [] for m in modes}
|
| 102 |
+
eps, rts, i_greedy = [], [], []
|
| 103 |
+
rng = np.random.default_rng(0)
|
| 104 |
+
for r in recs:
|
| 105 |
+
if int(r["state"]) != 0 or int(r["episode"]) not in keep:
|
| 106 |
+
continue
|
| 107 |
+
if not bool(r["true_is_failure"]):
|
| 108 |
+
continue
|
| 109 |
+
orr = np.asarray(r["onroute"], bool)
|
| 110 |
+
if not orr.any():
|
| 111 |
+
continue
|
| 112 |
+
eps.append(int(r["episode"])); rts.append(route_of(r["episode"]))
|
| 113 |
+
n = int(r["n_cand"])
|
| 114 |
+
for m in modes:
|
| 115 |
+
if m == "greedy_idx":
|
| 116 |
+
sc = -np.arange(n, dtype=float)
|
| 117 |
+
elif m == "random":
|
| 118 |
+
sc = rng.permutation(n).astype(float)
|
| 119 |
+
else:
|
| 120 |
+
s = r["scores"].get(m)
|
| 121 |
+
sc = None if s is None else np.asarray(s, np.float64)
|
| 122 |
+
out[m].append(float(orr[int(np.argmax(sc))]) if sc is not None else np.nan)
|
| 123 |
+
i_greedy.append(0)
|
| 124 |
+
return {m: np.asarray(v, float) for m, v in out.items()}, np.asarray(eps), rts
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
def rank_delta_vec(recs, keep, m, sel=None):
|
| 128 |
+
"""per-anchor (rank_pct of on-route under m) - (under greedy), on contrastive anchors."""
|
| 129 |
+
dv, eps = [], []
|
| 130 |
+
for r in recs:
|
| 131 |
+
if int(r["state"]) != 0 or int(r["episode"]) not in keep:
|
| 132 |
+
continue
|
| 133 |
+
if sel is not None and not sel(r):
|
| 134 |
+
continue
|
| 135 |
+
orr = np.asarray(r["onroute"], bool)
|
| 136 |
+
n = int(r["n_cand"])
|
| 137 |
+
if not (0 < int(orr.sum()) < n):
|
| 138 |
+
continue
|
| 139 |
+
sc = r["scores"].get(m)
|
| 140 |
+
if sc is None:
|
| 141 |
+
continue
|
| 142 |
+
a = rank_pct(np.asarray(sc, np.float64))[orr].mean()
|
| 143 |
+
b = rank_pct(-np.arange(n, dtype=float))[orr].mean()
|
| 144 |
+
dv.append(float(a - b)); eps.append(int(r["episode"]))
|
| 145 |
+
return np.asarray(dv, float), np.asarray(eps)
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
# ---------------------------------------------------------------- load -----------------------------
|
| 149 |
+
raw = {}
|
| 150 |
+
for a, _lab in ARMS:
|
| 151 |
+
recs = load_dir(ROOT / a)
|
| 152 |
+
if recs:
|
| 153 |
+
raw[a] = recs
|
| 154 |
+
if CTRL not in raw:
|
| 155 |
+
raise SystemExit(f"control {CTRL} has no parts on disk -- refusing to print anything")
|
| 156 |
+
|
| 157 |
+
eps_of = {a: {int(r["episode"]) for r in v if int(r["state"]) == 0} for a, v in raw.items()}
|
| 158 |
+
common = set.intersection(*eps_of.values())
|
| 159 |
+
print("landed S0 episodes per arm (completeness line, printed BEFORE any number):")
|
| 160 |
+
for a, lab in ARMS:
|
| 161 |
+
print(f" {a:24s} {len(eps_of.get(a, [])):3d} eps {len(raw.get(a, [])):5d} recs {lab}")
|
| 162 |
+
print(f"\nCOMMON EPISODE SET: {len(common)} episodes -> {sorted(common)}")
|
| 163 |
+
print("route census of the common set:")
|
| 164 |
+
cens = {}
|
| 165 |
+
for e in sorted(common):
|
| 166 |
+
cens.setdefault(route_of(e), []).append(e)
|
| 167 |
+
for k, v in sorted(cens.items()):
|
| 168 |
+
print(f" {k:10s} {len(v)} episodes {v}")
|
| 169 |
+
|
| 170 |
+
summ = {}
|
| 171 |
+
for a in raw:
|
| 172 |
+
r = [x for x in raw[a] if int(x["episode"]) in common]
|
| 173 |
+
modes = sorted({m for x in r for m in x["scores"]})
|
| 174 |
+
summ[a] = summarise_anchors(r, modes, seed=0, n_boot=N_BOOT)["states"]["S0"]
|
| 175 |
+
|
| 176 |
+
# ---------------------------------------------------------------- SELF-TEST ------------------------
|
| 177 |
+
print("\n[selftest] recomputed per-anchor flip vs edge_field.summarise_anchors (must be 0.00e+00):")
|
| 178 |
+
ok = True
|
| 179 |
+
FLIPV, FEPS, FRT = {}, {}, {}
|
| 180 |
+
for a in raw:
|
| 181 |
+
modes = sorted({m for x in raw[a] for m in x["scores"]}) + ["greedy_idx", "random"]
|
| 182 |
+
v, e, rt = flip_vectors([x for x in raw[a] if int(x["episode"]) in common], common, modes)
|
| 183 |
+
FLIPV[a], FEPS[a], FRT[a] = v, e, rt
|
| 184 |
+
# `random` is NOT comparable bitwise: summarise_anchors advances a single rng across its
|
| 185 |
+
# (mode, anchor) loop, so an independent recomputation draws a different permutation. It is a
|
| 186 |
+
# null column, not a measurement, so the self-test asserts 0 on the DETERMINISTIC modes and
|
| 187 |
+
# prints the random column's difference instead of asserting on it.
|
| 188 |
+
errs, per = [], []
|
| 189 |
+
for m, fv in v.items():
|
| 190 |
+
ref = summ[a]["flip"].get(m, {}).get("rate_covered_anchors", np.nan)
|
| 191 |
+
if not (np.isfinite(ref) and len(fv)):
|
| 192 |
+
continue
|
| 193 |
+
e = abs(float(np.nanmean(fv)) - float(ref))
|
| 194 |
+
per.append(f"{m}={e:.0e}")
|
| 195 |
+
if m != "random":
|
| 196 |
+
errs.append(e)
|
| 197 |
+
e_max = max(errs) if errs else float("nan")
|
| 198 |
+
n_ref = summ[a]["flip"].get("rsm", {}).get("n_covered", -1)
|
| 199 |
+
good = np.isfinite(e_max) and e_max < 1e-12 and len(v["rsm"]) == n_ref
|
| 200 |
+
ok &= bool(good)
|
| 201 |
+
print(f" {a:24s} n_flip={len(v['rsm']):4d} (harness {n_ref:4d}) max abs err (deterministic "
|
| 202 |
+
f"modes) {e_max:.2e} {'OK' if good else '*** MISMATCH'} [{' '.join(per)}]")
|
| 203 |
+
# rank delta must also reproduce the published cell
|
| 204 |
+
dv, de = rank_delta_vec([x for x in raw[CTRL] if int(x["episode"]) in common], common, "rsm")
|
| 205 |
+
ref = summ[CTRL]["scorers"]["rsm"]["delta_vs_greedy"]["mean"]
|
| 206 |
+
err = abs(float(dv.mean()) - float(ref))
|
| 207 |
+
print(f" {CTRL:24s} rank delta recomputed {dv.mean():+.6f} vs harness {ref:+.6f} err {err:.2e}"
|
| 208 |
+
f" {'OK' if err < 1e-12 else '*** MISMATCH'}")
|
| 209 |
+
ok &= err < 1e-12
|
| 210 |
+
if not ok:
|
| 211 |
+
raise SystemExit("*** SELF-TEST FAILED -- no number is reported from a harness that disagrees "
|
| 212 |
+
"with its own metric")
|
| 213 |
+
|
| 214 |
+
# ---------------------------------------------------------------- clause 3 table -------------------
|
| 215 |
+
print("\n### CLAUSE 3 -- counterfactual flip rate at failure anchors (contract b89c430: "
|
| 216 |
+
'"the sharpest number")')
|
| 217 |
+
print(" rate over the covered failure anchors; episode-cluster bootstrap over the SAME episodes")
|
| 218 |
+
hdr = (f"{'arm':24s} {'nflip':>5s} {'eps':>4s} | {'rsm':>22s} {'permuted:rsm':>22s} "
|
| 219 |
+
f"{'greedy':>22s} {'idql':>22s} | {'rsm-greedy':>24s} {'rsm-perm':>24s}")
|
| 220 |
+
print(hdr); print("-" * len(hdr))
|
| 221 |
+
FLIP = {}
|
| 222 |
+
for a, lab in ARMS:
|
| 223 |
+
if a not in raw:
|
| 224 |
+
continue
|
| 225 |
+
v, e = FLIPV[a], FEPS[a]
|
| 226 |
+
cells = {m: boot_ci(v[m], e) for m in ("rsm", "permuted:rsm", "greedy_idx", "idql") if m in v}
|
| 227 |
+
dg = boot_ci(v["rsm"] - v["greedy_idx"], e)
|
| 228 |
+
dp = boot_ci(v["rsm"] - v["permuted:rsm"], e) if "permuted:rsm" in v else None
|
| 229 |
+
FLIP[a] = dict(label=lab, n=int(len(v["rsm"])), n_eps=int(len(set(e.tolist()))),
|
| 230 |
+
rates={m: c for m, c in cells.items()}, d_vs_greedy=dg, d_vs_perm=dp)
|
| 231 |
+
print(f"{a:24s} {len(v['rsm']):5d} {len(set(e.tolist())):4d} | "
|
| 232 |
+
f"{fr(cells.get('rsm'))} {fr(cells.get('permuted:rsm'))} "
|
| 233 |
+
f"{fr(cells.get('greedy_idx'))} {fr(cells.get('idql'))} | {f(dg)} {f(dp)}")
|
| 234 |
+
|
| 235 |
+
# ---------------------------------------------------------------- the overlap ----------------------
|
| 236 |
+
print("\n### THE OVERLAP -- clause 3 and clause 2 are read out of the SAME route")
|
| 237 |
+
rts = FRT[CTRL]
|
| 238 |
+
comp = {}
|
| 239 |
+
for r in rts:
|
| 240 |
+
comp[r] = comp.get(r, 0) + 1
|
| 241 |
+
print(f" routes contributing clause-3 anchors: {comp}")
|
| 242 |
+
print(" (at S0 the only logged failure first edge is 0->5, so clause 3 is a SUBSET of the route that")
|
| 243 |
+
print(" run 33 measured as carrying the pooled clause-2 number: 0->5 d=+0.1340 vs on-route +0.0448)")
|
| 244 |
+
d_in, e_in = rank_delta_vec([x for x in raw[CTRL] if int(x["episode"]) in common], common, "rsm",
|
| 245 |
+
sel=lambda r: bool(r["true_is_failure"]))
|
| 246 |
+
d_out, e_out = rank_delta_vec([x for x in raw[CTRL] if int(x["episode"]) in common], common, "rsm",
|
| 247 |
+
sel=lambda r: not bool(r["true_is_failure"]))
|
| 248 |
+
ci_in, ci_out = boot_ci(d_in, e_in), boot_ci(d_out, e_out)
|
| 249 |
+
print(f" clause-2 delta ON the failure-edge anchors {f(ci_in)} n={ci_in['n']} eps={ci_in['n_episodes']}")
|
| 250 |
+
print(f" clause-2 delta OFF them (the other three routes){f(ci_out)} n={ci_out['n']} eps={ci_out['n_episodes']}")
|
| 251 |
+
|
| 252 |
+
# ---------------------------------------------------------------- the three clauses ----------------
|
| 253 |
+
print("\n### THE PRE-REGISTERED BAR, ALL THREE CLAUSES, AT THE BEST CELL (contract b89c430 verbatim)")
|
| 254 |
+
c = summ[CTRL]
|
| 255 |
+
cov = c["coverage"]
|
| 256 |
+
rk = c["scorers"]["rsm"]
|
| 257 |
+
c2_dg, c2_dp = rk["delta_vs_greedy"], rk["delta_vs_permuted"]
|
| 258 |
+
fl = FLIP[CTRL]
|
| 259 |
+
c1 = cov >= 0.8
|
| 260 |
+
c2 = (c2_dg["mean"] >= BAR) and (c2_dp["mean"] > 0) and (c2_dg["lo"] > 0)
|
| 261 |
+
c3 = (fl["rates"]["rsm"]["mean"] >= FLIP_BAR
|
| 262 |
+
and fl["rates"]["rsm"]["mean"] > fl["rates"]["greedy_idx"]["mean"])
|
| 263 |
+
c3_strict = c3 and fl["d_vs_greedy"]["lo"] > 0
|
| 264 |
+
for i, (flagv, txt, ev) in enumerate([
|
| 265 |
+
(c1, CLAUSES[1], f"coverage {cov:.3f} (S0 only; no S2 arm at this cell)"),
|
| 266 |
+
(c2, CLAUSES[2], f"d_vs_greedy {f(c2_dg).strip()} vs bar +{BAR:.2f}; d_vs_perm {f(c2_dp).strip()}"),
|
| 267 |
+
(c3, CLAUSES[3], f"flip {fr(fl['rates']['rsm']).strip()} vs bar {FLIP_BAR:.2f}; "
|
| 268 |
+
f"greedy {fr(fl['rates']['greedy_idx']).strip()}; "
|
| 269 |
+
f"paired rsm-greedy {f(fl['d_vs_greedy']).strip()}")], 1):
|
| 270 |
+
print(f" CLAUSE {i}: {'PASS' if flagv else 'FAIL'} {txt}")
|
| 271 |
+
print(f" evidence: {ev}")
|
| 272 |
+
print(f" CLAUSE 3 with the interval as well (paired rsm-greedy excludes 0): "
|
| 273 |
+
f"{'PASS' if c3_strict else 'FAIL'}")
|
| 274 |
+
print(f"\n CONJUNCTION (the bar as written): {'PASS' if (c1 and c2 and c3) else 'FAIL'}"
|
| 275 |
+
f" -- clauses passing: {sum([c1, c2, c3])}/3, failing: "
|
| 276 |
+
f"{[i for i, x in enumerate([c1, c2, c3], 1) if not x]}")
|
| 277 |
+
print(" The bar is a CONJUNCTION, so the verdict on #278 is unchanged: FAIL. What changes is the")
|
| 278 |
+
print(" auditable description of the failure -- it fails on clause 2 ALONE, with clauses 1 and 3")
|
| 279 |
+
print(" passing at the best cell, and clause 3 is the one the contract calls the sharpest number.")
|
| 280 |
+
print(" Caveat carried with clause 3: it lives on the 0->5 route, 5 held-out episodes, so its")
|
| 281 |
+
print(" cluster interval is wide and it is NOT independent evidence from the pooled clause-2 number.")
|
| 282 |
+
|
| 283 |
+
out = {"_meta": dict(common_episodes=sorted(common), n_boot=N_BOOT, bar=BAR, flip_bar=FLIP_BAR,
|
| 284 |
+
control=CTRL, contract="rise_stack/EDGE_TEST.md b89c430 (unchanged)",
|
| 285 |
+
route_census={k: v for k, v in sorted(cens.items())}),
|
| 286 |
+
"_clauses": {"text": CLAUSES,
|
| 287 |
+
"control_result": {"clause1_coverage": bool(c1), "clause2_rank": bool(c2),
|
| 288 |
+
"clause3_flip": bool(c3),
|
| 289 |
+
"clause3_flip_interval_too": bool(c3_strict),
|
| 290 |
+
"conjunction": bool(c1 and c2 and c3),
|
| 291 |
+
"n_passing": int(sum([c1, c2, c3]))}},
|
| 292 |
+
"_overlap": {"routes_of_clause3_anchors": comp,
|
| 293 |
+
"clause2_on_failure_edge_anchors": ci_in,
|
| 294 |
+
"clause2_off_failure_edge_anchors": ci_out},
|
| 295 |
+
"arms": {a: dict(coverage=summ[a]["coverage"], n_anchors=summ[a]["n_anchors"],
|
| 296 |
+
d_vs_greedy=summ[a]["scorers"]["rsm"].get("delta_vs_greedy"),
|
| 297 |
+
d_vs_perm=summ[a]["scorers"]["rsm"].get("delta_vs_permuted"),
|
| 298 |
+
flip=FLIP.get(a)) for a in raw},
|
| 299 |
+
"_reading": ("Clause 3 of the pre-registered three-clause bar PASSES at the best cell "
|
| 300 |
+
"(flip 0.745 >= 0.50 and > greedy 0.519) and clause 1 passes (coverage 0.904); "
|
| 301 |
+
"the conjunction FAILS on clause 2 alone (+0.0909 < +0.10). Clause 3's anchors "
|
| 302 |
+
"are the 0->5 route only, the same route that carries the pooled clause-2 "
|
| 303 |
+
"number, so the two are not independent evidence.")}
|
| 304 |
+
p = ROOT / "EDGE_FLIP_AUDIT.json"
|
| 305 |
+
json.dump(out, open(p, "w"), indent=1, default=float)
|
| 306 |
+
print(f"\nwrote {p}")
|
gen_q_rsm/rsm_rise/pipeline/scripts/real/edge_goalbound_auc.py
ADDED
|
@@ -0,0 +1,246 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
r"""#278 run 35 (reduction, no new arm, no model call): IS THERE **ANY** ALREADY-MEASURED CONFIGURATION
|
| 2 |
+
THAT RANKS THE DIRECTIONALLY-CORRECT ACTIONS ABOVE THE WRONG ONES AT THE **GOAL-BOUND** S0 ANCHORS,
|
| 3 |
+
IN UNITS THE PRE-REGISTERED BAR CANNOT REACH THERE?
|
| 4 |
+
|
| 5 |
+
Run 34 proved a property of the metric, not of a model: the headline d_vs_greedy is LEVERAGE-WEIGHTED
|
| 6 |
+
(w = n_off/(n-1)), and at the goal-bound anchors w_bar is 0.070-0.203, so clearing the pooled +0.10
|
| 7 |
+
would need a per-anchor AUC of 1.053 (destiny=goal) to 1.920 (route 0->2->3) -- ABOVE 1, i.e.
|
| 8 |
+
IMPOSSIBLE for a perfect scorer. Every ladder number since run 20 has therefore been reported in a
|
| 9 |
+
unit that is structurally incapable of certifying the states a planner actually needs.
|
| 10 |
+
|
| 11 |
+
The leverage-free statistic already exists inside the same identity (edge_ceiling2.py, verified to
|
| 12 |
+
4 dp against edge_field.rank_pct):
|
| 13 |
+
mean rank_pct over on-route = [ (n_on-1)/2 + n_off * AUC ] / (n-1)
|
| 14 |
+
The per-anchor Mann-Whitney AUC is the ONLY scorer-dependent term. Averaging it UNWEIGHTED over
|
| 15 |
+
anchors asks the planner question directly -- "does the scorer put on-route candidates above
|
| 16 |
+
off-route ones at this state" -- with chance at 0.5 and no leverage factor. This run reports that
|
| 17 |
+
number, with its cluster bootstrap and its permuted null, for EVERY arm on disk at the common S0
|
| 18 |
+
anchor set. It is a reduction of shards already measured; it cannot and does not move the fired
|
| 19 |
+
pre-registered rule on #278 (which stays FAIL / CLOSED and is printed unchanged beside it).
|
| 20 |
+
|
| 21 |
+
**IT IS A SECONDARY DIAGNOSTIC, NOT THE BAR.** The pre-registered metric and the +0.10 bar in
|
| 22 |
+
rise_stack/EDGE_TEST.md are untouched and byte-identical to b89c430.
|
| 23 |
+
|
| 24 |
+
MULTIPLICITY IS PRE-REGISTERED, because ~40 arms are screened: an arm COUNTS as clearing only if its
|
| 25 |
+
Bonferroni-adjusted interval (alpha = 0.05/K, K = number of arms screened, two-sided) excludes the
|
| 26 |
+
null. Raw 95% intervals are printed too and are explicitly labelled as screening-only.
|
| 27 |
+
|
| 28 |
+
PRE-REGISTERED READING (written before any goal-bound AUC was computed; the only goal-bound numbers
|
| 29 |
+
published so far are the CONTROL arm's AUCw 0.616 / greedy 0.475 from run 34, in WEIGHTED units):
|
| 30 |
+
(i) At least one arm has goal-bound AUC_u > 0.5 AND paired (rsm - permuted) > 0, BOTH with
|
| 31 |
+
Bonferroni intervals excluding the null -> the scorer DOES rank directionally-correct actions
|
| 32 |
+
at the goal-bound states; the pooled FAIL is then a limit of the leverage-weighted metric at
|
| 33 |
+
those anchors, not an absence of signal. Name the arm, its number, and say plainly that this
|
| 34 |
+
is not a pass of the pre-registered bar.
|
| 35 |
+
(ii) No arm clears both under Bonferroni, and the CONTROL's raw interval does not exclude the null
|
| 36 |
+
either -> the closed negative is ROBUST in leverage-free units: there is no measurable
|
| 37 |
+
preference for the correct direction at the goal-bound anchors on anything trained so far.
|
| 38 |
+
(iii) Point estimates above the null but no interval excludes it -> UNDERPOWERED at 8-10 held-out
|
| 39 |
+
episodes; report the episode count a half-width would need and say the cell cannot decide.
|
| 40 |
+
|
| 41 |
+
CAVEAT THAT MUST TRAVEL WITH EVERY NUMBER HERE (measured from data/derived/cooking_v5_split.json):
|
| 42 |
+
NO held-out S0 episode reaches S4. The "goal-bound" group is routes 0->1->3 and 0->2->3, i.e.
|
| 43 |
+
COOKING-bound; route 2->3->4 does not start at S0. That is the owner's stitching point itself --
|
| 44 |
+
answering "what to do at S0 to reach the goal" requires composing across episodes -- and it means
|
| 45 |
+
this cell measures destiny=cooking, never destiny=S4.
|
| 46 |
+
|
| 47 |
+
Cross-arm comparisons carry run 33's candidate gate: the anchors are identical across arms
|
| 48 |
+
(ee_xyz and logged action 291/291) but 45-99 % of the 128 candidates are redrawn, so between-arm
|
| 49 |
+
differences include sampling noise (candidate-matched rho 0.903 at this cell, rung AB). Each arm's
|
| 50 |
+
OWN AUC vs its OWN greedy/permuted is within-arm and unaffected.
|
| 51 |
+
"""
|
| 52 |
+
import sys, os, json, glob
|
| 53 |
+
import numpy as np
|
| 54 |
+
|
| 55 |
+
sys.path.insert(0, "/proj/dmfexp/zwhong/rsm_rise/scripts/real")
|
| 56 |
+
from edge_ceiling2 import arm as ceiling_arm, auc as mw_auc
|
| 57 |
+
|
| 58 |
+
ROOT = "/proj/dmfexp/zwhong/rsm_rise/status/real"
|
| 59 |
+
SPLIT = json.load(open("/proj/dmfexp/zwhong/rsm_rise/data/derived/cooking_v5_split.json"))["episodes"]
|
| 60 |
+
COMMON = [7, 9, 12, 22, 46, 52, 54, 68, 73, 86, 105, 107, 120, 131, 137, 204, 223, 224, 230, 231]
|
| 61 |
+
CONTROL = "edge_T_rise"
|
| 62 |
+
NB, SEED = 20000, 0
|
| 63 |
+
COLS = {"rsm": "score_rsm", "perm": "score_permuted__rsm",
|
| 64 |
+
"idql": "score_idql", "permi": "score_permuted__idql"}
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def route_of(e):
|
| 68 |
+
return "->".join(str(x) for x in SPLIT[str(int(e))]["path"])
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def destiny_of(e):
|
| 72 |
+
return "goalbound" if SPLIT[str(int(e))]["final_state"] in (3, 4) else "failure"
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
GOALBOUND = [e for e in COMMON if destiny_of(e) == "goalbound"]
|
| 76 |
+
FAILURE = [e for e in COMMON if destiny_of(e) == "failure"]
|
| 77 |
+
GROUPS = [("DEST_goalbound", GOALBOUND), ("DEST_failure", FAILURE), ("ALL", COMMON)]
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def per_anchor(d, keep):
|
| 81 |
+
"""Per-anchor Mann-Whitney AUC of on-route vs off-route candidates, per scorer.
|
| 82 |
+
Same loop, same filters, same `auc` as edge_ceiling2.arm -- only the aggregation differs."""
|
| 83 |
+
out = {k: [] for k in COLS}
|
| 84 |
+
out["greedy"] = []
|
| 85 |
+
EP, W = [], []
|
| 86 |
+
for f in sorted(glob.glob(f"{d}/edge_parts/*.npz")):
|
| 87 |
+
e = int(f.split("/")[-1][2:-4])
|
| 88 |
+
if e not in keep:
|
| 89 |
+
continue
|
| 90 |
+
z = np.load(f, allow_pickle=True)
|
| 91 |
+
if "onroute" not in z.files:
|
| 92 |
+
continue
|
| 93 |
+
onr = np.asarray(z["onroute"], bool)
|
| 94 |
+
for i in range(onr.shape[0]):
|
| 95 |
+
o = onr[i]
|
| 96 |
+
n = o.size
|
| 97 |
+
n_on = int(o.sum())
|
| 98 |
+
if not (0 < n_on < n):
|
| 99 |
+
continue
|
| 100 |
+
EP.append(e)
|
| 101 |
+
W.append((n - n_on) / (n - 1.0))
|
| 102 |
+
out["greedy"].append(mw_auc(-np.arange(n, dtype=float), o))
|
| 103 |
+
for k, key in COLS.items():
|
| 104 |
+
out[k].append(mw_auc(z[key][i].astype(np.float64), o) if key in z.files else np.nan)
|
| 105 |
+
return ({k: np.asarray(v) for k, v in out.items()},
|
| 106 |
+
np.asarray(EP, int), np.asarray(W, float))
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def boot_matrix(EP, nb=NB, seed=SEED):
|
| 110 |
+
"""Cluster (episode) bootstrap as an exact count matrix: B[b,i] = times anchor i's episode drawn."""
|
| 111 |
+
u = np.unique(EP)
|
| 112 |
+
rng = np.random.default_rng(seed)
|
| 113 |
+
draw = rng.choice(u.size, (nb, u.size), replace=True)
|
| 114 |
+
cnt = np.zeros((nb, u.size), np.int32)
|
| 115 |
+
np.add.at(cnt, (np.repeat(np.arange(nb), u.size), draw.ravel()), 1)
|
| 116 |
+
idx = np.searchsorted(u, EP)
|
| 117 |
+
return cnt[:, idx].astype(np.float64), u.size
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def ci(v, B, alpha):
|
| 121 |
+
"""Mean of v with a cluster-bootstrap percentile interval at level alpha (two-sided)."""
|
| 122 |
+
m = float(np.mean(v))
|
| 123 |
+
bm = (B @ v) / B.sum(1)
|
| 124 |
+
return m, float(np.percentile(bm, 100 * alpha / 2)), float(np.percentile(bm, 100 * (1 - alpha / 2)))
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
# ---------------- arms on disk at the common S0 anchor set ----------------
|
| 128 |
+
ARMS = []
|
| 129 |
+
for d in sorted(glob.glob(f"{ROOT}/edge_*")):
|
| 130 |
+
have = {int(f.split("/")[-1][2:-4]) for f in glob.glob(f"{d}/edge_parts/*.npz")}
|
| 131 |
+
if set(COMMON).issubset(have):
|
| 132 |
+
ARMS.append(d.rstrip("/").split("/")[-1])
|
| 133 |
+
K = len(ARMS)
|
| 134 |
+
ALPHA_B = 0.05 / max(K, 1)
|
| 135 |
+
print(f"S0 arms covering all {len(COMMON)} common held-out episodes: K = {K}")
|
| 136 |
+
print(f" goal-bound (destiny cooking) episodes: {GOALBOUND} routes "
|
| 137 |
+
f"{sorted({route_of(e) for e in GOALBOUND})}")
|
| 138 |
+
print(f" failure episodes: {FAILURE} routes "
|
| 139 |
+
f"{sorted({route_of(e) for e in FAILURE})}")
|
| 140 |
+
print(f" NO held-out S0 episode reaches S4: final states "
|
| 141 |
+
f"{sorted({SPLIT[str(e)]['final_state'] for e in COMMON})}")
|
| 142 |
+
print(f" Bonferroni alpha = 0.05/{K} = {ALPHA_B:.5f} (two-sided, {NB} cluster bootstraps)\n")
|
| 143 |
+
|
| 144 |
+
# ---------------- SELF-TEST, printed before any new number ----------------
|
| 145 |
+
print("SELF-TEST -- per-anchor AUCs must reproduce edge_ceiling2.arm() exactly (it produced every")
|
| 146 |
+
print("published ceiling/%ceil number), on the CONTROL arm, for every group:")
|
| 147 |
+
ok = True
|
| 148 |
+
for g, eps in GROUPS:
|
| 149 |
+
A, EP, W = per_anchor(f"{ROOT}/{CONTROL}", set(eps))
|
| 150 |
+
r = ceiling_arm(f"{ROOT}/{CONTROL}", keep=set(eps))
|
| 151 |
+
w_rsm = float((W * A["rsm"]).sum() / W.sum())
|
| 152 |
+
d_rsm = float((W * (A["rsm"] - A["greedy"])).mean())
|
| 153 |
+
e1 = abs(w_rsm - r["auc_rsm"]["weighted"])
|
| 154 |
+
e2 = abs(d_rsm - r["d_vs_greedy_rsm"])
|
| 155 |
+
e3 = abs(len(W) - r["n_anchors"])
|
| 156 |
+
ok &= (e1 < 1e-12 and e2 < 1e-12 and e3 == 0)
|
| 157 |
+
print(f" {g:16s} n={len(W):4d} (harness {r['n_anchors']:4d}) AUCw err {e1:.2e} "
|
| 158 |
+
f"d_vs_greedy err {e2:.2e} [harness d_rsm {r['d_vs_greedy_rsm']:+.4f}]")
|
| 159 |
+
assert ok, "self-test FAILED -- no number printed"
|
| 160 |
+
print(" PASS -- the reduction reads the same anchors and the same scores as every published cell.\n")
|
| 161 |
+
|
| 162 |
+
# ---------------- the table ----------------
|
| 163 |
+
res = {"_meta": dict(K=K, arms=ARMS, alpha_bonf=ALPHA_B, nb=NB,
|
| 164 |
+
goalbound_episodes=GOALBOUND, failure_episodes=FAILURE,
|
| 165 |
+
note="UNWEIGHTED per-anchor Mann-Whitney AUC, on-route vs off-route candidates; "
|
| 166 |
+
"chance 0.5; secondary diagnostic, NOT the pre-registered bar")}
|
| 167 |
+
for g, eps in GROUPS:
|
| 168 |
+
print(f"\n### GROUP {g} ({len(eps)} episodes: {eps})")
|
| 169 |
+
hdr = (f"{'arm':38s} {'ep':>2s} {'anc':>4s} | {'AUCu_rsm':>8s} {'raw95':>17s} "
|
| 170 |
+
f"{'bonf':>17s} | {'greedy':>6s} {'perm':>6s} {'idql':>6s} | "
|
| 171 |
+
f"{'rsm-perm':>9s} {'bonf':>17s}")
|
| 172 |
+
print(hdr)
|
| 173 |
+
print("-" * len(hdr))
|
| 174 |
+
res[g] = {}
|
| 175 |
+
for a in ARMS:
|
| 176 |
+
A, EP, W = per_anchor(f"{ROOT}/{a}", set(eps))
|
| 177 |
+
if not len(W):
|
| 178 |
+
continue
|
| 179 |
+
B, nep = boot_matrix(EP)
|
| 180 |
+
m, lo, hi = ci(A["rsm"], B, 0.05)
|
| 181 |
+
_, blo, bhi = ci(A["rsm"], B, ALPHA_B)
|
| 182 |
+
dp, dplo, dphi = ci(A["rsm"] - A["perm"], B, 0.05)
|
| 183 |
+
_, dpblo, dpbhi = ci(A["rsm"] - A["perm"], B, ALPHA_B)
|
| 184 |
+
dg, dglo, dghi = ci(A["rsm"] - A["greedy"], B, 0.05)
|
| 185 |
+
_, dgblo, dgbhi = ci(A["rsm"] - A["greedy"], B, ALPHA_B)
|
| 186 |
+
row = dict(n_episodes=int(nep), n_anchors=int(len(W)), w_bar=float(W.mean()),
|
| 187 |
+
auc_rsm=m, auc_rsm_raw95=[lo, hi], auc_rsm_bonf=[blo, bhi],
|
| 188 |
+
auc_greedy=float(A["greedy"].mean()), auc_perm=float(np.nanmean(A["perm"])),
|
| 189 |
+
auc_idql=float(np.nanmean(A["idql"])), auc_permi=float(np.nanmean(A["permi"])),
|
| 190 |
+
d_rsm_perm=dp, d_rsm_perm_raw95=[dplo, dphi], d_rsm_perm_bonf=[dpblo, dpbhi],
|
| 191 |
+
d_rsm_greedy=dg, d_rsm_greedy_raw95=[dglo, dghi],
|
| 192 |
+
d_rsm_greedy_bonf=[dgblo, dgbhi],
|
| 193 |
+
clears_bonf=bool(blo > 0.5 and dpblo > 0.0),
|
| 194 |
+
clears_raw=bool(lo > 0.5 and dplo > 0.0))
|
| 195 |
+
res[g][a] = row
|
| 196 |
+
star = "**" if row["clears_bonf"] else (" *" if row["clears_raw"] else " ")
|
| 197 |
+
print(f"{a:38s} {nep:2d} {len(W):4d} | {m:8.3f} [{lo:+.3f},{hi:+.3f}] "
|
| 198 |
+
f"[{blo:+.3f},{bhi:+.3f}] | {A['greedy'].mean():6.3f} "
|
| 199 |
+
f"{np.nanmean(A['perm']):6.3f} {np.nanmean(A['idql']):6.3f} | "
|
| 200 |
+
f"{dp:+9.4f} [{dpblo:+.3f},{dpbhi:+.3f}]{star}")
|
| 201 |
+
|
| 202 |
+
# ---------------- the mechanical reading ----------------
|
| 203 |
+
G = res["DEST_goalbound"]
|
| 204 |
+
clear_b = [a for a, r in G.items() if r["clears_bonf"]]
|
| 205 |
+
clear_r = [a for a, r in G.items() if r["clears_raw"]]
|
| 206 |
+
above = [a for a, r in G.items() if r["auc_rsm"] > 0.5 and r["d_rsm_perm"] > 0]
|
| 207 |
+
ctrl = G.get(CONTROL, {})
|
| 208 |
+
print("\n" + "=" * 100)
|
| 209 |
+
print(f"GOAL-BOUND CELL: {len(G)} arms screened; {len(above)} have point estimates above BOTH nulls; "
|
| 210 |
+
f"{len(clear_r)} clear at raw 95 %; {len(clear_b)} clear under Bonferroni.")
|
| 211 |
+
if clear_b:
|
| 212 |
+
best = max(clear_b, key=lambda a: G[a]["auc_rsm"])
|
| 213 |
+
print(f"READING (i) FIRES: {len(clear_b)} arm(s) clear both nulls under Bonferroni. Best: {best} "
|
| 214 |
+
f"AUC_u {G[best]['auc_rsm']:.3f} bonf {G[best]['auc_rsm_bonf']}, "
|
| 215 |
+
f"rsm-perm {G[best]['d_rsm_perm']:+.4f} bonf {G[best]['d_rsm_perm_bonf']}.")
|
| 216 |
+
print(" -> the scorer ranks directionally-correct actions at the goal-bound S0 anchors; the "
|
| 217 |
+
"pooled FAIL is a limit of the leverage-weighted metric there. NOT a pass of the bar.")
|
| 218 |
+
elif not clear_r and not (ctrl and ctrl["auc_rsm_raw95"][0] > 0.5):
|
| 219 |
+
print("READING (ii) FIRES: no arm clears under Bonferroni and the control's raw interval does not "
|
| 220 |
+
"exclude chance either -> the closed negative is ROBUST in leverage-free units.")
|
| 221 |
+
if ctrl:
|
| 222 |
+
hw = (ctrl["auc_rsm_raw95"][1] - ctrl["auc_rsm_raw95"][0]) / 2
|
| 223 |
+
need = ctrl["auc_rsm"] - 0.5
|
| 224 |
+
print(f" control AUC_u {ctrl['auc_rsm']:.3f} raw95 {ctrl['auc_rsm_raw95']}, "
|
| 225 |
+
f"half-width {hw:.4f}, distance from chance {need:+.4f}, "
|
| 226 |
+
f"episodes needed for the point estimate to clear chance: "
|
| 227 |
+
f"{(ctrl['n_episodes'] * (hw / max(need, 1e-9)) ** 2):.0f} (vs {ctrl['n_episodes']} today)")
|
| 228 |
+
else:
|
| 229 |
+
print("READING (iii) FIRES: point estimates above the nulls but no arm clears under Bonferroni "
|
| 230 |
+
"-> the cell is UNDERPOWERED at this episode count and cannot decide.")
|
| 231 |
+
if ctrl:
|
| 232 |
+
hw = (ctrl["auc_rsm_raw95"][1] - ctrl["auc_rsm_raw95"][0]) / 2
|
| 233 |
+
need = max(ctrl["auc_rsm"] - 0.5, 1e-9)
|
| 234 |
+
print(f" control AUC_u {ctrl['auc_rsm']:.3f} raw95 {ctrl['auc_rsm_raw95']} "
|
| 235 |
+
f"(raw-95 clearing arms: {clear_r})")
|
| 236 |
+
print(f" half-width {hw:.4f} vs distance from chance {need:+.4f} -> "
|
| 237 |
+
f"~{ctrl['n_episodes'] * (hw / need) ** 2:.0f} held-out goal-bound episodes needed "
|
| 238 |
+
f"(today {ctrl['n_episodes']}).")
|
| 239 |
+
print("=" * 100)
|
| 240 |
+
print("\nThe pre-registered #278 verdict is UNCHANGED and is not a function of anything above:")
|
| 241 |
+
print(" clause 1 coverage 0.904 PASS | clause 2 +0.0909 [+0.0373,+0.1480] vs +0.10 FAIL | "
|
| 242 |
+
"clause 3 flip 0.745 vs greedy 0.519 PASS -> CONJUNCTION FAIL, #278 stays CLOSED.")
|
| 243 |
+
|
| 244 |
+
out = f"{ROOT}/EDGE_GOALBOUND_AUC.json"
|
| 245 |
+
json.dump(res, open(out, "w"), indent=1, default=float)
|
| 246 |
+
print("\nwrote", out)
|
gen_q_rsm/rsm_rise/pipeline/scripts/real/edge_interaction_AA.py
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
r"""#278 run 29: the PAIRED interaction of the successor x depth 2x2, with a cluster bootstrap.
|
| 2 |
+
|
| 3 |
+
Run 28's `_edgeAA_matched.json` reports the interaction as a difference of four independently
|
| 4 |
+
bootstrapped arm means (-0.0061) with no interval, so it cannot say whether the landscape is a
|
| 5 |
+
plane. This re-reads the SAME edge_parts/*.npz and computes the statistic PAIRED at the anchor
|
| 6 |
+
level -- every anchor that exists in all four arms -- so the arm-to-arm anchor noise cancels and the
|
| 7 |
+
bootstrap is over episodes only. No model call, no new experiment: CPU re-read.
|
| 8 |
+
|
| 9 |
+
d(arm, anchor) = rank_pct_rsm - rank_pct_greedy (the metric's own per-anchor contribution)
|
| 10 |
+
successor effect = mean_a [ d(T,a) - d(V,a) ] at depth h 1.01
|
| 11 |
+
mean_a [ d(AA,a) - d(ha,a) ] at depth h 0.34
|
| 12 |
+
depth effect = mean_a [ d(ha,a) - d(V,a) ] on R_XL_ft_v0
|
| 13 |
+
mean_a [ d(AA,a) - d(T,a) ] on R_XL
|
| 14 |
+
INTERACTION = mean_a [ (d(AA,a)-d(T,a)) - (d(ha,a)-d(V,a)) ]
|
| 15 |
+
|
| 16 |
+
An interaction whose CI covers 0 means the two axes ADD: the four measured corners then determine
|
| 17 |
+
the whole plane, and no unmeasured combination of successor x depth can reach the +0.10 bar.
|
| 18 |
+
"""
|
| 19 |
+
import sys, json
|
| 20 |
+
import numpy as np
|
| 21 |
+
from pathlib import Path
|
| 22 |
+
|
| 23 |
+
sys.path.insert(0, "/proj/dmfexp/zwhong/rsm_rise/scripts/real")
|
| 24 |
+
from edge_report import load_dir
|
| 25 |
+
from edge_field import rank_pct
|
| 26 |
+
|
| 27 |
+
ROOT = Path("/proj/dmfexp/zwhong/rsm_rise/status/real")
|
| 28 |
+
ARMS = {"AA": "edge_AA_rxl_ha", # R_XL, h 0.34
|
| 29 |
+
"T": "edge_T_rise", # R_XL, h 1.01
|
| 30 |
+
"ha": "edge_Z_goalep_ha", # R_XL_ft_v0, h 0.34
|
| 31 |
+
"V": "edge_V_goalep"} # R_XL_ft_v0, h 1.01
|
| 32 |
+
N_BOOT, SEED, STATE = 4000, 0, 0
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def per_anchor(d):
|
| 36 |
+
"""{(episode, frame): d_vs_greedy} over contrastive S0 anchors."""
|
| 37 |
+
out = {}
|
| 38 |
+
for r in load_dir(ROOT / d):
|
| 39 |
+
if int(r["state"]) != STATE:
|
| 40 |
+
continue
|
| 41 |
+
orr = np.asarray(r["onroute"], bool)
|
| 42 |
+
n = int(r["n_cand"])
|
| 43 |
+
if not (0 < int(orr.sum()) < n): # needs both classes to order anything
|
| 44 |
+
continue
|
| 45 |
+
sc = r["scores"].get("rsm")
|
| 46 |
+
if sc is None:
|
| 47 |
+
continue
|
| 48 |
+
g = rank_pct(-np.arange(n, dtype=float))[orr].mean()
|
| 49 |
+
out[(int(r["episode"]), int(r["frame"]))] = float(rank_pct(np.asarray(sc, np.float64))[orr].mean() - g)
|
| 50 |
+
return out
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
P = {k: per_anchor(v) for k, v in ARMS.items()}
|
| 54 |
+
for k, v in P.items():
|
| 55 |
+
print(f"{ARMS[k]:22s} {len(v):4d} contrastive S0 anchors, {len({e for e, _ in v}):3d} episodes")
|
| 56 |
+
keys = sorted(set.intersection(*[set(v) for v in P.values()]))
|
| 57 |
+
eps = np.array([e for e, _ in keys])
|
| 58 |
+
print(f"\nPAIRED anchor set present in ALL FOUR arms: {len(keys)} anchors over {len(set(eps.tolist()))} episodes\n")
|
| 59 |
+
D = {k: np.array([P[k][a] for a in keys]) for k in ARMS}
|
| 60 |
+
|
| 61 |
+
uniq = np.unique(eps)
|
| 62 |
+
rng = np.random.default_rng(SEED)
|
| 63 |
+
draws = [np.concatenate([np.where(eps == e)[0] for e in rng.choice(uniq, len(uniq), replace=True)])
|
| 64 |
+
for _ in range(N_BOOT)]
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def ci(v):
|
| 68 |
+
b = np.array([v[i].mean() for i in draws])
|
| 69 |
+
return dict(mean=float(v.mean()), lo=float(np.percentile(b, 2.5)), hi=float(np.percentile(b, 97.5)),
|
| 70 |
+
p_ne0=float(2 * min((b <= 0).mean(), (b >= 0).mean())), n=int(len(v)))
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def f(d):
|
| 74 |
+
return f"{d['mean']:+.4f} [{d['lo']:+.4f},{d['hi']:+.4f}] p={d['p_ne0']:.3f}"
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
out = {"n_paired_anchors": len(keys), "n_episodes": int(len(uniq)), "n_boot": N_BOOT,
|
| 78 |
+
"arms": {k: ci(D[k]) for k in ARMS},
|
| 79 |
+
"succ_effect_h101": ci(D["T"] - D["V"]), "succ_effect_h034": ci(D["AA"] - D["ha"]),
|
| 80 |
+
"depth_effect_rxlftv0": ci(D["ha"] - D["V"]), "depth_effect_rxl": ci(D["AA"] - D["T"]),
|
| 81 |
+
"interaction": ci((D["AA"] - D["T"]) - (D["ha"] - D["V"])),
|
| 82 |
+
"best_corner": ci(np.max(np.stack([D[k] for k in ARMS]), axis=0))}
|
| 83 |
+
print("ARM MEANS on the paired set (d_vs_greedy):")
|
| 84 |
+
for k, a in ARMS.items():
|
| 85 |
+
print(f" {a:22s} {f(out['arms'][k])}")
|
| 86 |
+
print("\nPAIRED EFFECTS:")
|
| 87 |
+
print(f" successor (R_XL - R_XL_ft_v0) at h 1.01 {f(out['succ_effect_h101'])}")
|
| 88 |
+
print(f" successor (R_XL - R_XL_ft_v0) at h 0.34 {f(out['succ_effect_h034'])}")
|
| 89 |
+
print(f" depth (h 0.34 - h 1.01) on R_XL_ft_v0 {f(out['depth_effect_rxlftv0'])}")
|
| 90 |
+
print(f" depth (h 0.34 - h 1.01) on R_XL {f(out['depth_effect_rxl'])}")
|
| 91 |
+
print(f" INTERACTION {f(out['interaction'])}")
|
| 92 |
+
i = out["interaction"]
|
| 93 |
+
out["additive"] = bool(i["lo"] <= 0 <= i["hi"])
|
| 94 |
+
print("\nVERDICT: the two axes are " + ("ADDITIVE (interaction CI covers 0) -- the four measured corners "
|
| 95 |
+
"determine the plane and no unmeasured successor x depth combination reaches +0.10"
|
| 96 |
+
if out["additive"] else "NON-ADDITIVE (interaction CI excludes 0)"))
|
| 97 |
+
json.dump(out, open(ROOT / "_edgeAA_interaction.json", "w"), indent=1)
|
| 98 |
+
print("-> status/real/_edgeAA_interaction.json")
|
gen_q_rsm/rsm_rise/pipeline/scripts/real/edge_matched_AA.py
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
r"""#278 run 28: RUNG AA -- the last empty cell of the successor x depth 2x2, read on a COMMON
|
| 2 |
+
anchor set, with its rule PRE-REGISTERED in this file before any AA part existed.
|
| 3 |
+
|
| 4 |
+
THE 2x2. Rung T measured the successor at depth h 1.01 and rung Z measured the depth axis on the
|
| 5 |
+
GOAL_EPISODE successor. Their two best settings were never combined:
|
| 6 |
+
|
| 7 |
+
depth h 1.01 (b0.99 g0.995) depth h 0.34 (b0.99 g0.9925)
|
| 8 |
+
R_XL (shipped) edge_T_rise +0.0909 edge_AA_rxl_ha <- THIS WAVE
|
| 9 |
+
R_XL_ft_v0 (GOAL_EP) edge_V_goalep +0.0872 edge_Z_goalep_ha +0.0879
|
| 10 |
+
|
| 11 |
+
Main effects measured on identical anchors: successor +0.0037 (T-V), depth +0.0007 (ha-V). If the
|
| 12 |
+
two are additive, AA lands near +0.0916 -- still under the +0.10 bar. Running it is what makes the
|
| 13 |
+
negative a complete factorial instead of a hole in the design.
|
| 14 |
+
|
| 15 |
+
PRE-REGISTERED RULE (control = edge_T_rise, the best cell measured to date; every number below is
|
| 16 |
+
read on the COMMON landed episode set, with the per-arm n printed, per the standing rule from run 27):
|
| 17 |
+
(a) edge_AA_rxl_ha >= +0.10 AND above its permuted control -> BAR CLEARED. Write the
|
| 18 |
+
configuration into configs/baselines.yaml and rise_stack/EDGE_TEST.md with these numbers, post
|
| 19 |
+
the passing table, close #278.
|
| 20 |
+
(b) edge_AA_rxl_ha < +0.10 -> the 2x2 is complete and every standard-practice rung on this test is
|
| 21 |
+
closed. Write the negative into rise_stack/EDGE_TEST.md with the ladder table, name the
|
| 22 |
+
near-miss configuration and its number, and close #278 on the failed rung.
|
| 23 |
+
ADDITIVITY, reported either way: interaction = (AA - T) - (ha - V). |interaction| inside the
|
| 24 |
+
bootstrap noise -> the successor and depth axes are additive and the landscape is a plane, so no
|
| 25 |
+
unmeasured combination of them can reach the bar; that is the statement that closes the design.
|
| 26 |
+
"""
|
| 27 |
+
import sys, json
|
| 28 |
+
import numpy as np
|
| 29 |
+
sys.path.insert(0, "/proj/dmfexp/zwhong/rsm_rise/scripts/real")
|
| 30 |
+
from pathlib import Path
|
| 31 |
+
from edge_report import load_dir
|
| 32 |
+
from edge_field import summarise_anchors
|
| 33 |
+
|
| 34 |
+
ROOT = Path("/proj/dmfexp/zwhong/rsm_rise/status/real")
|
| 35 |
+
# arm -> (successor, beta, gamma, h = E[extra hops], E[reads], horizon frames, cap)
|
| 36 |
+
ARMS = [("edge_AA_rxl_ha", "R_XL", 0.99, 0.9925, 0.34, 1.34, 132, 6),
|
| 37 |
+
("edge_T_rise", "R_XL", 0.99, 0.9950, 1.01, 2.01, 199, 11),
|
| 38 |
+
("edge_Z_goalep_ha", "R_XL_ft_v0", 0.99, 0.9925, 0.34, 1.34, 132, 6),
|
| 39 |
+
("edge_V_goalep", "R_XL_ft_v0", 0.99, 0.9950, 1.01, 2.01, 199, 11)]
|
| 40 |
+
BAR = 0.10
|
| 41 |
+
CTRL = "edge_T_rise"
|
| 42 |
+
CELL = {("R_XL", 0.34): "edge_AA_rxl_ha", ("R_XL", 1.01): "edge_T_rise",
|
| 43 |
+
("R_XL_ft_v0", 0.34): "edge_Z_goalep_ha", ("R_XL_ft_v0", 1.01): "edge_V_goalep"}
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def stats(recs, keep):
|
| 47 |
+
r = [x for x in recs if int(x["episode"]) in keep]
|
| 48 |
+
if not r:
|
| 49 |
+
return None
|
| 50 |
+
modes = sorted({m for x in r for m in x["scores"]})
|
| 51 |
+
s = summarise_anchors(r, modes, seed=0, n_boot=2000)["states"].get("S0", {})
|
| 52 |
+
sr = s.get("scorers", {}).get("rsm", {})
|
| 53 |
+
return dict(n=s.get("n_anchors"), cov=s.get("coverage"),
|
| 54 |
+
dg=sr.get("delta_vs_greedy", {}), dp=sr.get("delta_vs_permuted", {}))
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def f(d):
|
| 58 |
+
return f"{d['mean']:+.4f}[{d['lo']:+.4f},{d['hi']:+.4f}]"
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
raw = {}
|
| 62 |
+
for a, *_ in ARMS:
|
| 63 |
+
recs = load_dir(ROOT / a)
|
| 64 |
+
if recs:
|
| 65 |
+
raw[a] = recs
|
| 66 |
+
|
| 67 |
+
eps = {a: {int(r["episode"]) for r in v} for a, v in raw.items()}
|
| 68 |
+
common = set.intersection(*eps.values()) if eps else set()
|
| 69 |
+
print("landed episodes per arm:")
|
| 70 |
+
for a, *_ in ARMS:
|
| 71 |
+
print(f" {a:22s} {len(eps.get(a, [])):3d} episodes, {len(raw.get(a, [])):4d} records")
|
| 72 |
+
print(f"\nCOMMON EPISODE SET: {len(common)} episodes -> {sorted(common)}\n")
|
| 73 |
+
|
| 74 |
+
hdr = (f"{'arm':22s} {'successor':12s} {'beta':>6s} {'gamma':>7s} {'h':>5s} {'cap':>4s} "
|
| 75 |
+
f"{'anc':>4s} {'cov':>5s} | {'d_vs_greedy (COMMON)':>26s} | {'d_vs_perm':>26s}")
|
| 76 |
+
print(hdr)
|
| 77 |
+
print("-" * len(hdr))
|
| 78 |
+
out = {}
|
| 79 |
+
for a, succ, b, g, h, rds, horiz, cap in ARMS:
|
| 80 |
+
if a not in raw:
|
| 81 |
+
print(f"{a:22s} -- no parts")
|
| 82 |
+
continue
|
| 83 |
+
s = stats(raw[a], common)
|
| 84 |
+
if s is None:
|
| 85 |
+
print(f"{a:22s} -- no S0 anchors on the common episodes")
|
| 86 |
+
continue
|
| 87 |
+
out[a] = dict(successor=succ, beta=b, gamma=g, h=h, e_reads=rds, horizon=horiz, cap=cap, **s)
|
| 88 |
+
tag = " <- CONTROL" if a == CTRL else (" <- CLEARS BAR" if s["dg"].get("mean", 0) >= BAR else "")
|
| 89 |
+
print(f"{a:22s} {succ:12s} {b:6.3f} {g:7.4f} {h:5.2f} {cap:4d} "
|
| 90 |
+
f"{s['n']:4d} {s['cov']:5.3f} | {f(s['dg']):>26s} | {f(s['dp']):>26s}{tag}")
|
| 91 |
+
|
| 92 |
+
print("\n2x2 (d_vs_greedy on the COMMON episodes):")
|
| 93 |
+
print(f" {'':12s} {'h 1.01':>10s} {'h 0.34':>10s} {'depth effect':>14s}")
|
| 94 |
+
rows = {}
|
| 95 |
+
for succ in ("R_XL", "R_XL_ft_v0"):
|
| 96 |
+
a1, a0 = CELL[(succ, 1.01)], CELL[(succ, 0.34)]
|
| 97 |
+
if a1 in out and a0 in out:
|
| 98 |
+
v1, v0 = out[a1]["dg"]["mean"], out[a0]["dg"]["mean"]
|
| 99 |
+
rows[succ] = (v1, v0)
|
| 100 |
+
print(f" {succ:12s} {v1:+10.4f} {v0:+10.4f} {v0 - v1:+14.4f}")
|
| 101 |
+
else:
|
| 102 |
+
print(f" {succ:12s} -- incomplete")
|
| 103 |
+
if len(rows) == 2:
|
| 104 |
+
se = rows["R_XL"][0] - rows["R_XL_ft_v0"][0]
|
| 105 |
+
se0 = rows["R_XL"][1] - rows["R_XL_ft_v0"][1]
|
| 106 |
+
inter = (rows["R_XL"][1] - rows["R_XL"][0]) - (rows["R_XL_ft_v0"][1] - rows["R_XL_ft_v0"][0])
|
| 107 |
+
print(f" successor effect at h 1.01 {se:+.4f} at h 0.34 {se0:+.4f} INTERACTION {inter:+.4f}")
|
| 108 |
+
out["_2x2"] = dict(succ_effect_h101=se, succ_effect_h034=se0, interaction=inter)
|
| 109 |
+
|
| 110 |
+
if CTRL in out and "edge_AA_rxl_ha" in out:
|
| 111 |
+
aa = out["edge_AA_rxl_ha"]["dg"]
|
| 112 |
+
ct = out[CTRL]["dg"]
|
| 113 |
+
clears = aa["mean"] >= BAR and out["edge_AA_rxl_ha"]["dp"]["mean"] > 0
|
| 114 |
+
verdict = ("(a) BAR CLEARED by edge_AA_rxl_ha -- write configs/baselines.yaml + EDGE_TEST.md and close #278"
|
| 115 |
+
if clears else
|
| 116 |
+
"(b) BAR NOT CLEARED -- the successor x depth 2x2 is complete and every standard-practice rung on "
|
| 117 |
+
"this test is closed; write the negative with the near-miss configuration and close #278")
|
| 118 |
+
print(f"\ncontrol {CTRL} = {f(ct)} AA = {f(aa)} bar +{BAR:.2f}")
|
| 119 |
+
print(f"PRE-REGISTERED VERDICT: {verdict}")
|
| 120 |
+
out["_rule"] = dict(bar=BAR, control=CTRL, ctrl=ct, aa=aa, cleared=bool(clears),
|
| 121 |
+
n_common_episodes=len(common), verdict=verdict)
|
| 122 |
+
json.dump(out, open(ROOT / "_edgeAA_matched.json", "w"), indent=1, default=float)
|
| 123 |
+
print("-> status/real/_edgeAA_matched.json")
|
gen_q_rsm/rsm_rise/pipeline/scripts/real/edge_matched_AB.py
ADDED
|
@@ -0,0 +1,183 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
r"""#278 run 30: RUNG AB -- the PARTICLE axis measured AT THE BEST CELL, on a COMMON anchor set,
|
| 2 |
+
with its rule PRE-REGISTERED (status/real/EDGE_RUNG_AB_RULE.md, gen_q 097da065) before any AB part
|
| 3 |
+
existed.
|
| 4 |
+
|
| 5 |
+
THE HOLE. Rung 4 closed the particle axis with "16 -> 256 buys 0.0000" and the fitted attenuation
|
| 6 |
+
law d(n) = d_inf / sqrt(1 + k/n), d_inf +0.0669, k 4.87. Every arm behind that law pinned proposer
|
| 7 |
+
pi05_cooking_sn1_knn0p03/ws_s0/9999 at gamma 0.999. The best cell edge_T_rise (+0.0909) pins
|
| 8 |
+
pi05_cooking_rise/rise_s0/29999 at gamma 0.995 and has only ever run at 16 particles.
|
| 9 |
+
|
| 10 |
+
THE NUMBER THAT CHOSE IT. RANK_CTRL (#276, 2026-09-24T13:14:55Z): on the same anchors and the same
|
| 11 |
+
checkpoint the 'rise' proposer's candidate score CV is 0.008 against ~0.045-0.050 on the sn arms
|
| 12 |
+
(var_t 3.4e-05 vs ~1e-03). Six times tighter scores -> particle noise is a far larger share of the
|
| 13 |
+
score spread here -> k is expected to be LARGER and the sn1k3 saturation does not transfer.
|
| 14 |
+
|
| 15 |
+
PRE-REGISTERED PREDICTION, transferring k = 4.87 unchanged to d(16) = +0.0909:
|
| 16 |
+
d_inf +0.1038 d(256) +0.1028 d(128) +0.1018 d(64) +0.1000 d(32) +0.0967
|
| 17 |
+
|
| 18 |
+
PRE-REGISTERED RULE (control = edge_T_rise; COMMON landed episodes; per-arm n printed):
|
| 19 |
+
(a) edge_AB_rise_p256 >= +0.10 AND above its own permuted control -> BAR CLEARED; write
|
| 20 |
+
configs/baselines.yaml + rise_stack/EDGE_TEST.md, post the passing table, close #278 on a PASS.
|
| 21 |
+
(b) < +0.10 -> refit the law on THIS arm's points (16, 32 free, 64, 256) and report d_inf, k
|
| 22 |
+
beside (+0.0669, 4.87).
|
| 23 |
+
(b1) refit d_inf >= +0.10 -> the asymptote clears but no runnable particle count does; name
|
| 24 |
+
the count that would be needed and leave #278 open under NEEDS OWNER.
|
| 25 |
+
(b2) refit d_inf < +0.10 -> the read-out-noise axis is exhausted at the best cell too;
|
| 26 |
+
#278 closes again on the negative with the refit as rung AB of the ladder.
|
| 27 |
+
|
| 28 |
+
No second harness: the anchor reduction is edge_field.summarise_anchors via edge_report.load_dir
|
| 29 |
+
(as every other rung), and the curve/free-32-point construction is edge_scorer_noise +
|
| 30 |
+
edge_particle_curve's own fit form.
|
| 31 |
+
"""
|
| 32 |
+
import sys, json
|
| 33 |
+
import numpy as np
|
| 34 |
+
from scipy.optimize import curve_fit
|
| 35 |
+
sys.path.insert(0, "/proj/dmfexp/zwhong/rsm_rise/scripts/real")
|
| 36 |
+
from pathlib import Path
|
| 37 |
+
from scipy.stats import spearmanr
|
| 38 |
+
from edge_report import load_dir
|
| 39 |
+
from edge_field import summarise_anchors
|
| 40 |
+
import edge_scorer_noise as esn
|
| 41 |
+
|
| 42 |
+
ROOT = Path("/proj/dmfexp/zwhong/rsm_rise/status/real")
|
| 43 |
+
# arm -> (particles, label)
|
| 44 |
+
ARMS = [("edge_T_rise", 16, "p16 (control, shipped best cell)"),
|
| 45 |
+
("edge_AB_rise_p16_s202", 16, "p16, scorer-seed 202 (replicate)"),
|
| 46 |
+
("edge_AB_rise_p64", 64, "p64"),
|
| 47 |
+
("edge_AB_rise_p256", 256, "p256 <- the pre-registered headline")]
|
| 48 |
+
BAR = 0.10
|
| 49 |
+
CTRL = "edge_T_rise"
|
| 50 |
+
HEAD = "edge_AB_rise_p256"
|
| 51 |
+
PRED = {16: 0.0909, 32: 0.0967, 64: 0.1000, 128: 0.1018, 256: 0.1028}
|
| 52 |
+
SN1K3 = dict(d_inf=0.0669494433403113, k=4.874319282134451)
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def stats(recs, keep):
|
| 56 |
+
r = [x for x in recs if int(x["episode"]) in keep]
|
| 57 |
+
if not r:
|
| 58 |
+
return None
|
| 59 |
+
modes = sorted({m for x in r for m in x["scores"]})
|
| 60 |
+
s = summarise_anchors(r, modes, seed=0, n_boot=2000)["states"].get("S0", {})
|
| 61 |
+
sr = s.get("scorers", {}).get("rsm", {})
|
| 62 |
+
return dict(n=s.get("n_anchors"), cov=s.get("coverage"),
|
| 63 |
+
dg=sr.get("delta_vs_greedy", {}), dp=sr.get("delta_vs_permuted", {}))
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def f(d):
|
| 67 |
+
return f"{d['mean']:+.4f}[{d['lo']:+.4f},{d['hi']:+.4f}]" if d else " --"
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
raw = {}
|
| 71 |
+
for a, *_ in ARMS:
|
| 72 |
+
recs = load_dir(ROOT / a)
|
| 73 |
+
if recs:
|
| 74 |
+
raw[a] = recs
|
| 75 |
+
|
| 76 |
+
eps = {a: {int(r["episode"]) for r in v} for a, v in raw.items()}
|
| 77 |
+
common = set.intersection(*eps.values()) if eps else set()
|
| 78 |
+
print("landed episodes per arm (the completeness line, printed BEFORE any number):")
|
| 79 |
+
for a, p, lab in ARMS:
|
| 80 |
+
print(f" {a:24s} {len(eps.get(a, [])):3d} episodes, {len(raw.get(a, [])):4d} records {lab}")
|
| 81 |
+
print(f"\nCOMMON EPISODE SET: {len(common)} episodes -> {sorted(common)}\n")
|
| 82 |
+
|
| 83 |
+
hdr = (f"{'arm':24s} {'P':>5s} {'anc':>4s} {'cov':>5s} | {'d_vs_greedy (COMMON)':>26s} | "
|
| 84 |
+
f"{'d_vs_perm':>26s} | {'pred':>8s}")
|
| 85 |
+
print(hdr); print("-" * len(hdr))
|
| 86 |
+
out = {}
|
| 87 |
+
for a, p, lab in ARMS:
|
| 88 |
+
if a not in raw:
|
| 89 |
+
print(f"{a:24s} {p:5d} -- no parts yet"); continue
|
| 90 |
+
s = stats(raw[a], common)
|
| 91 |
+
if s is None:
|
| 92 |
+
print(f"{a:24s} {p:5d} -- no S0 anchors on the common episodes"); continue
|
| 93 |
+
out[a] = dict(particles=p, label=lab, **s)
|
| 94 |
+
tag = " <- CONTROL" if a == CTRL else (" <- CLEARS BAR" if s["dg"].get("mean", 0) >= BAR else "")
|
| 95 |
+
print(f"{a:24s} {p:5d} {s['n']:4d} {s['cov']:5.3f} | {f(s['dg']):>26s} | {f(s['dp']):>26s} | "
|
| 96 |
+
f"{PRED.get(p, float('nan')):+8.4f}{tag}")
|
| 97 |
+
|
| 98 |
+
# ---- the free 32-particle point + the candidate-matched reliability, on THIS arm ----
|
| 99 |
+
curve = {"points": [], "source": "edge_scorer_noise (same reduction as rung 4)"}
|
| 100 |
+
pairs = [r for r in ARMS if r[1] == 16 and r[0] in raw]
|
| 101 |
+
if len(pairs) == 2:
|
| 102 |
+
tags = [pairs[0][0], pairs[1][0]]
|
| 103 |
+
sets = [[r for r in esn.load_tag(t) if r["state"] == 0 and int(r["ep"]) in common] for t in tags]
|
| 104 |
+
if sets[0] and len(sets[0]) == len(sets[1]):
|
| 105 |
+
recs = sets[0]
|
| 106 |
+
ds = [esn.delta_vs_greedy(recs, [r["score"] for r in s]) for s in sets]
|
| 107 |
+
d16 = float(np.mean([d["mean"] for d in ds]))
|
| 108 |
+
avg = [np.mean([s[i]["score"] for s in sets], axis=0) for i in range(len(recs))]
|
| 109 |
+
d32 = esn.delta_vs_greedy(recs, avg)
|
| 110 |
+
curve["points"] += [{"effective_particles": 16, "d_vs_greedy": d16, "source": f"mean of {tags}"},
|
| 111 |
+
{"effective_particles": 32, "d_vs_greedy": d32["mean"],
|
| 112 |
+
"ci": [d32["lo"], d32["hi"]], "source": f"seed-average of {tags}"}]
|
| 113 |
+
rho = [spearmanr(np.asarray(sets[0][i]["score"], float),
|
| 114 |
+
np.asarray(sets[1][i]["score"], float)).correlation
|
| 115 |
+
for i in range(len(recs))]
|
| 116 |
+
rho = [x for x in rho if np.isfinite(x)]
|
| 117 |
+
# esn.load_tag exposes no raw action, so candidate identity is checked through the
|
| 118 |
+
# onroute mask, which is computed FROM the candidates: identical masks on every anchor means
|
| 119 |
+
# the two arms scored the same candidate set (the property that makes rho an exact
|
| 120 |
+
# reliability rather than a floor -- it held for rung 4's p16 pair and failed for its p64
|
| 121 |
+
# pair, where proposer float nondeterminism across GPUs perturbed the candidates).
|
| 122 |
+
ident = bool(all(np.array_equal(sets[0][i]["onroute"], sets[1][i]["onroute"])
|
| 123 |
+
for i in range(len(recs))))
|
| 124 |
+
curve["reliability_p16"] = {"median_rho": float(np.median(rho)), "n": len(rho),
|
| 125 |
+
"candidates_bitwise_identical": ident,
|
| 126 |
+
"sn1k3_reference_median_rho": 0.514}
|
| 127 |
+
print(f"\ncandidate-matched scorer reliability at P=16 on THIS arm: median rho "
|
| 128 |
+
f"{np.median(rho):.3f} (n={len(rho)}, candidates identical={ident}) "
|
| 129 |
+
f"vs 0.514 measured on sn1k3")
|
| 130 |
+
print(f"free 32-particle point (seed-average): {d32['mean']:+.4f}"
|
| 131 |
+
f"[{d32['lo']:+.4f},{d32['hi']:+.4f}] predicted {PRED[32]:+.4f}")
|
| 132 |
+
|
| 133 |
+
for a, p, lab in ARMS:
|
| 134 |
+
if p != 16 and a in out:
|
| 135 |
+
curve["points"].append({"effective_particles": p, "d_vs_greedy": out[a]["dg"]["mean"],
|
| 136 |
+
"ci": [out[a]["dg"]["lo"], out[a]["dg"]["hi"]], "source": a})
|
| 137 |
+
|
| 138 |
+
pts = sorted({(q["effective_particles"], q["d_vs_greedy"]) for q in curve["points"]})
|
| 139 |
+
if len(pts) >= 3:
|
| 140 |
+
n = np.array([q[0] for q in pts], float); d = np.array([q[1] for q in pts], float)
|
| 141 |
+
fn = lambda x, dinf, k: dinf / np.sqrt(1.0 + k / x)
|
| 142 |
+
try:
|
| 143 |
+
(dinf, k), _ = curve_fit(fn, n, d, p0=[0.10, 5.0], maxfev=40000)
|
| 144 |
+
curve["curve_fit"] = {"d_infinite_particles": float(dinf),
|
| 145 |
+
"k_noise_over_signal_at_1_particle": float(k),
|
| 146 |
+
"predicted": {int(x): float(fn(x, dinf, k)) for x in n},
|
| 147 |
+
"residual_max": float(np.max(np.abs(fn(n, dinf, k) - d))),
|
| 148 |
+
"sn1k3_reference": SN1K3}
|
| 149 |
+
print(f"\nREFIT ON THIS ARM: d_inf {dinf:+.4f}, k {k:.3f} "
|
| 150 |
+
f"(sn1k3: d_inf {SN1K3['d_inf']:+.4f}, k {SN1K3['k']:.3f}) "
|
| 151 |
+
f"max residual {curve['curve_fit']['residual_max']:.4f}")
|
| 152 |
+
print(" points: " + " ".join(f"n={int(x)} {y:+.4f}" for x, y in pts))
|
| 153 |
+
except Exception as e: # noqa: BLE001
|
| 154 |
+
curve["curve_fit_error"] = str(e)
|
| 155 |
+
print(f"\nREFIT FAILED: {e}")
|
| 156 |
+
out["_curve"] = curve
|
| 157 |
+
|
| 158 |
+
# ---- the mechanical rule ----
|
| 159 |
+
if CTRL in out and HEAD in out:
|
| 160 |
+
hd, ct = out[HEAD]["dg"], out[CTRL]["dg"]
|
| 161 |
+
clears = hd["mean"] >= BAR and out[HEAD]["dp"]["mean"] > 0
|
| 162 |
+
dinf = curve.get("curve_fit", {}).get("d_infinite_particles")
|
| 163 |
+
if clears:
|
| 164 |
+
verdict = ("(a) BAR CLEARED by edge_AB_rise_p256 -- write configs/baselines.yaml + "
|
| 165 |
+
"rise_stack/EDGE_TEST.md and close #278 on the PASS")
|
| 166 |
+
elif dinf is not None and dinf >= BAR:
|
| 167 |
+
verdict = ("(b1) p256 under the bar but the REFIT ASYMPTOTE clears it -- report the particle "
|
| 168 |
+
"count that would be needed and leave #278 open under NEEDS OWNER (a cost "
|
| 169 |
+
"decision, not a science one)")
|
| 170 |
+
else:
|
| 171 |
+
verdict = ("(b2) p256 under the bar AND the refit asymptote under it -- the read-out-noise "
|
| 172 |
+
"axis is exhausted at the best cell too; close #278 again on the negative with "
|
| 173 |
+
"rung AB added to the ladder")
|
| 174 |
+
print(f"\ncontrol {CTRL} = {f(ct)} p256 = {f(hd)} bar +{BAR:.2f}")
|
| 175 |
+
print(f"pre-registered prediction for p256 was {PRED[256]:+.4f}")
|
| 176 |
+
print(f"PRE-REGISTERED VERDICT: {verdict}")
|
| 177 |
+
out["_rule"] = dict(bar=BAR, control=CTRL, head=HEAD, ctrl=ct, p256=hd, cleared=bool(clears),
|
| 178 |
+
refit_d_inf=dinf, prediction=PRED, n_common_episodes=len(common),
|
| 179 |
+
verdict=verdict)
|
| 180 |
+
else:
|
| 181 |
+
print("\nRULE NOT APPLIED -- the p256 arm or the control is missing; this read is DIRECTIONAL ONLY.")
|
| 182 |
+
json.dump(out, open(ROOT / "_edgeAB_matched.json", "w"), indent=1, default=float)
|
| 183 |
+
print("-> status/real/_edgeAB_matched.json")
|
gen_q_rsm/rsm_rise/pipeline/scripts/real/edge_matched_AC.py
ADDED
|
@@ -0,0 +1,135 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
r"""#278 run 31: RUNG AC -- the FLOW-STEP (integration) axis measured AT THE BEST CELL, on a COMMON
|
| 2 |
+
anchor set, with its rule PRE-REGISTERED (scripts/real/payloads/EDGE_RUNG_AC_RULE.md) before any AC
|
| 3 |
+
part existed.
|
| 4 |
+
|
| 5 |
+
THE HOLE. Rung R closed the flow axis as FLAT (flow 4/8/16/32 -> +0.0727/+0.0716/+0.0679/+0.0696)
|
| 6 |
+
but every arm behind it -- edgeR_flow{4,16,32} and their control edgeQ_hz_g0995 -- pinned proposer
|
| 7 |
+
pi05_cooking_sn1_knn0p03/ws_s0/9999. The best cell edge_T_rise pins pi05_cooking_rise/rise_s0/29999
|
| 8 |
+
and EVERY rise-cell arm ever run (T, V, Z, AA, AB) has EDGE_FLOW=8. Same defect class as rung AB.
|
| 9 |
+
After this rung it is the LAST one: proposer (T), depth (AA's 2x2), successor (AA), label (V/Z) and
|
| 10 |
+
particles/N (AB) are all already measured AT this cell.
|
| 11 |
+
|
| 12 |
+
THE NUMBER THAT CHOSE IT (measured in rung AB's own output, status/real/_edgeAB_matched.json
|
| 13 |
+
field `_curve`): candidate-matched scorer reliability at P=16 is median rho 0.903 (n=291) at this
|
| 14 |
+
cell against 0.514 at sn1k3, and the refit particle law here is k 0.029 (vs 4.874) -- the read-out
|
| 15 |
+
is already at its asymptote. Rung R's null was measured through ~2x more read-out noise than this
|
| 16 |
+
arm carries, so a systematic integration effect is masked far less here.
|
| 17 |
+
|
| 18 |
+
PRE-REGISTERED PREDICTION (rung R transferred unchanged to d(flow 8) = +0.0909):
|
| 19 |
+
flow 4 +0.0920 flow 8 +0.0909 (control) flow 16 +0.0872 flow 32 +0.0889 -- FLAT, all < bar
|
| 20 |
+
Rung AB is why it is tested and not assumed: the transferred particle law predicted +0.1028 at p256
|
| 21 |
+
and the truth was +0.0913, with k off by a factor of 170.
|
| 22 |
+
|
| 23 |
+
PRE-REGISTERED RULE (control = edge_T_rise; COMMON landed episodes; per-arm n printed):
|
| 24 |
+
(a) ANY arm >= +0.10 AND above its own permuted control -> BAR CLEARED; report the SMALLEST
|
| 25 |
+
passing flow, write configs/baselines.yaml + rise_stack/EDGE_TEST.md, close #278 on a PASS.
|
| 26 |
+
(b) every arm < +0.10:
|
| 27 |
+
(b1) best arm above the control's point estimate AND d MONOTONE NON-DECREASING over
|
| 28 |
+
flow 8 -> 16 -> 32 -> integration still buying at the top of the range; name the flow
|
| 29 |
+
count that would be needed and leave #278 open under NEEDS OWNER (a cost decision).
|
| 30 |
+
(b2) otherwise (flat, non-monotone, or below the control) -> the INTEGRATION axis is exhausted
|
| 31 |
+
at the best cell too; every ladder axis has then been measured AT the best cell. Close
|
| 32 |
+
#278 on the negative with rungs AB and AC added to the ladder.
|
| 33 |
+
|
| 34 |
+
No second harness: the anchor reduction is edge_field.summarise_anchors via edge_report.load_dir,
|
| 35 |
+
exactly as in every other rung.
|
| 36 |
+
"""
|
| 37 |
+
import sys, json
|
| 38 |
+
import numpy as np
|
| 39 |
+
sys.path.insert(0, "/proj/dmfexp/zwhong/rsm_rise/scripts/real")
|
| 40 |
+
from pathlib import Path
|
| 41 |
+
from edge_report import load_dir
|
| 42 |
+
from edge_field import summarise_anchors
|
| 43 |
+
|
| 44 |
+
ROOT = Path("/proj/dmfexp/zwhong/rsm_rise/status/real")
|
| 45 |
+
# arm -> (flow steps, label)
|
| 46 |
+
ARMS = [("edge_AC_rise_flow4", 4, "flow 4"),
|
| 47 |
+
("edge_T_rise", 8, "flow 8 (control, shipped best cell)"),
|
| 48 |
+
("edge_AC_rise_flow16", 16, "flow 16"),
|
| 49 |
+
("edge_AC_rise_flow32", 32, "flow 32 <- top of the pre-registered range")]
|
| 50 |
+
BAR = 0.10
|
| 51 |
+
CTRL = "edge_T_rise"
|
| 52 |
+
PRED = {4: 0.0920, 8: 0.0909, 16: 0.0872, 32: 0.0889}
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def stats(recs, keep):
|
| 56 |
+
r = [x for x in recs if int(x["episode"]) in keep]
|
| 57 |
+
if not r:
|
| 58 |
+
return None
|
| 59 |
+
modes = sorted({m for x in r for m in x["scores"]})
|
| 60 |
+
s = summarise_anchors(r, modes, seed=0, n_boot=2000)["states"].get("S0", {})
|
| 61 |
+
sr = s.get("scorers", {}).get("rsm", {})
|
| 62 |
+
return dict(n=s.get("n_anchors"), cov=s.get("coverage"),
|
| 63 |
+
dg=sr.get("delta_vs_greedy", {}), dp=sr.get("delta_vs_permuted", {}))
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def f(d):
|
| 67 |
+
return f"{d['mean']:+.4f}[{d['lo']:+.4f},{d['hi']:+.4f}]" if d else " --"
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
raw = {}
|
| 71 |
+
for a, *_ in ARMS:
|
| 72 |
+
recs = load_dir(ROOT / a)
|
| 73 |
+
if recs:
|
| 74 |
+
raw[a] = recs
|
| 75 |
+
|
| 76 |
+
eps = {a: {int(r["episode"]) for r in v} for a, v in raw.items()}
|
| 77 |
+
common = set.intersection(*eps.values()) if eps else set()
|
| 78 |
+
print("landed episodes per arm (the completeness line, printed BEFORE any number):")
|
| 79 |
+
for a, fl, lab in ARMS:
|
| 80 |
+
print(f" {a:24s} {len(eps.get(a, [])):3d} episodes, {len(raw.get(a, [])):4d} records {lab}")
|
| 81 |
+
print(f"\nCOMMON EPISODE SET: {len(common)} episodes -> {sorted(common)}\n")
|
| 82 |
+
|
| 83 |
+
hdr = (f"{'arm':24s} {'flow':>5s} {'anc':>4s} {'cov':>5s} | {'d_vs_greedy (COMMON)':>26s} | "
|
| 84 |
+
f"{'d_vs_perm':>26s} | {'pred':>8s}")
|
| 85 |
+
print(hdr); print("-" * len(hdr))
|
| 86 |
+
out = {}
|
| 87 |
+
for a, fl, lab in ARMS:
|
| 88 |
+
if a not in raw:
|
| 89 |
+
print(f"{a:24s} {fl:5d} -- no parts yet"); continue
|
| 90 |
+
s = stats(raw[a], common)
|
| 91 |
+
if s is None:
|
| 92 |
+
print(f"{a:24s} {fl:5d} -- no S0 anchors on the common episodes"); continue
|
| 93 |
+
out[a] = dict(flow=fl, label=lab, **s)
|
| 94 |
+
tag = " <- CONTROL" if a == CTRL else (" <- CLEARS BAR" if s["dg"].get("mean", 0) >= BAR else "")
|
| 95 |
+
print(f"{a:24s} {fl:5d} {s['n']:4d} {s['cov']:5.3f} | {f(s['dg']):>26s} | {f(s['dp']):>26s} | "
|
| 96 |
+
f"{PRED.get(fl, float('nan')):+8.4f}{tag}")
|
| 97 |
+
|
| 98 |
+
# ---- the mechanical rule ----
|
| 99 |
+
have = [(a, o) for a, o in out.items() if a != "_rule"]
|
| 100 |
+
if CTRL in out and len(have) >= 2:
|
| 101 |
+
ct = out[CTRL]["dg"]
|
| 102 |
+
passing = [(out[a]["flow"], a) for a, o in have
|
| 103 |
+
if o["dg"].get("mean", 0) >= BAR and o["dp"].get("mean", 0) > 0]
|
| 104 |
+
passing.sort()
|
| 105 |
+
# monotonicity over the arms ABOVE the control (8 -> 16 -> 32), in flow order
|
| 106 |
+
up = sorted([(out[a]["flow"], out[a]["dg"]["mean"]) for a, o in have if out[a]["flow"] >= 8])
|
| 107 |
+
monotone = all(up[i + 1][1] >= up[i][1] - 1e-12 for i in range(len(up) - 1)) and len(up) >= 3
|
| 108 |
+
best_arm = max(have, key=lambda kv: kv[1]["dg"].get("mean", -9))
|
| 109 |
+
best = best_arm[1]["dg"]["mean"]
|
| 110 |
+
above_ctrl = best > ct["mean"]
|
| 111 |
+
if passing:
|
| 112 |
+
verdict = (f"(a) BAR CLEARED -- smallest passing flow = {passing[0][0]} ({passing[0][1]}); "
|
| 113 |
+
"write configs/baselines.yaml + rise_stack/EDGE_TEST.md and close #278 on the PASS")
|
| 114 |
+
elif above_ctrl and monotone:
|
| 115 |
+
verdict = ("(b1) every arm under the bar BUT d is monotone non-decreasing over flow 8->16->32 "
|
| 116 |
+
"and the best arm beats the control -- integration is still buying; name the flow "
|
| 117 |
+
"count that would be needed and leave #278 open under NEEDS OWNER (a cost decision)")
|
| 118 |
+
else:
|
| 119 |
+
verdict = ("(b2) every arm under the bar and the flow trend is flat / non-monotone / below the "
|
| 120 |
+
"control -- the INTEGRATION axis is exhausted at the best cell too. Every ladder "
|
| 121 |
+
"axis is now measured AT the best cell; close #278 on the negative with rungs AB "
|
| 122 |
+
"and AC added to the ladder")
|
| 123 |
+
print(f"\ncontrol {CTRL} = {f(ct)} best arm {best_arm[0]} = {best:+.4f} bar +{BAR:.2f}")
|
| 124 |
+
print(f"monotone over flow>=8: {monotone} best above control: {above_ctrl}")
|
| 125 |
+
print(f"flow-ordered d: " + " ".join(f"{fl}:{d:+.4f}" for fl, d in sorted(
|
| 126 |
+
[(out[a]["flow"], out[a]["dg"]["mean"]) for a, o in have])))
|
| 127 |
+
print(f"PRE-REGISTERED VERDICT: {verdict}")
|
| 128 |
+
out["_rule"] = dict(bar=BAR, control=CTRL, ctrl=ct, best_arm=best_arm[0], best=best,
|
| 129 |
+
cleared=bool(passing), smallest_passing_flow=(passing[0][0] if passing else None),
|
| 130 |
+
monotone_over_flow_ge_8=bool(monotone), best_above_control=bool(above_ctrl),
|
| 131 |
+
prediction=PRED, n_common_episodes=len(common), verdict=verdict)
|
| 132 |
+
else:
|
| 133 |
+
print("\nRULE NOT APPLIED -- the control or the new arms are missing; this read is DIRECTIONAL ONLY.")
|
| 134 |
+
json.dump(out, open(ROOT / "_edgeAC_matched.json", "w"), indent=1, default=float)
|
| 135 |
+
print("-> status/real/_edgeAC_matched.json")
|
gen_q_rsm/rsm_rise/pipeline/scripts/real/edge_matched_U.py
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""#278 run 19: rung U -- the SUCCESSOR CHECKPOINT varied at the rung-T winning cell.
|
| 2 |
+
|
| 3 |
+
ONE factor moves: the successor. Proposer (pi0.5 RISE rise_s0/29999), beta 0.99 / gamma 0.995,
|
| 4 |
+
flow 8, N=128, 16 particles, S0 anchors, seed 0, and the identical 25 held-out episodes are pinned
|
| 5 |
+
to edge_T_rise, which is therefore the control AND the fifth point of the same design.
|
| 6 |
+
|
| 7 |
+
Reported in BOTH units -- d_vs_greedy (the unit the +0.10 bar is written in) and the
|
| 8 |
+
leverage-weighted AUC_w from edge_ceiling2's exact identity -- with w_bar, the per-arm ceiling and
|
| 9 |
+
%ceiling, exactly as rung T reported.
|
| 10 |
+
|
| 11 |
+
Each arm also carries its SUCCESSOR GATE minmse_train/staymse_train (run 15 / the owner's
|
| 12 |
+
2026-09-23 12:35 note): < 1 means the successor's samples beat the trivial stay-put predictor on
|
| 13 |
+
its own training split. The pre-registered rung-U rule (posted on #278 before these numbers
|
| 14 |
+
existed) reads the gate against the ranking:
|
| 15 |
+
(a) xlnt > ctrl AND the gate orders the arms monotonically -> the gate is the binding constraint
|
| 16 |
+
and the next move is successor CAPACITY;
|
| 17 |
+
(b) the gate does NOT order the arms -> it is a necessary-not-sufficient screen, the +0.0909
|
| 18 |
+
ceiling is a property of the reward/latent rather than of sample quality, and the next rung
|
| 19 |
+
is #277's reward-NAME axis measured on the RISE proposer;
|
| 20 |
+
(c) xlnt >= +0.10 -> the bar is cleared.
|
| 21 |
+
"""
|
| 22 |
+
import sys, json
|
| 23 |
+
import numpy as np
|
| 24 |
+
sys.path.insert(0, "/proj/dmfexp/zwhong/rsm_rise/scripts/real")
|
| 25 |
+
from pathlib import Path
|
| 26 |
+
from edge_report import load_dir
|
| 27 |
+
from edge_field import summarise_anchors
|
| 28 |
+
import edge_ceiling2 as C
|
| 29 |
+
|
| 30 |
+
ROOT = Path("/proj/dmfexp/zwhong/rsm_rise/status/real")
|
| 31 |
+
CTRL = "edge_T_rise" # successor R_XL/ckpt_s100000.pt
|
| 32 |
+
ARMS = {"edge_U_xlnt": ("R_XL_ft_nt/ckpt_s110000.pt", 0.5490),
|
| 33 |
+
"edge_T_rise": ("R_XL/ckpt_s100000.pt (control)", 0.5784),
|
| 34 |
+
"edge_U_aug": ("AUG_invariant_t0p02_s0/ckpt_s100000.pt", 0.9863),
|
| 35 |
+
"edge_U_mlong": ("R_M_long/ckpt_s300000.pt", 0.9869),
|
| 36 |
+
"edge_U_m": ("R_M/ckpt_s100000.pt", 0.9992)}
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def stats(recs):
|
| 40 |
+
modes = sorted({m for x in recs for m in x["scores"]})
|
| 41 |
+
s = summarise_anchors(recs, modes, seed=0, n_boot=2000)["states"].get("S0", {})
|
| 42 |
+
sr = s.get("scorers", {}).get("rsm", {})
|
| 43 |
+
return dict(n=s.get("n_anchors"), cov=s.get("coverage"),
|
| 44 |
+
dg=sr.get("delta_vs_greedy", {}), dp=sr.get("delta_vs_permuted", {}),
|
| 45 |
+
rank=sr.get("onroute_rank_pct", {}))
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def f(d):
|
| 49 |
+
return f"{d['mean']:+.4f}[{d['lo']:+.4f},{d['hi']:+.4f}]"
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
out, order = {}, []
|
| 53 |
+
print(f"{'arm':13s} {'successor':40s} {'gate':>6s} {'eps':>3s} {'cov':>5s} {'anc':>4s} {'wbar':>5s} "
|
| 54 |
+
f"{'d_ceil':>7s} | {'d_vs_greedy':>24s} | {'d_vs_permuted':>24s} | {'AUCw':>6s} {'prm':>5s} "
|
| 55 |
+
f"{'need':>5s} {'%ceil':>6s}")
|
| 56 |
+
for a, (succ, gate) in ARMS.items():
|
| 57 |
+
recs = load_dir(ROOT / a)
|
| 58 |
+
if not recs:
|
| 59 |
+
print(f"{a:13s} {succ:40s} -- no parts yet")
|
| 60 |
+
continue
|
| 61 |
+
eps = sorted({int(r["episode"]) for r in recs})
|
| 62 |
+
A = stats(recs)
|
| 63 |
+
c = C.arm(str(ROOT / a))
|
| 64 |
+
# AUC_w the +0.10 bar demands at THIS arm's own leverage: d_bar / d_ceil of the AUC headroom
|
| 65 |
+
need = c["auc_perm"]["weighted"] + 0.10 / c["d_ceiling"] * (1.0 - c["auc_perm"]["weighted"]) \
|
| 66 |
+
if c["d_ceiling"] else float("nan")
|
| 67 |
+
pct = 100.0 * A["dg"]["mean"] / c["d_ceiling"] if c["d_ceiling"] else float("nan")
|
| 68 |
+
out[a] = dict(successor=succ, gate=gate, episodes=eps, arm=A, ceiling=c,
|
| 69 |
+
auc_w_needed=need, pct_of_ceiling=pct)
|
| 70 |
+
order.append((a, gate, A["dg"]["mean"], c["auc_rsm"]["weighted"]))
|
| 71 |
+
print(f"{a:13s} {succ:40s} {gate:6.4f} {len(eps):3d} {A['cov']:5.3f} {c['n_anchors']:4d} "
|
| 72 |
+
f"{c['w_mean']:5.3f} {c['d_ceiling']:+7.4f} | {f(A['dg']):>24s} | {f(A['dp']):>24s} | "
|
| 73 |
+
f"{c['auc_rsm']['weighted']:6.3f} {c['auc_perm']['weighted']:5.3f} {need:5.3f} {pct:5.1f}%")
|
| 74 |
+
|
| 75 |
+
# --- the pre-registered rule, evaluated mechanically -------------------------------------------
|
| 76 |
+
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])
|
| 77 |
+
rho_d = float(np.corrcoef(np.argsort(np.argsort(g)), np.argsort(np.argsort(d)))[0, 1])
|
| 78 |
+
rho_a = float(np.corrcoef(np.argsort(np.argsort(g)), np.argsort(np.argsort(au)))[0, 1])
|
| 79 |
+
best = max(order, key=lambda o: o[2])
|
| 80 |
+
ctrl_d = dict((o[0], o[2]) for o in order)[CTRL]
|
| 81 |
+
xl = dict((o[0], o[2]) for o in order).get("edge_U_xlnt")
|
| 82 |
+
verdict = ("(c) BAR CLEARED" if xl is not None and xl >= 0.10 else
|
| 83 |
+
"(a) gate binding -> capacity" if (xl is not None and xl > ctrl_d and rho_d <= -0.9) else
|
| 84 |
+
"(b) gate is necessary-not-sufficient -> reward-NAME axis on the RISE proposer")
|
| 85 |
+
print()
|
| 86 |
+
print(f"spearman(gate, d_vs_greedy) = {rho_d:+.3f} (gate is LOWER-is-better, so -1 = perfect ordering)")
|
| 87 |
+
print(f"spearman(gate, AUC_w) = {rho_a:+.3f}")
|
| 88 |
+
print(f"best arm = {best[0]} d = {best[2]:+.4f} control edge_T_rise d = {ctrl_d:+.4f}")
|
| 89 |
+
print(f"PRE-REGISTERED VERDICT: {verdict}")
|
| 90 |
+
out["_rule"] = dict(spearman_gate_d=rho_d, spearman_gate_aucw=rho_a, best=best[0],
|
| 91 |
+
best_d=best[2], ctrl_d=ctrl_d, xlnt_d=xl, verdict=verdict)
|
| 92 |
+
json.dump(out, open(ROOT / "_edgeU_matched.json", "w"), indent=1, default=float)
|
| 93 |
+
print("-> status/real/_edgeU_matched.json")
|
gen_q_rsm/rsm_rise/pipeline/scripts/real/edge_matched_V.py
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""#278 run 20: rung V -- the REWARD LABEL varied at the rung-T winning cell.
|
| 2 |
+
|
| 3 |
+
ONE factor moves: the reward label. Proposer (pi0.5 RISE rise_s0/29999), beta 0.99 / gamma 0.995,
|
| 4 |
+
flow 8, N=128, 16 particles, S0 anchors, seed 0, and the identical 25 held-out episodes are pinned
|
| 5 |
+
to edge_T_rise, which is therefore the control AND the fifth point of the same design. All four V
|
| 6 |
+
arms are 10k-step fine-tunes from the SAME base R_XL/ckpt_s100000.pt with beta_trunc_eps 0.02
|
| 7 |
+
unchanged, so capacity, steps and truncation are held fixed.
|
| 8 |
+
|
| 9 |
+
MEASURED BEFORE THE RUN (runs/real_cooking_v5/rsm/*/history.json, last row with the gate keys):
|
| 10 |
+
the stay-put gate minmse_train/staymse_train is IDENTICAL to 3 decimals across all four arms --
|
| 11 |
+
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.
|
| 12 |
+
The label trains the reward head, not the flow model, so sample quality is held fixed BY
|
| 13 |
+
CONSTRUCTION and any spread in the ranking is attributable to the label alone. That is what makes
|
| 14 |
+
rung V the clean test of the rung-U branch-(b) conclusion (the +0.0909 ceiling is a property of
|
| 15 |
+
the REWARD/LATENT rather than of sample quality).
|
| 16 |
+
|
| 17 |
+
Canonical reward names (rise_stack/REWARD_NAMES.md) with their positive-frame shares.
|
| 18 |
+
|
| 19 |
+
PRE-REGISTERED RUNG-V RULE (posted on #278 before these numbers existed):
|
| 20 |
+
(1) edge_V_goalep ~ edge_T_rise (inside its interval) -> the 10k extra steps are neutral and the
|
| 21 |
+
spread across the other three arms is the LABEL alone. If goalep DIFFERS from the control,
|
| 22 |
+
the label comparison is confounded by fine-tuning itself and differences are reported
|
| 23 |
+
against goalep instead.
|
| 24 |
+
(2) ANY arm >= +0.10 -> bar cleared.
|
| 25 |
+
(3) ALL FOUR inside the control's interval -> the reward-label axis is closed and the
|
| 26 |
+
standard-practice ladder on this test is exhausted at +0.0909 [+0.0373,+0.1480].
|
| 27 |
+
"""
|
| 28 |
+
import sys, json
|
| 29 |
+
import numpy as np
|
| 30 |
+
sys.path.insert(0, "/proj/dmfexp/zwhong/rsm_rise/scripts/real")
|
| 31 |
+
from pathlib import Path
|
| 32 |
+
from edge_report import load_dir
|
| 33 |
+
from edge_field import summarise_anchors
|
| 34 |
+
import edge_ceiling2 as C
|
| 35 |
+
|
| 36 |
+
ROOT = Path("/proj/dmfexp/zwhong/rsm_rise/status/real")
|
| 37 |
+
CTRL = "edge_T_rise" # R_XL/ckpt_s100000.pt, shipped GOAL_EPISODE head
|
| 38 |
+
# arm -> (label + checkpoint, stay-put gate measured from that checkpoint's own history.json)
|
| 39 |
+
ARMS = {"edge_T_rise": ("GOAL_EPISODE R_XL s100000 (control, shipped)", 0.5784),
|
| 40 |
+
"edge_V_goalep": ("GOAL_EPISODE R_XL_ft_v0 s110000 0.294", 0.5596),
|
| 41 |
+
"edge_V_goalseg": ("GOAL_SEGMENT R_XL_ft_v1 s110000 0.167", 0.5584),
|
| 42 |
+
"edge_V_win400": ("GOAL_WINDOW_400 R_XL_ft_B400 s110000 0.111", 0.5592),
|
| 43 |
+
"edge_V_win100": ("GOAL_WINDOW_100 R_XL_ft_B s110000 0.028", 0.5588)}
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def stats(recs):
|
| 47 |
+
modes = sorted({m for x in recs for m in x["scores"]})
|
| 48 |
+
s = summarise_anchors(recs, modes, seed=0, n_boot=2000)["states"].get("S0", {})
|
| 49 |
+
sr = s.get("scorers", {}).get("rsm", {})
|
| 50 |
+
return dict(n=s.get("n_anchors"), cov=s.get("coverage"),
|
| 51 |
+
dg=sr.get("delta_vs_greedy", {}), dp=sr.get("delta_vs_permuted", {}),
|
| 52 |
+
rank=sr.get("onroute_rank_pct", {}))
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def f(d):
|
| 56 |
+
return f"{d['mean']:+.4f}[{d['lo']:+.4f},{d['hi']:+.4f}]"
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
out, order = {}, []
|
| 60 |
+
print(f"{'arm':15s} {'reward label / checkpoint / pos share':44s} {'gate':>6s} {'eps':>3s} {'cov':>5s} "
|
| 61 |
+
f"{'anc':>4s} {'wbar':>5s} {'d_ceil':>7s} | {'d_vs_greedy':>24s} | {'d_vs_permuted':>24s} | "
|
| 62 |
+
f"{'AUCw':>6s} {'prm':>5s} {'need':>5s} {'%ceil':>6s}")
|
| 63 |
+
for a, (lab, gate) in ARMS.items():
|
| 64 |
+
recs = load_dir(ROOT / a)
|
| 65 |
+
if not recs:
|
| 66 |
+
print(f"{a:15s} {lab:44s} -- no parts yet")
|
| 67 |
+
continue
|
| 68 |
+
eps = sorted({int(r["episode"]) for r in recs})
|
| 69 |
+
A = stats(recs)
|
| 70 |
+
c = C.arm(str(ROOT / a))
|
| 71 |
+
need = c["auc_perm"]["weighted"] + 0.10 / c["d_ceiling"] * (1.0 - c["auc_perm"]["weighted"]) \
|
| 72 |
+
if c["d_ceiling"] else float("nan")
|
| 73 |
+
pct = 100.0 * A["dg"]["mean"] / c["d_ceiling"] if c["d_ceiling"] else float("nan")
|
| 74 |
+
out[a] = dict(label=lab, gate=gate, episodes=eps, arm=A, ceiling=c,
|
| 75 |
+
auc_w_needed=need, pct_of_ceiling=pct)
|
| 76 |
+
order.append((a, gate, A["dg"]["mean"], c["auc_rsm"]["weighted"], A["dg"]))
|
| 77 |
+
print(f"{a:15s} {lab:44s} {gate:6.4f} {len(eps):3d} {A['cov']:5.3f} {c['n_anchors']:4d} "
|
| 78 |
+
f"{c['w_mean']:5.3f} {c['d_ceiling']:+7.4f} | {f(A['dg']):>24s} | {f(A['dp']):>24s} | "
|
| 79 |
+
f"{c['auc_rsm']['weighted']:6.3f} {c['auc_perm']['weighted']:5.3f} {need:5.3f} {pct:5.1f}%")
|
| 80 |
+
|
| 81 |
+
# --- the pre-registered rule, evaluated mechanically -------------------------------------------
|
| 82 |
+
if order:
|
| 83 |
+
D = {o[0]: o[2] for o in order}
|
| 84 |
+
ctrl = D.get(CTRL)
|
| 85 |
+
ci = {o[0]: o[4] for o in order}
|
| 86 |
+
best = max(order, key=lambda o: o[2])
|
| 87 |
+
cleared = [o[0] for o in order if o[2] >= 0.10]
|
| 88 |
+
# (1) is the +10k-step control neutral? goalep inside the control's interval, both ways.
|
| 89 |
+
gp = D.get("edge_V_goalep")
|
| 90 |
+
neutral = (gp is not None and ctrl is not None
|
| 91 |
+
and ci[CTRL]["lo"] <= gp <= ci[CTRL]["hi"]
|
| 92 |
+
and ci["edge_V_goalep"]["lo"] <= ctrl <= ci["edge_V_goalep"]["hi"])
|
| 93 |
+
inside = [o[0] for o in order
|
| 94 |
+
if o[0] != CTRL and ctrl is not None and ci[CTRL]["lo"] <= o[2] <= ci[CTRL]["hi"]]
|
| 95 |
+
verdict = ("(2) BAR CLEARED by " + ",".join(cleared) if cleared else
|
| 96 |
+
"(3) label axis CLOSED -- all arms inside the control's interval"
|
| 97 |
+
if len(inside) == len(order) - 1 else
|
| 98 |
+
"(1b) a label MOVES the number: " +
|
| 99 |
+
",".join(o[0] for o in order if o[0] != CTRL and o[0] not in inside))
|
| 100 |
+
print()
|
| 101 |
+
print(f"control edge_T_rise d = {ctrl:+.4f} {f(ci[CTRL])}" if ctrl is not None else "control missing")
|
| 102 |
+
print(f"+10k-step control neutral (goalep ~ ctrl, both ways)? {neutral}")
|
| 103 |
+
print(f"best arm = {best[0]} d = {best[2]:+.4f} AUC_w {best[3]:.3f}")
|
| 104 |
+
print(f"arms inside the control's interval: {inside}")
|
| 105 |
+
print(f"PRE-REGISTERED VERDICT: {verdict}")
|
| 106 |
+
out["_rule"] = dict(ctrl_d=ctrl, goalep_d=gp, ft_control_neutral=bool(neutral),
|
| 107 |
+
inside_ctrl_interval=inside, best=best[0], best_d=best[2],
|
| 108 |
+
cleared=cleared, verdict=verdict)
|
| 109 |
+
json.dump(out, open(ROOT / "_edgeV_matched.json", "w"), indent=1, default=float)
|
| 110 |
+
print("-> status/real/_edgeV_matched.json")
|
gen_q_rsm/rsm_rise/pipeline/scripts/real/edge_matched_W.py
ADDED
|
@@ -0,0 +1,132 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""#278 run 22: rung W -- the REWARD LABEL x READ-OUT HORIZON interaction.
|
| 2 |
+
|
| 3 |
+
ONE factor moves off rung V: gamma 0.995 -> 0.999. Proposer (pi0.5 RISE rise_s0/29999), beta 0.99,
|
| 4 |
+
flow 8, N=128, 16 particles, S0 anchors, seed 0 and the same 25 held-out episodes are pinned, so
|
| 5 |
+
every g999 arm has an ALREADY-MEASURED matched control at g995 (status/real/_edgeV_matched.json)
|
| 6 |
+
and the design is a complete 4-label x 2-gamma table.
|
| 7 |
+
|
| 8 |
+
THE NUMBER THAT CHOSE IT (rung V, complete, anchor-for-anchor matched, stay-put gate held fixed at
|
| 9 |
+
0.5584-0.5596 so sample quality cannot vary across the label arms):
|
| 10 |
+
GOAL_EPISODE 0.294 -> +0.0872[+0.0436,+0.1368] | GOAL_WINDOW_400 0.111 -> +0.0125[-0.0114,+0.0296]
|
| 11 |
+
GOAL_SEGMENT 0.167 -> -0.0672[-0.1238,-0.0163] | GOAL_WINDOW_100 0.028 -> -0.0671[-0.1355,-0.0081]
|
| 12 |
+
The label is the largest lever on this test (spread 0.158 of d vs 0.005 for flow and 0.000 for
|
| 13 |
+
particles) but it only moves DOWN. REACHABILITY is the pre-registered explanation and it is
|
| 14 |
+
arithmetic: these are S0 anchors and the first GOAL_SEGMENT positive is ~673 frames away
|
| 15 |
+
(SEGMENTS.json: rest of 0->2 ~209 + 2->3 464) against a 199-frame horizon at gamma 0.995. The
|
| 16 |
+
corroborating number is #277's -- the SAME GOAL_SEGMENT checkpoint scores AUC 0.931 [0.89,0.96] on
|
| 17 |
+
goal detection at S0, measured at gamma 0.999 where the horizon (999) covers the 673. Rung Q closed
|
| 18 |
+
the horizon at +0.0690 but swept gamma with the DENSE shipped label ONLY, whose positives are already
|
| 19 |
+
reachable at 0.995 -- the one case where more horizon can only dilute. The interaction is untested.
|
| 20 |
+
|
| 21 |
+
PRE-REGISTERED RUNG-W RULE (posted on #278 before these numbers existed):
|
| 22 |
+
(a) ANY g999 arm >= +0.10 -> bar cleared; write the configuration and close #278.
|
| 23 |
+
(b) edge_W_goalseg_g999 ABOVE the upper bound of edge_V_goalseg's interval (-0.0163) -> the
|
| 24 |
+
label x horizon interaction is REAL and -0.0672 was a reachability artefact, not a verdict on
|
| 25 |
+
the label. Next rung is gamma 0.9995 on that label (horizon 1999).
|
| 26 |
+
(c) edge_W_goalep_g999 BELOW edge_V_goalep -> the dilution rung Q measured on the dense label is
|
| 27 |
+
reproduced, and (b)+(c) together mean the optimal gamma is LABEL-DEPENDENT: a publishable
|
| 28 |
+
structural finding about the read-out, not a tuning artefact.
|
| 29 |
+
(d) ALL FOUR g999 arms inside their own g995 arm's interval -> the interaction is NULL, the
|
| 30 |
+
label axis is closed at the dense default, and the standard-practice ladder on this test is
|
| 31 |
+
EXHAUSTED at +0.0909 [+0.0373,+0.1480]. Write the negative with the localised cause.
|
| 32 |
+
"""
|
| 33 |
+
import sys, json
|
| 34 |
+
import numpy as np
|
| 35 |
+
sys.path.insert(0, "/proj/dmfexp/zwhong/rsm_rise/scripts/real")
|
| 36 |
+
from pathlib import Path
|
| 37 |
+
from edge_report import load_dir
|
| 38 |
+
from edge_field import summarise_anchors
|
| 39 |
+
import edge_ceiling2 as C
|
| 40 |
+
|
| 41 |
+
ROOT = Path("/proj/dmfexp/zwhong/rsm_rise/status/real")
|
| 42 |
+
# label -> (canonical name + pos share, g995 arm dir, g999 arm dir, stay-put gate)
|
| 43 |
+
PAIRS = [("GOAL_EPISODE 0.294 R_XL_ft_v0", "edge_V_goalep", "edge_W_goalep_g999", 0.5596),
|
| 44 |
+
("GOAL_SEGMENT 0.167 R_XL_ft_v1", "edge_V_goalseg", "edge_W_goalseg_g999", 0.5584),
|
| 45 |
+
("GOAL_WINDOW_400 0.111 R_XL_ft_B400", "edge_V_win400", "edge_W_win400_g999", 0.5592),
|
| 46 |
+
("GOAL_WINDOW_100 0.028 R_XL_ft_B", "edge_V_win100", "edge_W_win100_g999", 0.5588)]
|
| 47 |
+
SHIPPED = "edge_T_rise" # R_XL s100000 at gamma 0.995, the best cell measured to date: +0.0909
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def stats(recs):
|
| 51 |
+
modes = sorted({m for x in recs for m in x["scores"]})
|
| 52 |
+
s = summarise_anchors(recs, modes, seed=0, n_boot=2000)["states"].get("S0", {})
|
| 53 |
+
sr = s.get("scorers", {}).get("rsm", {})
|
| 54 |
+
return dict(n=s.get("n_anchors"), cov=s.get("coverage"),
|
| 55 |
+
dg=sr.get("delta_vs_greedy", {}), dp=sr.get("delta_vs_permuted", {}),
|
| 56 |
+
rank=sr.get("onroute_rank_pct", {}))
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def f(d):
|
| 60 |
+
return f"{d['mean']:+.4f}[{d['lo']:+.4f},{d['hi']:+.4f}]"
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def read(a):
|
| 64 |
+
recs = load_dir(ROOT / a)
|
| 65 |
+
if not recs:
|
| 66 |
+
return None
|
| 67 |
+
A = stats(recs)
|
| 68 |
+
c = C.arm(str(ROOT / a))
|
| 69 |
+
need = (c["auc_perm"]["weighted"] + 0.10 / c["d_ceiling"] * (1.0 - c["auc_perm"]["weighted"])
|
| 70 |
+
if c["d_ceiling"] else float("nan"))
|
| 71 |
+
pct = 100.0 * A["dg"]["mean"] / c["d_ceiling"] if c["d_ceiling"] else float("nan")
|
| 72 |
+
return dict(episodes=sorted({int(r["episode"]) for r in recs}), arm=A, ceiling=c,
|
| 73 |
+
auc_w_needed=need, pct_of_ceiling=pct)
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
out = {}
|
| 77 |
+
hdr = (f"{'label / checkpoint':30s} {'gate':>6s} {'gamma':>6s} {'eps':>3s} {'anc':>4s} {'cov':>5s} "
|
| 78 |
+
f"{'wbar':>5s} | {'d_vs_greedy':>24s} | {'AUCw':>6s} {'prm':>5s} {'need':>5s} {'%ceil':>7s}")
|
| 79 |
+
print(hdr); print("-" * len(hdr))
|
| 80 |
+
for lab, a995, a999, gate in PAIRS:
|
| 81 |
+
for g, a in (("0.995", a995), ("0.999", a999)):
|
| 82 |
+
r = read(a)
|
| 83 |
+
if r is None:
|
| 84 |
+
print(f"{lab:30s} {gate:6.4f} {g:>6s} -- no parts yet ({a})")
|
| 85 |
+
continue
|
| 86 |
+
out[a] = dict(label=lab, gamma=float(g), gate=gate, **r)
|
| 87 |
+
c, A = r["ceiling"], r["arm"]
|
| 88 |
+
print(f"{lab:30s} {gate:6.4f} {g:>6s} {len(r['episodes']):3d} {c['n_anchors']:4d} "
|
| 89 |
+
f"{A['cov']:5.3f} {c['w_mean']:5.3f} | {f(A['dg']):>24s} | "
|
| 90 |
+
f"{c['auc_rsm']['weighted']:6.3f} {c['auc_perm']['weighted']:5.3f} "
|
| 91 |
+
f"{r['auc_w_needed']:5.3f} {r['pct_of_ceiling']:6.1f}%")
|
| 92 |
+
print()
|
| 93 |
+
|
| 94 |
+
# --- the pre-registered rule, evaluated mechanically -------------------------------------------
|
| 95 |
+
D = {a: v["arm"]["dg"] for a, v in out.items()}
|
| 96 |
+
g999 = [a for a in D if a.endswith("_g999")]
|
| 97 |
+
if g999:
|
| 98 |
+
cleared = [a for a in g999 if D[a]["mean"] >= 0.10]
|
| 99 |
+
# (b) the sparse label rescued by the reachable horizon?
|
| 100 |
+
seg_ok = ("edge_W_goalseg_g999" in D and "edge_V_goalseg" in D
|
| 101 |
+
and D["edge_W_goalseg_g999"]["mean"] > D["edge_V_goalseg"]["hi"])
|
| 102 |
+
# (c) the dense label diluted by the longer horizon (rung Q's mechanism reproduced)?
|
| 103 |
+
ep_down = ("edge_W_goalep_g999" in D and "edge_V_goalep" in D
|
| 104 |
+
and D["edge_W_goalep_g999"]["mean"] < D["edge_V_goalep"]["lo"])
|
| 105 |
+
# (d) every g999 arm inside its own g995 control's interval -> interaction NULL
|
| 106 |
+
pairs_done = [(a995, a999) for _, a995, a999, _ in PAIRS if a995 in D and a999 in D]
|
| 107 |
+
inside = [a999 for a995, a999 in pairs_done
|
| 108 |
+
if D[a995]["lo"] <= D[a999]["mean"] <= D[a995]["hi"]]
|
| 109 |
+
null = len(pairs_done) == len(PAIRS) and len(inside) == len(PAIRS)
|
| 110 |
+
best = max(D, key=lambda a: D[a]["mean"])
|
| 111 |
+
verdict = ("(a) BAR CLEARED by " + ",".join(cleared) if cleared else
|
| 112 |
+
"(d) interaction NULL -- every gamma 0.999 arm inside its own gamma 0.995 interval; "
|
| 113 |
+
"label axis closed at the dense default and the standard-practice ladder is EXHAUSTED"
|
| 114 |
+
if null else
|
| 115 |
+
"(b)+(c) optimal gamma is LABEL-DEPENDENT: sparse label rescued by the reachable "
|
| 116 |
+
"horizon AND dense label diluted by it" if (seg_ok and ep_down) else
|
| 117 |
+
"(b) sparse label RESCUED by the reachable horizon" if seg_ok else
|
| 118 |
+
"(c) dense label DILUTED by the longer horizon only" if ep_down else
|
| 119 |
+
"partial: horizon moves some arm outside its control, neither (b) nor (c) cleanly")
|
| 120 |
+
print(f"pairs complete: {len(pairs_done)}/{len(PAIRS)} g999 arms inside their g995 interval: {inside}")
|
| 121 |
+
print(f"(b) goalseg rescued (> {D['edge_V_goalseg']['hi']:+.4f})? {seg_ok}"
|
| 122 |
+
if "edge_V_goalseg" in D else "(b) goalseg control missing")
|
| 123 |
+
print(f"(c) goalep diluted (< {D['edge_V_goalep']['lo']:+.4f})? {ep_down}"
|
| 124 |
+
if "edge_V_goalep" in D else "(c) goalep control missing")
|
| 125 |
+
print(f"best arm overall = {best} d = {D[best]['mean']:+.4f} "
|
| 126 |
+
f"(shipped best to date edge_T_rise +0.0909; bar +0.10)")
|
| 127 |
+
print(f"PRE-REGISTERED VERDICT: {verdict}")
|
| 128 |
+
out["_rule"] = dict(cleared=cleared, seg_rescued=bool(seg_ok), goalep_diluted=bool(ep_down),
|
| 129 |
+
pairs_complete=len(pairs_done), inside_own_ctrl=inside, interaction_null=bool(null),
|
| 130 |
+
best=best, best_d=D[best]["mean"], verdict=verdict)
|
| 131 |
+
json.dump(out, open(ROOT / "_edgeW_matched.json", "w"), indent=1, default=float)
|
| 132 |
+
print("-> status/real/_edgeW_matched.json")
|
gen_q_rsm/rsm_rise/pipeline/scripts/real/edge_matched_X.py
ADDED
|
@@ -0,0 +1,136 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""#278 run 24: rung X -- the REWARD LABEL x READ-OUT HORIZON interaction, second step of gamma.
|
| 2 |
+
|
| 3 |
+
ONE factor moves off rung W: gamma 0.999 -> 0.9995. Proposer (pi0.5 RISE rise_s0/29999), beta 0.99
|
| 4 |
+
(inside the trained range beta_lo 0.95 / beta_hi 0.99), flow 8, N=128, 16 particles, S0 anchors,
|
| 5 |
+
seed 0 and the same 25 held-out episodes stay pinned, so every g9995 arm has an ALREADY-MEASURED
|
| 6 |
+
matched control at g999 (status/real/_edgeW_matched.json) and the design completes a 4-label x
|
| 7 |
+
3-gamma table. Nothing retrained, nothing bespoke.
|
| 8 |
+
|
| 9 |
+
THE NUMBER THAT CHOSE IT (rung W, COMPLETE 25/25, anchor-for-anchor matched, stay-put gate held
|
| 10 |
+
fixed per label so sample quality cannot vary across the horizon):
|
| 11 |
+
GOAL_WINDOW_400 0.111: +0.0125[-0.0114,+0.0296] at g0.995 -> +0.0546[+0.0107,+0.1030] at g0.999
|
| 12 |
+
-- the ONLY arm at any rung that a horizon change pushed clean OUTSIDE its own control's interval
|
| 13 |
+
(+0.0546 > +0.0296), and its AUC_w more than doubled away from the permuted null (0.543 -> 0.654
|
| 14 |
+
against perm 0.491 -> 0.500). The other three stayed inside their own controls:
|
| 15 |
+
GOAL_EPISODE +0.0872 -> +0.0741 | GOAL_SEGMENT -0.0672 -> -0.0629 | GOAL_WINDOW_100 -0.0671 -> -0.0516.
|
| 16 |
+
|
| 17 |
+
THE MECHANISM UNDER TEST IS ARITHMETIC (cache SEGMENTS.json, S0 anchors, horizon = 1/(1-gamma)):
|
| 18 |
+
first positive of... frames from an S0 anchor g0.995=199 g0.999=999 g0.9995=1999
|
| 19 |
+
GOAL_WINDOW_400 ~849 (209 + 464 + 176) no YES yes
|
| 20 |
+
GOAL_SEGMENT ~673 (209 + 464) no yes yes
|
| 21 |
+
GOAL_WINDOW_100 ~1149 (209 + 464 + 476) no no YES
|
| 22 |
+
S4 arrival itself ~1249 (209 + 464 + 576) no no YES
|
| 23 |
+
So if reachability is the mechanism, GOAL_WINDOW_100 is the arm that moves NEXT, and it moves at
|
| 24 |
+
gamma 0.9995 and NOT before. That was posted on #278 (run 23) BEFORE these numbers existed.
|
| 25 |
+
|
| 26 |
+
PRE-REGISTERED RUNG-X RULE (posted on #278 run 23, before any X part was read):
|
| 27 |
+
(a) ANY g9995 arm >= +0.10 -> bar cleared; write the configuration into configs/baselines.yaml and
|
| 28 |
+
rise_stack/EDGE_TEST.md with the numbers, post the passing table, close #278.
|
| 29 |
+
(b) edge_X_win100_g9995 ABOVE the upper bound of edge_W_win100_g999's interval -> the reachability
|
| 30 |
+
pre-registration is CONFIRMED: the horizon a label needs is a property of its positive geometry.
|
| 31 |
+
(c) edge_X_win400_g9995 keeps rising above edge_W_win400_g999 -> report the SMALLEST gamma that
|
| 32 |
+
clears the bar, per the owner's "report the smallest that passes".
|
| 33 |
+
(d) NOTHING moves (every g9995 arm inside its own g999 interval) -> the horizon axis is EXHAUSTED at
|
| 34 |
+
gamma 0.999 and the standard-practice ladder on this test is done; write the negative with the
|
| 35 |
+
localised cause (RISE proposer supplies cov 0.904 / ceiling +0.1898; the RSM scorer realises
|
| 36 |
+
47.9% of it, significantly above its permuted null 0.508, but 0.023 of AUC_w short of the bar).
|
| 37 |
+
"""
|
| 38 |
+
import sys, json
|
| 39 |
+
import numpy as np
|
| 40 |
+
sys.path.insert(0, "/proj/dmfexp/zwhong/rsm_rise/scripts/real")
|
| 41 |
+
from pathlib import Path
|
| 42 |
+
from edge_report import load_dir
|
| 43 |
+
from edge_field import summarise_anchors
|
| 44 |
+
import edge_ceiling2 as C
|
| 45 |
+
|
| 46 |
+
ROOT = Path("/proj/dmfexp/zwhong/rsm_rise/status/real")
|
| 47 |
+
# label -> (canonical name + pos share, g999 control dir, g9995 arm dir, stay-put gate)
|
| 48 |
+
PAIRS = [("GOAL_EPISODE 0.294 R_XL_ft_v0", "edge_W_goalep_g999", "edge_X_goalep_g9995", 0.5596),
|
| 49 |
+
("GOAL_SEGMENT 0.167 R_XL_ft_v1", "edge_W_goalseg_g999", "edge_X_goalseg_g9995", 0.5584),
|
| 50 |
+
("GOAL_WINDOW_400 0.111 R_XL_ft_B400", "edge_W_win400_g999", "edge_X_win400_g9995", 0.5592),
|
| 51 |
+
("GOAL_WINDOW_100 0.028 R_XL_ft_B", "edge_W_win100_g999", "edge_X_win100_g9995", 0.5588)]
|
| 52 |
+
BEST_TO_DATE = ("edge_T_rise", 0.0909) # R_XL s100000, GOAL_EPISODE, gamma 0.995; bar is +0.10
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def stats(recs):
|
| 56 |
+
modes = sorted({m for x in recs for m in x["scores"]})
|
| 57 |
+
s = summarise_anchors(recs, modes, seed=0, n_boot=2000)["states"].get("S0", {})
|
| 58 |
+
sr = s.get("scorers", {}).get("rsm", {})
|
| 59 |
+
return dict(n=s.get("n_anchors"), cov=s.get("coverage"),
|
| 60 |
+
dg=sr.get("delta_vs_greedy", {}), dp=sr.get("delta_vs_permuted", {}),
|
| 61 |
+
rank=sr.get("onroute_rank_pct", {}))
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def f(d):
|
| 65 |
+
return f"{d['mean']:+.4f}[{d['lo']:+.4f},{d['hi']:+.4f}]"
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def read(a):
|
| 69 |
+
recs = load_dir(ROOT / a)
|
| 70 |
+
if not recs:
|
| 71 |
+
return None
|
| 72 |
+
A = stats(recs)
|
| 73 |
+
c = C.arm(str(ROOT / a))
|
| 74 |
+
need = (c["auc_perm"]["weighted"] + 0.10 / c["d_ceiling"] * (1.0 - c["auc_perm"]["weighted"])
|
| 75 |
+
if c["d_ceiling"] else float("nan"))
|
| 76 |
+
pct = 100.0 * A["dg"]["mean"] / c["d_ceiling"] if c["d_ceiling"] else float("nan")
|
| 77 |
+
return dict(episodes=sorted({int(r["episode"]) for r in recs}), arm=A, ceiling=c,
|
| 78 |
+
auc_w_needed=need, pct_of_ceiling=pct)
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
out = {}
|
| 82 |
+
hdr = (f"{'label / checkpoint':30s} {'gate':>6s} {'gamma':>7s} {'eps':>3s} {'anc':>4s} {'cov':>5s} "
|
| 83 |
+
f"{'wbar':>5s} | {'d_vs_greedy':>24s} | {'AUCw':>6s} {'prm':>5s} {'need':>5s} {'%ceil':>7s}")
|
| 84 |
+
print(hdr); print("-" * len(hdr))
|
| 85 |
+
for lab, a999, a9995, gate in PAIRS:
|
| 86 |
+
for g, a in (("0.999", a999), ("0.9995", a9995)):
|
| 87 |
+
r = read(a)
|
| 88 |
+
if r is None:
|
| 89 |
+
print(f"{lab:30s} {gate:6.4f} {g:>7s} -- no parts yet ({a})")
|
| 90 |
+
continue
|
| 91 |
+
out[a] = dict(label=lab, gamma=float(g), gate=gate, **r)
|
| 92 |
+
c, A = r["ceiling"], r["arm"]
|
| 93 |
+
print(f"{lab:30s} {gate:6.4f} {g:>7s} {len(r['episodes']):3d} {c['n_anchors']:4d} "
|
| 94 |
+
f"{A['cov']:5.3f} {c['w_mean']:5.3f} | {f(A['dg']):>24s} | "
|
| 95 |
+
f"{c['auc_rsm']['weighted']:6.3f} {c['auc_perm']['weighted']:5.3f} "
|
| 96 |
+
f"{r['auc_w_needed']:5.3f} {r['pct_of_ceiling']:6.1f}%")
|
| 97 |
+
print()
|
| 98 |
+
|
| 99 |
+
# --- the pre-registered rule, evaluated mechanically -------------------------------------------
|
| 100 |
+
D = {a: v["arm"]["dg"] for a, v in out.items()}
|
| 101 |
+
g9995 = [a for a in D if a.endswith("_g9995")]
|
| 102 |
+
if g9995:
|
| 103 |
+
cleared = [a for a in g9995 if D[a]["mean"] >= 0.10]
|
| 104 |
+
# (b) the reachability pre-registration: GOAL_WINDOW_100 is the arm that moves at 0.9995
|
| 105 |
+
w100_ok = ("edge_X_win100_g9995" in D and "edge_W_win100_g999" in D
|
| 106 |
+
and D["edge_X_win100_g9995"]["mean"] > D["edge_W_win100_g999"]["hi"])
|
| 107 |
+
# (c) GOAL_WINDOW_400 keeps rising past its own g999 interval
|
| 108 |
+
w400_up = ("edge_X_win400_g9995" in D and "edge_W_win400_g999" in D
|
| 109 |
+
and D["edge_X_win400_g9995"]["mean"] > D["edge_W_win400_g999"]["hi"])
|
| 110 |
+
pairs_done = [(a999, a9995) for _, a999, a9995, _ in PAIRS if a999 in D and a9995 in D]
|
| 111 |
+
inside = [a for a999, a in pairs_done if D[a999]["lo"] <= D[a]["mean"] <= D[a999]["hi"]]
|
| 112 |
+
null = len(pairs_done) == len(PAIRS) and len(inside) == len(PAIRS)
|
| 113 |
+
best = max(D, key=lambda a: D[a]["mean"])
|
| 114 |
+
verdict = ("(a) BAR CLEARED by " + ",".join(cleared) if cleared else
|
| 115 |
+
"(d) horizon axis EXHAUSTED at gamma 0.999 -- every gamma 0.9995 arm inside its own "
|
| 116 |
+
"gamma 0.999 interval; the standard-practice ladder on this test is done" if null else
|
| 117 |
+
"(b)+(c) reachability CONFIRMED on both windows: the horizon a label needs is a "
|
| 118 |
+
"property of its positive geometry" if (w100_ok and w400_up) else
|
| 119 |
+
"(b) reachability CONFIRMED -- GOAL_WINDOW_100 moves at 0.9995 and not before"
|
| 120 |
+
if w100_ok else
|
| 121 |
+
"(c) GOAL_WINDOW_400 keeps rising; GOAL_WINDOW_100 did not move" if w400_up else
|
| 122 |
+
"partial: some arm moves outside its control, neither (b) nor (c) cleanly")
|
| 123 |
+
print(f"pairs complete: {len(pairs_done)}/{len(PAIRS)} g9995 arms inside their g999 interval: {inside}")
|
| 124 |
+
if "edge_W_win100_g999" in D:
|
| 125 |
+
print(f"(b) win100 moves (> {D['edge_W_win100_g999']['hi']:+.4f})? {w100_ok}")
|
| 126 |
+
if "edge_W_win400_g999" in D:
|
| 127 |
+
print(f"(c) win400 keeps rising (> {D['edge_W_win400_g999']['hi']:+.4f})? {w400_up}")
|
| 128 |
+
print(f"best arm overall = {best} d = {D[best]['mean']:+.4f} "
|
| 129 |
+
f"(best cell measured to date {BEST_TO_DATE[0]} {BEST_TO_DATE[1]:+.4f}; bar +0.10)")
|
| 130 |
+
print(f"PRE-REGISTERED VERDICT: {verdict}")
|
| 131 |
+
out["_rule"] = dict(cleared=cleared, win100_moved=bool(w100_ok), win400_rose=bool(w400_up),
|
| 132 |
+
pairs_complete=len(pairs_done), inside_own_ctrl=inside,
|
| 133 |
+
horizon_exhausted=bool(null), best=best, best_d=D[best]["mean"],
|
| 134 |
+
verdict=verdict)
|
| 135 |
+
json.dump(out, open(ROOT / "_edgeX_matched.json", "w"), indent=1, default=float)
|
| 136 |
+
print("-> status/real/_edgeX_matched.json")
|
gen_q_rsm/rsm_rise/pipeline/scripts/real/edge_matched_Y.py
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""#278 run 25: rung Y -- COMPOSITION DEPTH. The chain's beta, the one standard-practice scorer
|
| 2 |
+
axis every edge measurement to date left PINNED at 0.99.
|
| 3 |
+
|
| 4 |
+
ONE factor moves off the rung-W control. Proposer (pi0.5 RISE rise_s0/29999), label GOAL_EPISODE
|
| 5 |
+
(0.294 pos share, R_XL_ft_v0/ckpt_s110000.pt -- the best arm at every rung), gamma 0.999, flow 8,
|
| 6 |
+
N=128, 16 particles, S0 anchors, seed 0 and the same 25 held-out episodes stay pinned, so both beta
|
| 7 |
+
arms have an ALREADY-MEASURED matched control (status/real/_edgeW_matched.json):
|
| 8 |
+
edge_W_goalep_g999, beta 0.99 = +0.0741[+0.0324,+0.1229], AUC_w 0.709 vs perm 0.512, 40.0% ceil.
|
| 9 |
+
|
| 10 |
+
THE NUMBER THAT CHOSE IT: rung X fired its pre-registered clause (d) -- every gamma 0.9995 arm
|
| 11 |
+
landed INSIDE its own gamma 0.999 interval (goalep +0.0741 -> +0.0569, win400 +0.0546 -> +0.0670,
|
| 12 |
+
win100 -0.0516 -> -0.0526, goalseg -0.0629 -> -0.0472), `horizon_exhausted: true`. So the HORIZON
|
| 13 |
+
axis is done. beta is a DIFFERENT axis: gamma sets how far the read-out looks, beta sets how many
|
| 14 |
+
COMPOSITION steps the walk takes to get there -- and composition is the property this test claims
|
| 15 |
+
to measure. It has never been varied here.
|
| 16 |
+
|
| 17 |
+
THE DESIGN HOLDS THE HORIZON FIXED AND VARIES ONLY THE NUMBER OF HOPS IT IS BUILT FROM. With
|
| 18 |
+
p = (g-b)/(g(1-b)), E[extra hops] = p/(1-p), E[model reads] = 1/(1-p), frames/hop = b/(1-b),
|
| 19 |
+
E[total frames] = g/(1-g) -- at gamma 0.999 that last term is 999 for EVERY beta:
|
| 20 |
+
beta 0.99 (control) p 0.9009 E[extra] 9.1 E[reads] 10.1 99 frames/hop cap 67
|
| 21 |
+
beta 0.98 p 0.9510 E[extra] 19.4 E[reads] 20.4 49 frames/hop cap 138
|
| 22 |
+
beta 0.95 p 0.9810 E[extra] 51.6 E[reads] 52.6 19 frames/hop cap 360
|
| 23 |
+
so a difference between these arms is composition depth and nothing else.
|
| 24 |
+
|
| 25 |
+
IN THE TRAINED RANGE, CHECKED ON THE CHECKPOINT ITSELF: R_XL_ft_v0/ckpt_s110000.pt carries
|
| 26 |
+
beta_lo 0.95, beta_hi 0.99, beta_q 0.98, beta_trunc_eps 0.02, chunk 8. Both arms are inside it;
|
| 27 |
+
nothing below 0.95 is run (an out-of-range beta is a defect, not a data point).
|
| 28 |
+
|
| 29 |
+
PRE-REGISTERED RUNG-Y RULE (written and committed BEFORE any Y part was read):
|
| 30 |
+
(a) EITHER beta arm >= +0.10 -> BAR CLEARED; write the configuration into configs/baselines.yaml
|
| 31 |
+
and rise_stack/EDGE_TEST.md with the numbers, post the passing table, close #278.
|
| 32 |
+
(b) EITHER beta arm ABOVE the control's upper bound (+0.1229) -> composition depth IS a lever;
|
| 33 |
+
report the beta that wins and carry it to the GOAL_WINDOW_400 label (the other arm that a
|
| 34 |
+
horizon change moved) before anything else.
|
| 35 |
+
(c) BOTH arms BELOW the control's lower bound (+0.0324) -> deeper composition HURTS monotonically:
|
| 36 |
+
each extra hop compounds the successor's off-manifold error (the stay-put gate 0.5596 already
|
| 37 |
+
says its samples sit farther from the data than staying put), which LOCALISES the loss to the
|
| 38 |
+
chain's DEPTH rather than its horizon or its label. Publishable, and it says the next fix is
|
| 39 |
+
the successor's sample quality, not any knob of the read-out.
|
| 40 |
+
(d) BOTH arms INSIDE the control's interval -> the beta axis is FLAT over 9.1 -> 51.6 hops:
|
| 41 |
+
composition depth does not matter to this metric, the standard-practice ladder on this test is
|
| 42 |
+
EXHAUSTED, and the negative gets written with its localised cause and #278 closed.
|
| 43 |
+
"""
|
| 44 |
+
import sys, json
|
| 45 |
+
import numpy as np
|
| 46 |
+
sys.path.insert(0, "/proj/dmfexp/zwhong/rsm_rise/scripts/real")
|
| 47 |
+
from pathlib import Path
|
| 48 |
+
from edge_report import load_dir
|
| 49 |
+
from edge_field import summarise_anchors
|
| 50 |
+
import edge_ceiling2 as C
|
| 51 |
+
|
| 52 |
+
ROOT = Path("/proj/dmfexp/zwhong/rsm_rise/status/real")
|
| 53 |
+
CTRL = "edge_W_goalep_g999"
|
| 54 |
+
# arm dir -> (beta, p, E[extra hops], E[model reads], frames/hop, cap)
|
| 55 |
+
ARMS = [(CTRL, 0.99, 0.9009, 9.1, 10.1, 99, 67),
|
| 56 |
+
("edge_Y_goalep_b98", 0.98, 0.9510, 19.4, 20.4, 49, 138),
|
| 57 |
+
("edge_Y_goalep_b95", 0.95, 0.9810, 51.6, 52.6, 19, 360)]
|
| 58 |
+
GATE = 0.5596 # stay-put gate of the GOAL_EPISODE successor, fixed by construction
|
| 59 |
+
BEST_TO_DATE = ("edge_T_rise", 0.0909) # R_XL s100000, GOAL_EPISODE, gamma 0.995; bar is +0.10
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def stats(recs):
|
| 63 |
+
modes = sorted({m for x in recs for m in x["scores"]})
|
| 64 |
+
s = summarise_anchors(recs, modes, seed=0, n_boot=2000)["states"].get("S0", {})
|
| 65 |
+
sr = s.get("scorers", {}).get("rsm", {})
|
| 66 |
+
return dict(n=s.get("n_anchors"), cov=s.get("coverage"),
|
| 67 |
+
dg=sr.get("delta_vs_greedy", {}), dp=sr.get("delta_vs_permuted", {}),
|
| 68 |
+
rank=sr.get("onroute_rank_pct", {}))
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def f(d):
|
| 72 |
+
return f"{d['mean']:+.4f}[{d['lo']:+.4f},{d['hi']:+.4f}]"
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def read(a):
|
| 76 |
+
recs = load_dir(ROOT / a)
|
| 77 |
+
if not recs:
|
| 78 |
+
return None
|
| 79 |
+
A = stats(recs)
|
| 80 |
+
c = C.arm(str(ROOT / a))
|
| 81 |
+
need = (c["auc_perm"]["weighted"] + 0.10 / c["d_ceiling"] * (1.0 - c["auc_perm"]["weighted"])
|
| 82 |
+
if c["d_ceiling"] else float("nan"))
|
| 83 |
+
pct = 100.0 * A["dg"]["mean"] / c["d_ceiling"] if c["d_ceiling"] else float("nan")
|
| 84 |
+
return dict(episodes=sorted({int(r["episode"]) for r in recs}), arm=A, ceiling=c,
|
| 85 |
+
auc_w_needed=need, pct_of_ceiling=pct)
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
out = {}
|
| 89 |
+
hdr = (f"{'beta hops reads cap':22s} {'gate':>6s} {'eps':>3s} {'anc':>4s} {'cov':>5s} {'wbar':>5s} | "
|
| 90 |
+
f"{'d_vs_greedy':>24s} {'d_vs_permuted':>24s} | {'AUCw':>6s} {'prm':>5s} {'need':>5s} {'%ceil':>7s}")
|
| 91 |
+
print("=== rung Y: COMPOSITION DEPTH at fixed horizon (gamma 0.999, GOAL_EPISODE, RISE proposer) ===")
|
| 92 |
+
print(hdr); print("-" * len(hdr))
|
| 93 |
+
for a, beta, p, extra, reads, fph, cap in ARMS:
|
| 94 |
+
r = read(a)
|
| 95 |
+
if r is None:
|
| 96 |
+
print(f"{beta:<5.2f} {extra:5.1f} {reads:6.1f} {cap:4d} -- no parts yet ({a})")
|
| 97 |
+
continue
|
| 98 |
+
out[a] = dict(beta=beta, p=p, e_extra_hops=extra, e_reads=reads, frames_per_hop=fph, cap=cap,
|
| 99 |
+
gate=GATE, is_control=(a == CTRL), **r)
|
| 100 |
+
c, A = r["ceiling"], r["arm"]
|
| 101 |
+
print(f"{beta:<5.2f} {extra:5.1f} {reads:6.1f} {cap:4d} {GATE:6.4f} {len(r['episodes']):3d} "
|
| 102 |
+
f"{c['n_anchors']:4d} {A['cov']:5.3f} {c['w_mean']:5.3f} | {f(A['dg']):>24s} {f(A['dp']):>24s} | "
|
| 103 |
+
f"{c['auc_rsm']['weighted']:6.3f} {c['auc_perm']['weighted']:5.3f} "
|
| 104 |
+
f"{r['auc_w_needed']:5.3f} {r['pct_of_ceiling']:6.1f}%"
|
| 105 |
+
+ (" <- CONTROL (rung W, beta 0.99)" if a == CTRL else ""))
|
| 106 |
+
|
| 107 |
+
# --- the pre-registered rule, evaluated mechanically -------------------------------------------
|
| 108 |
+
D = {a: v["arm"]["dg"] for a, v in out.items()}
|
| 109 |
+
if CTRL in D and len(D) > 1:
|
| 110 |
+
lo, hi = D[CTRL]["lo"], D[CTRL]["hi"]
|
| 111 |
+
beta_arms = [a for a in D if a != CTRL]
|
| 112 |
+
cleared = [a for a in beta_arms if D[a]["mean"] >= 0.10]
|
| 113 |
+
above = [a for a in beta_arms if D[a]["mean"] > hi]
|
| 114 |
+
below = [a for a in beta_arms if D[a]["mean"] < lo]
|
| 115 |
+
inside = [a for a in beta_arms if lo <= D[a]["mean"] <= hi]
|
| 116 |
+
complete = len(beta_arms) == len(ARMS) - 1
|
| 117 |
+
monotone_down = complete and len(below) == len(beta_arms)
|
| 118 |
+
flat = complete and len(inside) == len(beta_arms)
|
| 119 |
+
best = max(D, key=lambda a: D[a]["mean"])
|
| 120 |
+
verdict = ("(a) BAR CLEARED by " + ",".join(cleared) if cleared else
|
| 121 |
+
"(c) deeper composition HURTS monotonically -- both beta arms below the control's "
|
| 122 |
+
"lower bound; the loss localises to the chain's DEPTH (off-manifold error compounding "
|
| 123 |
+
"per hop), not its horizon or its label" if monotone_down else
|
| 124 |
+
"(d) the beta axis is FLAT over 9.1 -> 51.6 hops: composition depth does not move this "
|
| 125 |
+
"metric and the standard-practice ladder on this test is EXHAUSTED" if flat else
|
| 126 |
+
"(b) composition depth IS a lever -- " + ",".join(above) +
|
| 127 |
+
" above the control's upper bound" if above else
|
| 128 |
+
f"partial: {len(beta_arms)}/{len(ARMS)-1} beta arms read, no clause fires yet")
|
| 129 |
+
print()
|
| 130 |
+
print(f"control edge_W_goalep_g999 (beta 0.99) = {f(D[CTRL])}")
|
| 131 |
+
print(f"beta arms complete: {len(beta_arms)}/{len(ARMS)-1} above {hi:+.4f}: {above} "
|
| 132 |
+
f"below {lo:+.4f}: {below} inside: {inside}")
|
| 133 |
+
print(f"best arm overall = {best} d = {D[best]['mean']:+.4f} "
|
| 134 |
+
f"(best cell measured to date {BEST_TO_DATE[0]} {BEST_TO_DATE[1]:+.4f}; bar +0.10)")
|
| 135 |
+
print(f"PRE-REGISTERED VERDICT: {verdict}")
|
| 136 |
+
out["_rule"] = dict(control=CTRL, ctrl_lo=lo, ctrl_hi=hi, cleared=cleared, above=above,
|
| 137 |
+
below=below, inside_own_ctrl=inside, arms_complete=len(beta_arms),
|
| 138 |
+
depth_hurts=bool(monotone_down), beta_axis_flat=bool(flat),
|
| 139 |
+
best=best, best_d=D[best]["mean"], verdict=verdict)
|
| 140 |
+
json.dump(out, open(ROOT / "_edgeY_matched.json", "w"), indent=1, default=float)
|
| 141 |
+
print("-> status/real/_edgeY_matched.json")
|