diff --git a/rsm_rise/scripts/real/_patch_gate_run28.py b/rsm_rise/scripts/real/_patch_gate_run28.py new file mode 100644 index 0000000000000000000000000000000000000000..1b04f90bdd1fae65abcad1dc691b385c93381d1c --- /dev/null +++ b/rsm_rise/scripts/real/_patch_gate_run28.py @@ -0,0 +1,118 @@ +#!/usr/bin/env python3 +"""Run-28 edits to scripts/real/selfcont_clean_venv.sh, applied once and kept for the record.""" +import sys + +p = "scripts/real/selfcont_clean_venv.sh" +s = open(p).read() + +old = '''# LSF 1889983 found that `rise_stack.run`/`check` were loading the DINOv2 *source* from +# /proj/dmfexp/zwhong/rsm_rise/cache/torch/hub/... -- the value of dino_hub_dir: in +# rise_stack/configs/baselines.yaml -- so on this machine three steps of every previous gate run +# were quietly reading the research tree. Point it inside $SCRATCH: the first use downloads the +# repo from github into exactly this path (torch.hub's own cache layout), later steps reuse it, +# and nothing outside $SCRATCH is readable for it. +export RISE_DINO_HUB_DIR="$SCRATCH/.torchhome/hub/facebookresearch_dinov2_main" +''' +new = '''# NO RISE_DINO_HUB_DIR export, deliberately, since 2026-09-24 (run 28). +# +# LSF 1889983 found `rise_stack.run`/`check` loading the DINOv2 *source* from +# /proj/dmfexp/zwhong/rsm_rise/cache/torch/hub/... -- the shipped value of dino_hub_dir: in +# rise_stack/configs/baselines.yaml -- and the repair was to export RISE_DINO_HUB_DIR into $SCRATCH. +# That fixed the GATE and not the file the reader gets: LSF 1905498 found the same 24 `dinov2.*` +# modules coming from the research tree in a process without the override. A gate that sets a variable +# QUICKSTART.md never mentions is not testing the reader's path, so the override is gone and +# `dino_hub_dir:` now ships as null. With null, rise_stack/scorers.py resolves +# $TORCH_HOME/hub/facebookresearch_dinov2_main -- which, with TORCH_HOME=$SCRATCH/.torchhome above, is +# byte-for-byte the path this line used to export, downloaded from github on first use. +# If a future tree reintroduces a research-tree default, STEP 10 must go red. Do not re-add this. + +# RSM_LIBERO_DIR is exported to a path that does not exist, deliberately. +# +# Until 2026-09-24 the vendored scorer defaulted it to /proj/dmfexp/zwhong/rsm_rise/code/gen_q/ +# rsm_libero and `_rsm_modules()` imported `model`, `train_rsm`, `is_ope` and `data` from there. This +# gate UNSET the variable, which on THIS cluster silently selected that default -- so every green run +# measured a scorer that raises `ModuleNotFoundError: No module named 'model'` anywhere else +# (LSF 1905498). Unsetting can no longer distinguish "used the vendored copy" from "found the cluster +# tree"; an invalid value can, because the only way past it is the vendored copy. +export RSM_LIBERO_DIR=/nonexistent-rsm-libero-a-clean-machine-has-no-cluster-tree +''' +assert old in s, "DINO hub export block not found" +s = s.replace(old, new, 1) + +STEP10 = r'''hdr "STEP 10 module provenance: score a decision IN THIS PROCESS, then ask sys.modules where every module came from" +# The replacement for STEP 9's log grep, and the reason is measured rather than anticipated. STEP 9 +# searches the log for the literal `/proj/dmfexp/zwhong/rsm_rise`. Two independent ways a leak evades +# that, both realised: `importlib.import_module` prints nothing, so there is no line to grep (the +# rsm_libero import), and `rsm_rise/code/gen_q` is a SYMLINK to +# `projs/issue_resolver_richardrl/gen_q_rsm`, so the resolved path does not contain the searched +# string either. A realpath walk of `sys.modules` after the work is done sees both. STEP 9 stays as +# well -- it catches a printed path that no module import explains -- but THIS is the binding one. +# +# `rise_stack.run.main()` is called in-process with exactly STEP 5's arguments, so the scan looks at +# an interpreter that scored a decision and not at one that only imported a package. The floor (250 +# module files) is what stops "clean" from meaning "the scan ran before anything was imported". +python - <<'PYPROV' +import json, os, sys +sys.argv = ["rise_stack.run"] +from rise_stack.run import main +from rise_stack import module_provenance as mp + +ck = os.environ["CKPTS"] +rc_run = main(["--policy", "random", "--scorer", "rsm", "--env", "replay", + "--hdf5", "rise_stack/fixtures/replay_cooking_v5_ep7.hdf5", + "--split", "rise_stack/fixtures/split.json", + "--video-root", "rise_stack/fixtures", + "--rsm-ckpt", ck + "/successor_rsm_real_RM_s0_100k.pt", + "--rsm-feat-stats", ck + "/successor_rsm_real_feat_stats.json", + "--rsm-hop-ckpt", ck + "/hop_head_rsm_real_gauss_r1.pt", + "--episodes", "1", "--n-cand", "8", "--horizon", "8", "--max-decisions", "1", + "--out", "runs/provenance"]) +print("in-process rise_stack.run rc =", 0 if rc_run in (0, None) else rc_run) +# Allowed: the clone, and $SCRATCH (the venv, the pip cache, TORCH_HOME -- everything this gate +# downloaded). interpreter_roots() adds the base interpreter that stands in for the reader's python3. +# Nothing else. A checkpoint directory needs no entry: checkpoints are data, not modules. +allow = [os.environ["REPO"], os.environ["SCRATCH"]] + mp.interpreter_roots() +rc = mp.report(allow, floor=250) +ins, out, roots, missing = mp.classify(allow) +jp = os.path.join(os.environ["SCRATCH"], "provenance.json") +json.dump({"rc": rc, "n": len(ins) + len(out), "roots": roots, "missing_roots": missing, + "foreign": [{"module": n, "path": p} for n, p in out]}, open(jp, "w"), indent=1) +print("provenance json:", jp) +sys.exit(rc if rc else (0 if rc_run in (0, None) else 4)) +PYPROV +echo "provenance rc=$?" + +''' + +anchor = "# Nine `rc=` labels and three sentinel strings, checked by a machine against an expectation table." +assert anchor in s, "verdict preamble not found" +s = s.replace(anchor, STEP10 + anchor, 1) + +old_expect = ''' "leakscan": 0, "whichscorer": 0,''' +new_expect = ''' "leakscan": 0, "whichscorer": 0, + # STEP 10: the in-process sys.modules realpath walk. rc=2 is a NON-RESULT (inspected fewer + # module files than the floor), rc=3 a leak, rc=4 the decision itself failed; all three + # must fail the gate, which is why the expectation is exactly 0 and not "non-fatal". + "provenance": 0, + "in-process rise_stack.run rc": 0,''' +assert old_expect in s +s = s.replace(old_expect, new_expect, 1) + +old_sent = '''SENTINELS = ["CLEAN: robomimic is not importable in this venv", + "VENDORED COPY LOADED: True", "LEAK SCAN: clean"]''' +new_sent = '''SENTINELS = ["CLEAN: robomimic is not importable in this venv", + "VENDORED COPY LOADED: True", "LEAK SCAN: clean", + # STEP 10. "clean" alone could in principle be printed by a scan that inspected nothing, + # so the floor is asserted in-process (rc=2) and the inspected count is printed next to it. + "MODULE PROVENANCE: clean", + # ...and the vendored rsm_libero is what resolved, under RSM_LIBERO_DIR=/nonexistent: + # `_rsm_modules()` announces its directory, so the log carries the provenance of the number. + "rsm_libero modules from"]''' +assert old_sent in s +s = s.replace(old_sent, new_sent, 1) + +assert "for step in range(1, 10):" in s +s = s.replace("for step in range(1, 10):", "for step in range(1, 11):", 1) + +open(p, "w").write(s) +print("patched", p) diff --git a/rsm_rise/scripts/real/_pr1_271_run15.sh b/rsm_rise/scripts/real/_pr1_271_run15.sh new file mode 100644 index 0000000000000000000000000000000000000000..74c7b8b0da90510e21ea01399d7b870dcdb2b50e --- /dev/null +++ b/rsm_rise/scripts/real/_pr1_271_run15.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +set -uo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +exec venv_rsm/bin/python scripts/real/build_pr1_271_run11.py \ + status/real/pr1_body_live_run15.md status/real/pr1_body_run15_patched.md diff --git a/rsm_rise/scripts/real/_pr1_271_run18.sh b/rsm_rise/scripts/real/_pr1_271_run18.sh new file mode 100644 index 0000000000000000000000000000000000000000..bb5ea05b234a731a43866ba22f1c32d1e47c6c0e --- /dev/null +++ b/rsm_rise/scripts/real/_pr1_271_run18.sh @@ -0,0 +1,9 @@ +#!/usr/bin/env bash +# run 18: fetch the LIVE PR-1 body, splice #271 section (11), PATCH it back. Never patches from a copy. +set -uo pipefail +ROOT=/proj/dmfexp/zwhong/rsm_rise +cd "$ROOT" || exit 1 +bash scripts/tmp/gh_get_pr.sh jmarangola/rsm_real 1 status/real/pr1_body_live_run18.md || exit 2 +"$ROOT/venv_rsm/bin/python" scripts/real/build_pr1_271_run18.py \ + status/real/pr1_body_live_run18.md status/real/pr1_body_run18_patched.md || exit 3 +exec bash scripts/tmp/gh_patch_pr.sh jmarangola/rsm_real 1 status/real/pr1_body_run18_patched.md diff --git a/rsm_rise/scripts/real/_pr1_271_run21.sh b/rsm_rise/scripts/real/_pr1_271_run21.sh new file mode 100644 index 0000000000000000000000000000000000000000..df4b2a50a2e913629f862b727df8f5bf777986bb --- /dev/null +++ b/rsm_rise/scripts/real/_pr1_271_run21.sh @@ -0,0 +1,9 @@ +#!/usr/bin/env bash +# run 21: fetch the LIVE PR-1 body, splice #271 section (12), PATCH it back. Never patches from a copy. +set -uo pipefail +ROOT=/proj/dmfexp/zwhong/rsm_rise +cd "$ROOT" || exit 1 +bash scripts/tmp/gh_get_pr.sh jmarangola/rsm_real 1 status/real/pr1_body_live_run21.md || exit 2 +"$ROOT/venv_rsm/bin/python" scripts/real/build_pr1_271_run21.py \ + status/real/pr1_body_live_run21.md status/real/pr1_body_run21_patched.md || exit 3 +exec bash scripts/tmp/gh_patch_pr.sh jmarangola/rsm_real 1 status/real/pr1_body_run21_patched.md diff --git a/rsm_rise/scripts/real/_px_wrappers/px_ordercost_run13.sh b/rsm_rise/scripts/real/_px_wrappers/px_ordercost_run13.sh new file mode 100644 index 0000000000000000000000000000000000000000..124ba8b6e4742de5bc4cb61e24c67cf66144acd6 --- /dev/null +++ b/rsm_rise/scripts/real/_px_wrappers/px_ordercost_run13.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +export SCRATCH=/proj/dmfexp/zwhong/scratch_patchexport/run18 +exec bash /proj/dmfexp/zwhong/rsm_rise/scripts/real/patchexport_order_cost.sh diff --git a/rsm_rise/scripts/real/_px_wrappers/px_ordercost_run14.sh b/rsm_rise/scripts/real/_px_wrappers/px_ordercost_run14.sh new file mode 100644 index 0000000000000000000000000000000000000000..1d660cb22b9a3deb40154504bec08f06934452d7 --- /dev/null +++ b/rsm_rise/scripts/real/_px_wrappers/px_ordercost_run14.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +export SCRATCH=/proj/dmfexp/zwhong/scratch_patchexport/run20 +exec bash /proj/dmfexp/zwhong/rsm_rise/scripts/real/patchexport_order_cost.sh diff --git a/rsm_rise/scripts/real/_px_wrappers/px_ordercost_run15.sh b/rsm_rise/scripts/real/_px_wrappers/px_ordercost_run15.sh new file mode 100644 index 0000000000000000000000000000000000000000..b1ce740d05e6a1fadabb3add69cbe931fad1b66d --- /dev/null +++ b/rsm_rise/scripts/real/_px_wrappers/px_ordercost_run15.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +export SCRATCH=/proj/dmfexp/zwhong/scratch_patchexport/run22 +exec bash /proj/dmfexp/zwhong/rsm_rise/scripts/real/patchexport_order_cost.sh diff --git a/rsm_rise/scripts/real/_px_wrappers/px_qsweight.sh b/rsm_rise/scripts/real/_px_wrappers/px_qsweight.sh new file mode 100644 index 0000000000000000000000000000000000000000..816badcd5269818f9c2ceb5086c36498cf1076ee --- /dev/null +++ b/rsm_rise/scripts/real/_px_wrappers/px_qsweight.sh @@ -0,0 +1,6 @@ +#!/usr/bin/env bash +# deliberately does NOT source scripts/env.sh: the RISE conda env has robomimic installed, which is +# exactly the condition under which section D cannot conclude anything. +export SCRATCH=/proj/dmfexp/zwhong/scratch_patchexport/run21 +export QS_PY=/proj/dmfexp/zwhong/rsm_rise/venv_rsm/bin/python +exec bash /proj/dmfexp/zwhong/rsm_rise/scripts/real/patchexport_quickstart_weight.sh diff --git a/rsm_rise/scripts/real/_px_wrappers/px_setupenv_run13.sh b/rsm_rise/scripts/real/_px_wrappers/px_setupenv_run13.sh new file mode 100644 index 0000000000000000000000000000000000000000..0cd579f697665d9982679595e3a37aaee6e38e5d --- /dev/null +++ b/rsm_rise/scripts/real/_px_wrappers/px_setupenv_run13.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +export SCRATCH=/proj/dmfexp/zwhong/scratch_patchexport/run19 +exec bash /proj/dmfexp/zwhong/rsm_rise/scripts/real/patchexport_setupenv_resolution.sh diff --git a/rsm_rise/scripts/real/_px_wrappers/px_sixway_run13.sh b/rsm_rise/scripts/real/_px_wrappers/px_sixway_run13.sh new file mode 100644 index 0000000000000000000000000000000000000000..1c898cee3bfff2f6c31d7a1daea93988e3aa09ef --- /dev/null +++ b/rsm_rise/scripts/real/_px_wrappers/px_sixway_run13.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +export SCRATCH=/proj/dmfexp/zwhong/scratch_patchexport/run17 +export SC_REPO=origin +export SC_REF=pull/11/head +exec bash /proj/dmfexp/zwhong/rsm_rise/scripts/real/patchexport_sixway_gate.sh diff --git a/rsm_rise/scripts/real/_px_wrappers/px_sixway_run14.sh b/rsm_rise/scripts/real/_px_wrappers/px_sixway_run14.sh new file mode 100644 index 0000000000000000000000000000000000000000..ed87a0987d7d921ecee6b73eaacdac93f60893ef --- /dev/null +++ b/rsm_rise/scripts/real/_px_wrappers/px_sixway_run14.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +export SCRATCH=/proj/dmfexp/zwhong/scratch_patchexport/run19 +export SC_REPO=origin +export SC_REF=pull/11/head +exec bash /proj/dmfexp/zwhong/rsm_rise/scripts/real/patchexport_sixway_gate.sh diff --git a/rsm_rise/scripts/real/_px_wrappers/px_sixway_run15.sh b/rsm_rise/scripts/real/_px_wrappers/px_sixway_run15.sh new file mode 100644 index 0000000000000000000000000000000000000000..fe9d523fdb34ed1e7e9f94c0c321be46d7e5215a --- /dev/null +++ b/rsm_rise/scripts/real/_px_wrappers/px_sixway_run15.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +export SCRATCH=/proj/dmfexp/zwhong/scratch_patchexport/run21 +export SC_REPO=origin +export SC_REF=pull/11/head +exec bash /proj/dmfexp/zwhong/rsm_rise/scripts/real/patchexport_sixway_gate.sh diff --git a/rsm_rise/scripts/real/_px_wrappers/px_whichscorer_run14.sh b/rsm_rise/scripts/real/_px_wrappers/px_whichscorer_run14.sh new file mode 100644 index 0000000000000000000000000000000000000000..fc75c4ed4a7cbc75cc70bc583332edac7db807f8 --- /dev/null +++ b/rsm_rise/scripts/real/_px_wrappers/px_whichscorer_run14.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +export SCRATCH=/proj/dmfexp/zwhong/scratch_patchexport/run23 +exec bash /proj/dmfexp/zwhong/rsm_rise/scripts/real/patchexport_whichscorer_resolution.sh diff --git a/rsm_rise/scripts/real/_run_actcond_spread_law.sh b/rsm_rise/scripts/real/_run_actcond_spread_law.sh new file mode 100644 index 0000000000000000000000000000000000000000..cbb19150d26dfc75cae93360312c5fb00894c721 --- /dev/null +++ b/rsm_rise/scripts/real/_run_actcond_spread_law.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +source wandb_env.sh >/dev/null 2>&1 || true +exec venv_rsm/bin/python scripts/real/actcond_spread_law.py \ + --out /proj/dmfexp/zwhong/rsm_rise/status/real/ACT_COND/SPREAD_LAW_run37.json diff --git a/rsm_rise/scripts/real/_run_all31.sh b/rsm_rise/scripts/real/_run_all31.sh new file mode 100644 index 0000000000000000000000000000000000000000..5349812e7190c12f71f1ae57d3ad690feb02fa3a --- /dev/null +++ b/rsm_rise/scripts/real/_run_all31.sh @@ -0,0 +1,27 @@ +#!/bin/bash +# run 31 (2026-09-24): all four cap-pair stitch reads landed (1894747/1896924/1896925/1896926), +# plus two GSC x130 cells from 1891659. Re-run the whole read-out stack on the enlarged set: +# the reducer (owns the `trunc` cap-axis sign convention), the clearance tally, run 29's measured +# prefix-forest lineage tally and run 30's shape tally. Nothing is re-scored; all four read only +# JSON already on disk. Each output goes to its own file so the diff against the run-30 numbers +# is mechanical. +set -u +cd /proj/dmfexp/zwhong/rsm_rise +export MUJOCO_GL=disable +PY=venv_rsm/bin/python +O=status/real/stitch_readout_run31 +mkdir -p $O +echo "[run_env] host=$(hostname) job=${LSB_JOBID:-none} $(date -u)" + +echo "=== reducer ===" +$PY scripts/real/reduce_stitch_matrix.py > $O/reduce.txt 2> $O/reduce.err; echo "reduce exit=$?" +echo "=== clearance ===" +$PY scripts/real/stitch_clearance_tally.py > $O/clearance.txt 2> $O/clearance.err; echo "clearance exit=$?" +echo "=== lineage ===" +$PY scripts/real/stitch_lineage_tally.py > $O/lineage.txt 2> $O/lineage.err; echo "lineage exit=$?" +echo "=== shape ===" +$PY scripts/real/stitch_shape_tally.py > $O/shape.txt 2> $O/shape.err; echo "shape exit=$?" + +echo "=== line counts ===" +wc -l $O/*.txt $O/*.err +echo "[exit] 0 $(date -u)" diff --git a/rsm_rise/scripts/real/_run_clearance.sh b/rsm_rise/scripts/real/_run_clearance.sh new file mode 100644 index 0000000000000000000000000000000000000000..80c35e4d292c21c02ac474a175dcda28cdd5bb6a --- /dev/null +++ b/rsm_rise/scripts/real/_run_clearance.sh @@ -0,0 +1,7 @@ +#!/bin/bash +set -u +cd /proj/dmfexp/zwhong/rsm_rise +export MUJOCO_GL=disable +echo "[run_env] host=$(hostname) job=${LSB_JOBID:-none} $(date -u)" +venv_rsm/bin/python scripts/real/stitch_clearance_tally.py +echo "[exit] $? $(date -u)" diff --git a/rsm_rise/scripts/real/_run_lineage.sh b/rsm_rise/scripts/real/_run_lineage.sh new file mode 100644 index 0000000000000000000000000000000000000000..b642153406ad8d88a26136e21c08d5016383ed81 --- /dev/null +++ b/rsm_rise/scripts/real/_run_lineage.sh @@ -0,0 +1,7 @@ +#!/bin/bash +set -u +cd /proj/dmfexp/zwhong/rsm_rise +export MUJOCO_GL=disable +echo "[run_env] host=$(hostname) job=${LSB_JOBID:-none} $(date -u)" +venv_rsm/bin/python scripts/real/stitch_lineage_tally.py +echo "[exit] $? $(date -u)" diff --git a/rsm_rise/scripts/real/_run_red31b.sh b/rsm_rise/scripts/real/_run_red31b.sh new file mode 100644 index 0000000000000000000000000000000000000000..454d5513ff18a0cb18be6d6b4dcc7e27436f6433 --- /dev/null +++ b/rsm_rise/scripts/real/_run_red31b.sh @@ -0,0 +1,16 @@ +#!/bin/bash +set -u +cd /proj/dmfexp/zwhong/rsm_rise +export MUJOCO_GL=disable +O=status/real/stitch_readout_run31 +echo "[run_env] host=$(hostname) job=${LSB_JOBID:-none} $(date -u)" +venv_rsm/bin/python scripts/real/reduce_stitch_matrix.py > $O/reduce.postfix2.txt 2> $O/reduce.postfix2.err +echo "post2 exit=$?" +echo "=== DIFF postfix (step-suffix flags only) vs postfix2 (+ base_parent strip) ===" +echo "=== expected: ONLY the 'independent bases' columns of the two cap rows and the pooled trunc row ===" +diff $O/reduce.postfix.txt $O/reduce.postfix2.txt +echo "=== diff exit=$? ===" +echo "=== the two lines that matter, final ===" +grep -n "independent bases\|^| \`trunc\`\|step-matched @110k\] \[base R_XL\] | 2 " $O/reduce.postfix2.txt | head +wc -l $O/reduce.postfix2.txt $O/reduce.postfix2.err +echo "[exit] 0 $(date -u)" diff --git a/rsm_rise/scripts/real/_run_red31post.sh b/rsm_rise/scripts/real/_run_red31post.sh new file mode 100644 index 0000000000000000000000000000000000000000..76f7963ef97152166341b4fb65a2dc408670b60b --- /dev/null +++ b/rsm_rise/scripts/real/_run_red31post.sh @@ -0,0 +1,13 @@ +#!/bin/bash +set -u +cd /proj/dmfexp/zwhong/rsm_rise +export MUJOCO_GL=disable +O=status/real/stitch_readout_run31 +echo "[run_env] host=$(hostname) job=${LSB_JOBID:-none} $(date -u)" +venv_rsm/bin/python scripts/real/reduce_stitch_matrix.py > $O/reduce.postfix.txt 2> $O/reduce.postfix.err +echo "post exit=$?" +echo "=== REGRESSION DIFF pre-fix vs post-fix (expected: ONLY the two @110k R_XL cap rows and the pooled trunc rows) ===" +diff $O/reduce.prefix.txt $O/reduce.postfix.txt +echo "=== diff exit=$? (0 = identical, 1 = differs) ===" +wc -l $O/reduce.prefix.txt $O/reduce.postfix.txt $O/reduce.postfix.err +echo "[exit] 0 $(date -u)" diff --git a/rsm_rise/scripts/real/_run_rwprofile.sh b/rsm_rise/scripts/real/_run_rwprofile.sh new file mode 100644 index 0000000000000000000000000000000000000000..f751a0fc99731ff31c03d16482e99ad2ea8864dd --- /dev/null +++ b/rsm_rise/scripts/real/_run_rwprofile.sh @@ -0,0 +1,7 @@ +#!/bin/bash +set -u +cd /proj/dmfexp/zwhong/rsm_rise +export MUJOCO_GL=disable +echo "[run_env] host=$(hostname) job=${LSB_JOBID:-none} $(date -u)" +venv_rsm/bin/python scripts/real/reward_head_profile.py +echo "[exit] $? $(date -u)" diff --git a/rsm_rise/scripts/real/_run_shape.sh b/rsm_rise/scripts/real/_run_shape.sh new file mode 100644 index 0000000000000000000000000000000000000000..8fc60e76edd231f419a0e0a6b34b5781f30cb4f8 --- /dev/null +++ b/rsm_rise/scripts/real/_run_shape.sh @@ -0,0 +1,7 @@ +#!/bin/bash +set -u +cd /proj/dmfexp/zwhong/rsm_rise +export MUJOCO_GL=disable +echo "[run_env] host=$(hostname) job=${LSB_JOBID:-none} $(date -u)" +venv_rsm/bin/python scripts/real/stitch_shape_tally.py +echo "[exit] $? $(date -u)" diff --git a/rsm_rise/scripts/real/_run_termaudit.sh b/rsm_rise/scripts/real/_run_termaudit.sh new file mode 100644 index 0000000000000000000000000000000000000000..fea49693fadf85f6a50397326297c59ff659e0de --- /dev/null +++ b/rsm_rise/scripts/real/_run_termaudit.sh @@ -0,0 +1,7 @@ +#!/bin/bash +set -u +cd /proj/dmfexp/zwhong/rsm_rise +export MUJOCO_GL=disable +echo "[run_env] host=$(hostname) job=${LSB_JOBID:-none} $(date -u)" +venv_rsm/bin/python scripts/real/terminal_handling_audit.py +echo "[exit] $? $(date -u)" diff --git a/rsm_rise/scripts/real/_sig_stride25.sh b/rsm_rise/scripts/real/_sig_stride25.sh new file mode 100644 index 0000000000000000000000000000000000000000..a5d18ea33ade1a9e3a6c377539ef920a8b485059 --- /dev/null +++ b/rsm_rise/scripts/real/_sig_stride25.sh @@ -0,0 +1,10 @@ +#!/usr/bin/env bash +# #271 run 8: the stitching number on the INDEPENDENT anchor set (stride 25, 250 anchors, hops 1,4) +# produced by run 7's bare run_stitch_number.sh. The published number is the stride-50 / 150-anchor +# measurement; this one shares no candidate draw with it (anchors are seeded by anchor INDEX), so the +# two together are a replicate of the whole stitching measurement, not of its bootstrap. +set -uo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +exec scripts/real/run_env.sh scripts/real/stitch_significance.py \ + --parts status/real/REWARD_HEAD_DIAG_STITCH_stride25.json_parts \ + --out status/real/STITCH_SIGNIFICANCE_stride25.json diff --git a/rsm_rise/scripts/real/_sig_stride25_matched.sh b/rsm_rise/scripts/real/_sig_stride25_matched.sh new file mode 100644 index 0000000000000000000000000000000000000000..f6f3be4fd5a008f74a4a05d9ba3246da6bc47fbb --- /dev/null +++ b/rsm_rise/scripts/real/_sig_stride25_matched.sh @@ -0,0 +1,12 @@ +#!/usr/bin/env bash +# #271 run 8: the stitching number on the stride-25 parts RESTRICTED to the anchors of the published +# stride-50 measurement (STITCH_SIGNIFICANCE.json as of 09:11, the numbers in CHECKPOINTS.md / the PDF / +# PR #1 / the HF card / the issue). Same anchor frames, INDEPENDENT candidate draw -- the exact +# analogue of the open-loop screen's noise floor, and the check that the published significance is not +# an artefact of one candidate draw. +set -uo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +exec scripts/real/run_env.sh scripts/real/stitch_significance.py \ + --parts status/real/REWARD_HEAD_DIAG_STITCH_stride25.json_parts \ + --restrict-to-parts status/real/STITCH_SIGNIFICANCE.json \ + --out status/real/STITCH_SIGNIFICANCE_matched.json diff --git a/rsm_rise/scripts/real/_sk_compare.sh b/rsm_rise/scripts/real/_sk_compare.sh new file mode 100644 index 0000000000000000000000000000000000000000..afb9a4666224853bb26dca65d7c9cd4abdfe44a9 --- /dev/null +++ b/rsm_rise/scripts/real/_sk_compare.sh @@ -0,0 +1,14 @@ +#!/usr/bin/env bash +# run 12: fold the four scoring-functional cells against the flagship prob/T=25 baseline +# (status/real/STITCH_DECOMP.json, the depth-1 decomposition from run 10) into ONE comparison JSON. +# Pure JSON arithmetic -- no GPU, no model loading. +set -uo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +exec python3 scripts/real/build_sk_compare.py \ + --cell prob_T25=$PWD/status/real/STITCH_DECOMP.json \ + --cell logit_T25=$PWD/status/real/SK_logit_T25.json \ + --cell prob_log_T25=$PWD/status/real/SK_prob_log_T25.json \ + --cell prob_T1=$PWD/status/real/SK_prob_T1.json \ + --cell prob_T100=$PWD/status/real/SK_prob_T100.json \ + --baseline prob_T25 --hops 2,4 \ + --out $PWD/status/real/SK_COMPARE.json diff --git a/rsm_rise/scripts/real/_sk_logit_T25.sh b/rsm_rise/scripts/real/_sk_logit_T25.sh new file mode 100644 index 0000000000000000000000000000000000000000..036db0d0c2230287c9301b4771606a005b74bcc2 --- /dev/null +++ b/rsm_rise/scripts/real/_sk_logit_T25.sh @@ -0,0 +1,17 @@ +#!/usr/bin/env bash +# run 12, scoring-functional sweep cell: score_kind=logit, temperature=25.0, flagship d1/beta=0.99. +# WHY this cell exists. Diagnostic 3's Q sits at chance while the SAME heads read the endpoint class +# at the chained latent at per-anchor AUC up to 0.941 (STITCH_DECOMP.json), and run 11 showed the +# read-out's HORIZON is not the culprit (fold-4 vs d1 moves the statistic by 0.0028 rms, below the +# ~0.005 GPU noise; within-anchor corr 0.977). The remaining suspect is the functional that turns +# 16 particle rewards into one ranking scalar. "prob" is mean sigma(logit/T): at T=25 the flagship +# de-saturates a head whose sigmoid ties at 1.000, but the surviving between-candidate spread is +# q_spread_cv ~ 0.0017 -- 4th significant figure. The sweep brackets that functional: "logit" is the +# T -> infinity linear limit, "prob_log" is gen_q#266's log-complement read-out, T=1 is the saturated +# end and T=100 the flat end. All 150 published anchors, one GPU, own parts dir so no two cells can +# share a draw; anchors already on disk are skipped, so the cell is preemption-safe and resumable. +set -uo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +DC_OUT=$PWD/status/real/SK_logit_T25.json bash scripts/real/run_stitch_decompose.sh \ + --with-q --q-score-kind logit --q-temperature 25.0 \ + --parts $PWD/status/real/SK_logit_T25.json_parts diff --git a/rsm_rise/scripts/real/_sk_prob_T1.sh b/rsm_rise/scripts/real/_sk_prob_T1.sh new file mode 100644 index 0000000000000000000000000000000000000000..3215cca355cf19769b6c1edb1801bd5e11143855 --- /dev/null +++ b/rsm_rise/scripts/real/_sk_prob_T1.sh @@ -0,0 +1,17 @@ +#!/usr/bin/env bash +# run 12, scoring-functional sweep cell: score_kind=prob, temperature=1.0, flagship d1/beta=0.99. +# WHY this cell exists. Diagnostic 3's Q sits at chance while the SAME heads read the endpoint class +# at the chained latent at per-anchor AUC up to 0.941 (STITCH_DECOMP.json), and run 11 showed the +# read-out's HORIZON is not the culprit (fold-4 vs d1 moves the statistic by 0.0028 rms, below the +# ~0.005 GPU noise; within-anchor corr 0.977). The remaining suspect is the functional that turns +# 16 particle rewards into one ranking scalar. "prob" is mean sigma(logit/T): at T=25 the flagship +# de-saturates a head whose sigmoid ties at 1.000, but the surviving between-candidate spread is +# q_spread_cv ~ 0.0017 -- 4th significant figure. The sweep brackets that functional: "logit" is the +# T -> infinity linear limit, "prob_log" is gen_q#266's log-complement read-out, T=1 is the saturated +# end and T=100 the flat end. All 150 published anchors, one GPU, own parts dir so no two cells can +# share a draw; anchors already on disk are skipped, so the cell is preemption-safe and resumable. +set -uo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +DC_OUT=$PWD/status/real/SK_prob_T1.json bash scripts/real/run_stitch_decompose.sh \ + --with-q --q-score-kind prob --q-temperature 1.0 \ + --parts $PWD/status/real/SK_prob_T1.json_parts diff --git a/rsm_rise/scripts/real/_sk_prob_T100.sh b/rsm_rise/scripts/real/_sk_prob_T100.sh new file mode 100644 index 0000000000000000000000000000000000000000..253daaf63b7243f2e622a821033a9827ae687ac1 --- /dev/null +++ b/rsm_rise/scripts/real/_sk_prob_T100.sh @@ -0,0 +1,17 @@ +#!/usr/bin/env bash +# run 12, scoring-functional sweep cell: score_kind=prob, temperature=100.0, flagship d1/beta=0.99. +# WHY this cell exists. Diagnostic 3's Q sits at chance while the SAME heads read the endpoint class +# at the chained latent at per-anchor AUC up to 0.941 (STITCH_DECOMP.json), and run 11 showed the +# read-out's HORIZON is not the culprit (fold-4 vs d1 moves the statistic by 0.0028 rms, below the +# ~0.005 GPU noise; within-anchor corr 0.977). The remaining suspect is the functional that turns +# 16 particle rewards into one ranking scalar. "prob" is mean sigma(logit/T): at T=25 the flagship +# de-saturates a head whose sigmoid ties at 1.000, but the surviving between-candidate spread is +# q_spread_cv ~ 0.0017 -- 4th significant figure. The sweep brackets that functional: "logit" is the +# T -> infinity linear limit, "prob_log" is gen_q#266's log-complement read-out, T=1 is the saturated +# end and T=100 the flat end. All 150 published anchors, one GPU, own parts dir so no two cells can +# share a draw; anchors already on disk are skipped, so the cell is preemption-safe and resumable. +set -uo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +DC_OUT=$PWD/status/real/SK_prob_T100.json bash scripts/real/run_stitch_decompose.sh \ + --with-q --q-score-kind prob --q-temperature 100.0 \ + --parts $PWD/status/real/SK_prob_T100.json_parts diff --git a/rsm_rise/scripts/real/_sk_prob_log_T25.sh b/rsm_rise/scripts/real/_sk_prob_log_T25.sh new file mode 100644 index 0000000000000000000000000000000000000000..9dd0bfbaedac66c816d584086b644a7771765f66 --- /dev/null +++ b/rsm_rise/scripts/real/_sk_prob_log_T25.sh @@ -0,0 +1,17 @@ +#!/usr/bin/env bash +# run 12, scoring-functional sweep cell: score_kind=prob_log, temperature=25.0, flagship d1/beta=0.99. +# WHY this cell exists. Diagnostic 3's Q sits at chance while the SAME heads read the endpoint class +# at the chained latent at per-anchor AUC up to 0.941 (STITCH_DECOMP.json), and run 11 showed the +# read-out's HORIZON is not the culprit (fold-4 vs d1 moves the statistic by 0.0028 rms, below the +# ~0.005 GPU noise; within-anchor corr 0.977). The remaining suspect is the functional that turns +# 16 particle rewards into one ranking scalar. "prob" is mean sigma(logit/T): at T=25 the flagship +# de-saturates a head whose sigmoid ties at 1.000, but the surviving between-candidate spread is +# q_spread_cv ~ 0.0017 -- 4th significant figure. The sweep brackets that functional: "logit" is the +# T -> infinity linear limit, "prob_log" is gen_q#266's log-complement read-out, T=1 is the saturated +# end and T=100 the flat end. All 150 published anchors, one GPU, own parts dir so no two cells can +# share a draw; anchors already on disk are skipped, so the cell is preemption-safe and resumable. +set -uo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +DC_OUT=$PWD/status/real/SK_prob_log_T25.json bash scripts/real/run_stitch_decompose.sh \ + --with-q --q-score-kind prob_log --q-temperature 25.0 \ + --parts $PWD/status/real/SK_prob_log_T25.json_parts diff --git a/rsm_rise/scripts/real/_sk_smoke.sh b/rsm_rise/scripts/real/_sk_smoke.sh new file mode 100644 index 0000000000000000000000000000000000000000..6bef3a046e8686d1db2a00e4d68ce012444fd1dd --- /dev/null +++ b/rsm_rise/scripts/real/_sk_smoke.sh @@ -0,0 +1,23 @@ +#!/usr/bin/env bash +# run 12: the SCORING-FUNCTIONAL smoke. Run 11 falsified the horizon explanation (fold-4 moves the +# stitching number by less than GPU noise) while the endpoint class IS present at the chained latent +# (C10_s1 per-anchor AUC 0.941). What is left between R(z_h) and Q is the functional that compresses +# R over 16 particles into one ranking scalar -- "prob" (mean sigma) at T=25, whose between-candidate +# spread sits in the 4th significant figure (q_spread_cv ~ 0.0017). This checks that the three rival +# functionals CONSTRUCT and return finite Q on one anchor before a GPU pack is spent on them +# (rsm_scorer asserts score_kind against the mode/backend, so a bad cell dies at construction). +# CPU Q values are NOT comparable to the published GPU ones -- loading and finiteness only. +set -uo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +rc=0 +for cell in "logit 25.0" "prob_log 25.0" "prob 1.0" "prob 100.0"; do + set -- $cell; K=$1; T=$2 + tag="${K}_T${T}" + echo "=================== smoke cell $tag ===================" + DC_OUT=$PWD/status/real/_sk_smoke_${tag}.json bash scripts/real/run_stitch_decompose.sh \ + --with-q --anchor-lo 0 --anchor-hi 1 \ + --q-score-kind "$K" --q-temperature "$T" \ + --parts $PWD/status/real/_sk_smoke_${tag}.json_parts || { echo "[smoke] FAILED $tag"; rc=1; } +done +echo "[smoke] overall rc=$rc" +exit $rc diff --git a/rsm_rise/scripts/real/_sn_seed1.sh b/rsm_rise/scripts/real/_sn_seed1.sh new file mode 100644 index 0000000000000000000000000000000000000000..64ee15b5d7e37ec120dfc5558398544c5e6212e4 --- /dev/null +++ b/rsm_rise/scripts/real/_sn_seed1.sh @@ -0,0 +1,11 @@ +#!/usr/bin/env bash +# #271 run 9: an INDEPENDENT candidate draw of the stitching number at the CANONICAL anchors +# (stride 50, hops 1,2,4, N=128, 16 heads). --seed changes only the per-anchor candidate draw +# (stitch_number.py seeds anchor ai with seed*1000003+ai), so seeds 1..4 plus the published seed 0 +# are five replicates with the same anchors, same weights, same endpoints machinery. +set -uo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +O=status/real/STITCH_DRAW_s1.json +[ -f "$O" ] && { echo "[sn] $O exists, skipping"; exit 0; } +SN_OUT=$PWD/$O bash scripts/real/run_stitch_number.sh --seed 1 \ + --parts $PWD/status/real/STITCH_DRAW_s1.json_parts diff --git a/rsm_rise/scripts/real/_sn_seed2.sh b/rsm_rise/scripts/real/_sn_seed2.sh new file mode 100644 index 0000000000000000000000000000000000000000..ef89b773fc6b39abe1c349ee387e26719e6c3185 --- /dev/null +++ b/rsm_rise/scripts/real/_sn_seed2.sh @@ -0,0 +1,11 @@ +#!/usr/bin/env bash +# #271 run 9: an INDEPENDENT candidate draw of the stitching number at the CANONICAL anchors +# (stride 50, hops 1,2,4, N=128, 16 heads). --seed changes only the per-anchor candidate draw +# (stitch_number.py seeds anchor ai with seed*1000003+ai), so seeds 1..4 plus the published seed 0 +# are five replicates with the same anchors, same weights, same endpoints machinery. +set -uo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +O=status/real/STITCH_DRAW_s2.json +[ -f "$O" ] && { echo "[sn] $O exists, skipping"; exit 0; } +SN_OUT=$PWD/$O bash scripts/real/run_stitch_number.sh --seed 2 \ + --parts $PWD/status/real/STITCH_DRAW_s2.json_parts diff --git a/rsm_rise/scripts/real/_sn_seed3.sh b/rsm_rise/scripts/real/_sn_seed3.sh new file mode 100644 index 0000000000000000000000000000000000000000..cfb4f913ad7f26aa48172796bb2588ae80753d34 --- /dev/null +++ b/rsm_rise/scripts/real/_sn_seed3.sh @@ -0,0 +1,11 @@ +#!/usr/bin/env bash +# #271 run 9: an INDEPENDENT candidate draw of the stitching number at the CANONICAL anchors +# (stride 50, hops 1,2,4, N=128, 16 heads). --seed changes only the per-anchor candidate draw +# (stitch_number.py seeds anchor ai with seed*1000003+ai), so seeds 1..4 plus the published seed 0 +# are five replicates with the same anchors, same weights, same endpoints machinery. +set -uo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +O=status/real/STITCH_DRAW_s3.json +[ -f "$O" ] && { echo "[sn] $O exists, skipping"; exit 0; } +SN_OUT=$PWD/$O bash scripts/real/run_stitch_number.sh --seed 3 \ + --parts $PWD/status/real/STITCH_DRAW_s3.json_parts diff --git a/rsm_rise/scripts/real/_sn_seed4.sh b/rsm_rise/scripts/real/_sn_seed4.sh new file mode 100644 index 0000000000000000000000000000000000000000..06742a0611018901c37217c95a2c66fa5f308907 --- /dev/null +++ b/rsm_rise/scripts/real/_sn_seed4.sh @@ -0,0 +1,11 @@ +#!/usr/bin/env bash +# #271 run 9: an INDEPENDENT candidate draw of the stitching number at the CANONICAL anchors +# (stride 50, hops 1,2,4, N=128, 16 heads). --seed changes only the per-anchor candidate draw +# (stitch_number.py seeds anchor ai with seed*1000003+ai), so seeds 1..4 plus the published seed 0 +# are five replicates with the same anchors, same weights, same endpoints machinery. +set -uo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +O=status/real/STITCH_DRAW_s4.json +[ -f "$O" ] && { echo "[sn] $O exists, skipping"; exit 0; } +SN_OUT=$PWD/$O bash scripts/real/run_stitch_number.sh --seed 4 \ + --parts $PWD/status/real/STITCH_DRAW_s4.json_parts diff --git a/rsm_rise/scripts/real/_srep.sh b/rsm_rise/scripts/real/_srep.sh new file mode 100644 index 0000000000000000000000000000000000000000..7fbd4ecb0cdd19de0a04168605e9138e118a6f73 --- /dev/null +++ b/rsm_rise/scripts/real/_srep.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +set -uo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +exec scripts/real/run_env.sh scripts/real/stitch_reproducibility.py \ + --label-a "stride50 draw" --label-b "stride25 draw, same anchors" diff --git a/rsm_rise/scripts/real/_tmp/pr12_run16.sh b/rsm_rise/scripts/real/_tmp/pr12_run16.sh new file mode 100644 index 0000000000000000000000000000000000000000..a35a20b41930a4afb0fb8debbf3ef76eac5a001c --- /dev/null +++ b/rsm_rise/scripts/real/_tmp/pr12_run16.sh @@ -0,0 +1,26 @@ +#!/usr/bin/env bash +set -euo pipefail +ROOT=/proj/dmfexp/zwhong/rsm_rise +WT=/proj/dmfexp/zwhong/scratch_pi05_200k/rsm_real +bash $ROOT/scripts/real/pi05_ft50_pr12.sh +cd $WT +git --no-pager status --short +if ! git diff --quiet; then + git add rise_stack/CHECKPOINTS.md + git commit -m "CHECKPOINTS: ft50 held-out table at 89-93k; withdraw argmin checkpoint selection, add plateau slope test + +The 'best checkpoint @ step N' readings in this section were argmin over ~80 noisy +evals with no noise model. Detrended, every one of the 16 series has z_best 0.62-2.45 +against ~2.0 expected from pure noise, so none is distinguishable from the noise band. +Replaced with the plateau OLS slope and its t-statistic, which splits the set: the two +BC fine-tunes are converged (stock_s0 t=-0.8) or regressing (stock_s1 t=+2.4 / +10.5) +and should be taken at ~50k, while the five RISE actors are still improving at 90k +(t=-4.5 .. -21.5) and should be taken at 200k. + +Co-Authored-By: Claude Opus 5 " + git push origin HEAD + git --no-pager log --oneline -1 +else + echo "NO CHANGE to CHECKPOINTS.md" +fi +echo PR12_RUN16_DONE diff --git a/rsm_rise/scripts/real/_tmp/pr12_run17.sh b/rsm_rise/scripts/real/_tmp/pr12_run17.sh new file mode 100644 index 0000000000000000000000000000000000000000..1933c9f21369dd396b0e99fbe6efca0111ba7593 --- /dev/null +++ b/rsm_rise/scripts/real/_tmp/pr12_run17.sh @@ -0,0 +1,28 @@ +#!/usr/bin/env bash +set -euo pipefail +ROOT=/proj/dmfexp/zwhong/rsm_rise +WT=/proj/dmfexp/zwhong/scratch_pi05_200k/rsm_real +bash $ROOT/scripts/real/pi05_ft50_pr12.sh +cd $WT +git --no-pager status --short +if ! git diff --quiet; then + git add rise_stack/CHECKPOINTS.md + git commit -m "CHECKPOINTS: measure whether the plateau slope is decaying; sharpen the 200k prediction to 5/5 + +The 200k projections here extrapolated a 50k-90k plateau slope linearly and noted +only that the cosine makes that an upper bound. That caveat is now measured rather +than assumed: ft50_slope_curvature.py splits the plateau at its midpoint in STEP, +fits an independent OLS line per half and tests the slope difference. Only 3 of 16 +series decelerate resolvably (stock_s0 c50/c10, sn1 c10). Re-projected at the +late-half rate all four predicted RISE passes survive and sn0p1_knn0p03 flips from +'just misses' to a pass, so the 150k check is now a 5-of-5 claim with sn1 (margin +0.047 cm) deciding it. Also records that stock_s0_ft50 is not merely converged but +regressing in the late half (t=+4.3), which strengthens the take-BC-at-50k rule. + +Co-Authored-By: Claude Opus 5 " + git push origin HEAD + git --no-pager log --oneline -1 +else + echo "NO CHANGE to CHECKPOINTS.md" +fi +echo PR12_RUN17_DONE diff --git a/rsm_rise/scripts/real/_tmp/pr12_run18.sh b/rsm_rise/scripts/real/_tmp/pr12_run18.sh new file mode 100644 index 0000000000000000000000000000000000000000..c7284df43781c3e3fe25997a6ada3328745d766d --- /dev/null +++ b/rsm_rise/scripts/real/_tmp/pr12_run18.sh @@ -0,0 +1,33 @@ +#!/usr/bin/env bash +set -euo pipefail +ROOT=/proj/dmfexp/zwhong/rsm_rise +WT=/proj/dmfexp/zwhong/scratch_pi05_200k/rsm_real +bash $ROOT/scripts/real/pi05_ft50_pr12.sh +cd $WT +git --no-pager status --short +if ! git diff --quiet; then + git add rise_stack/CHECKPOINTS.md + git commit -m "CHECKPOINTS: refresh the comparable table at 100-105k; fit the init-advantage decay on the paired gap + +All eight cells now have their 100 000 keep and the 8-cell planning screen at that +step is running (LSF 1917097/1917098). Table refreshed at 100-105k: four of the five +RISE actors improved their recovered fraction since 89-93k while both BC cells were +flat, the sign the slope fit predicts. + +The decay of the warm start's advantage over the from-base control was previously +derived by differencing two independently fitted lines, one per run -- which inflates +the uncertainty and can manufacture a slope difference neither curve supports. +ft50_initgap_decay.py instead interpolates the control onto the warm cell's eval steps +and fits the PAIRED gap as one series. The conclusion survives: the rate changes +significantly on both metrics (t_diff -3.8 / -4.7), so the whole-plateau line is the +misspecified one, and the late-half rate projects the gap to 0.078 cm (chunk10) / +0.035 cm (chunk50) at 200k from 0.194 / 0.156 cm now. Warm start still wins at 200k, +by a margin 2-4x smaller than today's; the gap is not a stable number. + +Co-Authored-By: Claude Opus 5 " + git push origin HEAD + git --no-pager log --oneline -1 +else + echo "NO CHANGE to CHECKPOINTS.md" +fi +echo PR12_RUN18_DONE diff --git a/rsm_rise/scripts/real/_tmp/pr12_run19.sh b/rsm_rise/scripts/real/_tmp/pr12_run19.sh new file mode 100644 index 0000000000000000000000000000000000000000..ce655f7865383ddb5836fd6b3989c6cfe9c8f412 --- /dev/null +++ b/rsm_rise/scripts/real/_tmp/pr12_run19.sh @@ -0,0 +1,42 @@ +#!/usr/bin/env bash +set -euo pipefail +ROOT=/proj/dmfexp/zwhong/rsm_rise +WT=/proj/dmfexp/zwhong/scratch_pi05_200k/rsm_real +bash $ROOT/scripts/real/pi05_ft50_pr12.sh +cd $WT +git --no-pager status --short +if ! git diff --quiet; then + git add rise_stack/CHECKPOINTS.md + git commit -m "CHECKPOINTS: no selection rule beats greedy -- episode-clustered, family-wise, and now bounded + +The offline selection-rule sweep judged a rule a winner on the raw sign of +(rule - greedy). At 50k that read 'beats greedy' in 6 of 8 cells, on margins of +0.004-0.010 cm, picked as the minimum over ~7 correlated rules, with no uncertainty +attached -- a winner's curse rather than a result. + +ft50_rule_significance.py adds the three missing pieces: the episode as the unit of +analysis (a cell's 705 decisions are 25 episodes, and decisions inside an episode share +a scene and the actor's error state), a paired standard error, and a family-wise +sign-flip permutation taking min-t over the whole rule family per draw. The +decision-to-episode map is not stored in scores.npz; it is reconstructed from the +per_episode prefix sums and proven by reproducing each episode's own greedy / oracle / +rsm mean to 3e-8 cm in every cell, aborting rather than falling back. + +Result: 0 of 8 cells have a deployable rule that beats greedy family-wise (best +per-cell p = 0.12), and pooled over all eight the best rule is -0.020 +- 0.014 cm at +p = 0.25. argmin|z| -- the rule the extremity mechanism predicts should work -- is +negative in all 8 cells, but those are eight readings of the same 25 episodes, not +eight independent replications. The deployed argmax is confirmed as the wrong rule: ++0.122 +- 0.022 cm worse than greedy pooled, t = +5.5, worse in 8 of 8 cells at t > +2. + +The by-product is a bound: 95% CI on the best rule [-0.048, +0.007] cm, under 7% of +each cell's greedy-to-oracle headroom. Nothing is left to fix in the selection step; +the critic has to be retrained at the matched horizon. + +Co-Authored-By: Claude Opus 5 " + git push origin HEAD 2>&1 | tail -3 + git --no-pager log --oneline -1 +else + echo "NO CHANGE to CHECKPOINTS.md" +fi +echo PR12_RUN19_DONE diff --git a/rsm_rise/scripts/real/absorption_probe.py b/rsm_rise/scripts/real/absorption_probe.py new file mode 100644 index 0000000000000000000000000000000000000000..e929b10b235ce993e30b1e2b75d7ee8561d1af09 --- /dev/null +++ b/rsm_rise/scripts/real/absorption_probe.py @@ -0,0 +1,191 @@ +#!/usr/bin/env python +"""WHERE DOES THE LOW-BETA GAIN COME FROM? A per-anchor mechanism probe (ACT_COND run 16, #278). + +Run 15 measured the R_M beta ladder RISING then SATURATING: vs logit@0.99 the rank-pct gain is ++0.0022 at 0.92, +0.0050 at 0.90, +0.0055 at 0.87 -- while the realized chain length keeps growing +(85 -> 109 -> 147 hops). The hypothesis offered there was ABSORPTION: at ~100 frames per successor +hop a chain that already runs past the end of the episode sees nothing new when it runs further. +That was flagged as a hypothesis, and this is the cheapest test of it that needs NO new GPU compute +-- it reads the per-anchor rows already cached in the snr JSONs. + +THE PREDICTION THAT SEPARATES THE READINGS. Split anchors by how long their chain ALREADY was at +the reference beta 0.99 (`chain_hops_mean`, the realized walk): + * ABSORPTION -> the anchors that were already long have nothing to gain from a longer chain, so + the gain concentrates in the SHORT-chain tercile and is ~0 in the LONG-chain tercile. + * UNIFORM EXTRAPOLATION DRIFT -> leaving the trained support perturbs every anchor's field alike, + so the gain is flat across terciles. + +THE CONFOUND THIS PROBE MUST NOT FALL FOR. rank_pct is bounded at 1.0 and the reference already +sits at 0.988, so any anchor that is near the ceiling cannot gain and an anchor that is low has room: +a split on chain length will reproduce a ceiling effect if chain length happens to correlate with +the reference rank_pct. So the SAME split is also run on the reference rank_pct itself, and the two +are reported side by side. If the ceiling split explains as much as the chain-length split, this +probe says nothing about absorption and the printout says so. + +All comparisons are the noise-matched logit-vs-logit ones (every logit cell sits at rep spearman +0.998-0.999), and every cell is checked anchor-by-anchor on (ep,t,stage) before anything is paired. +""" +import json, os, glob, argparse +import numpy as np +from scipy.stats import spearmanr + +D = "/proj/dmfexp/zwhong/rsm_rise/status/real/ACT_COND/snr" +OUT = "/proj/dmfexp/zwhong/rsm_rise/status/real/ACT_COND/ABSORPTION.json" +REF = "snr_beta99.json" +READ = "logit" +STATS = [("rank_pct", +1), ("spearman", -1)] + + +def akey(r): + return (int(r["ep"]), int(r["t"]), str(r.get("stage"))) + + +def boot_ci(d, n=20000, seed=0): + rng = np.random.default_rng(seed) + d = np.asarray(d, float) + return tuple(float(x) for x in np.percentile(d[rng.integers(0, len(d), (n, len(d)))].mean(1), + [2.5, 97.5])) + + +def terciles(v): + q = np.quantile(v, [1 / 3, 2 / 3]) + return np.digitize(v, q) # 0 = low, 1 = mid, 2 = high + + +def main(): + global READ, OUT + ap = argparse.ArgumentParser() + ap.add_argument("--read", default=READ, choices=["logit", "prob"], + help="read-out the whole probe runs under; the RTM-matched contrast is " + "read-out specific because the two read-outs rank the beta ladder " + "differently (run 17).") + ap.add_argument("--out", default=OUT) + a = ap.parse_args() + READ, OUT = a.read, a.out + print(f"READ-OUT = {READ} OUT = {OUT}") + cells = {} + for p in sorted(glob.glob(f"{D}/snr_beta*.json")): + j = json.load(open(p)) + cells[os.path.basename(p)] = j + ref = cells[REF] + refkeys = [akey(r) for r in ref["rows"]] + for c, j in cells.items(): + if len(j["rows"]) != len(refkeys) or any(akey(r) != k for r, k in zip(j["rows"], refkeys)): + raise SystemExit(f"FAIL {c}: anchors do not match {REF}; NOT pairable.") + print(f"ANCHOR IDENTITY: {len(cells)} cells x {len(refkeys)} anchors match {REF} EXACTLY.") + + hops = np.array([r["chain_hops_mean"] for r in ref["rows"]], float) + base = {s: np.array([r[f"{s}_{READ}"] for r in ref["rows"]], float) for s, _ in STATS} + stage = np.array([str(r.get("stage")) for r in ref["rows"]]) + print(f"\nreference {READ}@0.99: realized hops per anchor min {hops.min():.1f} " + f"median {np.median(hops):.1f} max {hops.max():.1f} " + f"IQR {np.subtract(*np.percentile(hops,[75,25])):.2f}") + + splits = {"chain hops @0.99": terciles(hops), + "rank_pct @0.99 (CEILING control)": terciles(base["rank_pct"])} + # how much do the two splits overlap? If they are nearly the same partition the probe is blind. + ag = float((splits["chain hops @0.99"] == splits["rank_pct @0.99 (CEILING control)"]).mean()) + rho_hb = float(spearmanr(hops, base["rank_pct"]).statistic) + print(f"the two splits assign the same tercile to {ag:.1%} of anchors (chance 1/3); " + f"spearman(hops, ref rank_pct) = {rho_hb:+.3f}") + print("per-tercile REFERENCE levels (so a ceiling effect is visible directly):") + for nm, g in splits.items(): + for t, lab in enumerate(("low ", "mid ", "high")): + m = g == t + print(f" {nm:<34} {lab} n={m.sum():3d} hops={hops[m].mean():7.1f} " + f"ref rank_pct={base['rank_pct'][m].mean():.4f} " + f"ref rho={base['spearman'][m].mean():+.3f} " + f"stages=" + ",".join(f"{s}:{int((stage[m]==s).sum())}" + for s in sorted(set(stage)))) + + out = {"n": len(refkeys), "ref": REF, "read": READ, "split_agreement": ag, + "spearman_hops_vs_ref_rank": rho_hb, "rows": []} + order = sorted((c for c in cells if c != REF), + key=lambda c: -float("0." + c.replace("snr_beta", "").replace(".json", ""))) + for stem, sign in STATS: + hdr = (f"\n{stem} gain vs {READ}@0.99 (sign {'higher' if sign>0 else 'lower'}=better), " + f"by tercile\n{'cell':<10} {'split':<34} {'low':>18} {'mid':>18} {'high':>18} " + f"{'rho(gain,split var)':>21}") + print(hdr); print("-" * 124) + for c in order: + y = np.array([r[f"{stem}_{READ}"] for r in cells[c]["rows"]], float) + gain = y - base[stem] + for nm, g in splits.items(): + cellstr = [] + rec = {"cell": c, "stat": stem, "split": nm, "overall": float(gain.mean()), + "tercile": []} + for t in range(3): + m = g == t + lo, hi = boot_ci(gain[m]) + cellstr.append(f"{gain[m].mean():+.4f}[{lo:+.4f},{hi:+.4f}]") + rec["tercile"].append({"t": t, "n": int(m.sum()), "mean": float(gain[m].mean()), + "lo": lo, "hi": hi}) + sv = hops if nm.startswith("chain") else base["rank_pct"] + r = float(spearmanr(sv, gain).statistic) + rec["spearman_gain_vs_split_var"] = r + print(f"{c.replace('snr_beta','0.').replace('.json',''):<10} {nm:<34} " + + " ".join(f"{s:>18}" for s in cellstr) + f" {r:>21.3f}") + out["rows"].append(rec) + + # ---- POWER of the chain-hops split, stated before any of its rows is read ---- + th = [hops[splits["chain hops @0.99"] == t].mean() for t in range(3)] + spread = max(th) - min(th) + powered = spread > 0.10 * float(np.median(hops)) + print(f"\nPOWER OF THE CHAIN-HOPS SPLIT: tercile means {th[0]:.2f} / {th[1]:.2f} / {th[2]:.2f} " + f"hops, spread {spread:.2f} = {100*spread/np.median(hops):.1f}% of the median.\n" + + (" -> POWERED: the terciles are genuinely different chain lengths." + if powered else + " -> UNDERPOWERED: E[hops] is set by BETA, not by the anchor -- the three terciles are\n" + " the same chain length to within a few percent, so this split cannot test absorption\n" + " at all. Its rows below are reported for completeness and carry NO verdict. Testing\n" + " absorption needs a probe that varies the horizon WITHIN an anchor (i.e. the beta\n" + " ladder itself), not a split across anchors.")) + + # ---- RTM-MATCHED CONTRAST ---- + # Terciles are cut on the REFERENCE cell's own rank_pct, which is measured with particle noise, + # so selection alone drives the low tercile up and the high tercile down in EVERY other cell -- + # regression to the mean, visible above in cells that are an overall TIE (0.95 low +0.0098, high + # -0.0029). Contrasting each cell against a BASELINE CELL rather than against the reference + # cancels that: both cells were selected by the same noisy variable and both sit at the same + # noise level (rep spearman 0.999 across the logit ladder), so the shared selection effect + # subtracts out and what remains is the effect of BETA. + BASE = "snr_beta95.json" # the last cell measured as an overall TIE vs logit@0.99 + if BASE in cells: + gsplit = splits["rank_pct @0.99 (CEILING control)"] + for stem, sign in STATS: + b = np.array([r[f"{stem}_{READ}"] for r in cells[BASE]["rows"]], float) + print(f"\nRTM-MATCHED: {stem} vs the BASELINE CELL {BASE.replace('snr_beta','0.').replace('.json','')} " + f"(not vs the reference), by tercile of ref rank_pct\n" + f"{'cell':<10} {'low (n=%d)' % int((gsplit==0).sum()):>20} " + f"{'mid (n=%d)' % int((gsplit==1).sum()):>20} " + f"{'high (n=%d)' % int((gsplit==2).sum()):>20} {'overall':>20}") + print("-" * 94) + for c in order: + if c == BASE: + continue + y = np.array([r[f"{stem}_{READ}"] for r in cells[c]["rows"]], float) + d = y - b + cs, rec = [], {"cell": c, "stat": stem, "vs": BASE, "tercile": []} + for t in list(range(3)) + [None]: + m = np.ones(len(d), bool) if t is None else (gsplit == t) + lo, hi = boot_ci(d[m]) + cs.append(f"{d[m].mean():+.4f}[{lo:+.4f},{hi:+.4f}]") + rec["tercile"].append({"t": t, "n": int(m.sum()), "mean": float(d[m].mean()), + "lo": lo, "hi": hi}) + print(f"{c.replace('snr_beta','0.').replace('.json',''):<10} " + + " ".join(f"{x:>20}" for x in cs)) + out.setdefault("rtm", []).append(rec) + out["rtm_baseline"] = BASE + out["hops_split_powered"] = bool(powered) + out["hops_tercile_means"] = [float(x) for x in th] + + print("\nREADING. ABSORPTION predicts the gain sits in the LOW-hops tercile and vanishes in the\n" + "HIGH-hops tercile. A CEILING effect predicts the same shape under the rank_pct split and\n" + "is the null this probe has to beat: compare the two split rows of the same cell. If both\n" + "splits separate the gain equally, the chain-length story is not established by this probe.") + json.dump(out, open(OUT, "w"), indent=1) + print(f"\nwrote {OUT}") + + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/real/act_json_regress.py b/rsm_rise/scripts/real/act_json_regress.py new file mode 100644 index 0000000000000000000000000000000000000000..988cb175aa4df95afbeeed8dd5e2810094293694 --- /dev/null +++ b/rsm_rise/scripts/real/act_json_regress.py @@ -0,0 +1,52 @@ +"""Diff two JSON result files field-by-field and exit 5 on any difference. + +ACT_COND (gen_q#278) house rule: a script may only be re-parameterised if the OLD invocation still +produces bit-identical output. This is that check, factored out so every run can use it. +Usage: act_json_regress.py --ref A.json --new B.json [--key summary] [--tol 0.0] +""" +import argparse, json, sys + + +def flat(o, pre=""): + out = {} + if isinstance(o, dict): + for k, v in o.items(): + out.update(flat(v, f"{pre}.{k}" if pre else str(k))) + elif isinstance(o, list): + for i, v in enumerate(o): + out.update(flat(v, f"{pre}[{i}]")) + elif isinstance(o, (int, float)) and not isinstance(o, bool): + out[pre] = float(o) + return out + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--ref", required=True) + ap.add_argument("--new", required=True) + ap.add_argument("--key", default=None, help="compare only this top-level key") + ap.add_argument("--tol", type=float, default=0.0, help="max allowed relative difference") + a = ap.parse_args() + ra, rb = json.load(open(a.ref)), json.load(open(a.new)) + if a.key: + ra, rb = ra[a.key], rb[a.key] + fa, fb = flat(ra), flat(rb) + bad, worst = [], 0.0 + for k, v in fa.items(): + if k not in fb: + bad.append(f"{k}: MISSING in new"); continue + d = abs(v - fb[k]) / max(abs(v), 1e-12) + worst = max(worst, d) + if d > a.tol: + bad.append(f"{k}: ref={v!r} new={fb[k]!r} rel={d:.3e}") + print(f"{len(fa)} fields compared (key={a.key}) worst rel {worst:.2e}") + if bad: + print(f"*** {len(bad)} MISMATCHES ***") + for b in bad[:12]: + print(" " + b) + sys.exit(5) + print("IDENTICAL") + + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/real/act_mcpredict.py b/rsm_rise/scripts/real/act_mcpredict.py new file mode 100644 index 0000000000000000000000000000000000000000..18add7c0969ec0c73beb7d5cf6d3c03e1ced2490 --- /dev/null +++ b/rsm_rise/scripts/real/act_mcpredict.py @@ -0,0 +1,286 @@ +#!/usr/bin/env python3 +"""ACT_COND run 30 (gen_q#278) -- IS THE MC INSTABILITY PREDICTABLE FROM A SINGLE DRAW? + +Run 29 measured that at the DEPLOYED cell (twin_rollout: particles=16, score_kind="prob") two +independent particle draws of the SAME 128-candidate cloud at the SAME state pick a DIFFERENT +argmax on 43.2% of anchors -- nearly twice as often as switching the read-out (23.5%, run 28). +Run 29's job 1892860 asks whether spending MORE particles fixes it. This script asks the +orthogonal and much cheaper question: + + does the scorer ALREADY KNOW, from the single draw it has in hand, that this particular + anchor's argmax is unstable? + +If it does, the fix is not a uniform particle budget but an ADAPTIVE one: spend the big budget on +the flagged minority and the deployed budget everywhere else. If it does not, instability is +unpredictable at runtime and only a uniform budget (or a tie-break) can help. + +OUTCOME (per anchor): unstable := top1_agree_prob < 1.0, i.e. at least one of the R-choose-2 draw +pairs picked a different argmax. + +PREDICTORS, IN TWO TIERS. The tier is the whole point and is pre-registered here: + TIER 1 -- computed from REPEAT 0 ONLY (act_sensitivity.py:238-254: q/ql = q_rep[0]). A closed-loop + scorer has exactly these in hand after its single draw, at zero extra cost. These are the only + ones that can become a runtime rule. + TIER 2 -- computed from the REPEAT STACK (act_sensitivity.py:287-301), the same stack that defines + the outcome. CIRCULAR BY CONSTRUCTION: snr/noise_var/rep_spearman and top1_agree are two + functionals of one set of draws. Reported for completeness and labelled NOT EVIDENCE; a high + AUC there says nothing about runtime predictability. + +HONEST LIMIT, stated up front: the tier-1 predictors come from draw 0, which is also one of the +draws entering the outcome. That is not circular in a way that manufactures signal (a wide +candidate cloud does not mechanically cause argmax disagreement ACROSS draws), but it is not clean +either. The clean version -- predictor from draw 0, outcome from draws 1..R-1 only -- needs the +per-draw argmax indices `top1_idx_prob`, which run 29's patch stores and which therefore exist in +the mcstab cells (job 1892860) but NOT in these run-27 xpick cells. When those land, rerun with +--strict-holdout; it costs no GPU. Until then every number here carries that caveat. + +DISCOVERY / HELD-OUT SPLIT: mrise is the DEPLOYED checkpoint and is the discovery cell. The +direction (sign of AUC-0.5) and the chosen predictor are fixed on it; mnt/xlrise/xlnt then confirm +or refute with the rule frozen. A predictor that flips sign across cells is reported as such. + +FAILS LOUD: rc=4 a cell file is missing (a partial read must not look like a result); rc=5 a +self-test fails (planted-perfect predictor must give AUC 1.0, a shuffled one must cover 0.5). +""" +import argparse, json, os, sys +import numpy as np + +TIER1 = ["margin12_rel_prob", "margin12_rel_logit", "margin12_prob", "margin12_logit", + "cv_prob", "tie_frac_prob", "var_a_prob", "asi_prob", "q0", + "cv_logit", "var_a_logit", "logit0", "stage"] +TIER2 = ["snr_prob", "snr_robust_prob", "noise_var_prob", "sig_var_prob", "rep_spearman_prob"] + + +def auc(y, x): + """Mann-Whitney AUC of predictor x for binary y, midrank tie handling. 0.5 = no information.""" + y = np.asarray(y, float); x = np.asarray(x, float) + m = np.isfinite(x) & np.isfinite(y) + y, x = y[m], x[m] + n1, n0 = float((y == 1).sum()), float((y == 0).sum()) + if n1 == 0 or n0 == 0: + return float("nan") + order = np.argsort(x, kind="mergesort") + xs = x[order] + ranks = np.empty(len(x), float) + i = 0 + while i < len(xs): # midranks for ties + j = i + while j + 1 < len(xs) and xs[j + 1] == xs[i]: + j += 1 + ranks[order[i:j + 1]] = 0.5 * (i + j) + 1.0 + i = j + 1 + return float((ranks[y == 1].sum() - n1 * (n1 + 1) / 2.0) / (n1 * n0)) + + +def boot_auc(y, x, n=10000, seed=0): + rng = np.random.default_rng(seed) + y = np.asarray(y, float); x = np.asarray(x, float) + n_a = len(y) + out = np.empty(n) + for b in range(n): + idx = rng.integers(0, n_a, n_a) + out[b] = auc(y[idx], x[idx]) + out = out[np.isfinite(out)] + return float(np.percentile(out, 2.5)), float(np.percentile(out, 97.5)) + + +def perm_p(y, x, n=10000, seed=1): + """Two-sided permutation p for |AUC-0.5| under label exchangeability.""" + rng = np.random.default_rng(seed) + obs = abs(auc(y, x) - 0.5) + y = np.asarray(y, float).copy() + hits = 0 + for _ in range(n): + rng.shuffle(y) + if abs(auc(y, x) - 0.5) >= obs - 1e-12: + hits += 1 + return (hits + 1) / (n + 1) + + +def load_cell(path): + if not os.path.exists(path): + print(f"*** MISSING CELL {path} -- refusing to report a partial read", file=sys.stderr) + sys.exit(4) + return json.load(open(path))["rows"] + + +def col(rows, k): + return np.array([r.get(k, np.nan) for r in rows], float) + + +def outcome(rows, key="top1_agree_prob"): + a = col(rows, key) + if not np.all(np.isfinite(a)): + print(f"*** {key} missing/non-finite on {int((~np.isfinite(a)).sum())} rows", file=sys.stderr) + sys.exit(5) + return (a < 1.0).astype(float), a + + +def selftest(): + rng = np.random.default_rng(7) + y = (rng.random(200) < 0.58).astype(float) + ok = True + a_perfect = auc(y, y + 1e-9 * rng.random(200)) + if not (a_perfect > 0.999): + print(f"*** SELFTEST planted-perfect predictor AUC={a_perfect:.4f} != 1.0"); ok = False + x = rng.normal(size=200) + lo, hi = boot_auc(y, x, n=2000, seed=3) + a_null = auc(y, x) + if not (lo <= 0.5 <= hi): + print(f"*** SELFTEST shuffled predictor CI [{lo:.3f},{hi:.3f}] excludes 0.5"); ok = False + a_const = auc(y, np.zeros(200)) + if abs(a_const - 0.5) > 1e-9: + print(f"*** SELFTEST constant predictor AUC={a_const:.6f} != 0.5"); ok = False + a_flip = auc(y, -(y + 1e-9 * rng.random(200))) + if not (a_flip < 0.001): + print(f"*** SELFTEST sign convention broken, inverted AUC={a_flip:.4f} != 0.0"); ok = False + print(f"[selftest] perfect={a_perfect:.4f} inverted={a_flip:.4f} constant={a_const:.4f} " + f"shuffled={a_null:.3f} CI[{lo:.3f},{hi:.3f}] -> {'PASS' if ok else 'FAIL'}") + if not ok: + sys.exit(5) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--xpick-dir", default="status/real/ACT_COND/xpick") + ap.add_argument("--file-tmpl", default="xpick_{c}.json") + ap.add_argument("--cells", default="mrise,mnt,xlrise,xlnt") + ap.add_argument("--discovery", default="mrise") + ap.add_argument("--flag-frac", type=float, default=0.30) + ap.add_argument("--boot", type=int, default=10000) + ap.add_argument("--perm", type=int, default=10000) + ap.add_argument("--strict-holdout", action="store_true", + help="outcome from draws 1..R-1 only (needs top1_idx_prob; mcstab cells)") + ap.add_argument("--out", default="status/real/ACT_COND/MCPREDICT_run30.json") + a = ap.parse_args() + + selftest() + cells = a.cells.split(",") + data = {} + for c in cells: + rows = load_cell(os.path.join(a.xpick_dir, a.file_tmpl.format(c=c))) + if a.strict_holdout: + idx = [r.get("top1_idx_prob") for r in rows] + if any(not isinstance(v, list) or len(v) < 3 for v in idx): + print("*** --strict-holdout needs top1_idx_prob with >=3 draws per row; " + "the run-27 xpick cells predate that field (run 29 patch).", file=sys.stderr) + sys.exit(5) + y = np.array([float(len(set(v[1:])) > 1) for v in idx]) + raw = np.array([float(np.mean([v[i] == v[j] for i in range(1, len(v)) + for j in range(i + 1, len(v))])) for v in idx]) + else: + y, raw = outcome(rows) + data[c] = (rows, y, raw) + + res = {"args": vars(a), "cells": {}, "note_tier2": "CIRCULAR BY CONSTRUCTION -- not evidence", + "strict_holdout": bool(a.strict_holdout)} + + print(f"\n{'='*104}\nOUTCOME: unstable := argmax differs on at least one draw pair" + f"{' (draws 1.. only, draw 0 held out)' if a.strict_holdout else ''}\n{'='*104}") + for c in cells: + rows, y, raw = data[c] + print(f" {c:<8} n={len(y):<5} unstable={y.mean():.3f} mean top1_agree={raw.mean():.3f}") + res["cells"][c] = {"n": int(len(y)), "unstable_frac": float(y.mean()), + "top1_agree_mean": float(raw.mean()), "auc": {}} + + disc = a.discovery + for tier, names in (("TIER 1 -- SINGLE DRAW, runtime-available at zero cost", TIER1), + ("TIER 2 -- repeat-derived, CIRCULAR, NOT EVIDENCE", TIER2)): + print(f"\n{'-'*104}\n{tier}\n{'-'*104}") + print(f" {'predictor':<18}" + "".join(f"{c:>22}" for c in cells) + " sign-consistent") + for k in names: + line, aucs = f" {k:<20}", {} + for c in cells: + rows, y, raw = data[c] + x = col(rows, k) + fin = x[np.isfinite(x)] + if len(fin) == 0: + line += f"{'absent':>22}"; aucs[c] = None; continue + if len(np.unique(fin)) < 2: + line += f"{'DEGEN(const)':>22}" + aucs[c] = {"auc": 0.5, "ci": [0.5, 0.5], "degenerate": True, + "const_value": float(fin[0])} + continue + v = auc(y, x) + lo, hi = boot_auc(y, x, n=a.boot, seed=11) + sig = not (lo <= 0.5 <= hi) + aucs[c] = {"auc": v, "ci": [lo, hi], "significant": bool(sig)} + if c == disc: + aucs[c]["perm_p"] = perm_p(y, x, n=a.perm, seed=12) + line += f"{v:>8.3f} [{lo:.3f},{hi:.3f}]{'*' if sig else ' '}" + # A point estimate on the far side of 0.5 with a CI covering it is UNINFORMATIVE, not + # reversed. Consistency is therefore judged over the cells where the predictor is + # SIGNIFICANT; "flips" is reserved for two significant cells disagreeing in sign. + sigc = [c for c in cells if aucs[c] and aucs[c].get("significant")] + sg = {np.sign(aucs[c]["auc"] - 0.5) for c in sigc} + flips = len(sg) > 1 + verdict = ("FLIPS" if flips else + f"sig on {len(sigc)}/{len(cells)}" if sigc else "no signal anywhere") + line += f" {verdict}" + print(line) + for c in cells: + if aucs[c]: + res["cells"][c]["auc"][k] = aucs[c] + res.setdefault("consistency", {})[k] = { + "significant_cells": sigc, "flips": bool(flips), "verdict": verdict} + + # ---- decision utility, rule FROZEN on the discovery cell then applied verbatim elsewhere ---- + rows_d, y_d, _ = data[disc] + best, best_gap = None, 0.0 + for k in TIER1: + e = res["cells"][disc]["auc"].get(k) + if not e or e.get("degenerate") or not e.get("significant"): + continue + if res["consistency"][k]["flips"]: + continue + g = abs(e["auc"] - 0.5) + if g > best_gap: + best, best_gap = k, g + if best is None: + print("\n*** no tier-1 predictor is significant on the discovery cell -- " + "MC instability is NOT predictable from a single draw; no rule to freeze.") + os.makedirs(os.path.dirname(a.out), exist_ok=True) + json.dump(res, open(a.out, "w"), indent=1) + print(f"wrote {a.out}") + return + direction = np.sign(auc(y_d, col(rows_d, best)) - 0.5) # +1: HIGH value => unstable + thr = np.nanpercentile(col(rows_d, best), + (1 - a.flag_frac) * 100 if direction > 0 else a.flag_frac * 100) + print(f"\n{'-'*104}\nDECISION UTILITY. Rule frozen on the DISCOVERY cell '{disc}': flag when " + f"{best} {'>=' if direction > 0 else '<='} {thr:.6g}\n" + f"(threshold = the {a.flag_frac*100:.0f}% of discovery anchors most likely unstable; " + f"applied VERBATIM to the other cells)\n{'-'*104}") + print(f" {'cell':<9}{'flagged':>9}{'recall':>9}{'chance':>9}{'lift':>8}" + f"{'precision':>11}{'base':>8}{'refit-lift':>10} unstable captured") + res["rule"] = {"predictor": best, "direction": int(direction), "threshold": float(thr), + "flag_frac_target": a.flag_frac, "frozen_on": disc, "cells": {}} + for c in cells: + rows, y, _ = data[c] + x = col(rows, best) + fl = (x >= thr) if direction > 0 else (x <= thr) + fl = fl & np.isfinite(x) + ff = float(fl.mean()) + rec = float(y[fl].sum() / max(y.sum(), 1)) + prec = float(y[fl].mean()) if fl.sum() else float("nan") + # REFIT: same predictor, threshold re-taken on THIS cell at the same flag fraction. If the + # frozen rule fails but the refit works, the threshold does not transfer; if both fail, the + # predictor carries no signal on this cell. + thr_c = np.nanpercentile(x, (1 - a.flag_frac) * 100 if direction > 0 else a.flag_frac * 100) + fl_c = ((x >= thr_c) if direction > 0 else (x <= thr_c)) & np.isfinite(x) + rec_c = float(y[fl_c].sum() / max(y.sum(), 1)) + lift_c = rec_c / max(float(fl_c.mean()), 1e-9) + print(f" {c:<9}{ff:>9.3f}{rec:>9.3f}{ff:>9.3f}{rec/max(ff,1e-9):>8.2f}" + f"{prec:>11.3f}{y.mean():>8.3f}{lift_c:>10.2f} {int(y[fl].sum())}/{int(y.sum())}") + res["rule"]["cells"][c] = {"flag_frac": ff, "recall": rec, "precision": prec, + "lift": rec / max(ff, 1e-9), "base_rate": float(y.mean()), + "captured": int(y[fl].sum()), "total_unstable": int(y.sum()), + "refit_lift": lift_c, "refit_recall": rec_c, + "refit_threshold": float(thr_c)} + print("\n lift 1.00 = the flag is no better than flagging that fraction at random.") + + os.makedirs(os.path.dirname(a.out), exist_ok=True) + json.dump(res, open(a.out, "w"), indent=1) + print(f"\nwrote {a.out}") + + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/real/act_mcstab_read.py b/rsm_rise/scripts/real/act_mcstab_read.py new file mode 100644 index 0000000000000000000000000000000000000000..ba103228f1814618ebf2b78a6ecbec64cc2a9184 --- /dev/null +++ b/rsm_rise/scripts/real/act_mcstab_read.py @@ -0,0 +1,239 @@ +"""ACT_COND run 29 (gen_q#278): MONTE-CARLO PICK INSTABILITY vs THE READ-OUT, AND CAN PARTICLES FIX IT? + +Run 28's headline was that swapping the read-out prob->logit moves the executed argmax on 23.5% of +anchors at the deployed cell (5.9 cm of first-step xyz). The SAME cells already carried the control +and nobody had read it: `top1_agree_prob` is the identical quantity with the OTHER factor varied -- +two INDEPENDENT PARTICLE DRAWS under ONE read-out, same cloud, same state -- and at the deployed cell +it is 0.568, i.e. the redraw changes the pick on 43.2% of anchors. MC noise is the LARGER source of +pick change. The deployed scorer is twin_rollout.py particles=16 score_kind=prob, so this is not a +diagnostic regime: it is the shipped configuration. + +This reader consumes the run-29 particle sweep (P = 16 / 32 / 64, two checkpoints, repeats=4) and +answers the only question that follows: IS IT FIXABLE BY SPENDING PARTICLES? + * the P-curve of top1_agree (and of rep_spearman / snr) -- does it climb, and towards what; + * `top1_agree_half`, two DISJOINT 2-draw averages, an effective 2x budget measured inside the P + cell itself. Pre-registered: it should track top1_agree at 2P. Two independent routes to the + same number is the check that the curve is estimator noise and not something else; + * the paired head-to-head at each P: (1 - top1_agree) vs (1 - xpick_agree) on the SAME anchors. + +IT REFUSES TO PRINT NUMBERS OFF A BROKEN PATCH. The run-29 patch is additive and repeat 0 keeps its +historical seed, so every REPEAT-0 field of the P=16 cells must reproduce xpick/xpick_.json +bit-for-bit. Mismatch => rc=5, nothing else is read. Repeat-DERIVED fields are excluded BY NAME and +the exclusion is printed: R goes 3 -> 4, so they legitimately move. Missing cells => rc=4. +""" +import argparse, json, math, os, sys +import numpy as np + +ROOT = "/proj/dmfexp/zwhong/rsm_rise" +# fields computed from the repeat stack; R changed 3 -> 4 so they are NOT part of the regression. +REPEAT_DERIVED = ("snr_", "top1_agree", "top1_idx", "top1_half_idx", "rep_spearman", "noise_var_", + "sig_var_", "margin12_rel_draws_") +# CUMULATIVE ACCUMULATOR fields, excluded BY EXACT NAME (run 31). rsm_scorer.chain_hop_acc is a +# running accumulator that act_sensitivity never resets (act_sensitivity.py:254), so a repeats=4 +# cell averages realized hops over 4/3 as many decisions as a repeats=3 cell. Same law, different +# sample -- these two are not repeat-0 statistics and never were. Pre-documented at +# build_snr_table.py:17, written BEFORE run 29, so this is not a post-hoc excuse. +# DELIBERATELY BY EXACT NAME, not the "chain_" prefix: chain_cap / chain_p_cont / +# chain_E_hops_expected are DETERMINISTIC CONFIG and must stay inside the gate -- a silently +# changed cap is exactly the bug this regression exists to catch. +ACCUMULATOR_FIELDS = ("chain_hops_mean", "chain_capped_frac") + + +def wilson(k, n, z=1.96): + if n <= 0: + return float("nan"), float("nan") + p = k / n + d = 1 + z * z / n + c = p + z * z / (2 * n) + h = z * math.sqrt(p * (1 - p) / n + z * z / (4 * n * n)) + return (c - h) / d, (c + h) / d + + +def boot_ci(d, n=20000, seed=0): + d = np.asarray(d, float) + if len(d) < 2: + return float("nan"), float("nan") + r = np.random.default_rng(seed) + m = d[r.integers(0, len(d), size=(n, len(d)))].mean(1) + return float(np.percentile(m, 2.5)), float(np.percentile(m, 97.5)) + + +def flat(o, pre=""): + out = {} + if isinstance(o, dict): + for k, v in o.items(): + out.update(flat(v, f"{pre}.{k}" if pre else str(k))) + elif isinstance(o, list): + for i, v in enumerate(o): + out.update(flat(v, f"{pre}[{i}]")) + elif isinstance(o, (int, float)) and not isinstance(o, bool): + out[pre] = float(o) + return out + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--dir", default=f"{ROOT}/status/real/ACT_COND/mcstab") + ap.add_argument("--xpick-dir", default=f"{ROOT}/status/real/ACT_COND/xpick") + ap.add_argument("--cells", default="mrise,mnt") + ap.add_argument("--particles", default="16,32,64") + ap.add_argument("--out", default=f"{ROOT}/status/real/ACT_COND/MCSTAB_run29.json") + a = ap.parse_args() + cellnames = [c for c in a.cells.split(",") if c] + PS = [int(x) for x in a.particles.split(",") if x] + + cells, missing = {}, [] + for c in cellnames: + for P in PS: + p = f"{a.dir}/mc_{c}_p{P}.json" + if not os.path.exists(p): + missing.append(p) + else: + cells[(c, P)] = json.load(open(p)) + if missing: + print("MISSING CELLS -- a partial job is not a result:") + [print(" " + m) for m in missing] + sys.exit(4) + + # ------------------------------------------------------------------ REGRESSION (rc=5 on fail) + print("=" * 104) + print("REGRESSION: the run-29 patch is ADDITIVE and repeat 0 keeps its seed, so every REPEAT-0") + print("field of the P=16 cells must reproduce the run-27 xpick cell bit-for-bit.") + print("EXCLUDED BY NAME (repeat-derived, R 3 -> 4): " + ", ".join(REPEAT_DERIVED)) + print("=" * 104) + Pbase = min(PS) + nbad = 0 + for c in cellnames: + ref_p = f"{a.xpick_dir}/xpick_{c}.json" + if not os.path.exists(ref_p): + print(f" {c}: no reference {ref_p} -- SKIPPED (cannot regress)") + continue + ref = json.load(open(ref_p))["rows"] + new = cells[(c, Pbase)]["rows"] + if len(ref) != len(new): + print(f"*** {c}: {len(ref)} ref rows vs {len(new)} new rows"); nbad += 1; continue + nf, worst, bad, tally, acc = 0, 0.0, [], {}, {} + for i, (r0, r1) in enumerate(zip(ref, new)): + fa, fb = flat(r0), flat(r1) + for k, v in fa.items(): + if any(k.startswith(x) or f".{x}" in k for x in REPEAT_DERIVED): + continue + base = k.split(".")[-1] + if base in ACCUMULATOR_FIELDS: + if k in fb: + acc.setdefault(base, ([], []))[0].append(v) + acc[base][1].append(fb[k]) + continue + if k not in fb: + bad.append(f"({i}).{k}: MISSING in new") + tally[k + " MISSING"] = tally.get(k + " MISSING", 0) + 1 + continue + nf += 1 + d = abs(v - fb[k]) / max(abs(v), 1e-12) + worst = max(worst, d) + if d > 0: + bad.append(f"({i}).{k}: ref={v!r} new={fb[k]!r}") + tally[k] = tally.get(k, 0) + 1 + # The excluded accumulators are PRINTED, not hidden: an exclusion the reader cannot see is + # indistinguishable from a gate that was quietly turned off. Means only -- they are a + # different SAMPLE of the same geometric hop law, so equality is not expected and a large + # shift in the MEAN would still be worth chasing. + for base, (rv, nv) in sorted(acc.items()): + print(f" {c} [SAMPLING-ONLY, excluded] {base}: ref mean {np.mean(rv):.4f} " + f"new mean {np.mean(nv):.4f} (cumulative accumulator, R 3 -> 4; not a repeat-0 stat)") + if bad: + print(f"*** {c}: {len(bad)} MISMATCHES over {len(tally)} FIELD(S) ***") + for k in sorted(tally, key=lambda z: -tally[z]): + print(f" {k}: {tally[k]} row(s)") + [print(" e.g. " + b) for b in bad[:5]] + nbad += 1 + else: + print(f" {c} P={Pbase}: {nf} fields worst rel {worst:.2e} IDENTICAL") + if nbad: + print("\nThe additive patch moved a pre-existing field. The run-29 numbers must not be read " + "until this is explained.") + sys.exit(5) + + # ------------------------------------------------------------------ THE PARTICLE CURVE + res = {} + print("\n" + "=" * 104) + print("PICK REPRODUCIBILITY vs PARTICLE BUDGET. top1_agree = P(two independent particle draws of") + print("the SAME 128-candidate cloud at the SAME state pick the SAME action). Deployed = P16/prob.") + print("=" * 104) + print(f"{'cell':<8}{'P':>5}{'read':>7}{'n':>5}{'top1_agree':>12}{'Wilson95':>20}" + f"{'half(2x)':>10}{'rep_rho':>9}{'snr':>10}{'xpick_agree':>13}") + print("-" * 104) + for c in cellnames: + for P in PS: + rows = cells[(c, P)]["rows"] + n = len(rows) + xa = float(np.mean([r["xpick_agree"] for r in rows])) + for kind in ("prob", "logit"): + t = np.array([r[f"top1_agree_{kind}"] for r in rows]) + h = np.array([r[f"top1_agree_half_{kind}"] for r in rows]) + rr = float(np.mean([r[f"rep_spearman_{kind}"] for r in rows])) + sn = float(np.mean([r[f"sig_var_{kind}"] for r in rows]) / + max(np.mean([r[f"noise_var_{kind}"] for r in rows]), 1e-30)) + # top1_agree is a mean over pairs per anchor; the Wilson interval is taken on the + # effective pair count (n anchors x pairs) -- it is an agreement RATE over pairs. + npair = n * 6 # R=4 -> 6 ordered-unordered pairs per anchor + lo, hi = wilson(t.mean() * npair, npair) + print(f"{c:<8}{P:>5}{kind:>7}{n:>5}{t.mean():>12.3f}{f'[{lo:.3f}, {hi:.3f}]':>20}" + f"{np.nanmean(h):>10.3f}{rr:>9.4f}{sn:>10.3f}{xa:>13.3f}") + res[f"{c}_p{P}_{kind}"] = dict(n=n, top1_agree=float(t.mean()), wilson=[lo, hi], + half=float(np.nanmean(h)), rep_spearman=rr, snr=sn, + xpick_agree=xa) + print("-" * 104) + + # ------------- PRE-REGISTERED CHECK: half(P) should track top1_agree(2P) ------------- + print("\nPRE-REGISTERED: `half` at P averages two draws, an effective 2x budget, so it should") + print("track top1_agree at 2P. Two independent routes to the same number; a large gap means the") + print("curve is not simple estimator noise.") + print(f"{'cell':<8}{'read':>7}{'P':>5}{'half(P)':>10}{'top1(2P)':>10}{'gap':>9}") + print("-" * 104) + for c in cellnames: + for kind in ("prob", "logit"): + for P in PS: + if 2 * P not in PS: + continue + hp = res[f"{c}_p{P}_{kind}"]["half"] + t2 = res[f"{c}_p{2*P}_{kind}"]["top1_agree"] + print(f"{c:<8}{kind:>7}{P:>5}{hp:>10.3f}{t2:>10.3f}{hp-t2:>+9.3f}") + + # ------------- PAIRED HEAD-TO-HEAD: MC redraw vs read-out switch, same anchors ------------- + print("\nPAIRED HEAD-TO-HEAD on the SAME anchors: which factor changes the executed pick more,") + print("redrawing the particles (same read-out) or switching the read-out (same draw)?") + print("d = (1 - top1_agree_prob) - (1 - xpick_agree) > 0 means MC NOISE DOMINATES.") + print(f"{'cell':<8}{'P':>5}{'n':>5}{'MC disagree':>13}{'readout dis':>13}{'d':>9}{'bootCI95':>22}" + f"{'dominant':>10}") + print("-" * 104) + for c in cellnames: + for P in PS: + rows = cells[(c, P)]["rows"] + mc = 1 - np.array([r["top1_agree_prob"] for r in rows]) + ro = 1 - np.array([r["xpick_agree"] for r in rows]) + d = mc - ro + lo, hi = boot_ci(d) + dom = "MC" if lo > 0 else ("read-out" if hi < 0 else "ns") + print(f"{c:<8}{P:>5}{len(rows):>5}{mc.mean():>13.3f}{ro.mean():>13.3f}{d.mean():>+9.3f}" + f"{f'[{lo:+.3f}, {hi:+.3f}]':>22}{dom:>10}") + res[f"{c}_p{P}_prob"].update(mc_disagree=float(mc.mean()), ro_disagree=float(ro.mean()), + d_mc_minus_ro=float(d.mean()), d_ci=[lo, hi], dominant=dom) + + # ------------- per-stage, deployed cell ------------- + print("\nPER-STAGE top1_agree_prob (deployed read-out):") + for c in cellnames: + for P in PS: + rows = cells[(c, P)]["rows"] + by = sorted({r["stage"] for r in rows}) + line = " ".join(f"S{s}: {np.mean([r['top1_agree_prob'] for r in rows if r['stage']==s]):.3f}" + for s in by) + print(f" {c:<8} P={P:<4} {line}") + + os.makedirs(os.path.dirname(a.out) or ".", exist_ok=True) + json.dump(res, open(a.out, "w"), indent=1) + print(f"\nwrote {a.out}") + + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/real/act_pickdist.py b/rsm_rise/scripts/real/act_pickdist.py new file mode 100644 index 0000000000000000000000000000000000000000..aed598aee7fba66ead2ecbc117f88cb61e5b45ad --- /dev/null +++ b/rsm_rise/scripts/real/act_pickdist.py @@ -0,0 +1,356 @@ +"""ACT_COND run 28 (gen_q#278): IS THE READ-OUT'S 23.5% ARGMAX DISAGREEMENT A BEHAVIOUR CHANGE, OR A +RELABELLING AMONG NEAR-DUPLICATE CANDIDATES? + +Run 27 measured the thing runs 25/26 had not: at the DEPLOYED cell the `prob` and `logit` argmaxes over +the 128-candidate cloud disagree on 47/200 anchors (agree 0.765). That kills the "closed-loop no-op" +reading. But an INDEX disagreement is not yet a BEHAVIOUR difference: the cloud is 128 stage-matched +LOGGED chunks, many of which are near-duplicates of each other, so two different indices can be the +same motion to within a millimetre. The quantity that decides whether the eval stream must A/B the +switch is the DISTANCE IN ACTION SPACE between the two picks, measured against the cloud's own spread. + +NO GPU AND NO MODEL. The candidate cloud is built from the hdf5 + a fixed-seed rng stream, and run 27 +stored `xpick_prob_idx` / `xpick_logit_idx` per anchor. So this script REPLAYS the anchor/candidate +construction of act_sensitivity.py exactly (same code path, same rng consumption order: choice(cands) +-> permutation(states) -> probe_target), indexes the two picks, and measures them. It computes nothing +on the network. + +IT REFUSES TO PRINT NUMBERS OFF A MISALIGNED REPLAY. Two gates, both fatal (rc=5): + * every anchor's (ep, t, stage, route) must match the stored row, in order; + * every anchor's `probe_src` must match. probe_src is drawn AFTER the candidate draw, so matching + it on all anchors proves the rng stream was aligned at the moment the candidates were drawn -- + the only thing that could silently corrupt this measurement. + * free internal check: on AGREEING anchors (prob_idx == logit_idx) every distance must be exactly 0. + +Distances are reported three ways, because they answer different questions: + * FIRST-STEP xyz in cm -- the closed loop replans, so step 0 is what actually gets executed; + * whole-chunk L2 in trainer-NORMALISED units (2*(a-lo)/(hi-lo)-1), all 10 coords on one scale; + * GRIPPER at step 0 -- a discrete decision (open vs close); a flip there is the most consequential + single-coordinate difference the switch can make. +Each is normalised by the CLOUD's own spread (mean pairwise distance over the 128 candidates), so +"different index, same motion" and "different index, different motion" are distinguishable. +PLUS the paired quality proxy that needs no model: is the `logit` pick CLOSER to the anchor's own +logged goal-route chunk than the `prob` pick? Bootstrap CI + Wilcoxon over disagreeing anchors. +""" +import argparse, json, os, sys, collections +import numpy as np + +ROOT = "/proj/dmfexp/zwhong/rsm_rise" +GOAL_PATH = "2->3->4" +FAIL_PATHS = ("0->5", "0->2->6") +CELLS = ["mrise", "mnt", "xlrise", "xlnt"] + + +def boot_ci(d, n=20000, seed=0): + d = np.asarray(d, float) + if len(d) < 2: + return float("nan"), float("nan") + r = np.random.default_rng(seed) + m = d[r.integers(0, len(d), size=(n, len(d)))].mean(1) + return float(np.percentile(m, 2.5)), float(np.percentile(m, 97.5)) + + +def wilcoxon(d): + d = np.asarray(d, float); d = d[d != 0] + n = len(d) + if n < 6: + return float("nan") + a = np.abs(d); o = np.argsort(a, kind="mergesort") + rk = np.empty(n, float); rk[o] = np.arange(1, n + 1) + s = np.sort(a); i = 0 + while i < n: + j = i + while j + 1 < n and s[j + 1] == s[i]: + j += 1 + if j > i: + rk[o[i:j + 1]] = np.arange(i + 1, j + 2).mean() + i = j + 1 + W = rk[d > 0].sum() + mu = n * (n + 1) / 4.0 + sd = np.sqrt(n * (n + 1) * (2 * n + 1) / 24.0) + if sd <= 0: + return float("nan") + from math import erfc, sqrt + return float(erfc(abs(W - mu) / sd / sqrt(2.0))) + + +def replay(a): + """Rebuild the anchor list and, per anchor, the 128 candidate chunks -- CPU only, no model.""" + import h5py + split = json.load(open(a.split))["episodes"] + meta = np.load(f"{a.cache}/meta.npz", allow_pickle=True) + ep_from = np.asarray(meta["ep_from"]) + f = h5py.File(a.hdf5, "r"); d = f["data"] + lo = np.array(json.loads(d.attrs["action_min"]), np.float32) + hi = np.array(json.loads(d.attrs["action_max"]), np.float32) + spl = lambda k: split.get(str(int(k.split("_")[1])), {}).get("split", "") + path = lambda k: str(d[k].attrs.get("path", "")) + train = [k for k in d if spl(k) == "train"] + rng = np.random.default_rng(a.seed) + chunk_pool = collections.defaultdict(list) + state_pool = collections.defaultdict(list) + fail_pool = collections.defaultdict(list) + anchors = [] + for k in train: + g = d[k]; ep = int(k.split("_")[1]) + A = np.asarray((g["actions_raw"] if "actions_raw" in g else g["actions"])[()], np.float32) + stg = np.asarray(g["annot"]["edge_from"][()]) + for t in range(0, len(A) - a.horizon, a.stride): + s0 = int(stg[t]); ch = A[t:t + a.horizon] + chunk_pool[s0].append(ch) + state_pool[s0].append(int(ep_from[ep] + t)) + if path(k) in FAIL_PATHS: + fail_pool[s0].append(ch) + if a.anchor_routes == "all" or path(k) == GOAL_PATH: + anchors.append((ep, t, s0, path(k))) + by_stage = collections.defaultdict(list) + for x in anchors: + by_stage[x[2]].append(x) + if len(anchors) > a.max_anchors: + stages = sorted(by_stage) + quota = {s: a.max_anchors // len(stages) for s in stages} + left = a.max_anchors - sum(min(quota[s], len(by_stage[s])) for s in stages) + for s in sorted(stages, key=lambda s: -len(by_stage[s])): + take = min(left, max(0, len(by_stage[s]) - quota[s])) + quota[s] += take; left -= take + picked = [] + for s in stages: + v = by_stage[s]; n = min(quota[s], len(v)) + picked += [v[i] for i in sorted(rng.choice(len(v), size=n, replace=False))] + anchors = sorted(picked, key=lambda x: (x[0], x[1])) + fail_stages = [s for s, v in fail_pool.items() if v] + + def probe_target(s0): + if fail_pool[s0]: + rng.integers(len(fail_pool[s0])); return "failure_same_stage" + if fail_stages: + sp = fail_stages[int(rng.integers(len(fail_stages)))] + rng.integers(len(fail_pool[sp])); return "failure_other_stage" + others = [s for s, v in chunk_pool.items() if s != s0 and v] + sp = others[int(rng.integers(len(others)))] + rng.integers(len(chunk_pool[sp])); return "offstage" + + NC, NS = a.n_cand, a.n_state + out = [] + for (ep, t, s0, route) in anchors: + if len(chunk_pool[s0]) < NC or len(state_pool[s0]) < NS + 1: + continue # consumes no rng -- mirrors the measurer + gi = int(ep_from[ep] + t) + g = d[f"demo_{ep}"] + a0 = np.asarray((g["actions_raw"] if "actions_raw" in g else g["actions"])[t:t + a.horizon], np.float32) + ci = rng.choice(len(chunk_pool[s0]), size=NC, replace=False) + cands = np.stack([chunk_pool[s0][i] for i in ci]) + [j for j in rng.permutation(len(state_pool[s0])) if state_pool[s0][j] != gi][:NS] + psrc = probe_target(s0) + out.append(dict(ep=ep, t=t, stage=s0, route=route, probe_src=psrc, cands=cands, a0=a0)) + f.close() + return out, lo, hi + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--hdf5", default=f"{ROOT}/data/raw/cooking_v5_expert_suboptimal.hdf5") + ap.add_argument("--split", default=f"{ROOT}/data/derived/cooking_v5_split.json") + ap.add_argument("--cache", default=f"{ROOT}/cache/real_cooking_v5") + ap.add_argument("--xpick-dir", default=f"{ROOT}/status/real/ACT_COND/xpick") + ap.add_argument("--horizon", type=int, default=8) + ap.add_argument("--stride", type=int, default=25) + ap.add_argument("--n-cand", type=int, default=128) + ap.add_argument("--n-state", type=int, default=128) + ap.add_argument("--max-anchors", type=int, default=200) + ap.add_argument("--anchor-routes", default="all") + ap.add_argument("--seed", type=int, default=0) + ap.add_argument("--out", required=True) + # ---- run 29 (gen_q#278), ADDITIVE: the same replay answers "how far apart are two picks?" for + # ANY pair of stored index fields, not just prob-vs-logit. Run 29 needs it for the MC pair + # (two independent particle draws under ONE read-out), which run 28's numbers must be compared + # against. Every default below reproduces the run-28 invocation byte-for-byte. + # A field may be "name" (scalar) or "name:i" (i-th element of a stored list). + ap.add_argument("--cells", default=",".join(CELLS)) + ap.add_argument("--file-tmpl", default="xpick_{c}.json") + ap.add_argument("--idx-a", default="xpick_prob_idx") + ap.add_argument("--idx-b", default="xpick_logit_idx") + ap.add_argument("--label-a", default="prob") + ap.add_argument("--label-b", default="logit") + a = ap.parse_args() + CELLS[:] = [c for c in a.cells.split(",") if c] + LA, LB = a.label_a, a.label_b + + def getidx(r, spec): + nm, _, k = spec.partition(":") + v = r.get(nm) + if v is None: + return None + if k != "": + v = v[int(k)] if int(k) < len(v) else None + return v + + cells = {} + missing = [] + for c in CELLS: + p = f"{a.xpick_dir}/{a.file_tmpl.format(c=c)}" + if not os.path.exists(p): + missing.append(p); continue + cells[c] = json.load(open(p)) + if missing: + print("MISSING CELLS -- a partial job is not a result:"); [print(" " + m) for m in missing] + sys.exit(4) + + rep, lo, hi = replay(a) + span = (hi - lo).astype(np.float64) + print(f"[replay] rebuilt {len(rep)} anchors, action span xyz(cm) " + f"{np.round(100*span[:3],2)} gripper span {span[-1]:.3f}", flush=True) + + # ---------------- GATE 1/2: the replay must line up with every stored row ---------------- + fatal = 0 + for c, cd in cells.items(): + rows = cd["rows"] + if len(rows) != len(rep): + print(f"*** {c}: replay has {len(rep)} anchors, cell has {len(rows)}"); fatal += 1; continue + bad = [] + for i, (r, q) in enumerate(zip(rows, rep)): + if (int(r["ep"]), int(r["t"]), int(r["stage"]), str(r["route"])) != \ + (q["ep"], q["t"], q["stage"], q["route"]): + bad.append(f"{i}:anchor {r['ep']},{r['t']} vs {q['ep']},{q['t']}") + elif str(r["probe_src"]) != q["probe_src"]: + bad.append(f"{i}:probe_src {r['probe_src']} vs {q['probe_src']}") + if len(bad) > 5: + break + if bad: + print(f"*** {c}: REPLAY MISALIGNED ({len(bad)}+ mismatches): " + "; ".join(bad)); fatal += 1 + else: + print(f"[gate] {c}: {len(rows)} anchors + probe_src ALIGNED " + f"(rng stream proven aligned at the candidate draw)") + if fatal: + print("\nThe rng replay does not reproduce the measured cells. Every distance below would be " + "computed off the WRONG candidate cloud. Nothing is printed.") + sys.exit(5) + + def nrm(ch): # trainer-normalised [-1,1] chunk + return (2.0 * (ch.astype(np.float64) - lo) / span - 1.0) + + res = {} + for c, cd in cells.items(): + rows = cd["rows"] + per = [] + for r, q in zip(rows, rep): + pi, li = getidx(r, a.idx_a), getidx(r, a.idx_b) + if pi is None or li is None or not np.isfinite(pi) or not np.isfinite(li): + continue + pi, li = int(pi), int(li) + C, a0 = q["cands"], q["a0"] + Cn = nrm(C) + cp, cl, an = Cn[pi], Cn[li], nrm(a0) + # cloud spread: mean pairwise distance over the 128 candidates (same metric, same units) + flat = Cn.reshape(len(Cn), -1) + G = flat @ flat.T + sq = np.diag(G) + D2 = np.maximum(sq[:, None] + sq[None, :] - 2 * G, 0.0) + cloud_full = float(np.sqrt(D2)[np.triu_indices(len(Cn), 1)].mean()) + xyz = C[:, 0, :3].astype(np.float64) * 100.0 # cm, first step + dx = xyz[:, None, :] - xyz[None, :, :] + cloud_xyz = float(np.sqrt((dx ** 2).sum(-1))[np.triu_indices(len(xyz), 1)].mean()) + per.append(dict( + stage=int(r["stage"]), agree=bool(pi == li), + d_full=float(np.linalg.norm(cp - cl)), + d_xyz_cm=float(np.linalg.norm(xyz[pi] - xyz[li])), + # gripper flip judged on the NORMALISED coordinate, i.e. relative to the midpoint of + # [action_min, action_max] -- sign() on the RAW value would be identically positive if + # the corpus encodes the gripper on [0,1] and the column would silently read 0.000. + grip_flip=bool(np.sign(cp[0, -1]) != np.sign(cl[0, -1])), + d_grip=float(abs(cp[0, -1] - cl[0, -1])), + cloud_full=cloud_full, cloud_xyz_cm=cloud_xyz, + # paired quality proxy: which pick is closer to the anchor's own logged chunk? + p_to_log=float(np.linalg.norm(cp - an)), l_to_log=float(np.linalg.norm(cl - an)), + p_to_log_xyz=float(np.linalg.norm(xyz[pi] - 100.0 * a0[0, :3].astype(np.float64))), + l_to_log_xyz=float(np.linalg.norm(xyz[li] - 100.0 * a0[0, :3].astype(np.float64))), + # per-coordinate |diff| at step 0, normalised units: says WHICH of the 10 coords the + # read-out switch actually moves, so "gripper" is not taken on faith. + dcoord=[float(abs(cp[0, k] - cl[0, k])) for k in range(C.shape[2])], + )) + # ---- free internal check: agreeing anchors must have exactly zero distance ---- + bad0 = [p for p in per if p["agree"] and (p["d_full"] != 0.0 or p["d_xyz_cm"] != 0.0)] + if bad0: + print(f"*** {c}: {len(bad0)} AGREEING anchors with non-zero pick distance -- indexing bug") + sys.exit(5) + res[c] = per + + dis = {c: [p for p in v if not p["agree"]] for c, v in res.items()} + print("\n" + "=" * 108) + print(f"PICK DISTANCE: when {LA} and {LB} pick DIFFERENT candidates, how different is the MOTION?") + print("=" * 108) + print(f"{'cell':<9}{'n_dis':>6}{'d_xyz cm':>10}{'cloud cm':>10}{'ratio':>8}" + f"{'d_full':>9}{'cloud':>8}{'ratio':>8}{'grip flip':>11}{'d_grip':>8}") + print("-" * 108) + summ = {} + for c in CELLS: + v = dis[c] + if not v: + print(f"{c:<9}{0:>6} (no disagreeing anchors)"); continue + m = lambda k: float(np.mean([p[k] for p in v])) + s = dict(n_dis=len(v), d_xyz_cm=m("d_xyz_cm"), cloud_xyz_cm=m("cloud_xyz_cm"), + ratio_xyz=m("d_xyz_cm") / m("cloud_xyz_cm"), d_full=m("d_full"), + cloud_full=m("cloud_full"), ratio_full=m("d_full") / m("cloud_full"), + grip_flip_frac=float(np.mean([p["grip_flip"] for p in v])), d_grip=m("d_grip"), + med_xyz_cm=float(np.median([p["d_xyz_cm"] for p in v]))) + summ[c] = s + print(f"{c:<9}{s['n_dis']:>6}{s['d_xyz_cm']:>10.3f}{s['cloud_xyz_cm']:>10.3f}" + f"{s['ratio_xyz']:>8.3f}{s['d_full']:>9.3f}{s['cloud_full']:>8.3f}{s['ratio_full']:>8.3f}" + f"{s['grip_flip_frac']:>11.3f}{s['d_grip']:>8.3f}") + print("\nratio = mean pick-to-pick distance / mean PAIRWISE distance inside the same 128-candidate") + print("cloud. ~0 => different index, same motion (a relabelling: the change is behaviourally") + print("inert). ~1 => the two picks are as different as two random candidates in the cloud.") + + print(f"\nPAIRED QUALITY PROXY (no model): is the `{LB}` pick CLOSER to the anchor's own LOGGED") + print(f"goal-route chunk than the `{LA}` pick? d = ({LA}->logged) - ({LB}->logged), over the") + print(f"disagreeing anchors only. d > 0 favours {LB}.") + print(f"{'cell':<9}{'n':>5}{'d_full':>10}{'bootCI95':>22}{'wilcox p':>11}{'d_xyz cm':>10}" + f"{'bootCI95':>22}{'favours':>10}") + print("-" * 108) + for c in CELLS: + v = dis[c] + if not v: + continue + df = np.array([p["p_to_log"] - p["l_to_log"] for p in v]) + dxy = np.array([p["p_to_log_xyz"] - p["l_to_log_xyz"] for p in v]) + lo1, hi1 = boot_ci(df); lo2, hi2 = boot_ci(dxy) + pw = wilcoxon(df) + fav = LB if lo1 > 0 else (LA if hi1 < 0 else "ns") + summ[c].update(d_tolog_full=float(df.mean()), d_tolog_full_ci=[lo1, hi1], d_tolog_full_p=pw, + d_tolog_xyz_cm=float(dxy.mean()), d_tolog_xyz_ci=[lo2, hi2], favours=fav) + print(f"{c:<9}{len(v):>5}{df.mean():>10.4f}{f'[{lo1:.4f}, {hi1:.4f}]':>22}{pw:>11.2e}" + f"{dxy.mean():>10.4f}{f'[{lo2:.4f}, {hi2:.4f}]':>22}{fav:>10}") + + print("\nPER-COORDINATE mean |diff| at step 0 (normalised units, disagreeing anchors), and the same") + print("for a RANDOM candidate pair in the same cloud would be ~the cloud spread per coord:") + for c in CELLS: + v = dis[c] + if not v: + continue + M = np.array([p["dcoord"] for p in v]).mean(0) + print(f" {c:<9} " + " ".join(f"c{k}:{M[k]:.3f}" for k in range(len(M)))) + summ[c]["dcoord_mean"] = [float(x) for x in M] + + print("\nPER-STAGE pick distance ratio (xyz, first step), deployed cell first:") + for c in CELLS: + v = dis[c] + if not v: + continue + by = collections.defaultdict(list) + for p in v: + by[p["stage"]].append(p) + cells_s = " ".join(f"S{s}: {np.mean([p['d_xyz_cm'] for p in by[s]])/np.mean([p['cloud_xyz_cm'] for p in by[s]]):.3f} " + f"(n={len(by[s])})" for s in sorted(by)) + print(f" {c:<9} {cells_s}") + summ[c]["by_stage_ratio_xyz"] = {f"S{s}": float(np.mean([p['d_xyz_cm'] for p in by[s]]) / + np.mean([p['cloud_xyz_cm'] for p in by[s]])) + for s in sorted(by)} + + os.makedirs(os.path.dirname(a.out) or ".", exist_ok=True) + json.dump(dict(args=vars(a), summary=summ, + per_anchor={c: [{k: v2 for k, v2 in p.items()} for p in res[c]] for c in res}), + open(a.out, "w"), indent=1) + print(f"\nwrote {a.out}") + + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/real/act_referee.py b/rsm_rise/scripts/real/act_referee.py new file mode 100644 index 0000000000000000000000000000000000000000..04eac26d6f46a3ec9c0132e09a6b6592593e82cb --- /dev/null +++ b/rsm_rise/scripts/real/act_referee.py @@ -0,0 +1,275 @@ +"""ACT_COND run 29 (gen_q#278): WHEN THE TWO READ-OUTS PICK DIFFERENT ACTIONS, DOES AN INDEPENDENTLY +TRAINED SUCCESSOR PREFER EITHER PICK? + +Where this sits. Run 27 measured that the `prob` -> `logit` read-out switch changes the EXECUTED +candidate on 47/200 anchors at the deployed cell (argmax agreement 0.765). Run 28 measured that those +47 disagreements are real motion, not relabelling (5.9 cm of first-step xyz, 36% of the cloud's own +spread, gripper flipping on 12.8% of them), and that the only quality statistic available -- distance +to the anchor's own logged chunk -- is NULL on all four checkpoints with inconsistent signs. So the +run-26 "adopt logit" recommendation was withdrawn. The binding limit on that withdrawal is that +NOTHING has ever scored the two picks with an instrument that did not itself choose them. + +This script is that instrument. A REFEREE is a DIFFERENT successor checkpoint -- a different training +seed and/or reward variant and/or width -- that played no part in the selection. For every anchor it +re-scores the SAME 128-candidate cloud and reports where each read-out's pick lands in the REFEREE's +own ordering. Both picks are logged goal-route chunks from the same stage, so a referee has no +degenerate way to prefer one: it must actually rank them. + +WHAT IT IS NOT. A referee is another RSM trained on the same corpus with the same objective, so this +measures whether the FAMILY's value ordering prefers a pick -- not task success. If the read-out +disagreement comes from something every member of the family shares, the panel will inherit it and +agree for the wrong reason. That is why the panel spans two seeds, two reward variants and two widths, +and why the diagonal (referee == the cell's own model) is carried as a CALIBRATION row rather than +dropped: it shows what a maximally-biased referee looks like (it must rank its own read-out's pick +first), so an off-diagonal effect can be read against that ceiling. + +PRE-REGISTERED DECISION RULE (written before the panel ran): + * "logit's picks are better" requires d_rank > 0 with a bootstrap CI excluding 0 for a MAJORITY of + the held-out referees under BOTH referee read-outs. Symmetrically for prob. + * Anything else -- ns, or split across referees, or split across referee read-outs -- is NULL, the + run-28 withdrawal stands, `prob` stays deployed, and the run reports the tightest bound achieved. + * The primary panel is the DEPLOYED width/family; different-width referees are reported as a + robustness row and cannot by themselves carry the claim. + +GATE, FATAL (rc=5). Run with --ref-ckpt equal to the cell's own checkpoint and the same seed, this +script must reproduce run 27's stored numbers BIT-IDENTICALLY: q0, rank_pct_prob, rank_pct_logit, +xpick_prob_idx, xpick_logit_idx. The anchor/candidate/state/interp construction below is a copy of +act_sensitivity.py's, and that gate is what proves the copy consumes the rng identically -- a silent +divergence would move every number here and nothing else would catch it. Missing/short cells rc=4. +""" +import argparse, collections, json, os, sys, time +import numpy as np + +ROOT = "/proj/dmfexp/zwhong/rsm_rise" +sys.path.insert(0, f"{ROOT}/scripts/real") +GOAL_PATH = "2->3->4" +FAIL_PATHS = ("0->5", "0->2->6") + +# The four run-27 cells, with the exact checkpoints their payloads used. +CELL_CKPT = { + "mrise": f"{ROOT}/runs/real_cooking_v5/rsm/R_M_ft_v0_rise/ckpt_s120000.pt", + "mnt": f"{ROOT}/runs/real_cooking_v5/rsm/R_M_ft_v0_nt/ckpt_s120000.pt", + "xlrise": f"{ROOT}/runs/real_cooking_v5/rsm/R_XL_ft_rise/ckpt_s110000.pt", + "xlnt": f"{ROOT}/runs/real_cooking_v5/rsm/R_XL_ft_nt/ckpt_s110000.pt", +} + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--hdf5", default=f"{ROOT}/data/raw/cooking_v5_expert_suboptimal.hdf5") + ap.add_argument("--split", default=f"{ROOT}/data/derived/cooking_v5_split.json") + ap.add_argument("--cache", default=f"{ROOT}/cache/real_cooking_v5") + ap.add_argument("--xpick-dir", default=f"{ROOT}/status/real/ACT_COND/xpick") + ap.add_argument("--cell", required=True, choices=sorted(CELL_CKPT)) + ap.add_argument("--ref-ckpt", required=True) + ap.add_argument("--ref-tag", required=True) + ap.add_argument("--hop-ckpt", default=f"{ROOT}/runs/real_cooking_v5/hop/gauss/policy_r1.pt") + # every knob below is the run-27 cell's value; they are arguments only so the gate can prove it. + ap.add_argument("--mode", default="chain") + ap.add_argument("--beta", type=float, default=0.99) + ap.add_argument("--gamma", type=float, default=0.999) + ap.add_argument("--particles", type=int, default=16) + ap.add_argument("--temperature", type=float, default=25.0) + ap.add_argument("--chain-cap", type=int, default=0) + ap.add_argument("--n-cand", type=int, default=128) + ap.add_argument("--n-state", type=int, default=128) + ap.add_argument("--n-interp", type=int, default=10) + ap.add_argument("--horizon", type=int, default=8) + ap.add_argument("--stride", type=int, default=25) + ap.add_argument("--max-anchors", type=int, default=200) + ap.add_argument("--anchor-routes", default="all", choices=["all", "goal"]) + ap.add_argument("--seed", type=int, default=0) + ap.add_argument("--out", required=True) + a = ap.parse_args() + t0 = time.time() + import h5py, torch + from twin_rollout import Scorer + + xp = f"{a.xpick_dir}/xpick_{a.cell}.json" + if not os.path.exists(xp): + print(f"MISSING run-27 cell {xp} -- a referee row without the picks it judges is not a result") + sys.exit(4) + stored = json.load(open(xp))["rows"] + self_ref = os.path.realpath(a.ref_ckpt) == os.path.realpath(CELL_CKPT[a.cell]) + print(f"[ref] cell={a.cell} referee={a.ref_tag} self_referee={self_ref} " + f"stored_rows={len(stored)}", flush=True) + + rng = np.random.default_rng(a.seed) + os.makedirs(os.path.dirname(a.out) or ".", exist_ok=True) + split = json.load(open(a.split))["episodes"] + meta = np.load(f"{a.cache}/meta.npz", allow_pickle=True) + ep_from = np.asarray(meta["ep_from"]) + zf = np.load(f"{a.cache}/z.f16.npy", mmap_mode="r") + pf = np.load(f"{a.cache}/proprio.f32.npy", mmap_mode="r") + st = np.load(f"{a.cache}/feat_stats.npz") + dd = int(zf.shape[1] + pf.shape[1]) + mu, sd = st["mu"][:dd].astype(np.float32), st["sd"][:dd].astype(np.float32) + zclip = float(st["z_clip"]) if "z_clip" in st.files else 10.0 + + f = h5py.File(a.hdf5, "r"); d = f["data"] + lo = np.array(json.loads(d.attrs["action_min"]), np.float32) + hi = np.array(json.loads(d.attrs["action_max"]), np.float32) + spl = lambda k: split.get(str(int(k.split("_")[1])), {}).get("split", "") + path = lambda k: str(d[k].attrs.get("path", "")) + train = [k for k in d if spl(k) == "train"] + + # ---- VERBATIM from act_sensitivity.py: pools, anchors, stratification, per-anchor draws ---- + chunk_pool = collections.defaultdict(list) + state_pool = collections.defaultdict(list) + fail_pool = collections.defaultdict(list) + anchors = [] + for k in train: + g = d[k]; ep = int(k.split("_")[1]) + A = np.asarray((g["actions_raw"] if "actions_raw" in g else g["actions"])[()], np.float32) + stg = np.asarray(g["annot"]["edge_from"][()]) + for t in range(0, len(A) - a.horizon, a.stride): + s0 = int(stg[t]); ch = A[t:t + a.horizon] + chunk_pool[s0].append(ch) + state_pool[s0].append(int(ep_from[ep] + t)) + if path(k) in FAIL_PATHS: + fail_pool[s0].append(ch) + if a.anchor_routes == "all" or path(k) == GOAL_PATH: + anchors.append((ep, t, s0, path(k))) + by_stage = collections.defaultdict(list) + for x in anchors: + by_stage[x[2]].append(x) + if len(anchors) > a.max_anchors: + stages = sorted(by_stage) + quota = {s: a.max_anchors // len(stages) for s in stages} + left = a.max_anchors - sum(min(quota[s], len(by_stage[s])) for s in stages) + for s in sorted(stages, key=lambda s: -len(by_stage[s])): + take = min(left, max(0, len(by_stage[s]) - quota[s])) + quota[s] += take; left -= take + picked = [] + for s in stages: + v = by_stage[s]; n = min(quota[s], len(v)) + picked += [v[i] for i in sorted(rng.choice(len(v), size=n, replace=False))] + anchors = sorted(picked, key=lambda x: (x[0], x[1])) + fail_stages = [s for s, v in fail_pool.items() if v] + + def probe_target(s0): + if fail_pool[s0]: + return fail_pool[s0][int(rng.integers(len(fail_pool[s0])))], "failure_same_stage" + if fail_stages: + sp = fail_stages[int(rng.integers(len(fail_stages)))] + return fail_pool[sp][int(rng.integers(len(fail_pool[sp])))], "failure_other_stage" + others = [s for s, v in chunk_pool.items() if s != s0 and v] + sp = others[int(rng.integers(len(others)))] + return chunk_pool[sp][int(rng.integers(len(chunk_pool[sp])))], "offstage" + + sc = Scorer("rsm", lo, hi, rsm_ckpt=a.ref_ckpt, seed=a.seed, rsm_mode=a.mode, rsm_beta=a.beta, + rsm_gamma=a.gamma, rsm_particles=a.particles, rsm_dim=dd, + rsm_temperature=a.temperature, rsm_hop_ckpt=a.hop_ckpt) + if a.chain_cap: + sc.rsm.backend.chain_cap_override = int(a.chain_cap) + rsm = sc.rsm; dev = rsm.device + + def feat(gi): + z = np.concatenate([np.asarray(zf[gi], np.float32), np.asarray(pf[gi], np.float32)]) + return np.clip((z - mu) / sd, -zclip, zclip).astype(np.float32) + + NC, NS, NI = a.n_cand, a.n_state, a.n_interp + rows, gate_fail, aligned = [], [], 0 + for ai, (ep, t, s0, route) in enumerate(anchors): + if len(chunk_pool[s0]) < NC or len(state_pool[s0]) < NS + 1: + continue + gi = int(ep_from[ep] + t) + x0 = feat(gi) + g = d[f"demo_{ep}"] + a0 = np.asarray((g["actions_raw"] if "actions_raw" in g else g["actions"])[t:t + a.horizon], + np.float32) + ci = rng.choice(len(chunk_pool[s0]), size=NC, replace=False) + cands = np.stack([chunk_pool[s0][i] for i in ci]) + si = [j for j in rng.permutation(len(state_pool[s0])) if state_pool[s0][j] != gi][:NS] + states = np.stack([feat(state_pool[s0][j]) for j in si]) + af, probe_src = probe_target(s0) + lam = np.linspace(0.0, 1.0, NI, dtype=np.float32) + interp = np.stack([(1 - l) * a0 + l * af for l in lam]) + X = np.concatenate([np.repeat(x0[None], NC, 0), states, + np.repeat(x0[None], NI + 1, 0)], 0) + A = np.concatenate([cands, np.repeat(a0[None], NS, 0), interp, a0[None]], 0) + with torch.no_grad(): + rsm.score(torch.as_tensor(X, dtype=torch.float32, device=dev), A, + seed=a.seed + 7919 * (ai + 1)) + q = rsm.last_q.double().cpu().numpy() + ql = rsm.last_q_logit + ql = np.full_like(q, np.nan) if ql is None else ql.double().cpu().numpy() + qa, la = q[:NC], ql[:NC] + q00, l00 = q[-1], ql[-1] + + # ---- alignment with the stored row: the rng stream must be where run 27 left it ---- + sr = stored[len(rows)] if len(rows) < len(stored) else None + if sr is None or (int(sr["ep"]), int(sr["t"]), int(sr["stage"]), str(sr["route"]), + str(sr["probe_src"])) != (ep, t, s0, route, probe_src): + gate_fail.append(f"row{len(rows)}: replay ({ep},{t},S{s0},{route},{probe_src}) vs stored " + + (f"({sr['ep']},{sr['t']},S{sr['stage']},{sr['route']},{sr['probe_src']})" + if sr else "MISSING")) + if len(gate_fail) > 5: + break + continue + aligned += 1 + p_idx, l_idx = int(sr["xpick_prob_idx"]), int(sr["xpick_logit_idx"]) + r = {"ep": ep, "t": t, "stage": s0, "route": route, "probe_src": probe_src, + "prob_idx": p_idx, "logit_idx": l_idx, "agree": int(p_idx == l_idx), + # referee scores of the two picks, both referee read-outs + "ref_q_prob_at_probpick": float(qa[p_idx]), "ref_q_prob_at_logitpick": float(qa[l_idx]), + "ref_q_logit_at_probpick": float(la[p_idx]), "ref_q_logit_at_logitpick": float(la[l_idx]), + # where each pick lands in the REFEREE's own ordering (strict-less, run-27 convention) + "ref_rank_prob_probpick": float((qa < qa[p_idx]).mean()), + "ref_rank_prob_logitpick": float((qa < qa[l_idx]).mean()), + "ref_rank_logit_probpick": float((la < la[p_idx]).mean()), + "ref_rank_logit_logitpick": float((la < la[l_idx]).mean()), + # the referee's own pick, and the cloud scale it is measured against + "ref_argmax_prob": int(np.argmax(qa)), "ref_argmax_logit": int(np.argmax(la)), + "ref_cloud_mean_prob": float(qa.mean()), "ref_cloud_std_prob": float(qa.std()), + "ref_cloud_mean_logit": float(la.mean()), "ref_cloud_std_logit": float(la.std()), + # free: the referee's own version of the run-25/26 logged-chunk statistic + "ref_q0_prob": float(q00), "ref_q0_logit": float(l00), + "ref_rank_pct_logged_prob": float((qa < q00).mean()), + "ref_rank_pct_logged_logit": float((la < l00).mean())} + # ---- the bit-identity gate, only meaningful when the referee IS the cell's own model ---- + if self_ref: + chk = [("q0", float(q00), float(sr["q0"])), ("logit0", float(l00), float(sr["logit0"])), + ("rank_pct_prob", float((qa < q00).mean()), float(sr["rank_pct_prob"])), + ("rank_pct_logit", float((la < l00).mean()), float(sr["rank_pct_logit"])), + ("xpick_prob_idx", float(np.argmax(qa)), float(p_idx)), + ("xpick_logit_idx", float(np.argmax(la)), float(l_idx))] + for nm, got, want in chk: + if not (got == want or abs(got - want) <= 1e-12 * max(1.0, abs(want))): + gate_fail.append(f"row{len(rows)} {nm}: got {got!r} stored {want!r}") + rows.append(r) + if len(rows) % 25 == 0: + print(f" [{len(rows)}/{len(anchors)}] ep{ep} t{t} S{s0} " + f"agree={r['agree']} ({time.time()-t0:.0f}s)", flush=True) + + out = {"args": vars(a), "cell": a.cell, "ref_tag": a.ref_tag, "ref_ckpt": a.ref_ckpt, + "self_referee": self_ref, "n_anchors": len(rows), "n_aligned": aligned, + "rows": rows, "host": os.uname().nodename, "seconds": time.time() - t0} + if gate_fail: + out["GATE_FAIL"] = gate_fail + json.dump(out, open(a.out + ".GATEFAIL", "w"), indent=1) + print("\n*** GATE FAILED -- refusing to write a readable result ***") + for m in gate_fail[:10]: + print(" " + m) + f.close() + sys.exit(5) + if len(rows) != len(stored): + print(f"*** short: {len(rows)} rows vs {len(stored)} stored -- partial is not a result") + f.close() + sys.exit(4) + json.dump(out, open(a.out, "w"), indent=1) + dis = [r for r in rows if not r["agree"]] + d_prob = np.array([r["ref_rank_prob_logitpick"] - r["ref_rank_prob_probpick"] for r in dis]) + d_logit = np.array([r["ref_rank_logit_logitpick"] - r["ref_rank_logit_probpick"] for r in dis]) + print(f"\n[ref] {a.cell} <- {a.ref_tag}: {len(rows)} anchors, {len(dis)} disagreeing" + f"{' (SELF-REFEREE, calibration row -- gate PASSED bit-identical)' if self_ref else ''}") + print(f" d_rank(referee prob) mean {d_prob.mean():+.4f} median {np.median(d_prob):+.4f} " + f"logit-pick better on {float((d_prob > 0).mean()):.3f}") + print(f" d_rank(referee logit) mean {d_logit.mean():+.4f} median {np.median(d_logit):+.4f} " + f"logit-pick better on {float((d_logit > 0).mean()):.3f}") + print(f"\nwrote {a.out} ({time.time()-t0:.0f}s)", flush=True) + f.close() + + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/real/act_rescore_read.py b/rsm_rise/scripts/real/act_rescore_read.py new file mode 100644 index 0000000000000000000000000000000000000000..ff8926e9dbc6120bac7a88c5ee65a58492ee0926 --- /dev/null +++ b/rsm_rise/scripts/real/act_rescore_read.py @@ -0,0 +1,357 @@ +"""ACT_COND run 32 (gen_q#278): READ THE TWO-STAGE TIE-BREAK CELLS (job 1893988). + +Run 31 resolved the pre-registered fork toward NEAR-TIE: under a strict hold-out the best single-draw +predictor of an unstable executed pick is the top-1-vs-top-2 MARGIN, and it is the only predictor that +transfers to the held-out checkpoint. The indicated fix is therefore a TIE-BREAK (rescore the top-K +candidates with M particles) rather than a uniform budget -- which is also the only reading consistent +with the uniform curve, where 4x particles bought just +6.7 points of top-1 agreement. + +PRE-REGISTERED READ (run 31 section 5, written BEFORE the cells existed): + two-stage at K=16 costs 128*16 + 16*64 = 3072 particle-evals = 1.5x the deployed 2048, and the + UNIFORM curve needed 2x (P=32) to reach top1_agree 0.590 from 0.557. THE TIE-BREAK WINS IFF IT + BEATS 0.590. If it lands at or below the uniform curve at matched compute, the near-tie reading + predicted the wrong fix and that is what gets reported. + CORRECTION TO RUN 31's ARITHMETIC, carried here rather than quietly fixed: K=32 costs + 128*16 + 32*64 = 4096 = 2.00x, not the 1.75x the run-31 text stated (measured `rs_cost_ts` agrees: + 3072 / 4096). So K=32's matched-compute bar is EXACTLY the uniform P=32 point, 0.590. + +IT REFUSES TO PRINT NUMBERS OFF A BROKEN PATCH. Three gates, each rc-distinct: + rc=4 a cell is missing (a partial job is not a result). + rc=5 REGRESSION: the run-31 rescore patch is ADDITIVE and issues its own seeds, so every non-`rs_` + field must reproduce the run-29 mcstab P=16 cell BIT-FOR-BIT -- including the repeat-derived + fields, since repeats=4 on both sides. Excluded by exact name: chain_hops_mean / + chain_capped_frac, the cumulative accumulator of run 31 section 0/1 -- the tie-break's extra + score() calls legitimately feed it -- and the exclusion is PRINTED with both means. + rc=6 PAIRED CONTROL: `rs_ctl_*` is the tie-break-OFF arm at the same seed and the same + candidates-only batch shape, so it CANNOT depend on K. If it differs between the K=16 and + K=32 cells the pairing is broken and the ts-vs-ctl contrast is not attributable to the + rescore. This gate is the reason the control was run at all. + +DEGENERACY GUARD, printed before the verdict: a tie-break that collapsed onto a fixed candidate would +score top1_agree 1.000 and look like a triumph. We print the number of DISTINCT picked indices and +the pick entropy for both arms, plus the ts-vs-ctl pick change rate (a no-op tie-break is also a +possible and reportable outcome). +""" +import argparse, json, math, os, sys +import numpy as np + +ROOT = "/proj/dmfexp/zwhong/rsm_rise" +ACCUMULATOR_FIELDS = ("chain_hops_mean", "chain_capped_frac") +RS_PREFIX = "rs_" + + +def wilson(k, n, z=1.96): + if n <= 0: + return float("nan"), float("nan") + p = k / n + d = 1 + z * z / n + c = p + z * z / (2 * n) + h = z * math.sqrt(p * (1 - p) / n + z * z / (4 * n * n)) + return (c - h) / d, (c + h) / d + + +def boot_ci(d, n=20000, seed=0): + d = np.asarray(d, float) + if len(d) < 2: + return float("nan"), float("nan") + r = np.random.default_rng(seed) + m = d[r.integers(0, len(d), size=(n, len(d)))].mean(1) + return float(np.percentile(m, 2.5)), float(np.percentile(m, 97.5)) + + +def flat(o, pre=""): + out = {} + if isinstance(o, dict): + for k, v in o.items(): + out.update(flat(v, f"{pre}.{k}" if pre else str(k))) + elif isinstance(o, list): + for i, v in enumerate(o): + out.update(flat(v, f"{pre}[{i}]")) + elif isinstance(o, (int, float)) and not isinstance(o, bool): + out[pre] = float(o) + return out + + +def agree(idx): + """top1_agree, the run-29 definition verbatim: mean over the C(R,2) unordered pairs of draws of + (argmax_i == argmax_j). act_sensitivity.py:336.""" + idx = list(idx) + pr = [(i, j) for i in range(len(idx)) for j in range(i + 1, len(idx))] + return float(np.mean([idx[i] == idx[j] for i, j in pr])) if pr else float("nan") + + +def entropy(idx): + _, cnt = np.unique(np.asarray(idx), return_counts=True) + p = cnt / cnt.sum() + return float(-(p * np.log2(p)).sum()) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--dir", default=f"{ROOT}/status/real/ACT_COND/rescore") + ap.add_argument("--mcstab-dir", default=f"{ROOT}/status/real/ACT_COND/mcstab") + ap.add_argument("--cells", default="mrise,mnt") + ap.add_argument("--ks", default="16,32") + ap.add_argument("--uniform-ps", default="16,32,64") + ap.add_argument("--out", default=f"{ROOT}/status/real/ACT_COND/RESCORE_run32.json") + a = ap.parse_args() + cellnames = [c for c in a.cells.split(",") if c] + KS = [int(x) for x in a.ks.split(",") if x] + PS = [int(x) for x in a.uniform_ps.split(",") if x] + + cells, missing = {}, [] + for c in cellnames: + for K in KS: + p = f"{a.dir}/rs_{c}_K{K}.json" + if not os.path.exists(p): + missing.append(p) + else: + cells[(c, K)] = json.load(open(p)) + if missing: + print("MISSING CELLS -- a partial job is not a result:") + [print(" " + m) for m in missing] + sys.exit(4) + + # ------------------------------------------------------------- GATE 1: REGRESSION (rc=5) + print("=" * 112) + print("GATE 1 / REGRESSION: the run-31 rescore block is ADDITIVE, runs AFTER the chain section and") + print("issues its own seeds, so every NON-`rs_` field must reproduce the run-29 mcstab P=16 cell") + print("bit-for-bit -- repeat-derived fields INCLUDED (repeats=4 on both sides).") + print("EXCLUDED BY EXACT NAME (cumulative accumulator, run 31 s0/s1): " + ", ".join(ACCUMULATOR_FIELDS)) + print("=" * 112) + nbad = 0 + for c in cellnames: + ref_p = f"{a.mcstab_dir}/mc_{c}_p16.json" + if not os.path.exists(ref_p): + print(f" {c}: no reference {ref_p} -- SKIPPED (cannot regress)") + continue + ref = json.load(open(ref_p))["rows"] + for K in KS: + new = cells[(c, K)]["rows"] + if len(ref) != len(new): + print(f"*** {c} K={K}: {len(ref)} ref rows vs {len(new)} new rows"); nbad += 1; continue + nf, worst, bad, tally, acc = 0, 0.0, [], {}, {} + for i, (r0, r1) in enumerate(zip(ref, new)): + fa, fb = flat(r0), flat(r1) + for k, v in fa.items(): + if k.startswith(RS_PREFIX): + continue + base = k.split(".")[-1].split("[")[0] + if base in ACCUMULATOR_FIELDS: + if k in fb: + acc.setdefault(base, ([], []))[0].append(v) + acc[base][1].append(fb[k]) + continue + if k not in fb: + bad.append(f"({i}).{k}: MISSING in new") + tally[k + " MISSING"] = tally.get(k + " MISSING", 0) + 1 + continue + nf += 1 + d = abs(v - fb[k]) / max(abs(v), 1e-12) + worst = max(worst, d) + if d > 0: + bad.append(f"({i}).{k}: ref={v!r} new={fb[k]!r}") + tally[k] = tally.get(k, 0) + 1 + for base, (rv, nv) in sorted(acc.items()): + print(f" {c} K={K} [SAMPLING-ONLY, excluded] {base}: ref mean {np.mean(rv):.4f} " + f"new mean {np.mean(nv):.4f} (tie-break score() calls feed the same accumulator)") + if bad: + print(f"*** {c} K={K}: {len(bad)} MISMATCHES over {len(tally)} FIELD(S) ***") + for k in sorted(tally, key=lambda z: -tally[z]): + print(f" {k}: {tally[k]} row(s)") + [print(" e.g. " + b) for b in bad[:5]] + nbad += 1 + else: + print(f" {c} K={K}: {nf} fields worst rel {worst:.2e} IDENTICAL to mc_{c}_p16") + if nbad: + print("\nThe additive tie-break patch moved a pre-existing field. Nothing else is read.") + sys.exit(5) + + # ------------------------------------------------------------- GATE 2: PAIRED CONTROL (rc=6) + print("\n" + "=" * 112) + print("GATE 2 / PAIRED CONTROL: `rs_ctl_*` is the tie-break-OFF arm at the same seed and the same") + print("candidates-only batch shape. It cannot depend on K; if it does, the pairing is broken and") + print("the ts-vs-ctl contrast is not attributable to the rescore.") + print("=" * 112) + nbad = 0 + for c in cellnames: + if len(KS) < 2: + print(f" {c}: only one K -- gate inapplicable"); continue + base = cells[(c, KS[0])]["rows"] + for K in KS[1:]: + oth = cells[(c, K)]["rows"] + diff = 0 + for r0, r1 in zip(base, oth): + for k in r0: + if k.startswith("rs_ctl_") and flat({k: r0[k]}) != flat({k: r1[k]}): + diff += 1 + if diff: + print(f"*** {c}: rs_ctl_* differs between K={KS[0]} and K={K} in {diff} field(s) ***") + nbad += 1 + else: + print(f" {c}: rs_ctl_* IDENTICAL between K={KS[0]} and K={K} -- pairing intact") + if nbad: + sys.exit(6) + + # ------------------------------------------------------------- DEGENERACY GUARD + print("\n" + "=" * 112) + print("DEGENERACY GUARD. A tie-break that collapsed onto a fixed candidate would score") + print("top1_agree 1.000 and look like a triumph. distinct = # distinct picked indices over all") + print("anchors x draws (out of 128 candidates); H = entropy of that pick distribution in bits.") + print("chg = fraction of anchor-draws where the two-stage pick DIFFERS from the control pick") + print("(chg = 0 would mean the tie-break is a NO-OP, also a reportable outcome).") + print("=" * 112) + print(f"{'cell':<8}{'K':>4}{'read':>7}{'ctl distinct':>14}{'ctl H':>8}{'ts distinct':>13}{'ts H':>7}{'chg':>8}") + print("-" * 112) + deg = {} + for c in cellnames: + for K in KS: + rows = cells[(c, K)]["rows"] + for kind in ("prob", "logit"): + ci = [i for r in rows for i in r[f"rs_ctl_top1_idx_{kind}"]] + ti = [i for r in rows for i in r[f"rs_ts_top1_idx_{kind}"]] + chg = float(np.mean([x != y for x, y in zip(ci, ti)])) + print(f"{c:<8}{K:>4}{kind:>7}{len(set(ci)):>14}{entropy(ci):>8.2f}" + f"{len(set(ti)):>13}{entropy(ti):>7.2f}{chg:>8.3f}") + deg[f"{c}_K{K}_{kind}"] = dict(ctl_distinct=len(set(ci)), ctl_H=entropy(ci), + ts_distinct=len(set(ti)), ts_H=entropy(ti), + ts_vs_ctl_change=chg) + print("-" * 112) + + # ------------------------------------------------------------- THE UNIFORM REFERENCE CURVE + uni = {} + for c in cellnames: + for P in PS: + p = f"{a.mcstab_dir}/mc_{c}_p{P}.json" + if os.path.exists(p): + rows = json.load(open(p))["rows"] + for kind in ("prob", "logit"): + uni[(c, P, kind)] = float(np.mean([r[f"top1_agree_{kind}"] for r in rows])) + + # ------------------------------------------------------------- MAIN: ts vs ctl, PAIRED + print("\n" + "=" * 112) + print("TIE-BREAK vs CONTROL, PAIRED on the same anchors and the same seed. top1_agree = P(two") + print("independent particle draws pick the SAME action). cost is in particle-evals, measured") + print("(`rs_cost_*`), not assumed. Deployed = prob.") + print("=" * 112) + print(f"{'cell':<8}{'K':>4}{'read':>7}{'n':>5}{'ctl':>8}{'ts':>8}{'delta':>9}{'bootCI95':>22}" + f"{'cost x':>8}{'uniform@cost':>14}{'verdict':>10}") + print("-" * 112) + res = {"degeneracy": deg, "uniform": {f"{c}_p{P}_{k}": v for (c, P, k), v in uni.items()}} + for c in cellnames: + for K in KS: + rows = cells[(c, K)]["rows"] + n = len(rows) + cx = float(np.mean([r["rs_cost_ts"] for r in rows]) / + max(np.mean([r["rs_cost_ctl"] for r in rows]), 1e-30)) + for kind in ("prob", "logit"): + ac = np.array([agree(r[f"rs_ctl_top1_idx_{kind}"]) for r in rows]) + at = np.array([agree(r[f"rs_ts_top1_idx_{kind}"]) for r in rows]) + d = at - ac + lo, hi = boot_ci(d) + # matched-compute bar: the uniform point at the SAME multiple of the deployed budget. + # cost 1.5x and 2.0x -> the nearest uniform point AT OR BELOW the tie-break's cost is + # P=16 (1x) for 1.5x, but run 31 pre-registered the STRICTER bar, P=32 (2x) = the + # uniform curve's 2x point, for BOTH K. Printed as `uniform@cost`; the stricter bar + # is the one the verdict uses, and it is quoted from the same file, not hardcoded. + bar = uni.get((c, 32, kind), float("nan")) + lo_t, hi_t = wilson(at.mean() * n * 6, n * 6) + if not np.isfinite(bar): + vd = "no-ref" + elif lo_t > bar: + vd = "WIN" + elif hi_t < bar: + vd = "LOSE" + else: + vd = "ns" + print(f"{c:<8}{K:>4}{kind:>7}{n:>5}{ac.mean():>8.3f}{at.mean():>8.3f}{d.mean():>+9.3f}" + f"{f'[{lo:+.3f}, {hi:+.3f}]':>22}{cx:>8.2f}{bar:>14.3f}{vd:>10}") + res[f"{c}_K{K}_{kind}"] = dict( + n=n, ctl=float(ac.mean()), ts=float(at.mean()), delta=float(d.mean()), + delta_ci=[lo, hi], ts_wilson=[lo_t, hi_t], cost_x=cx, uniform_2x_bar=bar, + verdict=vd) + print("-" * 112) + + # ------------------------------------------------------------- PAIRED matched-compute verdict + # The point-bar verdict above compares a mean against a NUMBER. The uniform P=32 cell was run on + # the SAME 200 anchors (same stratification, same seed), so the comparison can be PAIRED, which + # removes anchor-to-anchor variance -- by far the largest term here. The pre-registered verdict + # stays the point bar (that is what was written down before the cells existed); this is the + # stronger version of the same test and both are printed. Alignment is CHECKED, not assumed: + # if (ep, t, stage, route) does not match row-for-row the pairing is skipped and said so. + print("\n" + "=" * 112) + print("PAIRED matched-compute verdict: ts(K) vs the UNIFORM 2x cell (P=32) on the SAME anchors.") + print("d = top1_agree(ts) - top1_agree(uniform P=32); d > 0 means the tie-break beats uniform 2x.") + print("=" * 112) + print(f"{'cell':<8}{'K':>4}{'read':>7}{'n':>5}{'ts':>8}{'uni2x':>8}{'d':>9}{'bootCI95':>22}{'verdict':>10}") + print("-" * 112) + for c in cellnames: + up = f"{a.mcstab_dir}/mc_{c}_p32.json" + if not os.path.exists(up): + print(f" {c}: no uniform P=32 cell -- SKIPPED"); continue + urows = json.load(open(up))["rows"] + for K in KS: + rows = cells[(c, K)]["rows"] + key = lambda r: (r["ep"], r["t"], r["stage"], r["route"]) + if len(urows) != len(rows) or any(key(x) != key(y) for x, y in zip(rows, urows)): + print(f" {c} K={K}: anchors DO NOT ALIGN with the P=32 cell -- pairing skipped") + continue + for kind in ("prob", "logit"): + at = np.array([agree(r[f"rs_ts_top1_idx_{kind}"]) for r in rows]) + au = np.array([u[f"top1_agree_{kind}"] for u in urows]) + d = at - au + lo, hi = boot_ci(d) + vd = "WIN" if lo > 0 else ("LOSE" if hi < 0 else "ns") + print(f"{c:<8}{K:>4}{kind:>7}{len(rows):>5}{at.mean():>8.3f}{au.mean():>8.3f}" + f"{d.mean():>+9.3f}{f'[{lo:+.3f}, {hi:+.3f}]':>22}{vd:>10}") + res[f"{c}_K{K}_{kind}"].update(paired_uni2x=float(au.mean()), + paired_delta=float(d.mean()), + paired_ci=[lo, hi], paired_verdict=vd) + print("-" * 112) + + # replication check: the ctl arm is a fresh 128-row candidates-only measurement of the SAME + # quantity the uniform P=16 cell reports off its first 128 rows of a 267-row call. They are not + # required to be equal (different batch composition => different draws) but a large gap would + # mean the candidates-only call is not the deployed cloud. + print("\nREPLICATION: ctl (candidates-only call, this job) vs uniform P=16 (first 128 rows of the") + print("267-row call, run 29). Same quantity, different batch composition -- a large gap means the") + print("tie-break is not being measured on the deployed cloud.") + for c in cellnames: + for kind in ("prob", "logit"): + u = uni.get((c, 16, kind), float("nan")) + v = res[f"{c}_K{KS[0]}_{kind}"]["ctl"] + print(f" {c:<8}{kind:>7} ctl {v:.3f} uniform P=16 {u:.3f} gap {v-u:+.3f}") + + # ------------------------------------------------------------- PER STAGE (deployed read-out) + print("\nPER-STAGE ctl -> ts, prob (deployed). Run 31: S3 is the worst stage at every budget.") + for c in cellnames: + for K in KS: + rows = cells[(c, K)]["rows"] + st = sorted({r["stage"] for r in rows}) + line = " ".join( + f"S{s}: {np.mean([agree(r['rs_ctl_top1_idx_prob']) for r in rows if r['stage']==s]):.3f}" + f"->{np.mean([agree(r['rs_ts_top1_idx_prob']) for r in rows if r['stage']==s]):.3f}" + for s in st) + print(f" {c:<8} K={K:<4} {line}") + + # ------------------------------------------------------------- MARGIN (mechanical, flagged) + print("\nMARGIN top1-vs-top2 (relative). FLAGGED AS MECHANICAL: rescoring the top-K with 4x the") + print("particles sharpens the head of the score vector BY CONSTRUCTION, so a larger ts margin is") + print("NOT independent evidence of a better pick. Printed because run 31's fork was decided on") + print("the margin and the reader should see what the tie-break did to it.") + for c in cellnames: + for K in KS: + rows = cells[(c, K)]["rows"] + for kind in ("prob",): + mc = float(np.mean([r[f"rs_ctl_margin12_rel_{kind}"] for r in rows])) + mt = float(np.mean([r[f"rs_ts_margin12_rel_{kind}"] for r in rows])) + print(f" {c:<8} K={K:<4} {kind}: ctl {mc:.4f} -> ts {mt:.4f} (x{mt/max(mc,1e-12):.2f})") + res[f"{c}_K{K}_{kind}"].update(margin_ctl=mc, margin_ts=mt) + + os.makedirs(os.path.dirname(a.out) or ".", exist_ok=True) + json.dump(res, open(a.out, "w"), indent=1) + print(f"\nwrote {a.out}") + + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/real/act_run21_primary.py b/rsm_rise/scripts/real/act_run21_primary.py new file mode 100644 index 0000000000000000000000000000000000000000..9a1a2b70cdf1425f337b6022ae7d40cd5135aa4d --- /dev/null +++ b/rsm_rise/scripts/real/act_run21_primary.py @@ -0,0 +1,155 @@ +#!/usr/bin/env python3 +"""ACT_COND run 21/24 PRIMARY READ (gen_q#278) -- the registered deployed-width table. + +This script COMPUTES NOTHING. It reads the JSON that `xl2x2_test.py` already wrote (the same +implementation that produced the run-20 XL numbers, byte-verified identical by job 1889493) and +prints the ONE row that runs 21-23 pre-registered, with the two pieces of context without which the +row has burned us before: + + * the XL reference contrast (rise@0.90 minus rise@0.99 at width 4096): +0.0358 rank pct, + -0.0684 monotone rho, +14.378 margin z (mean). TRANSFERS = the deployed-width contrast lands + within ~2x of these; HEADROOM = at or below a third. + * the ATTAINABLE MAXIMUM of every bounded statistic at the deployed-width baseline. Run 23 found + mrise@0.99 already at rank pct 0.9859, so the largest contrast rank_pct can express is +0.0141 -- + BELOW the +0.0179 TRANSFERS threshold. A small rank_pct contrast here is CENSORING, NOT + evidence for HEADROOM, and this script refuses to print the row without its ceiling. + +margin_z is unbounded above and is therefore the PRIMARY statistic at this width (registered run 23, +before the test cells existed). rank_pct and spearman are printed with `max_attainable` and a +`censored` flag beside them. +""" +import argparse, json, sys + +XL_REF = { # rise@0.90 minus rise@0.99 at width 4096 (run 20, reproduced in run 23) + "rank_pct": 0.0358, + "spearman": -0.0684, + "margin_z": 14.378, +} +TRANSFERS_FRAC = 0.5 # "within ~2x of XL" -> |contrast| >= 0.5 * |XL| +HEADROOM_FRAC = 1.0 / 3.0 # "at or below a third" +SIGN = {"rank_pct": +1, "spearman": -1, "margin_z": +1} # direction of "better" +BOUND = {"rank_pct": 1.0, "spearman": -1.0} # hard bound; margin_z has none + + +def ceiling(stem, base): + """Largest contrast the statistic can express from this baseline, in the better direction.""" + if stem not in BOUND: + return None + return BOUND[stem] - base + + +def classify(stem, obs, cap): + xl = XL_REF[stem] + frac = obs / xl if xl else float("nan") + if cap is not None and abs(cap) < abs(xl) * TRANSFERS_FRAC: + return "CENSORED (cannot reach TRANSFERS even in principle)", frac + if frac >= TRANSFERS_FRAC: + return "TRANSFERS", frac + if frac <= HEADROOM_FRAC: + return "HEADROOM", frac + return "between TRANSFERS and HEADROOM", frac + + +# --- run 25 addition, justified by ONE number --------------------------------------------------- +# The prob/margin_z row of the deployed-width read came back as +2,229,259 ("frac XL 155046, +# TRANSFERS"). It is ONE anchor: at beta=0.90 the prob read-out underflows and that anchor's +# candidate-cloud sd is 1.75e-10, so its margin_z is 4.4e8 and it alone sets the mean. The paired +# MEDIAN of the same 200 differences is +0.1434. A mean that disagrees with its own median by +# 1.6e7x is not a measurement, so this reader now prints the paired median beside the mean and +# stamps TAIL-DRIVEN over any verdict where they disagree by more than TAIL_RATIO. +TAIL_RATIO = 3.0 +PER_ANCHOR = {"rank_pct": "rank_pct_{read}", "spearman": "spearman_{read}", "margin_z": None} + + +def per_anchor_diff(cell_dir, stem, read, beta, ref_beta="99"): + """Paired per-anchor contrast (test minus ref) straight off the cell JSONs; None if unavailable.""" + import os + b = beta.replace("0.", "").rstrip(".") + fa = os.path.join(cell_dir, f"snr_beta{b}.json") + fb = os.path.join(cell_dir, f"snr_beta{ref_beta}.json") + if not (os.path.exists(fa) and os.path.exists(fb)): + return None + def vals(f): + rows = json.load(open(f))["rows"] + if stem == "margin_z": + s0 = "q0" if read == "prob" else "logit0" + return [(r[s0] - r[f"mean_a_{read}"]) / max(r[f"var_a_{read}"] ** 0.5, 1e-300) + for r in rows] + return [r[PER_ANCHOR[stem].format(read=read)] for r in rows] + va, vb = vals(fa), vals(fb) + if len(va) != len(vb): + return None + d = sorted(x - y for x, y in zip(va, vb)) + n = len(d) + return d[n // 2] if n % 2 else 0.5 * (d[n // 2 - 1] + d[n // 2]) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--src", default="status/real/ACT_COND/M2X2_raw_run21.json", + help="output of xl2x2_test.py --scale raw on the deployed-width dirs") + ap.add_argument("--arm", default="rise") + ap.add_argument("--beta", default="0.90") + ap.add_argument("--out", default="status/real/ACT_COND/PRIMARY_run21.json") + ap.add_argument("--cell-dir", default=None, + help="arm dir holding snr_beta{90,95,99}.json; enables the paired-median column") + ap.add_argument("--label", default="deployed width (1024)", + help="what family --src describes; printed verbatim in the header") + a = ap.parse_args() + + j = json.load(open(a.src)) + if j.get("scale") != "raw": + sys.exit(f"FAIL: --src was written on scale {j.get('scale')!r}; the registered levels are RAW") + rows = [w for w in j["within"] if w["arm"] == a.arm and w["beta"] == a.beta] + if not rows: + sys.exit(f"FAIL: no within-arm rows for {a.arm}@{a.beta} in {a.src}") + + print(f"PRIMARY READ -- {a.label}, {a.arm}@{a.beta} MINUS {a.arm}@0.99, same paired " + f"anchors (n={j['n']})") + print(f"scope limit: v0_provenance-reward family at {a.label}, never 'R_M'.\n") + hdr = (f"{'read':<6} {'statistic':<10} {'base(0.99)':>11} {'test(0.90)':>11} {'contrast':>10} " + f"{'bootCI95':>21} {'wilcox_p':>10} {'XL ref':>9} {'frac XL':>8} {'med d':>9} " + f"{'max att':>9} verdict") + print(hdr + "\n" + "-" * len(hdr)) + out = [] + for read in ("logit", "prob"): + for stem in ("margin_z", "rank_pct", "spearman"): # primary first + w = next((r for r in rows if r["read"] == read and r["stat"] == stem), None) + if w is None: + continue + base, test, obs = w["ref_mean_raw"], w["mean_raw"], w["dmean"] + cap = ceiling(stem, base) + verdict, frac = classify(stem, obs, cap) + censored = cap is not None and abs(cap) < abs(XL_REF[stem]) * TRANSFERS_FRAC + med = per_anchor_diff(a.cell_dir, stem, read, a.beta) if a.cell_dir else None + # the tail guard applies ONLY to unbounded statistics. rank_pct and spearman live in + # a compact interval and cannot blow up; a mean/median gap there is skew (and they + # already carry `max att`). XL prob/spearman tripped the unscoped guard at ratio 10.1 + # with both numbers inside [-1, 1], which is exactly the false positive this excludes. + tail = (stem not in BOUND and med is not None and abs(med) > 0 + and abs(obs / med) > TAIL_RATIO) + if tail: + verdict = f"TAIL-DRIVEN (mean/median={obs / med:.3g}) -- {verdict} NOT READABLE" + print(f"{read:<6} {stem:<10} {base:>11.4f} {test:>11.4f} {obs:>10.4f} " + f"[{w['boot_lo']:>9.4f},{w['boot_hi']:>9.4f}] {w['wilcoxon_p']:>10.2e} " + f"{XL_REF[stem]:>9.4f} {frac:>8.2f} " + f"{('%9.4f' % med) if med is not None else ' n/a'} " + f"{('%9.4f' % cap) if cap is not None else ' none'} {verdict}") + out.append({"read": read, "stat": stem, "base": base, "test": test, "contrast": obs, + "boot_lo": w["boot_lo"], "boot_hi": w["boot_hi"], + "wilcoxon_p": w["wilcoxon_p"], "paired_verdict": w["verdict"], + "xl_ref": XL_REF[stem], "frac_of_xl": frac, + "max_attainable": cap, "censored": bool(censored), + "paired_median_contrast": med, "tail_driven": bool(tail), + "transfers_verdict": verdict}) + print("\nPRIMARY = margin_z (unbounded above). rank_pct and spearman are read ONLY beside " + "'max att';\nwhere 'max att' is smaller than half the XL reference the row is CENSORED and " + "carries NO\nevidence either way -- it is not a null. A row stamped TAIL-DRIVEN has a mean that " + f"disagrees with\nits own paired median by more than {TAIL_RATIO}x and carries no verdict at all.") + json.dump({"src": a.src, "label": a.label, "arm": a.arm, "beta": a.beta, "n": j["n"], + "xl_ref": XL_REF, "rows": out}, open(a.out, "w"), indent=1) + print(f"\nwrote {a.out}") + + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/real/act_sensitivity.py b/rsm_rise/scripts/real/act_sensitivity.py new file mode 100644 index 0000000000000000000000000000000000000000..696da967f732b75214daefd8b680d6f7cee343e1 --- /dev/null +++ b/rsm_rise/scripts/real/act_sensitivity.py @@ -0,0 +1,498 @@ +"""ACT_COND Task 2 (gen_q#278): HOW MUCH of the successor's score is action-driven? + +The owner asked for sensitivity, not for a rank: "All we need is for the network to be sensitive enough +to action to pick actions leading to goal state." A rank number alone cannot answer that -- a value that +is 99% state and 1% action can still rank correctly at an easy anchor and be useless in the loop. + +Per anchor (a real TRAIN-split frame, stage-labelled), ONE score() call carries three populations so the +particle noise is common (CRN) across all of them and the comparison is paired: + + ACTION-SENSITIVITY INDEX asi = Var_a q(x0, a_j) / Var_s q(x_i, a0) + numerator : 128 stage-matched LOGGED candidate chunks at the anchor's FIXED state + denominator : the anchor's own LOGGED chunk at 128 stage-matched OTHER states + Near zero => the value is a state function and cannot rank actions (the COLLAPSE_ANALYSIS failure + mode, and exactly what the RISE/IQL critic did in sim: Q(s,a) ~ V(s), rank-pct ~0.5). + TIE STRUCTURE fraction of the 128 candidates tied at the max (rel tol) and the CV of the + scores, reported BESIDE every rank number: the prob read-out saturates on this corpus and a rank + without its tie count has burned this project before. + MONOTONE PROBE a(lam) = (1-lam) a_logged + lam a_failure, lam over 10 steps at the same + state. q should FALL monotonically; Spearman(lam, q) is the cheapest direct test that the net is + sensitive in the right DIRECTION and not merely sensitive. + READ-OUT prob and logit come out of the same call (`.last_q` / `.last_q_logit`), so + every number above is reported under both. There is no general read-out rule. + +Sharding: --shard i --n-shard k splits the anchor list, one payload per GPU of a packed job. +""" +import argparse, json, os, sys, collections, time +import numpy as np + +ROOT = "/proj/dmfexp/zwhong/rsm_rise" +sys.path.insert(0, f"{ROOT}/scripts/real") +GOAL_PATH = "2->3->4" +FAIL_PATHS = ("0->5", "0->2->6") + + +def spearman(x, y): + def rank(v): + o = np.argsort(v, kind="mergesort"); r = np.empty(len(v), float); r[o] = np.arange(len(v)) + # average ties + s = np.sort(v); i = 0 + while i < len(v): + j = i + while j + 1 < len(v) and s[j + 1] == s[i]: + j += 1 + if j > i: + r[o[i:j + 1]] = np.arange(i, j + 1).mean() + i = j + 1 + return r + rx, ry = rank(np.asarray(x, float)), rank(np.asarray(y, float)) + if rx.std() < 1e-12 or ry.std() < 1e-12: + return 0.0 + return float(np.corrcoef(rx, ry)[0, 1]) + + +def tie_stats(s, rtol=1e-9): + s = np.asarray(s, np.float64) + mx = s.max() + scale = max(abs(mx), 1e-30) + tied = int((s >= mx - rtol * scale).sum()) + mu = s.mean() + cv = float(s.std() / abs(mu)) if abs(mu) > 1e-30 else float("nan") + return tied / len(s), cv + + +def margin_stats(s): + """Top1-minus-top2 margin of a candidate cloud, absolute and scale-free. + + WHY (run 30, gen_q#278). `tie_stats` counts EXACT ties and is measured CONSTANT at 1/128 on + all 800 anchors of all four run-27 cells, both read-outs -- so the stream's mandated tie + statistic carries ZERO information about whether the executed pick is stable. Run 29 measured + that the argmax moves on 43.2% of anchors at the deployed cell while `rep_spearman` stays + 0.98, and diagnosed NEAR-ties at the top of the cloud; nothing in the instrument could see a + near-tie. This is that field. `rel` divides by the cloud's own spread, so it is comparable + ACROSS checkpoints and read-outs (prob and logit live on wildly different scales) -- which is + exactly where run 30 found the raw spread statistics stop transferring. + ADDITIVE: computed from arrays already in hand, no rng consumed, no extra forward pass. + """ + s = np.asarray(s, np.float64) + o = np.sort(s) + m12 = float(o[-1] - o[-2]) + sd = float(s.std()) + return m12, (m12 / sd if sd > 1e-30 else float("nan")) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--hdf5", default=f"{ROOT}/data/raw/cooking_v5_expert_suboptimal.hdf5") + ap.add_argument("--split", default=f"{ROOT}/data/derived/cooking_v5_split.json") + ap.add_argument("--cache", default=f"{ROOT}/cache/real_cooking_v5") + ap.add_argument("--ckpt", default=f"{ROOT}/runs/real_cooking_v5/rsm/R_M/ckpt_s100000.pt") + ap.add_argument("--hop-ckpt", default=f"{ROOT}/runs/real_cooking_v5/hop/gauss/policy_r1.pt") + ap.add_argument("--mode", default="chain") + ap.add_argument("--beta", type=float, default=0.99) + ap.add_argument("--gamma", type=float, default=0.999) + ap.add_argument("--particles", type=int, default=16) + ap.add_argument("--temperature", type=float, default=25.0) + # CHAIN-LENGTH LEVER (gen_q#278 carry-forward). 0 = the legitimate cap, computed from + # (beta, gamma) by chain_cap() so P(N>cap)<=1e-3. A non-zero override TRUNCATES the walk: + # it is a different (biased-short) estimator, not a cheaper one, and is used here ONLY to + # measure how chain length dilutes action sensitivity -- never to tune a success number. + ap.add_argument("--chain-cap", type=int, default=0) + ap.add_argument("--n-cand", type=int, default=128) + ap.add_argument("--n-state", type=int, default=128) + ap.add_argument("--n-interp", type=int, default=10) + ap.add_argument("--horizon", type=int, default=8) + ap.add_argument("--stride", type=int, default=25) + ap.add_argument("--max-anchors", type=int, default=240) + ap.add_argument("--anchor-routes", default="all", choices=["all", "goal"], + help="which episodes anchors come from. The goal route 2->3->4 never visits S0/S1, " + "so `goal` can only report S2/S3; the sensitivity index is a property of the " + "VALUE AT A STATE and is well defined at a failure-route anchor too, so `all` " + "is the default and the anchor's route is recorded on every row.") + ap.add_argument("--shard", type=int, default=0) + ap.add_argument("--n-shard", type=int, default=1) + ap.add_argument("--seed", type=int, default=0) + ap.add_argument("--repeats", type=int, default=1, + help="independent PARTICLE draws of the SAME score() call per anchor. 1 (default) " + "is the historical behaviour and is byte-identical: repeat 0 always uses the " + "historical seed and every headline stat is taken from repeat 0. >1 adds the " + "read-out NOISE FLOOR -- between-candidate spread vs across-draw spread (SNR) " + "and top-1 agreement. ASI is signal/signal and says nothing about whether the " + "spread survives the estimator noise; SNR is the quantity that decides whether " + "the read-out can actually PICK an action.") + ap.add_argument("--rescore-top", type=int, default=0, + help="run 31: TWO-STAGE TIE-BREAK. Score all n_cand candidates with --particles, " + "keep the top-K by q_logit, rescore ONLY those with --rescore-particles. 0 " + "(default) is OFF and the whole block is skipped, so every cell measured " + "before this flag existed is byte-identical. Motivated by run 31: the " + "near-tie margin predicts pick instability better than any spread statistic " + "and transfers to the held-out checkpoint, while a UNIFORM 4x particle budget " + "buys only +6.7 points of top-1 agreement.") + ap.add_argument("--rescore-particles", type=int, default=0, + help="M in the two-stage tie-break; needs --rescore-top.") + ap.add_argument("--out", required=True) + a = ap.parse_args() + if bool(a.rescore_top) != bool(a.rescore_particles): + sys.exit("--rescore-top and --rescore-particles must be given together") + t0 = time.time() + import h5py, torch + from twin_rollout import Scorer + rng = np.random.default_rng(a.seed) + os.makedirs(os.path.dirname(a.out) or ".", exist_ok=True) + + split = json.load(open(a.split))["episodes"] + meta = np.load(f"{a.cache}/meta.npz", allow_pickle=True) + ep_from, ep_to = np.asarray(meta["ep_from"]), np.asarray(meta["ep_to"]) + zf = np.load(f"{a.cache}/z.f16.npy", mmap_mode="r") + pf = np.load(f"{a.cache}/proprio.f32.npy", mmap_mode="r") + st = np.load(f"{a.cache}/feat_stats.npz") + dd = int(zf.shape[1] + pf.shape[1]) + mu, sd = st["mu"][:dd].astype(np.float32), st["sd"][:dd].astype(np.float32) + zclip = float(st["z_clip"]) if "z_clip" in st.files else 10.0 + + f = h5py.File(a.hdf5, "r"); d = f["data"] + lo = np.array(json.loads(d.attrs["action_min"]), np.float32) + hi = np.array(json.loads(d.attrs["action_max"]), np.float32) + spl = lambda k: split.get(str(int(k.split("_")[1])), {}).get("split", "") + path = lambda k: str(d[k].attrs.get("path", "")) + train = [k for k in d if spl(k) == "train"] + + # ---- pools, keyed by stage: logged chunks (all train routes), states (train), failure chunks ---- + chunk_pool = collections.defaultdict(list) # stage -> [H,10] chunks + state_pool = collections.defaultdict(list) # stage -> global cache index + fail_pool = collections.defaultdict(list) + anchors = [] # (ep, t, stage) on TRAIN goal-route episodes + for k in train: + g = d[k]; ep = int(k.split("_")[1]) + A = np.asarray((g["actions_raw"] if "actions_raw" in g else g["actions"])[()], np.float32) + stg = np.asarray(g["annot"]["edge_from"][()]) + for t in range(0, len(A) - a.horizon, a.stride): + s0 = int(stg[t]); ch = A[t:t + a.horizon] + chunk_pool[s0].append(ch) + state_pool[s0].append(int(ep_from[ep] + t)) + if path(k) in FAIL_PATHS: + fail_pool[s0].append(ch) + if a.anchor_routes == "all" or path(k) == GOAL_PATH: + anchors.append((ep, t, s0, path(k))) + print(f"[sens] train eps {len(train)}; anchors({a.anchor_routes}) {len(anchors)} " + f"{dict(collections.Counter(f'S{x[2]}' for x in anchors))}; " + f"pool per stage {{{', '.join(f'S{s}:{len(v)}' for s, v in sorted(chunk_pool.items()))}}}; " + f"fail pool {{{', '.join(f'S{s}:{len(v)}' for s, v in sorted(fail_pool.items()))}}}", flush=True) + # STRATIFY BY STAGE. The corpus spends most of its frames in S0/S2, so a uniform draw would put + # ~10 anchors in S3 and the per-stage row for it would be noise. Equal quota per stage, the + # leftover redistributed to the stages that still have anchors. + by_stage = collections.defaultdict(list) + for x in anchors: + by_stage[x[2]].append(x) + if len(anchors) > a.max_anchors: + stages = sorted(by_stage) + quota = {s: a.max_anchors // len(stages) for s in stages} + left = a.max_anchors - sum(min(quota[s], len(by_stage[s])) for s in stages) + for s in sorted(stages, key=lambda s: -len(by_stage[s])): + take = min(left, max(0, len(by_stage[s]) - quota[s])) + quota[s] += take; left -= take + picked = [] + for s in stages: + v = by_stage[s]; n = min(quota[s], len(v)) + picked += [v[i] for i in sorted(rng.choice(len(v), size=n, replace=False))] + anchors = sorted(picked, key=lambda x: (x[0], x[1])) + print(f"[sens] after stratification: {dict(collections.Counter(f'S{x[2]}' for x in anchors))}", flush=True) + anchors = anchors[a.shard::a.n_shard] + print(f"[sens] shard {a.shard}/{a.n_shard}: {len(anchors)} anchors", flush=True) + + sc = Scorer("rsm", lo, hi, rsm_ckpt=a.ckpt, seed=a.seed, rsm_mode=a.mode, rsm_beta=a.beta, + rsm_gamma=a.gamma, rsm_particles=a.particles, rsm_dim=dd, + rsm_temperature=a.temperature, rsm_hop_ckpt=a.hop_ckpt) + if a.chain_cap: + # THE OVERRIDE LIVES ON THE BACKEND, NOT THE SCORER. RSMScorer.score() delegates to + # self.backend.q(...), and it is MLPBackend._q that reads getattr(self,"chain_cap_override"). + # Setting it on the RSMScorer is a SILENT no-op: cap 2, cap 9 and the default cap 67 then + # return bit-identical q (measured, 2026-09-23). Asserted below against the realized cap. + sc.rsm.backend.chain_cap_override = int(a.chain_cap) + print(f"[sens] CHAIN CAP OVERRIDE = {a.chain_cap} on {type(sc.rsm.backend).__name__} " + f"(truncated estimator)", flush=True) + rsm = sc.rsm; dev = rsm.device + + def feat(gi): + z = np.concatenate([np.asarray(zf[gi], np.float32), np.asarray(pf[gi], np.float32)]) + return np.clip((z - mu) / sd, -zclip, zclip).astype(np.float32) + + NC, NS, NI = a.n_cand, a.n_state, a.n_interp + # MONOTONE-PROBE TARGET. The failure routes (0->5, 0->2->6) never enter stages 1 and 3, so a + # same-stage failure chunk does not exist there. Dropping those anchors would have left the whole + # measurement on S2 (which is what the first launch did: 33 of 80 anchors, S2 only). Fall back, + # in order, to a failure chunk from ANOTHER stage, then to any other-stage logged chunk -- both are + # still "an action this state should not take" -- and record WHICH source each anchor used so the + # Spearman is aggregated per source and no fallback is silently mixed into the headline. + fail_stages = [s for s, v in fail_pool.items() if v] + def probe_target(s0): + if fail_pool[s0]: + return fail_pool[s0][int(rng.integers(len(fail_pool[s0])))], "failure_same_stage" + if fail_stages: + sp = fail_stages[int(rng.integers(len(fail_stages)))] + return fail_pool[sp][int(rng.integers(len(fail_pool[sp])))], "failure_other_stage" + others = [s for s, v in chunk_pool.items() if s != s0 and v] + sp = others[int(rng.integers(len(others)))] + return chunk_pool[sp][int(rng.integers(len(chunk_pool[sp])))], "offstage" + rows = [] + skipped = collections.Counter() + for ai, (ep, t, s0, route) in enumerate(anchors): + if len(chunk_pool[s0]) < NC or len(state_pool[s0]) < NS + 1: + skipped[f"S{s0}:pool<{NC}"] += 1 + continue + gi = int(ep_from[ep] + t) + x0 = feat(gi) + g = d[f"demo_{ep}"] + a0 = np.asarray((g["actions_raw"] if "actions_raw" in g else g["actions"])[t:t + a.horizon], np.float32) + ci = rng.choice(len(chunk_pool[s0]), size=NC, replace=False) + cands = np.stack([chunk_pool[s0][i] for i in ci]) # [NC,H,10] + si = [j for j in rng.permutation(len(state_pool[s0])) if state_pool[s0][j] != gi][:NS] + states = np.stack([feat(state_pool[s0][j]) for j in si]) # [NS,D] + af, probe_src = probe_target(s0) + lam = np.linspace(0.0, 1.0, NI, dtype=np.float32) + interp = np.stack([(1 - l) * a0 + l * af for l in lam]) # [NI,H,10] + # one call: [128 cands @ x0 | a0 @ 128 states | 10 interpolants @ x0 | a0 @ x0] + X = np.concatenate([np.repeat(x0[None], NC, 0), states, + np.repeat(x0[None], NI + 1, 0)], 0) + A = np.concatenate([cands, np.repeat(a0[None], NS, 0), interp, a0[None]], 0) + # REPEATS = independent particle draws of the same call. Repeat 0 keeps the historical + # seed, so --repeats 1 is byte-identical to every cell measured before this flag existed and + # --repeats R leaves every headline stat below (which reads q/ql = repeat 0) comparable to them. + q_rep, l_rep = [], [] + for rep in range(max(1, a.repeats)): + with torch.no_grad(): + rsm.score(torch.as_tensor(X, dtype=torch.float32, device=dev), A, + seed=a.seed + 7919 * (ai + 1) + 104729 * rep) + cs = getattr(rsm, "chain_hop_acc", None) or {} + qr = rsm.last_q.double().cpu().numpy() + lr = rsm.last_q_logit + lr = np.full_like(qr, np.nan) if lr is None else lr.double().cpu().numpy() + q_rep.append(qr); l_rep.append(lr) + q, ql = q_rep[0], l_rep[0] + qa, qs, qi, q00 = q[:NC], q[NC:NC + NS], q[NC + NS:NC + NS + NI], q[-1] + la, ls, li, l00 = ql[:NC], ql[NC:NC + NS], ql[NC + NS:NC + NS + NI], ql[-1] + r = {"ep": ep, "t": t, "stage": s0, "route": route, "probe_src": probe_src, + "q0": float(q00), "logit0": float(l00), + "var_a_prob": float(qa.var()), "var_s_prob": float(qs.var()), + "var_a_logit": float(la.var()), "var_s_logit": float(ls.var()), + "mean_a_prob": float(qa.mean()), "mean_s_prob": float(qs.mean()), + "mean_a_logit": float(la.mean()), "mean_s_logit": float(ls.mean()), + "spearman_prob": spearman(lam, qi), "spearman_logit": spearman(lam, li), + "interp_drop_prob": float(qi[0] - qi[-1]), "interp_drop_logit": float(li[0] - li[-1]), + "rank_pct_prob": float((qa < q00).mean()), "rank_pct_logit": float((la < l00).mean())} + r["tie_frac_prob"], r["cv_prob"] = tie_stats(qa) + r["tie_frac_logit"], r["cv_logit"] = tie_stats(la) + # NEAR-TIE MARGIN (run 30). Single-draw (repeat 0), so a closed-loop scorer has these in + # hand at zero extra cost -- the pre-registered candidate for an ADAPTIVE particle budget. + r["margin12_prob"], r["margin12_rel_prob"] = margin_stats(qa) + r["margin12_logit"], r["margin12_rel_logit"] = margin_stats(la) + r["asi_prob"] = r["var_a_prob"] / max(r["var_s_prob"], 1e-30) + r["asi_logit"] = r["var_a_logit"] / max(r["var_s_logit"], 1e-30) + # ---- READ-OUT CROSS-PICK (run 27, gen_q#278). ADDITIVE ONLY: computed from `qa`/`la`, the + # SAME 128 candidate scores of the SAME score() call (prob = rsm.last_q, logit = + # rsm.last_q_logit), so it consumes no rng, issues no extra forward pass, and cannot move any + # field above. WHY IT EXISTS: runs 25/26 recommended switching the deployed read-out from + # `prob` to `logit` on RANK statistics of the LOGGED chunk. The closed loop does not execute + # the logged chunk -- it executes argmax over the candidate cloud. A read-out switch is only + # a closed-loop change to the extent the two ARGMAXES DIFFER, and that number was never + # measured. `xpick_agree` is it; the two cross-ranks say how bad the loser is under the + # winner's own metric when they do differ (1.0 = the loser was the winner's top choice too). + if np.all(np.isfinite(la)) and np.all(np.isfinite(qa)): + ip, il = int(np.argmax(qa)), int(np.argmax(la)) + r["xpick_prob_idx"], r["xpick_logit_idx"] = ip, il + r["xpick_agree"] = float(ip == il) + # rank pct of EACH read-out's pick under the OTHER read-out's scores (strict-less, the + # same convention as rank_pct_* above so the two columns are directly comparable). + r["xpick_probpick_rank_under_logit"] = float((la < la[ip]).mean()) + r["xpick_logitpick_rank_under_prob"] = float((qa < qa[il]).mean()) + # whole-ordering agreement of the two read-outs over the candidate cloud. If this is + # ~1.0 the read-out is a monotone relabelling here and the switch is a closed-loop no-op. + r["xpick_spearman_cand"] = spearman(qa, la) + else: + r["xpick_agree"] = float("nan") + # NOISE FLOOR. ASI is var(candidates)/var(states) -- a ratio of two SIGNALS, so it is blind + # to a regime where both collapse into the estimator noise. With R independent particle + # draws of the same 128 candidates at the same state: signal = var ACROSS candidates of the + # per-candidate mean over draws; noise = mean ACROSS candidates of the var over draws. + # top1_agree is the decision-level version: does the read-out pick the SAME action twice? + if len(q_rep) > 1: + for nm, reps in (("prob", q_rep), ("logit", l_rep)): + M = np.stack([z[:NC] for z in reps]) # [R, NC], candidates only + sig = float(M.mean(0).var()) + noi = float(M.var(0, ddof=1).mean()) + pairs = [(i, j) for i in range(len(M)) for j in range(i + 1, len(M))] + top1 = [int(np.argmax(z)) for z in M] + # ROBUST DENOMINATOR (run 10). `noi` is the MEAN over candidates of the + # per-candidate variance across draws. Under `logit` the scores are unbounded + # (q_logit = mean_i logit_i; the reward head reaches logits ~ +121, rsm_scorer.py:33), + # so a few extreme candidates can set both sig and noi -- which is exactly the regime + # where the measured logit SNRcorr was 0.03 while the rank correlation between draws + # was +0.998. The median denominator says whether that is heteroscedasticity or a + # genuinely flat field. Additive only: it consumes no rng and changes no other field. + r[f"noise_var_med_{nm}"] = float(np.median(M.var(0, ddof=1))) + r[f"snr_robust_{nm}"] = sig / max(r[f"noise_var_med_{nm}"], 1e-30) + r[f"sig_var_{nm}"], r[f"noise_var_{nm}"] = sig, noi + r[f"snr_{nm}"] = sig / max(noi, 1e-30) + r[f"top1_agree_{nm}"] = float(np.mean([top1[i] == top1[j] for i, j in pairs])) + # run 30: the margin of EACH draw, so "did the margin predict the disagreement" + # can be asked without draw 0 (the strict hold-out: predictor from draw 0, outcome + # from draws 1.. only). Read off M, no rng, no extra forward pass. + r[f"margin12_rel_draws_{nm}"] = [margin_stats(z)[1] for z in M] + r[f"rep_spearman_{nm}"] = float(np.mean([spearman(M[i], M[j]) for i, j in pairs])) + # ---- MC PICK INSTABILITY (run 29, gen_q#278). ADDITIVE ONLY: read off `M`, the + # repeat scores already stacked above -- no extra forward pass, no rng consumed. + # WHY: run 28 showed the prob->logit switch moves the executed pick on 23.5% of + # anchors at the deployed cell. `top1_agree_{nm}` is the SAME quantity with the + # OTHER factor varied (redraw the particles, hold the read-out), and it is LOWER. + # To compare the two on distance as well as on rate, act_pickdist needs the indices, + # so store them. `top1_agree_half_{nm}` is the deployable question: does AVERAGING + # draws stabilise the pick? Two disjoint half-averages of floor(R/2) draws each are + # two independent picks at an effective 2x particle budget, so it predicts the + # particle curve this run measures directly. NaN for R < 4 (no disjoint halves). + r[f"top1_idx_{nm}"] = [int(v) for v in top1] + h = len(M) // 2 + r[f"top1_agree_half_{nm}"] = ( + float(int(np.argmax(M[:h].mean(0))) == int(np.argmax(M[h:2 * h].mean(0)))) + if len(M) >= 4 else float("nan")) + r[f"top1_half_idx_{nm}"] = ([int(np.argmax(M[:h].mean(0))), int(np.argmax(M[h:2 * h].mean(0)))] + if len(M) >= 4 else None) + # realized walk length: the x-axis of the dilution curve must be ACTUAL hops, not the + # nominal cap (the coin usually stops long before a loose cap binds). + for k in ("cap", "p_cont", "E_hops_expected"): + if cs.get(k) is not None: + r[f"chain_{k}"] = float(cs[k]) + if cs.get("decisions"): + r["chain_hops_mean"] = float(cs["hops_sum"]) / float(cs["decisions"]) + r["chain_capped_frac"] = float(cs["capped_sum"]) / float(cs["decisions"]) + # FAIL LOUD: a requested cap that does not reach the walk is the exact silent bug this + # sweep was built to avoid measuring through. + if a.chain_cap and r.get("chain_cap") is not None and int(r["chain_cap"]) != int(a.chain_cap): + raise RuntimeError(f"chain cap override NOT APPLIED: requested {a.chain_cap}, " + f"walk ran at cap {r['chain_cap']}") + # ---- TWO-STAGE TIE-BREAK (run 31, gen_q#278). + # PLACED HERE, AFTER the chain-stat section, DELIBERATELY: `cs` above is a live REFERENCE to + # rsm.chain_hop_acc, a cumulative accumulator mutated in place by every score() call, so a + # block of extra calls placed before it would silently inflate chain_hops_mean / + # chain_capped_frac for rescore cells only. (That accumulator is also what made run 30's + # "[CAP ALARM] capped_frac=0.0312" a false alarm -- it fired on a 32-decision prefix.) + # ENTIRELY SKIPPED unless --rescore-top, so + # every cell measured before this flag is byte-identical: the block below issues its own + # score() calls with their OWN seeds, and RSMScorer builds a fresh generator per seed + # (dwm_readout.q: `self._gen(crn_seed)`), so it consumes no rng from the loop above. + # + # THE TRAP, and the reason this cannot reuse the call above: `rescore_top` takes the top-K of + # the WHOLE input array (dwm_readout.py:180-183, `torch.topk(ql, K)` over all rows). The + # packed call above carries NC candidates + NS STATES + NI interpolants + 1 = 267 rows, so a + # rescore on it would rank candidates against STATES and spend the big budget on whichever + # mixture scored high. The tie-break has to see the 128 candidates ALONE, hence its own call. + # + # PAIRED CONTROL, same batch shape and the SAME seed: `ctl` is the identical candidates-only + # call with the tie-break OFF. Stage 1 is therefore bit-identical between ctl and two-stage + # and the ONLY difference is the top-K rescore -- so a change in pick stability is attributable + # to the tie-break and not to the batch shape. Comparing against the 267-row call instead + # would confound the two. + if a.rescore_top: + Xc = np.repeat(x0[None], NC, 0) + for tag, K, M in (("ctl", 0, 0), ("ts", int(a.rescore_top), int(a.rescore_particles))): + rq, rl = [], [] + for rep in range(max(1, a.repeats)): + with torch.no_grad(): + rsm.score(torch.as_tensor(Xc, dtype=torch.float32, device=dev), cands, + seed=a.seed + 31337 + 7919 * (ai + 1) + 104729 * rep, + rescore_top=K, n_particles_rescore=M) + qq = rsm.last_q.double().cpu().numpy() + ll = rsm.last_q_logit + ll = np.full_like(qq, np.nan) if ll is None else ll.double().cpu().numpy() + rq.append(qq); rl.append(ll) + for nm, S in (("prob", np.stack(rq)), ("logit", np.stack(rl))): + r[f"rs_{tag}_top1_idx_{nm}"] = [int(np.argmax(v)) for v in S] + r[f"rs_{tag}_margin12_{nm}"], r[f"rs_{tag}_margin12_rel_{nm}"] = margin_stats(S[0]) + # COST, recorded per anchor so the curve is read against compute and not against K: + # stage 1 is NC*particles particle-evals, the rescore adds K*M. + r["rs_cost_ctl"] = float(NC * a.particles) + r["rs_cost_ts"] = float(NC * a.particles + a.rescore_top * a.rescore_particles) + rows.append(r) + if ai == 0 or len(rows) % 10 == 0: + print(f" [{len(rows)}] ep{ep} t{t} S{s0} asi_logit={r['asi_logit']:.3f} " + f"asi_prob={r['asi_prob']:.3f} rho_logit={r['spearman_logit']:+.2f} " + f"ties_prob={r['tie_frac_prob']*NC:.0f}/{NC} ({time.time()-t0:.0f}s)", flush=True) + + out = {"args": vars(a), "n_anchors": len(rows), "rows": rows, + "host": os.uname().nodename, "seconds": time.time() - t0} + # aggregate, per stage and pooled. The index is a RATIO, so the pooled number is the ratio of the + # pooled variances, not the mean of per-anchor ratios; both are reported (the mean of ratios is + # dominated by anchors with a near-zero state variance). + def agg(sub): + if not sub: + return {} + z = {} + for kind in ("prob", "logit"): + va = np.array([r[f"var_a_{kind}"] for r in sub]); vs = np.array([r[f"var_s_{kind}"] for r in sub]) + asi = np.array([r[f"asi_{kind}"] for r in sub]) + z[kind] = {"n": len(sub), + "asi_pooled": float(va.mean() / max(vs.mean(), 1e-30)), + "asi_median": float(np.median(asi)), "asi_mean": float(asi.mean()), + "var_a_mean": float(va.mean()), "var_s_mean": float(vs.mean()), + "spearman_mean": float(np.mean([r[f"spearman_{kind}"] for r in sub])), + "spearman_frac_neg1": float(np.mean([r[f"spearman_{kind}"] <= -0.99 for r in sub])), + "spearman_by_probe_src": { + src: {"n": sum(1 for r in sub if r["probe_src"] == src), + "mean": float(np.mean([r[f"spearman_{kind}"] for r in sub + if r["probe_src"] == src]))} + for src in sorted({r["probe_src"] for r in sub})}, + "interp_drop_mean": float(np.mean([r[f"interp_drop_{kind}"] for r in sub])), + "tie_frac_mean": float(np.mean([r[f"tie_frac_{kind}"] for r in sub])), + "cv_mean": float(np.nanmean([r[f"cv_{kind}"] for r in sub])), + "rank_pct_mean": float(np.mean([r[f"rank_pct_{kind}"] for r in sub])), + "rank_pct_mean_goal_route": ( + float(np.mean([r[f"rank_pct_{kind}"] for r in sub if r["route"] == GOAL_PATH])) + if any(r["route"] == GOAL_PATH for r in sub) else None), + "n_goal_route": sum(1 for r in sub if r["route"] == GOAL_PATH)} + if all(f"snr_{kind}" in r for r in sub): + sg = np.array([r[f"sig_var_{kind}"] for r in sub]) + nz = np.array([r[f"noise_var_{kind}"] for r in sub]) + z[kind].update({ + # pooled like ASI: ratio of the pooled variances, not the mean of the ratios. + "snr_pooled": float(sg.mean() / max(nz.mean(), 1e-30)), + "snr_median": float(np.median([r[f"snr_{kind}"] for r in sub])), + "sig_var_mean": float(sg.mean()), "noise_var_mean": float(nz.mean()), + "top1_agree_mean": float(np.mean([r[f"top1_agree_{kind}"] for r in sub])), + "top1_agree_half_mean": ( + float(np.mean([r[f"top1_agree_half_{kind}"] for r in sub])) + if all(f"top1_agree_half_{kind}" in r for r in sub) + and np.all(np.isfinite([r[f"top1_agree_half_{kind}"] for r in sub])) else None), + "rep_spearman_mean": float(np.mean([r[f"rep_spearman_{kind}"] for r in sub]))}) + return z + out["by_stage"] = {f"S{s}": agg([r for r in rows if r["stage"] == s]) + for s in sorted({r["stage"] for r in rows})} + out["pooled"] = agg(rows) + out["skipped"] = dict(skipped) + hm = [r["chain_hops_mean"] for r in rows if "chain_hops_mean" in r] + if hm: + out["chain"] = {"hops_mean": float(np.mean(hm)), "hops_min": float(np.min(hm)), + "hops_max": float(np.max(hm)), + "cap": rows[0].get("chain_cap"), "p_cont": rows[0].get("chain_p_cont"), + "capped_frac_mean": float(np.mean([r.get("chain_capped_frac", 0.0) for r in rows]))} + print(f"[sens] realized chain: {out['chain']}", flush=True) + out["probe_src_counts"] = dict(collections.Counter(r["probe_src"] for r in rows)) + print(f"[sens] skipped {dict(skipped)}; probe sources {out['probe_src_counts']}", flush=True) + json.dump(out, open(a.out, "w"), indent=1) + print(f"\n{'scope':>8}{'read':>7}{'n':>5}{'asi_pool':>10}{'asi_med':>9}{'var_a':>11}{'var_s':>11}" + f"{'rho':>7}{'rho=-1':>8}{'ties/128':>10}{'cv':>10}{'rankpct':>9}") + for scope, z in list(out["by_stage"].items()) + [("POOLED", out["pooled"])]: + for kind in ("prob", "logit"): + if kind not in z: + continue + v = z[kind] + print(f"{scope:>8}{kind:>7}{v['n']:>5}{v['asi_pooled']:>10.3f}{v['asi_median']:>9.3f}" + f"{v['var_a_mean']:>11.3e}{v['var_s_mean']:>11.3e}{v['spearman_mean']:>7.2f}" + f"{v['spearman_frac_neg1']:>8.2f}{v['tie_frac_mean']*a.n_cand:>10.1f}" + f"{v['cv_mean']:>10.2e}{v['rank_pct_mean']:>9.3f}" + + (f" snr={v['snr_pooled']:8.3f} top1={v['top1_agree_mean']:.3f} " + f"reprho={v['rep_spearman_mean']:+.3f}" if "snr_pooled" in v else "")) + print(f"\nwrote {a.out} ({len(rows)} anchors, {time.time()-t0:.0f}s)", flush=True) + f.close() + + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/real/act_xpick_read.py b/rsm_rise/scripts/real/act_xpick_read.py new file mode 100644 index 0000000000000000000000000000000000000000..5e557bc320a6da8b5191f7d6f4718bc571dc898a --- /dev/null +++ b/rsm_rise/scripts/real/act_xpick_read.py @@ -0,0 +1,162 @@ +#!/usr/bin/env python3 +"""ACT_COND run 27 (gen_q#278) -- READ the read-out cross-pick cells. Computes nothing on the model. + +WHY. Runs 25/26 recommended switching the deployed read-out from `prob` to `logit`, on rank +statistics of the LOGGED chunk, replicated on four checkpoints. The closed loop does not execute +the logged chunk; it executes argmax over the candidate cloud. So the switch is a closed-loop +change ONLY to the extent the two ARGMAXES DIFFER. This reads that number. + +It also runs a REGRESSION CHECK: the run-27 cells re-run the run-21/run-14 beta=0.99 cells with +byte-identical arguments and a purely additive patch, so every PRE-EXISTING field must reproduce. +A mismatch means the additive patch was not additive, and this script exits non-zero. +""" +import argparse, json, math, os, sys + +def load(p): + with open(p) as f: + return json.load(f) + +def mean(v): + return float(sum(v) / len(v)) if v else float("nan") + +def median(v): + if not v: + return float("nan") + s = sorted(v); n = len(s) + return float(s[n // 2] if n % 2 else 0.5 * (s[n // 2 - 1] + s[n // 2])) + +def wilson(k, n, z=1.96): + """Binomial CI. argmax agreement is a PROPORTION and at k=n the normal interval is [1,1], + which would read as certainty off 200 anchors; Wilson keeps an honest lower bound.""" + if n == 0: + return (float("nan"), float("nan")) + p = k / n + d = 1 + z * z / n + c = (p + z * z / (2 * n)) / d + h = z * math.sqrt(max(p * (1 - p) / n + z * z / (4 * n * n), 0.0)) / d + return (max(0.0, c - h), min(1.0, c + h)) + +NEW = ("xpick_prob_idx", "xpick_logit_idx", "xpick_agree", + "xpick_probpick_rank_under_logit", "xpick_logitpick_rank_under_prob", + "xpick_spearman_cand") + +def regress(new_rows, ref_rows, tol): + """Every field the reference already had must reproduce. Anchors are matched on (ep,t).""" + ref = {(r["ep"], r["t"]): r for r in ref_rows} + bad, worst, nfield = [], 0.0, 0 + for r in new_rows: + k = (r["ep"], r["t"]) + if k not in ref: + bad.append(f"anchor {k} absent from reference"); continue + for f, v in ref[k].items(): + if f in NEW: + continue + w = r.get(f, "") + nfield += 1 + if isinstance(v, float) and isinstance(w, float): + if math.isnan(v) and math.isnan(w): + continue + d = abs(v - w) + rel = d / max(abs(v), 1e-30) + worst = max(worst, rel) + if d > tol and rel > tol: + bad.append(f"{k}.{f}: ref={v!r} new={w!r}") + elif v != w: + bad.append(f"{k}.{f}: ref={v!r} new={w!r}") + return bad, worst, nfield + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--dir", default="/proj/dmfexp/zwhong/rsm_rise/status/real/ACT_COND") + ap.add_argument("--cells", default="mrise,mnt,xlrise,xlnt") + ap.add_argument("--tol", type=float, default=1e-9) + ap.add_argument("--out", default="") + a = ap.parse_args() + + tags = [t for t in a.cells.split(",") if t] + missing = [t for t in tags if not os.path.exists(f"{a.dir}/xpick/xpick_{t}.json")] + if missing: + print("MISSING CELLS (nothing to read yet): " + " ".join(missing)) + sys.exit(4) + + out, rc = {"cells": {}}, 0 + print("=" * 108) + print("READ-OUT CROSS-PICK: does switching prob -> logit change the ACTION the closed loop executes?") + print("=" * 108) + hdr = (f"{'cell':<9}{'n':>5}{'agree':>8}{'wilsonCI95':>18}{'rho(cand)':>11}" + f"{'probpick|logit':>16}{'logitpick|prob':>16}{'n_disagree':>12}") + print(hdr); print("-" * len(hdr)) + for t in tags: + d = load(f"{a.dir}/xpick/xpick_{t}.json") + rows = [r for r in d["rows"] if "xpick_agree" in r and not math.isnan(r["xpick_agree"])] + n = len(rows) + k = int(sum(r["xpick_agree"] for r in rows)) + lo, hi = wilson(k, n) + dis = [r for r in rows if r["xpick_agree"] == 0.0] + # cross-ranks are only meaningful where the picks DIFFER: where they agree both are 1.0 by + # construction and averaging them in would dilute the number toward 1. + c = {"n": n, "n_agree": k, "agree": k / n if n else float("nan"), + "agree_ci95": [lo, hi], "n_disagree": len(dis), + "spearman_cand_mean": mean([r["xpick_spearman_cand"] for r in rows]), + "spearman_cand_median": median([r["xpick_spearman_cand"] for r in rows]), + "probpick_rank_under_logit_disagree_mean": mean( + [r["xpick_probpick_rank_under_logit"] for r in dis]), + "logitpick_rank_under_prob_disagree_mean": mean( + [r["xpick_logitpick_rank_under_prob"] for r in dis]), + "probpick_rank_under_logit_disagree_median": median( + [r["xpick_probpick_rank_under_logit"] for r in dis]), + "logitpick_rank_under_prob_disagree_median": median( + [r["xpick_logitpick_rank_under_prob"] for r in dis]), + "by_stage": {}} + for s in sorted({r["stage"] for r in rows}): + sub = [r for r in rows if r["stage"] == s] + c["by_stage"][f"S{s}"] = {"n": len(sub), + "agree": mean([r["xpick_agree"] for r in sub])} + ref_p = f"{a.dir}/snr_{t}/snr_beta99.json" + if os.path.exists(ref_p): + bad, worst, nf = regress(d["rows"], load(ref_p)["rows"], a.tol) + c["regression"] = {"ref": ref_p, "n_fields": nf, "worst_rel": worst, + "n_mismatch": len(bad), "mismatch_head": bad[:8]} + if bad: + rc = 5 + else: + c["regression"] = {"ref": ref_p, "status": "reference absent"} + out["cells"][t] = c + print(f"{t:<9}{n:>5}{c['agree']:>8.3f} [{lo:.3f}, {hi:.3f}]" + f"{c['spearman_cand_mean']:>11.4f}" + f"{c['probpick_rank_under_logit_disagree_mean']:>16.4f}" + f"{c['logitpick_rank_under_prob_disagree_mean']:>16.4f}" + f"{len(dis):>12d}") + print() + print("cross-rank columns are over the DISAGREEING anchors only (where they agree both are 1.0 " + "by construction).") + print() + print("REGRESSION vs the run-21/run-14 beta=0.99 cells (the additive patch must move nothing):") + for t in tags: + r = out["cells"][t]["regression"] + if "n_mismatch" in r: + v = ("IDENTICAL" if r["n_mismatch"] == 0 + else f"*** {r['n_mismatch']} MISMATCHES ***") + print(f" {t:<9} {r['n_fields']:>6d} fields worst rel {r['worst_rel']:.2e} {v}") + for m in r["mismatch_head"]: + print(f" {m}") + else: + print(f" {t:<9} {r['status']}") + print() + print("STAGE BREAKDOWN of argmax agreement:") + for t in tags: + bs = out["cells"][t]["by_stage"] + print(f" {t:<9} " + " ".join(f"{s}: {v['agree']:.3f} (n={v['n']})" + for s, v in sorted(bs.items()))) + if a.out: + os.makedirs(os.path.dirname(a.out), exist_ok=True) + with open(a.out, "w") as f: + json.dump(out, f, indent=1) + print(f"\nwrote {a.out}") + if rc: + print("\nFAIL: the additive patch changed a pre-existing field. " + "The run-27 numbers must not be read until this is explained.") + sys.exit(rc) + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/real/actcond_audit.py b/rsm_rise/scripts/real/actcond_audit.py new file mode 100644 index 0000000000000000000000000000000000000000..f7d42684e58c7b086176c09f67cdc6f1a0fea847 --- /dev/null +++ b/rsm_rise/scripts/real/actcond_audit.py @@ -0,0 +1,339 @@ +"""ACT_COND Task 1 (gen_q#278): static audit of the action-conditioning path, written as ASSERTIONS. + +Traces one candidate chunk from scripts/real/twin_rollout.py:Scorer.pick into the successor forward pass +and checks, LOUDLY (non-zero exit on any failure): + + A0 ALIGNMENT cache act.f32.npy / proprio.f32.npy at meta.ep_from[ep]+t == hdf5 demo_ actions_raw[t] + / obs.ee_state[t]. If the episode order of the cache and of the hdf5 disagree, every + eval anchor scores a DIFFERENT state than the one it thinks it is scoring. + A1 UNITS trainer chunk (data.py:_chunk_at on the cache) vs scorer chunk (hdf5 actions_raw slice), + max abs difference over --n-chunks anchors. Counterfactual: the same difference if the + eval had read the normalised `actions` dataset instead -- that is the size of the silent + bug this assertion rules out. Also: neither side clips the action. + A2 ORDER the flatten is time-major on both sides; a dim-major (transposed) flatten is shown to + differ, so the test has power. + A3 DIM checkpoint d_act / chunk / adim vs the cache's adim vs the hdf5's action width vs what + the scorer builds; and d_in vs the feature the evaluator hands it. + A4 JACOBIAN finite-difference || dq/d(a/sd_a) || vs || dq/dx || at the SAME anchor, in one score() + call so the particle noise is common (CRN) and the difference is a real derivative. + Both read-outs (prob and logit). Action units are per-1-sd-of-dataset so the two norms + are comparable; raw-unit numbers are reported too. + A5 DEAD DIMS exact per-action-coordinate FD (80 coords = 8 frames x 10 dims), reported per coordinate + (summed over the chunk) and per chunk position. + +CPU-affordable by construction: the Jacobian uses the d1 read-out (one hop). --jac-mode chain repeats it +on the deployed coin-chain read-out and belongs in a packed GPU job. +""" +import argparse, json, os, sys, time +import numpy as np + +ROOT = "/proj/dmfexp/zwhong/rsm_rise" +sys.path.insert(0, f"{ROOT}/scripts/real") +RSM_LIBERO = f"{ROOT}/code/gen_q/rsm_libero" + +RESULTS = [] # (name, ok, detail) + + +def ck_d_in_guess(cond_in, d_act, d_task, n_fourier): + """OccFlow: d_cond = d_z + d_act + d_task + (2*n_fourier+1); enc is identity so d_z == d_in.""" + return cond_in - d_act - d_task - (2 * n_fourier + 1) + + +def check(name, ok, detail): + RESULTS.append((name, bool(ok), detail)) + print(f"[{'PASS' if ok else 'FAIL'}] {name}: {detail}", flush=True) + return bool(ok) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--hdf5", default=f"{ROOT}/data/raw/cooking_v5_expert_suboptimal.hdf5") + ap.add_argument("--split", default=f"{ROOT}/data/derived/cooking_v5_split.json") + ap.add_argument("--cache", default=f"{ROOT}/cache/real_cooking_v5") + ap.add_argument("--ckpt", default=f"{ROOT}/runs/real_cooking_v5/rsm/R_M/ckpt_s100000.pt") + ap.add_argument("--hop-ckpt", default=f"{ROOT}/runs/real_cooking_v5/hop/gauss/policy_r1.pt") + ap.add_argument("--n-chunks", type=int, default=100) + ap.add_argument("--horizon", type=int, default=8) + ap.add_argument("--jac-anchors", type=int, default=16) + ap.add_argument("--jac-mode", default="d1", choices=["d1", "chain", "fold"]) + ap.add_argument("--jac-probes", type=int, default=64, help="random sphere directions for ||dq/dx||") + ap.add_argument("--jac-h", type=float, default=0.01, help="FD step, in units of 1 sd of the input") + ap.add_argument("--beta", type=float, default=0.99) + ap.add_argument("--gamma", type=float, default=0.999) + ap.add_argument("--particles", type=int, default=16) + ap.add_argument("--temperature", type=float, default=25.0) + ap.add_argument("--seed", type=int, default=0) + ap.add_argument("--out", default=f"{ROOT}/status/real/ACTCOND_AUDIT.json") + a = ap.parse_args() + t0 = time.time() + import h5py, torch + rng = np.random.default_rng(a.seed) + out = {"args": vars(a), "host": os.uname().nodename, "t_start": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())} + + # ---------------------------------------------------------------- cache + hdf5 + meta = np.load(f"{a.cache}/meta.npz", allow_pickle=True) + act_cache = np.load(f"{a.cache}/act.f32.npy", mmap_mode="r") + pr_cache = np.load(f"{a.cache}/proprio.f32.npy", mmap_mode="r") + zf = np.load(f"{a.cache}/z.f16.npy", mmap_mode="r") + st = np.load(f"{a.cache}/feat_stats.npz") + ep_from, ep_to = np.asarray(meta["ep_from"]), np.asarray(meta["ep_to"]) + cache_adim = int(meta["adim"]); cache_dim = int(meta["dim"]) + f = h5py.File(a.hdf5, "r") + d = f["data"] + demos = sorted([k for k in d], key=lambda k: int(k.split("_")[1])) + print(f"[audit] cache {len(ep_from)} eps / {len(act_cache)} frames, adim={cache_adim}, dim={cache_dim}; " + f"hdf5 {len(demos)} demos", flush=True) + check("A0.n_episodes", len(ep_from) == len(demos), + f"cache {len(ep_from)} vs hdf5 {len(demos)} episodes") + + # ---------------------------------------------------------------- A0 alignment + n_ep_check = min(len(demos), len(ep_from)) + len_bad = [] + for e in range(n_ep_check): + n_h = d[f"demo_{e}"]["actions_raw"].shape[0] if "actions_raw" in d[f"demo_{e}"] else d[f"demo_{e}"]["actions"].shape[0] + n_c = int(ep_to[e] - ep_from[e]) + if n_h != n_c: + len_bad.append((e, n_h, n_c)) + check("A0.episode_lengths", not len_bad, + "all episode lengths agree" if not len_bad else f"{len(len_bad)} mismatches, first {len_bad[:3]}") + + anchors = [] # (ep, t) sampled from valid goal-route episodes first, then anywhere + split = json.load(open(a.split))["episodes"] if os.path.exists(a.split) else {} + for _ in range(a.n_chunks * 4): + e = int(rng.integers(0, n_ep_check)) + L = int(ep_to[e] - ep_from[e]) + if L <= a.horizon + 1: + continue + anchors.append((e, int(rng.integers(0, L - a.horizon)))) + if len(anchors) >= a.n_chunks: + break + dA, dP = [], [] + for e, t in anchors: + g = d[f"demo_{e}"] + ar = np.asarray((g["actions_raw"] if "actions_raw" in g else g["actions"])[t], np.float32) + ac = np.asarray(act_cache[ep_from[e] + t], np.float32) + dA.append(np.abs(ar - ac).max()) + if "obs" in g and "ee_state" in g["obs"]: + ee = np.asarray(g["obs"]["ee_state"][t], np.float32) + dP.append(np.abs(ee - np.asarray(pr_cache[ep_from[e] + t], np.float32)).max()) + dA = np.array(dA); dP = np.array(dP) if dP else np.array([np.nan]) + check("A0.act_cache_eq_hdf5_actions_raw", float(dA.max()) < 1e-5, + f"max|cache.act - hdf5.actions_raw| = {dA.max():.3e} over {len(dA)} frames") + check("A0.proprio_cache_eq_hdf5_ee_state", (not np.isfinite(dP).all()) or float(np.nanmax(dP)) < 1e-4, + f"max|cache.proprio - hdf5.obs.ee_state| = {np.nanmax(dP):.3e}") + out["A0"] = {"n_episodes_cache": int(len(ep_from)), "n_demos_hdf5": len(demos), + "length_mismatches": len_bad[:10], "max_abs_act_diff": float(dA.max()), + "max_abs_proprio_diff": float(np.nanmax(dP))} + + # ---------------------------------------------------------------- A1 units (trainer vs scorer chunk) + sys.path.insert(0, RSM_LIBERO) + from data import LiberoRSMData + data = LiberoRSMData(a.cache, chunk=a.horizon, in_ram=False, normalize=True) + idx = np.array([ep_from[e] + t for e, t in anchors], np.int64) + epi = np.array([e for e, t in anchors], np.int64) + trainer_chunks = data._chunk_at(idx, epi) # [n, 80] EXACT trainer code path + scorer_chunks, norm_chunks = [], [] + for e, t in anchors: + g = d[f"demo_{e}"] + A = np.asarray((g["actions_raw"] if "actions_raw" in g else g["actions"])[t:t + a.horizon], np.float32) + scorer_chunks.append(A) + norm_chunks.append(np.asarray(g["actions"][t:t + a.horizon], np.float32)) + scorer_chunks = np.stack(scorer_chunks); norm_chunks = np.stack(norm_chunks) + # the scorer's own flatten, from rsm_scorer._flat_chunk + scorer_flat = scorer_chunks.reshape(len(anchors), -1) + diff = np.abs(trainer_chunks - scorer_flat) + wrong = np.abs(trainer_chunks - norm_chunks.reshape(len(anchors), -1)) + check("A1.units_trainer_eq_scorer", float(diff.max()) < 1e-5, + f"max|trainer_chunk - scorer_chunk| = {diff.max():.3e} over {len(anchors)} chunks " + f"(counterfactual: if eval read the NORMALISED `actions` it would be {wrong.max():.3f})") + lo = np.array(json.loads(d.attrs["action_min"]), np.float32) + hi = np.array(json.loads(d.attrs["action_max"]), np.float32) + outside = int(((scorer_chunks < lo) | (scorer_chunks > hi)).sum()) + check("A1.no_clipping_either_side", True, + f"neither data.py nor _flat_chunk clips the action; {outside} of {scorer_chunks.size} raw values " + f"lie outside the hdf5 [action_min, action_max] box (the box has a 2% margin, so 0 is expected)") + out["A1"] = {"max_abs_diff": float(diff.max()), "counterfactual_normalised": float(wrong.max()), + "n_chunks": len(anchors), "values_outside_action_box": outside, + "action_min": lo.tolist(), "action_max": hi.tolist()} + + # ---------------------------------------------------------------- A2 flatten order + probe = np.arange(a.horizon * cache_adim, dtype=np.float32).reshape(1, a.horizon, cache_adim) + time_major = probe.reshape(1, -1) + dim_major = np.transpose(probe, (0, 2, 1)).reshape(1, -1) + t_ok = bool((trainer_chunks[0].reshape(a.horizon, cache_adim) == scorer_chunks[0]).all()) + power = float(np.abs(trainer_chunks - np.transpose(scorer_chunks, (0, 2, 1)).reshape(len(anchors), -1)).max()) + check("A2.flatten_time_major_both_sides", t_ok and float(np.abs(time_major - dim_major).max()) > 0, + f"trainer flat[j*{cache_adim}+dim] == chunk[j, dim] on real data: {t_ok}; " + f"a dim-major flatten of the same chunks would differ by {power:.4f} (test has power)") + out["A2"] = {"time_major_match": t_ok, "dim_major_max_abs_diff": power} + + # ---------------------------------------------------------------- A3 dimensionality + ck = torch.load(a.ckpt, map_location="cpu", weights_only=False) + cfg = ck.get("config", {}) + ck_d_act, ck_chunk = int(ck["d_act"]), int(cfg.get("chunk", 8)) + ck_adim = ck_d_act // ck_chunk + # d_in lives at the TOP level of the blob, not in config (is_ope.load_critic reads ck["d_in"] + # and refuses a cache of another width, so a mismatch here would already have raised). + ck_d_in = int(ck.get("d_in", cfg.get("d_z", -1))); ck_d_z = int(cfg.get("d_z", -1)) + dd = int(zf.shape[1] + pr_cache.shape[1]) + h_adim = int(d[demos[0]]["actions_raw"].shape[1]) if "actions_raw" in d[demos[0]] else int(d[demos[0]]["actions"].shape[1]) + ok3 = (ck_d_act == ck_chunk * ck_adim == a.horizon * cache_adim) and ck_adim == cache_adim == h_adim + check("A3.d_act", ok3, + f"ckpt d_act={ck_d_act} chunk={ck_chunk} -> adim={ck_adim}; cache adim={cache_adim}; " + f"hdf5 action width={h_adim}; eval horizon={a.horizon} -> d_act={a.horizon * cache_adim}") + # ck["config"] carries no d_in on this checkpoint, so the d_in / d_act / d_cond check is made + # against the WEIGHTS: OccFlow.cond is mlp([d_cond, width, width]) with + # d_cond = d_z + d_act + d_task + (2*n_fourier + 1), and the flow's first Linear therefore pins + # every one of those widths. A d_act the checkpoint was not built with cannot survive this. + fsd = ck["flow"] if "flow" in ck else ck.get("flow_state", {}) + ck_cond_in = next((int(v.shape[1]) for k_, v in fsd.items() if k_.endswith("cond.0.weight")), None) + d_task = next((int(v.shape[1]) for k_, v in fsd.items() + if "task" in k_ and k_.endswith(".weight") and v.dim() == 2), None) + n_fourier = int(cfg.get("n_fourier", 6)) + expect = None if (ck_cond_in is None or d_task is None) else ck_d_in_guess(ck_cond_in, ck_d_act, d_task, n_fourier) + check("A3.d_cond_from_weights", expect is not None and expect == dd, + f"flow cond.0 in_features={ck_cond_in} = d_z + d_act({ck_d_act}) + d_task({d_task}) + " + f"(2*{n_fourier}+1) -> d_z={expect}; evaluator feature dim dd = z({zf.shape[1]}) + " + f"proprio({pr_cache.shape[1]}) = {dd} (ckpt config d_in={ck_d_in}, absent = -1)") + sd_stats = st["sd"][:dd] + check("A3.feat_stats_sd_floor", float(sd_stats.min()) >= 1e-3 - 1e-9, + f"feat_stats sd min = {float(sd_stats.min()):.3e} (data.py floors at 1e-3)") + out["A3"] = {"cond_in_features": ck_cond_in, "d_task": d_task, "d_z_from_weights": expect, + "ckpt_d_act": ck_d_act, "ckpt_chunk": ck_chunk, "ckpt_adim": ck_adim, + "cache_adim": cache_adim, "hdf5_adim": h_adim, "ckpt_d_in": ck_d_in, + "eval_d_in": dd, "ckpt_d_z": ck_d_z, + "feat_stats_sd_min": float(sd_stats.min()), + "q_action_winrate_in_ckpt": ck.get("q_action_winrate", None), + "step": ck.get("step", None)} + + # ---------------------------------------------------------------- A4/A5 Jacobian + mu = st["mu"][:dd].astype(np.float32); sd = st["sd"][:dd].astype(np.float32) + zclip = float(st["z_clip"]) if "z_clip" in st.files else 10.0 + from twin_rollout import Scorer + sc = Scorer("rsm", lo, hi, rsm_ckpt=a.ckpt, seed=a.seed, rsm_mode=a.jac_mode, + rsm_beta=a.beta, rsm_gamma=a.gamma, rsm_particles=a.particles, rsm_dim=dd, + rsm_temperature=a.temperature, + rsm_hop_ckpt=(a.hop_ckpt if (a.jac_mode != "d1" and os.path.exists(a.hop_ckpt)) else "")) + rsm = sc.rsm + dev = rsm.device + # per-coordinate action sd over the whole corpus: the unit that makes the two norms comparable + a_sd = np.asarray(act_cache[::17], np.float32).std(0) + a_sd = np.maximum(a_sd, 1e-6) + a_sd_flat = np.tile(a_sd, a.horizon).astype(np.float32) # [80] + out["action_sd_per_coord"] = a_sd.tolist() + + # anchors for the Jacobian: valid-split goal-route episodes, stride 25, as in logged_action_rank + def path(k): + return str(d[k].attrs.get("path", "")) + goal = [k for k in demos if path(k) == "2->3->4" + and split.get(str(int(k.split('_')[1])), {}).get("split") == "valid"] + jac_anchors = [] + for k in (goal or demos): + e = int(k.split("_")[1]); L = int(ep_to[e] - ep_from[e]) + stg = np.asarray(d[k]["annot"]["edge_from"][()]) if "annot" in d[k] else np.zeros(L, np.int16) + for t in range(0, L - a.horizon, 25): + jac_anchors.append((e, t, int(stg[t]))) + rng2 = np.random.default_rng(a.seed + 1) + if len(jac_anchors) > a.jac_anchors: + sel = rng2.choice(len(jac_anchors), size=a.jac_anchors, replace=False) + jac_anchors = [jac_anchors[i] for i in sorted(sel)] + print(f"[audit] Jacobian on {len(jac_anchors)} anchors, mode={a.jac_mode}, " + f"h={a.jac_h} sd, probes={a.jac_probes}", flush=True) + + h = float(a.jac_h) + nA = a.horizon * cache_adim + m = int(a.jac_probes) + g_a_prob, g_a_logit, g_x_prob, g_x_logit = [], [], [], [] + coord_prob, coord_logit = [], [] + pos_prob, pos_logit = [], [] + q0s, ql0s = [], [] + for ai, (e, t, s0) in enumerate(jac_anchors): + gi = ep_from[e] + t + feat = np.concatenate([np.asarray(zf[gi], np.float32), np.asarray(pr_cache[gi], np.float32)]) + x0 = np.clip((feat - mu) / sd, -zclip, zclip).astype(np.float32) + g = d[f"demo_{e}"] + a0 = np.asarray((g["actions_raw"] if "actions_raw" in g else g["actions"])[t:t + a.horizon], np.float32) + a0f = a0.reshape(-1) + # --- one batch: [baseline | action +-h*sd*e_j (state fixed) | state +-h*u_i (action fixed)] + A_rows = [a0f] + for j in range(nA): + for s in (+1.0, -1.0): + v = a0f.copy(); v[j] += s * h * a_sd_flat[j]; A_rows.append(v) + U = rng2.normal(size=(m, len(x0))).astype(np.float32) + U /= np.linalg.norm(U, axis=1, keepdims=True) + X_rows = [x0] * (1 + 2 * nA) + for i in range(m): + for s in (+1.0, -1.0): + X_rows.append((x0 + s * h * U[i]).astype(np.float32)) + A_rows.append(a0f) + Xb = torch.as_tensor(np.stack(X_rows), dtype=torch.float32, device=dev) + Ab = np.stack(A_rows).reshape(-1, a.horizon, cache_adim) + with torch.no_grad(): + rsm.score(Xb, Ab, seed=a.seed + 1000 + ai) + q = rsm.last_q.double().cpu().numpy() + ql = rsm.last_q_logit + ql = q * 0.0 if ql is None else ql.double().cpu().numpy() + q0s.append(q[0]); ql0s.append(ql[0]) + ap_, am_ = q[1:1 + 2 * nA:2], q[2:1 + 2 * nA:2] + lp_, lm_ = ql[1:1 + 2 * nA:2], ql[2:1 + 2 * nA:2] + ga_p = (ap_ - am_) / (2 * h) # d q / d (a_j / sd_j) [80] + ga_l = (lp_ - lm_) / (2 * h) + o = 1 + 2 * nA + xp_, xm_ = q[o::2], q[o + 1::2] + lxp_, lxm_ = ql[o::2], ql[o + 1::2] + dd_p = (xp_ - xm_) / (2 * h) # directional derivatives along unit u_i + dd_l = (lxp_ - lxm_) / (2 * h) + D = len(x0) + g_a_prob.append(np.linalg.norm(ga_p)); g_a_logit.append(np.linalg.norm(ga_l)) + g_x_prob.append(np.sqrt(D * np.mean(dd_p ** 2))) + g_x_logit.append(np.sqrt(D * np.mean(dd_l ** 2))) + coord_prob.append(np.linalg.norm(ga_p.reshape(a.horizon, cache_adim), axis=0)) + coord_logit.append(np.linalg.norm(ga_l.reshape(a.horizon, cache_adim), axis=0)) + pos_prob.append(np.linalg.norm(ga_p.reshape(a.horizon, cache_adim), axis=1)) + pos_logit.append(np.linalg.norm(ga_l.reshape(a.horizon, cache_adim), axis=1)) + if ai == 0 or (ai + 1) % 4 == 0: + print(f" anchor {ai+1}/{len(jac_anchors)} ep{e} t{t} S{s0}: q0={q[0]:.4f} logit0={ql[0]:.3f} " + f"|g_a|={g_a_logit[-1]:.4f} |g_x|={g_x_logit[-1]:.4f} ({time.time()-t0:.0f}s)", flush=True) + + ga_p_m, ga_l_m = float(np.mean(g_a_prob)), float(np.mean(g_a_logit)) + gx_p_m, gx_l_m = float(np.mean(g_x_prob)), float(np.mean(g_x_logit)) + r_p = ga_p_m / max(gx_p_m, 1e-12); r_l = ga_l_m / max(gx_l_m, 1e-12) + check("A4.action_jacobian_not_negligible", r_l > 0.01, + f"[logit] ||dq/d(a/sd_a)|| = {ga_l_m:.4f} vs ||dq/dx|| = {gx_l_m:.4f} -> ratio {r_l:.4f}; " + f"[prob] {ga_p_m:.5f} vs {gx_p_m:.5f} -> ratio {r_p:.4f} " + f"(both per 1 sd of the corresponding input; fails below 0.01)") + cp = np.mean(np.stack(coord_prob), 0); cl = np.mean(np.stack(coord_logit), 0) + pp = np.mean(np.stack(pos_prob), 0); pl = np.mean(np.stack(pos_logit), 0) + dead = [int(i) for i in range(cache_adim) if cl[i] < 1e-3 * cl.max()] + names = ["x", "y", "z", "R00", "R10", "R20", "R01", "R11", "R21", "grip"] + check("A5.no_dead_action_coordinate", not dead, + "per-coordinate |dq/d(a_i/sd_i)| (logit, summed over the 8 chunk frames): " + + ", ".join(f"{names[i]}={cl[i]:.4f}" for i in range(cache_adim)) + + ("" if not dead else f" DEAD: {[names[i] for i in dead]}")) + out["A4"] = {"mode": a.jac_mode, "n_anchors": len(jac_anchors), "h_sd_units": h, "probes": m, + "g_action_prob": ga_p_m, "g_action_logit": ga_l_m, + "g_state_prob": gx_p_m, "g_state_logit": gx_l_m, + "ratio_prob": r_p, "ratio_logit": r_l, + "g_action_logit_per_anchor": [float(v) for v in g_a_logit], + "g_state_logit_per_anchor": [float(v) for v in g_x_logit], + "q0_mean": float(np.mean(q0s)), "logit0_mean": float(np.mean(ql0s))} + out["A5"] = {"coord_names": names, + "per_coord_logit": cl.tolist(), "per_coord_prob": cp.tolist(), + "per_chunk_pos_logit": pl.tolist(), "per_chunk_pos_prob": pp.tolist(), + "dead_coords": [names[i] for i in dead]} + + out["results"] = [{"name": n, "ok": o, "detail": det} for n, o, det in RESULTS] + out["n_fail"] = sum(1 for _, o, _ in RESULTS if not o) + out["seconds"] = time.time() - t0 + os.makedirs(os.path.dirname(a.out), exist_ok=True) + json.dump(out, open(a.out, "w"), indent=1) + print(f"\n==== {len(RESULTS) - out['n_fail']}/{len(RESULTS)} assertions passed " + f"({out['seconds']:.0f}s) -> {a.out}", flush=True) + for n, o, det in RESULTS: + print(f" {'ok ' if o else 'FAIL'} {n}") + f.close() + sys.exit(1 if out["n_fail"] else 0) + + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/real/actcond_conc_leaderboard.py b/rsm_rise/scripts/real/actcond_conc_leaderboard.py new file mode 100644 index 0000000000000000000000000000000000000000..8f8a081b88ed4ddffea04bdb0a4dd53e33c85939 --- /dev/null +++ b/rsm_rise/scripts/real/actcond_conc_leaderboard.py @@ -0,0 +1,174 @@ +#!/usr/bin/env python +"""ACT_COND run 53b -- the three things the sweep's headline numbers do not yet answer. + +The run-53 sweep established (W2) that the checkpoint ranking induced by the pose-matched pair +concordance REPLICATES across pools (median Spearman 0.586 over 84 pool-pairs, 88.1% positive) but +(W3) that the SPECIFIC ordering run 52 printed -- v0lit worst -- holds on only 17.6% of the 17 pools that +carry all three of that triple. Three follow-ons, all off the same already-written JSON, no new read of +RANK_CTRL's caches: + + (1) W5 FAILED (permuted arm within 0.02 of 0.5 on 79.5% of cells, not >= 95%). Is that estimator BIAS + or is it sampling noise? The honest test is not the point deviation but each cell's own bootstrap: + how many permuted CIs exclude 0.5, and is the signed deviation centred? + (2) THE DELIVERABLE. If the ranking replicates, then the leaderboard it induces is the thing other + streams would actually use. Per pool, convert each checkpoint's paired concordance to a + within-pool percentile (so pools with different spreads are commensurable), average over pools. + (3) IS IT WORTH THE TROUBLE? Compare the concordance ranking to the plain route-AUC ranking on the + same pools: if they agree everywhere, the pose-matched construction buys nothing and the cheaper + statistic should be used. And SPLIT-HALF: build the leaderboard on a random half of the pools and + on the other half, and correlate. That is the direct estimate of how reliable a model SELECTION + by this statistic would be -- the number a user of the recommendation needs. +""" +import argparse, json, os +import numpy as np + + +def spearman(a, b): + a, b = np.asarray(a, float), np.asarray(b, float) + if len(a) < 3: + return float("nan") + def rk(x): + o = np.argsort(x, kind="mergesort"); r = np.empty(len(x), float) + r[o] = np.arange(len(x), dtype=float) + for v in np.unique(x): + m = x == v + if m.sum() > 1: + r[m] = r[m].mean() + return r + ra, rb = rk(a) - rk(a).mean(), rk(b) - rk(b).mean() + den = np.sqrt((ra ** 2).sum() * (rb ** 2).sum()) + return float((ra * rb).sum() / den) if den > 0 else float("nan") + + +def leaderboard(groups, key="paired", min_ck=4): + """within-pool percentile of each checkpoint, averaged over the pools that carry it""" + acc = {} + for g in groups: + if g["n_ckpts"] < min_ck: + continue + cks = list(g["ck"]); vals = np.array([g["ck"][c][key] for c in cks], float) + order = np.argsort(np.argsort(vals)) # 0 = worst + pct = order / max(len(cks) - 1, 1) + for c, p, v in zip(cks, pct, vals): + a = acc.setdefault(c, {"pct": [], "val": [], "pools": 0}) + a["pct"].append(float(p)); a["val"].append(float(v)); a["pools"] += 1 + rows = [{"ckpt": c, "n_pools": a["pools"], "mean_pct": float(np.mean(a["pct"])), + "mean_paired": float(np.mean(a["val"])), "sd_paired": float(np.std(a["val"]))} + for c, a in acc.items()] + rows.sort(key=lambda r: -r["mean_pct"]) + return rows + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--inp", default="status/real/ACT_COND/CONC_SWEEP_run53.json") + ap.add_argument("--out", default="status/real/ACT_COND/CONC_LEADER_run53b.json") + ap.add_argument("--tol", default="tol_0p02") + ap.add_argument("--seed", type=int, default=0) + a = ap.parse_args() + D = json.load(open(a.inp)) + groups = D[a.tol]["groups"] + out = {"run": "53b", "stream": "ACT_COND", "tol": a.tol, "src": os.path.abspath(a.inp)} + + # ---- (1) is the permuted arm biased, or noisy? ------------------------------------------ + dev, excl, n = [], 0, 0 + for c in D["per_cache"]: + if not c.get("ok"): + continue + for stg, ps in c["per_stage"].items(): + v = ps.get(a.tol) + if not v or v["pairs_total"] < 100: + continue + n += 1 + dev.append(v["permuted"]["mean"] - 0.5) + if v["permuted"]["lo"] > 0.5 or v["permuted"]["hi"] < 0.5: + excl += 1 + dev = np.array(dev) + out["W5_diagnosis"] = { + "n_cells": n, "mean_signed_dev": float(dev.mean()), "median_signed_dev": float(np.median(dev)), + "sd_signed_dev": float(dev.std()), "frac_positive": float((dev > 0).mean()), + "n_cells_whose_own_CI_excludes_0p5": excl, "frac_cells_CI_excludes_0p5": excl / max(n, 1), + "reading": "a CENTRED deviation with ~5% of cells' own CIs excluding 0.5 is sampling noise at " + "the cell level and the paired statistic is unaffected; a shifted mean or a large " + "excess of exclusions would be estimator bias and would void the sweep"} + + # ---- (2) the leaderboard ---------------------------------------------------------------- + lb = leaderboard(groups) + out["leaderboard"] = lb + + # ---- (3a) does the pose-matched construction buy anything over plain route AUC? ---------- + rows = [] + for g in groups: + if g["n_ckpts"] < 6: + continue + cks = list(g["ck"]) + rows.append({"pool": g["example_dir"], "stage": g["stage"], "n_ckpts": len(cks), + "spearman_conc_vs_auc": spearman([g["ck"][c]["paired"] for c in cks], + [g["ck"][c]["route_auc_rsm"] for c in cks])}) + sp = np.array([r["spearman_conc_vs_auc"] for r in rows if np.isfinite(r["spearman_conc_vs_auc"])]) + out["conc_vs_routeauc"] = {"n_pools": len(rows), + "median_spearman": float(np.median(sp)) if len(sp) else float("nan"), + "p25": float(np.percentile(sp, 25)) if len(sp) else float("nan"), + "p75": float(np.percentile(sp, 75)) if len(sp) else float("nan"), + "rows": rows} + + # ---- (3b) split-half reliability of the leaderboard -------------------------------------- + big = [g for g in groups if g["n_ckpts"] >= 4] + rng = np.random.default_rng(a.seed) + sh = [] + for _ in range(200): + idx = rng.permutation(len(big)) + A = leaderboard([big[i] for i in idx[:len(big) // 2]]) + B = leaderboard([big[i] for i in idx[len(big) // 2:]]) + da = {r["ckpt"]: r["mean_pct"] for r in A}; db = {r["ckpt"]: r["mean_pct"] for r in B} + sh_ck = sorted(set(da) & set(db)) + if len(sh_ck) >= 8: + sh.append(spearman([da[c] for c in sh_ck], [db[c] for c in sh_ck])) + sh = np.array([x for x in sh if np.isfinite(x)]) + out["split_half"] = {"n_draws": int(len(sh)), "n_pools_used": len(big), + "median_spearman": float(np.median(sh)) if len(sh) else float("nan"), + "p05": float(np.percentile(sh, 5)) if len(sh) else float("nan"), + "p95": float(np.percentile(sh, 95)) if len(sh) else float("nan")} + + # ---- (4) the run-52 triple, pool by pool ------------------------------------------------- + out["triple_rows"] = D[a.tol]["run52_triple_W3"]["rows"] + out["triple_frac_v0lit_last"] = D[a.tol]["run52_triple_W3"]["frac_v0lit_last"] + + with open(a.out, "w") as f: + json.dump(out, f, indent=1, default=float) + print("wrote", a.out) + + w = out["W5_diagnosis"] + print("\n=== (1) W5: permuted arm. mean signed dev %+.4f (median %+.4f, sd %.4f), %.1f%% positive; " + "own CI excludes 0.5 on %d/%d = %.1f%% of cells ===" + % (w["mean_signed_dev"], w["median_signed_dev"], w["sd_signed_dev"], + 100 * w["frac_positive"], w["n_cells_whose_own_CI_excludes_0p5"], w["n_cells"], + 100 * w["frac_cells_CI_excludes_0p5"])) + print("\n=== (2) LEADERBOARD: mean within-pool percentile of the paired concordance ===") + print(" %-58s %6s %8s %9s" % ("checkpoint", "pools", "meanpct", "mean_pair")) + for r in lb[:12]: + print(" %-58s %6d %8.3f %+9.4f" + % (r["ckpt"].split("real_cooking_v5/rsm/")[-1], r["n_pools"], r["mean_pct"], + r["mean_paired"])) + print(" ...") + for r in lb[-8:]: + print(" %-58s %6d %8.3f %+9.4f" + % (r["ckpt"].split("real_cooking_v5/rsm/")[-1], r["n_pools"], r["mean_pct"], + r["mean_paired"])) + c = out["conc_vs_routeauc"] + print("\n=== (3a) concordance vs plain route AUC, within pool: median Spearman %.3f " + "[p25 %.3f, p75 %.3f] over %d pools ===" % (c["median_spearman"], c["p25"], c["p75"], + c["n_pools"])) + s = out["split_half"] + print("=== (3b) SPLIT-HALF reliability of the leaderboard over %d pools: median Spearman %.3f " + "[p05 %.3f, p95 %.3f] ===" % (s["n_pools_used"], s["median_spearman"], s["p05"], s["p95"])) + print("\n=== (4) the run-52 triple, all %d pools carrying it (v0lit last on %.1f%%) ===" + % (len(out["triple_rows"]), 100 * out["triple_frac_v0lit_last"])) + print(" %-40s %-4s %9s %9s %9s %s" % ("pool", "stg", "R_M", "ft_v0", "ft_v0lit", "v0lit_last")) + for r in out["triple_rows"]: + print(" %-40s %-4s %+9.4f %+9.4f %+9.4f %s" + % (r["pool"][:40], r["stage"], r["R_M"], r["ft_v0"], r["ft_v0lit"], r["v0lit_last"])) + + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/real/actcond_conc_sweep.py b/rsm_rise/scripts/real/actcond_conc_sweep.py new file mode 100644 index 0000000000000000000000000000000000000000..97a5f224173e0f7c83883d06c70669e2c8478d4c --- /dev/null +++ b/rsm_rise/scripts/real/actcond_conc_sweep.py @@ -0,0 +1,397 @@ +#!/usr/bin/env python +"""ACT_COND run 53 -- IS THE POSE-MATCHED PAIR CONCORDANCE A USABLE MODEL-SELECTION STATISTIC, OR DID +RUN 52 GENERALISE FROM THREE CHECKPOINTS ON ONE POOL? + +Run 52 section 10 handed the other streams a recommendation: the pose-matched pair concordance at 0.02 m +"separates checkpoints" (+0.227 / +0.212 / -0.130 on an identical pool) and is the candidate statistic for +the action-ranking bar that pose adjacency does not contaminate. That rests on THREE checkpoints and ONE +pool -- and the same run 52 proved a statistic can move 13x with the pool at a byte-identical model. So +the precondition for the recommendation is untested: DOES THE RANKING IT INDUCES REPLICATE ACROSS POOLS? + +This script measures exactly that, on work that is already paid for. RANK_CTRL's status/real/rankctrl/ +holds 935 cached scoring pools whose per_anchor.npz carry the arrays the statistic consumes. Grouping +them by a 26-key POOL SIGNATURE with rsm_ckpt and label EXCLUDED gives ~102 pool groups, 67 with >= 2 +distinct checkpoints, the largest fixed pool carrying 83 checkpoints. Nothing is re-scored; nothing of +RANK_CTRL's is written; every cache is (size, mtime) freeze-witnessed across its read. + +THE STATISTIC, unchanged from run 52 (imported, not reimplemented, so the two artifacts cannot drift): +inside an anchor, every candidate PAIR whose pose_dist differs by < tol and whose route labels DIFFER; +how often is the higher-scored one the on-route one? 0.5 is chance at any K -- which is why, unlike the +R^2 thresholds that made three of run 52's calls meaningless, a fixed threshold IS legitimate here. The +headline is always the PAIRED rsm-minus-permuted difference on identical anchors, episode-cluster +bootstrapped. + +GUARDS, carried over verbatim. A0 stage-aware finiteness (a stage whose route_margin is undefined is +dropped and counted, never nan-filled). A1, the loud regression: every published top1_argmax and route +auc cell is recomputed from the npz by an independent implementation and must agree to 1e-9. Across ~935 +caches that is ~13k of RANK_CTRL's published cells. A cache failing A1 is EXCLUDED and NAMED -- but, +unlike run 52's single-cache abort, one bad cache must not void a 935-cache sweep, so the failure is +recorded per cache and the sweep continues. +""" +import argparse, hashlib, json, os, sys, time, traceback +from multiprocessing import Pool + +import numpy as np + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from actcond_route_asi_multi import (auc, ep_boot, key_of, pose_matched_concordance, # noqa: E402 + regression_check) + +# the pool signature: every config key that describes the POOL, with rsm_ckpt and label EXCLUDED so that +# caches differing ONLY in the checkpoint land in the same group. +POOL_KEYS = ["K", "beta", "gamma", "particles", "arm", "distractor_source", "stride", "pool_stride", + "min_gap", "n_anchor_episodes", "anchor_split", "entry_window", "pool_entry_window", + "entry_lo", "pool_entry_lo", "horizon", "goal_pool_entry_lo", "goal_pool_entry_window", + "seed", "chain_seed", "pose_match", "reverse_drop_own", "reverse_cand0", "grip_tol", + "hop_ckpt", "pool_desc", "n_anchors"] + + +class CacheError(Exception): + pass + + +def one_cache(args): + dirname, root, seed, tols = args + t0 = time.time() + src = os.path.join(root, dirname) + npz_p, js_p = os.path.join(src, "per_anchor.npz"), os.path.join(src, "logged_action_rank.json") + try: + if not (os.path.exists(npz_p) and os.path.exists(js_p)): + raise CacheError("missing per_anchor.npz or logged_action_rank.json") + st0 = {p: (os.stat(p).st_size, os.stat(p).st_mtime) for p in (npz_p, js_p)} + d = np.load(npz_p, allow_pickle=True) + sj = json.load(open(js_p)) + scorers = [s for s in sj.get("scorers", []) if key_of(s) in d.files] + if "rsm" not in scorers or "permuted:rsm" not in scorers: + raise CacheError(f"needs both rsm and permuted:rsm arms, has {scorers}") + for nm in ("route_pose_dist", "route_margin", "route_label", "ep", "stage"): + if nm not in d.files: + raise CacheError(f"npz lacks {nm}") + P = np.asarray(d["route_pose_dist"], float) + M = np.asarray(d["route_margin"], float) + L = np.asarray(d["route_label"], float) + eps = np.asarray(d["ep"]).astype(int) + stage = np.asarray(d["stage"]).astype(int) + n_anch, K = P.shape + + # ---- A0 ----------------------------------------------------------------------------- + for nm in [key_of(s) for s in scorers] + ["route_pose_dist"]: + arr = np.asarray(d[nm], float) + if arr.shape != (n_anch, K): + raise CacheError(f"A0 shape: {nm} {arr.shape} != {(n_anch, K)}") + if not np.isfinite(arr).all(): + raise CacheError(f"A0 finite: {nm} has {int((~np.isfinite(arr)).sum())} non-finite") + stages_ok, dropped = [], {} + for st in sorted(set(stage.tolist())): + sel = stage == st + nbad = int((~np.isfinite(M[sel])).sum()) + int((~np.isfinite(L[sel])).sum()) + if nbad: + dropped[f"S{st}"] = {"n_anchors": int(sel.sum()), "n_nonfinite_cells": nbad} + continue + lv = set(np.unique(L[sel]).tolist()) + if not lv <= {0.0, 1.0}: + raise CacheError(f"A0 label: route_label not binary at S{st}, uniques {sorted(lv)[:6]}") + stages_ok.append(st) + if not stages_ok: + raise CacheError("no stage has a finite route_margin/route_label") + + # ---- A1, against RANK_CTRL's published cells ------------------------------------------- + reg, bad, n_cells = regression_check(sj, d, stage, scorers, stages_ok) + if bad: + raise CacheError("A1 regression: %d/%d published cells do NOT reproduce; worst %s" + % (len(bad), n_cells, + max(bad, key=lambda r: abs(r[2] - r[1]))[0])) + + S_r = np.asarray(d[key_of("rsm")], float) + S_p = np.asarray(d[key_of("permuted:rsm")], float) + per_stage = {} + for st in stages_ok: + sel = stage == st + Ps, Ms, Ls, es = P[sel], M[sel], L[sel], eps[sel] + cell = {"n_anchors": int(sel.sum()), "n_episodes": int(len(np.unique(es))), + "label_mean": float(Ls.mean()), + "pose_ratio_cand0": float(Ps[:, 1:].mean() / max(Ps[:, 0].mean(), 1e-12))} + for t in tols: + kk = ("tol_%g" % t).replace(".", "p") + cr, per_r = pose_matched_concordance(S_r[sel], Ps, Ms, Ls, es, t, seed=seed) + cp, per_p = pose_matched_concordance(S_p[sel], Ps, Ms, Ls, es, t, seed=seed) + cell[kk] = {"rsm": cr["boot"], "permuted": cp["boot"], + "paired": ep_boot(per_r - per_p, es, seed=seed), + "pairs_total": cr["pairs_total"], + "pairs_per_anchor_med": cr["pairs_per_anchor_med"], + "n_anchors_used": cr["n_anchors_used"]} + for k in ("rsm", "permuted", "paired"): # per-episode detail is not needed here + cell[kk][k].pop("per_episode", None) + # the route AUC of the rsm arm on the same stage, for reference against the run-52 tables + idx = np.flatnonzero(sel) + cell["route_auc_rsm"] = float(np.nanmean([auc(S_r[i], L[i]) for i in idx])) + cell["route_auc_permuted"] = float(np.nanmean([auc(S_p[i], L[i]) for i in idx])) + per_stage[f"S{st}"] = cell + + st1 = {p: (os.stat(p).st_size, os.stat(p).st_mtime) for p in (npz_p, js_p)} + if st0 != st1: + raise CacheError("input changed under the read (size/mtime freeze witness)") + + return {"dir": dirname, "ok": True, "secs": round(time.time() - t0, 2), + "pool_sig": [str(sj.get(k)) for k in POOL_KEYS], + "rsm_ckpt": sj.get("rsm_ckpt"), "label": sj.get("label"), "K": int(K), + "arm": sj.get("arm"), "n_regression_cells": n_cells, + "stages_dropped": dropped, "per_stage": per_stage, + "npz": {"size": st0[npz_p][0], "mtime": st0[npz_p][1]}} + except CacheError as e: + return {"dir": dirname, "ok": False, "why": str(e), "secs": round(time.time() - t0, 2)} + except Exception as e: # never let one cache void the sweep + return {"dir": dirname, "ok": False, "why": "UNEXPECTED %s: %s" % (type(e).__name__, e), + "traceback": traceback.format_exc()[-1500:], "secs": round(time.time() - t0, 2)} + + +def spearman_simple(a, b): + a, b = np.asarray(a, float), np.asarray(b, float) + if len(a) < 3 or np.allclose(a, a[0]) or np.allclose(b, b[0]): + return float("nan") + def rk(x): + o = np.argsort(x, kind="mergesort"); r = np.empty(len(x), float); r[o] = np.arange(len(x), dtype=float) + # average ties + for v in np.unique(x): + m = x == v + if m.sum() > 1: + r[m] = r[m].mean() + return r + ra, rb = rk(a), rk(b) + ra -= ra.mean(); rb -= rb.mean() + den = np.sqrt((ra ** 2).sum() * (rb ** 2).sum()) + return float((ra * rb).sum() / den) if den > 0 else float("nan") + + +def analyse(cells, tol_key, min_pairs): + """Group by (pool signature, stage) and ask whether the checkpoint RANKING replicates across pools.""" + groups = {} + for c in cells: + if not c.get("ok"): + continue + for stg, ps in c["per_stage"].items(): + v = ps.get(tol_key) + if v is None or v["pairs_total"] < min_pairs: + continue + g = groups.setdefault(("|".join(c["pool_sig"]), stg), + {"stage": stg, "K": c["K"], "arm": c["arm"], "dirs": [], "ck": {}}) + g["dirs"].append(c["dir"]) + # a checkpoint appearing twice on the identical pool would be a duplicate cache; keep the + # first and count the collision rather than silently averaging + g["ck"].setdefault(c["rsm_ckpt"], {"paired": v["paired"]["mean"], + "paired_lo": v["paired"]["lo"], + "paired_hi": v["paired"]["hi"], + "rsm": v["rsm"]["mean"], + "permuted": v["permuted"]["mean"], + "pairs": v["pairs_total"], "dir": c["dir"], + "route_auc_rsm": ps["route_auc_rsm"], "dups": 0}) + g["ck"][c["rsm_ckpt"]]["dups"] += 1 + out = [] + for (sig, stg), g in groups.items(): + out.append({"stage": stg, "K": g["K"], "arm": g["arm"], "n_ckpts": len(g["ck"]), + "n_dirs": len(g["dirs"]), "example_dir": sorted(g["dirs"])[0], + "pool_sig_hash": hashlib.md5(sig.encode()).hexdigest()[:12], "ck": g["ck"]}) + out.sort(key=lambda r: -r["n_ckpts"]) + return out + + +def cross_pool(groups, min_shared): + """The crux: do two pools rank the SAME checkpoints the same way?""" + rows = [] + for i in range(len(groups)): + for j in range(i + 1, len(groups)): + A, B = groups[i], groups[j] + shared = sorted(set(A["ck"]) & set(B["ck"])) + if len(shared) < min_shared: + continue + a = [A["ck"][c]["paired"] for c in shared] + b = [B["ck"][c]["paired"] for c in shared] + rows.append({"a": A["example_dir"], "b": B["example_dir"], + "stage_a": A["stage"], "stage_b": B["stage"], + "n_shared": len(shared), "spearman": spearman_simple(a, b), + "pearson": float(np.corrcoef(a, b)[0, 1]) if len(shared) > 2 else float("nan")}) + return rows + + +TRIPLE = ["runs/real_cooking_v5/rsm/R_M/ckpt_s100000.pt", + "runs/real_cooking_v5/rsm/R_M_ft_v0/ckpt_s110000.pt", + "runs/real_cooking_v5/rsm/R_M_ft_v0lit/ckpt_s110000.pt"] + + +def triple_check(groups): + """W3: run 52 printed +0.212 / +0.227 / -0.130 for R_M / ft_v0 / ft_v0lit on ONE pool. On how many + pools that carry all three does v0lit actually rank last?""" + rows = [] + for g in groups: + have = {} + for ck, v in g["ck"].items(): + for t in TRIPLE: + if ck.endswith(t): + have[t] = v["paired"] + if len(have) < 3: + continue + order = sorted(TRIPLE, key=lambda t: have[t]) + rows.append({"pool": g["example_dir"], "stage": g["stage"], "K": g["K"], + "R_M": have[TRIPLE[0]], "ft_v0": have[TRIPLE[1]], "ft_v0lit": have[TRIPLE[2]], + "v0lit_last": order[0] == TRIPLE[2], "worst": os.path.basename( + os.path.dirname(order[0]))}) + return {"n_pools_with_all_three": len(rows), + "frac_v0lit_last": (float(np.mean([r["v0lit_last"] for r in rows])) if rows + else float("nan")), + "rows": rows} + + +def step_series(groups, min_steps): + """W4: within a fixed pool, checkpoints that differ ONLY in the training step of the same run dir.""" + rows = [] + for g in groups: + byrun = {} + for ck, v in g["ck"].items(): + run, base = os.path.dirname(ck), os.path.basename(ck) + if not (base.startswith("ckpt_s") and base.endswith(".pt")): + continue + try: + step = int(base[len("ckpt_s"):-3]) + except ValueError: + continue + byrun.setdefault(run, []).append((step, v["paired"])) + for run, pts in byrun.items(): + if len(pts) < min_steps: + continue + pts.sort() + st = [p[0] for p in pts]; vv = [p[1] for p in pts] + rows.append({"pool": g["example_dir"], "stage": g["stage"], "run": os.path.basename(run), + "n_steps": len(pts), "steps": st, "paired": vv, + "spearman_vs_step": spearman_simple(st, vv), + "delta_last_first": vv[-1] - vv[0]}) + fin = [r["spearman_vs_step"] for r in rows if np.isfinite(r["spearman_vs_step"])] + return {"n_series": len(rows), "n_series_finite": len(fin), + "frac_positive_spearman": float(np.mean(np.array(fin) > 0)) if fin else float("nan"), + "median_spearman": float(np.median(fin)) if fin else float("nan"), "rows": rows} + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--root", default="status/real/rankctrl") + ap.add_argument("--out", default="status/real/ACT_COND/CONC_SWEEP_run53.json") + ap.add_argument("--seed", type=int, default=0) + ap.add_argument("--procs", type=int, default=8) + ap.add_argument("--limit", type=int, default=0) + ap.add_argument("--min-pairs", type=int, default=100) + ap.add_argument("--min-shared", type=int, default=8) + a = ap.parse_args() + tols = (0.02, 0.05) + + dirs = sorted(dn for dn in os.listdir(a.root) + if os.path.isfile(os.path.join(a.root, dn, "per_anchor.npz"))) + if a.limit: + dirs = dirs[:a.limit] + print("[sweep] %d caches, %d procs" % (len(dirs), a.procs), flush=True) + t0 = time.time() + with Pool(a.procs) as pool: + cells = pool.map(one_cache, [(dn, a.root, a.seed, tols) for dn in dirs], chunksize=4) + ok = [c for c in cells if c.get("ok")] + bad = [c for c in cells if not c.get("ok")] + print("[sweep] %d/%d caches ok in %.1fs; %d excluded" + % (len(ok), len(cells), time.time() - t0, len(bad)), flush=True) + for c in bad[:40]: + print(" EXCLUDED %-44s %s" % (c["dir"], c["why"]), flush=True) + + raw_p = a.out + ".raw.json" + os.makedirs(os.path.dirname(a.out), exist_ok=True) + with open(raw_p, "w") as f: # raw per-cache results land BEFORE any analysis, so a + json.dump(cells, f, default=float) # bug in the grouping cannot cost the 935-cache read + print("[sweep] wrote raw", raw_p, flush=True) + + n_reg = sum(c["n_regression_cells"] for c in ok) + a1_fail = [c for c in bad if c["why"].startswith("A1 regression")] + + # ---- W5 null sanity, over every (cache, stage) cell ------------------------------------- + perm_dev, sign_agree, sign_n = [], 0, 0 + for c in ok: + for stg, ps in c["per_stage"].items(): + v2, v5 = ps.get("tol_0p02"), ps.get("tol_0p05") + if v2 and v2["pairs_total"] >= 100: + perm_dev.append(abs(v2["permuted"]["mean"] - 0.5)) + if v2 and v5 and v2["pairs_total"] >= 100 and v5["pairs_total"] >= 100: + sign_n += 1 + sign_agree += int(np.sign(v2["paired"]["mean"]) == np.sign(v5["paired"]["mean"])) + perm_dev = np.array(perm_dev) if perm_dev else np.array([np.nan]) + + res = {"run": 53, "stream": "ACT_COND", + "question": "run 52 recommended the pose-matched pair concordance as a model-selection " + "statistic on the evidence of 3 checkpoints on 1 pool. Does the checkpoint " + "ranking it induces REPLICATE ACROSS POOLS?", + "inputs_are": "RANK_CTRL's caches under status/real/rankctrl, READ-ONLY, freeze-witnessed " + "per cache. Nothing re-scored, nothing of theirs written.", + "n_caches": len(cells), "n_ok": len(ok), "n_excluded": len(bad), + "n_published_cells_reproduced": n_reg, "n_caches_failing_A1": len(a1_fail), + "excluded": [{"dir": c["dir"], "why": c["why"]} for c in bad], + "null_sanity_W5": {"n_cells": int(len(perm_dev)), + "frac_permuted_within_0p02_of_0p5": + float(np.mean(perm_dev <= 0.02)), + "max_abs_dev": float(np.nanmax(perm_dev)), + "median_abs_dev": float(np.nanmedian(perm_dev))}, + "tol_sign_agreement_W7": {"n_cells": sign_n, + "frac_same_sign": float(sign_agree) / max(sign_n, 1)}, + "per_cache": cells} + for tk in ("tol_0p02", "tol_0p05"): + groups = analyse(cells, tk, a.min_pairs) + xp = cross_pool([g for g in groups if g["n_ckpts"] >= 3], a.min_shared) + sp = np.array([r["spearman"] for r in xp if np.isfinite(r["spearman"])]) + multi = [g for g in groups if g["n_ckpts"] >= 2] + res[tk] = { + "n_groups": len(groups), "n_groups_multi_ckpt": len(multi), + "largest_group": (max(groups, key=lambda g: g["n_ckpts"]) if groups else None), + "groups": groups, + "run52_triple_W3": triple_check(groups), + "step_series_W4": step_series(groups, 4), + "cross_pool": {"n_pairs": len(xp), "min_shared": a.min_shared, + "median_spearman": float(np.median(sp)) if len(sp) else float("nan"), + "frac_positive": float(np.mean(sp > 0)) if len(sp) else float("nan"), + "p25": float(np.percentile(sp, 25)) if len(sp) else float("nan"), + "p75": float(np.percentile(sp, 75)) if len(sp) else float("nan"), + "rows": xp}, + } + os.makedirs(os.path.dirname(a.out), exist_ok=True) + with open(a.out, "w") as f: + json.dump(res, f, indent=1, default=float) + print("[sweep] wrote", a.out, flush=True) + + # ---- printed summary ------------------------------------------------------------------- + print("\n=== A1 GUARD: %d published (scorer,stage) cells of RANK_CTRL's reproduced from the npz; " + "%d caches failed A1 ===" % (n_reg, len(a1_fail))) + print("=== W5 null: permuted concordance within 0.02 of 0.5 on %.1f%% of %d cells (max dev %.4f) ===" + % (100 * res["null_sanity_W5"]["frac_permuted_within_0p02_of_0p5"], + res["null_sanity_W5"]["n_cells"], res["null_sanity_W5"]["max_abs_dev"])) + print("=== W7 tol sign agreement: %.1f%% of %d cells ===" + % (100 * res["tol_sign_agreement_W7"]["frac_same_sign"], sign_n)) + for tk in ("tol_0p02", "tol_0p05"): + r = res[tk] + print("\n--- %s: %d (pool,stage) groups, %d with >=2 checkpoints ---" + % (tk, r["n_groups"], r["n_groups_multi_ckpt"])) + g = r["largest_group"] + if g: + vals = np.array([v["paired"] for v in g["ck"].values()]) + excl = sum(1 for v in g["ck"].values() if v["paired_lo"] > 0 or v["paired_hi"] < 0) + print(" largest pool: %s stage %s K=%d %d checkpoints" + % (g["example_dir"], g["stage"], g["K"], g["n_ckpts"])) + print(" W1 paired concordance spread %.4f (min %.4f max %.4f), CI excludes 0 on %d/%d (%.0f%%)" + % (vals.max() - vals.min(), vals.min(), vals.max(), excl, len(vals), + 100 * excl / len(vals))) + t3 = r["run52_triple_W3"] + print(" W3 run-52 triple on %d pools carrying all three: v0lit ranks last on %.1f%%" + % (t3["n_pools_with_all_three"], 100 * t3["frac_v0lit_last"])) + s4 = r["step_series_W4"] + print(" W4 training-step series (>=4 steps, fixed pool): %d series, %.1f%% positive Spearman, " + "median %.3f" % (s4["n_series"], 100 * s4["frac_positive_spearman"], + s4["median_spearman"])) + x = r["cross_pool"] + print(" W2 cross-pool: %d pool-pairs sharing >=%d checkpoints; median Spearman %.3f " + "[p25 %.3f, p75 %.3f], %.1f%% positive" + % (x["n_pairs"], x["min_shared"], x["median_spearman"], x["p25"], x["p75"], + 100 * x["frac_positive"])) + + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/real/actcond_deployed_asi.py b/rsm_rise/scripts/real/actcond_deployed_asi.py new file mode 100644 index 0000000000000000000000000000000000000000..808ad924df096dd7ce3a306c95a7e25f9a96efdd --- /dev/null +++ b/rsm_rise/scripts/real/actcond_deployed_asi.py @@ -0,0 +1,178 @@ +#!/usr/bin/env python +"""ACT_COND run 36 -- ACTION SENSITIVITY ON THE *DEPLOYED* CANDIDATE CLOUD. + +WHY THIS EXISTS. Every ACT_COND sensitivity number to date (runs 1-35) used 128 stage-matched +LOGGED chunks as the candidate cloud (`act_sensitivity.py:11`). The scorer that actually ships +ranks 128 draws from the pi0.5 PROPOSER, and `scorer_openloop.py:149-152` already measured that +those two clouds are not the same object: proposer draws displace 23.5 +- 3.4 mm while injected +logged chunks displace 134-158 mm. A ~6x narrower cloud is a strictly harder ranking problem, so +"conditioning is sensitive" measured on logged chunks does NOT automatically transfer to the cloud +the scorer is handed at read-out -- and "how the scorer feeds candidates at read-out" is this +stream's ownership. This script closes that gap with ZERO new GPU: the EDGE runs already persisted +per-candidate scores to scores.npz (`scorer_openloop.py:722`). + +THE ESTIMAND. One variance decomposition, computed IDENTICALLY on both clouds: + within-decision var_a = mean over decisions of var over the N candidates at that decision + between-decision var_s = var over decisions of the per-decision mean score + ASI_dep = var_a / var_s frac_action = var_a / (var_a + var_s) +NOTE this is NOT the same denominator as `act_sensitivity.py`'s ASI (which fixes one chunk and +varies the state over 128 states). That is exactly why both sides are recomputed here under the +SAME formula from `mean_a_*` / `var_a_*`; the numbers in this file must not be compared to the +ASI column of runs 34/35. + +THE BUILT-IN CONTROL. The same npz carries `score_idql` on the IDENTICAL candidate clouds. The +RISE/IQL critic is the documented instance of the failure mode this stream guards against +(model.py: "a value that scores STATES but cannot rank ACTIONS"); in SIM its Q(s,a) ~ V(s). So its +frac_action on these very clouds is the reference for what "state function" looks like here, and +the RSM's number is only meaningful beside it. `score_permuted_*` shuffles the assignment of scores to candidates within a decision, so it +preserves within-row variance up to the per-episode re-seed -- it is NOT a control for this +statistic, and is reported only as a file-integrity check (MEASURED: var_a agrees to 0.5-12 %, +i.e. seed noise, exactly as the construction predicts). +""" +import argparse, json, os, sys +from pathlib import Path +import numpy as np + +ROOT = "/proj/dmfexp/zwhong/rsm_rise" + +MATCH = dict(rsm_ckpt=f"{ROOT}/runs/real_cooking_v5/rsm/R_M/ckpt_s100000.pt", + rsm_hop_ckpt=f"{ROOT}/runs/real_cooking_v5/hop/flow/policy_r1.pt", + rsm_score_kind="prob", rsm_temperature=25.0, rsm_beta=0.99, rsm_gamma=0.999) + + +def decomp(S): + """S [D, N] -> within/between decomposition, dropping non-finite rows.""" + ok = np.isfinite(S).all(1) + S = S[ok] + if S.shape[0] < 3: + return None + va = float(np.mean(S.var(axis=1, ddof=1))) # action-driven, within decision + mu = S.mean(axis=1) + vs = float(mu.var(ddof=1)) # state-driven, between decisions + cv = S.std(axis=1, ddof=1) / np.maximum(np.abs(S.mean(axis=1)), 1e-12) + # tie fraction at the max, same rel tol as act_sensitivity + tie = [] + for r in S: + m = r.max() + tie.append(float(np.mean(np.abs(r - m) <= 1e-6 * max(abs(m), 1e-12) + 1e-12))) + return dict(n_dec=int(S.shape[0]), n_cand=int(S.shape[1]), + var_a=va, var_s=vs, + asi_dep=(va / vs if vs > 0 else float("inf")), + frac_action=va / (va + vs) if (va + vs) > 0 else float("nan"), + cv_mean=float(np.mean(cv)), tie_frac_mean=float(np.mean(tie)), + tie_at_max_per_128=float(np.mean(tie) * S.shape[1]), + score_mean=float(S.mean()), score_min=float(S.min()), score_max=float(S.max())) + + +def boot_frac(S, B=5000, seed=0): + """Bootstrap over DECISIONS (the sampling unit) for frac_action.""" + ok = np.isfinite(S).all(1); S = S[ok] + D = S.shape[0] + if D < 3: + return (float("nan"), float("nan")) + rng = np.random.default_rng(seed) + per_var = S.var(axis=1, ddof=1); per_mu = S.mean(axis=1) + out = np.empty(B) + for b in range(B): + i = rng.integers(0, D, D) + va = per_var[i].mean(); vs = per_mu[i].var(ddof=1) + out[b] = va / (va + vs) if (va + vs) > 0 else np.nan + return (float(np.nanpercentile(out, 2.5)), float(np.nanpercentile(out, 97.5))) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--glob-root", default=f"{ROOT}/status/real") + ap.add_argument("--logged-shards", nargs="*", default=[ + f"{ROOT}/status/real/ACT_COND/flowhop/act_sensitivity_flowhop_s{i}.json" for i in range(4)]) + ap.add_argument("--boot", type=int, default=5000) + ap.add_argument("--out", default=f"{ROOT}/status/real/ACT_COND/DEPLOYED_ASI_run36.json") + a = ap.parse_args() + + res = {"match_required": MATCH, "deployed": [], "logged": {}, "notes": []} + + # ---------- (1) DEPLOYED cloud: every EDGE dir whose config matches MINE exactly ---------- + cand_dirs = sorted({p.parent for p in Path(a.glob_root).glob("*/scores.npz")}) + print(f"[dep] {len(cand_dirs)} dirs carry scores.npz", flush=True) + for d in cand_dirs: + cfg_p = d / "scorer_openloop.json" + if not cfg_p.exists(): + continue + cfg = json.load(open(cfg_p)) + args_ = cfg.get("args", cfg) + mism = [k for k, v in MATCH.items() + if not (k in args_ and (args_[k] == v or + (isinstance(v, float) and isinstance(args_[k], (int, float)) + and abs(args_[k] - v) < 1e-9)))] + if mism: + continue + z = np.load(d / "scores.npz") + if "score_rsm" not in z.files: + continue + row = {"dir": d.name, "policy": args_.get("policy", "?"), + "n_cand_cfg": args_.get("n_cand"), "particles": args_.get("rsm_particles"), + "stride": args_.get("stride")} + for m in ("rsm", "idql", "permuted_rsm"): + k = "score_" + m + if k in z.files: + dc = decomp(z[k].astype(np.float64)) + if dc is not None: + dc["frac_action_ci"] = boot_frac(z[k].astype(np.float64), a.boot) + row[m] = dc + res["deployed"].append(row) + print(f"[dep] {d.name:32s} N={row['n_cand_cfg']} " + f"rsm frac_action={row.get('rsm',{}).get('frac_action',float('nan')):.4f} " + f"idql={row.get('idql',{}).get('frac_action',float('nan')):.4f}", flush=True) + + # ---------- (2) LOGGED cloud: the SAME decomposition from my own 800 anchors ---------- + for kind in ("prob", "logit"): + rows = [] + for sh in a.logged_shards: + if not os.path.exists(sh): + continue + d = json.load(open(sh)) + rows += d["rows"] + if not rows: + continue + va = np.array([r[f"var_a_{kind}"] for r in rows], float) + mu = np.array([r[f"mean_a_{kind}"] for r in rows], float) + ok = np.isfinite(va) & np.isfinite(mu) + va, mu = va[ok], mu[ok] + v_a = float(va.mean()); v_s = float(mu.var(ddof=1)) + rng = np.random.default_rng(0); B = a.boot; out = np.empty(B) + for b in range(B): + i = rng.integers(0, len(va), len(va)) + x = va[i].mean(); y = mu[i].var(ddof=1) + out[b] = x / (x + y) if (x + y) > 0 else np.nan + res["logged"][kind] = dict( + n_anchors=int(len(va)), var_a=v_a, var_s=v_s, + asi_dep=(v_a / v_s if v_s > 0 else float("inf")), + frac_action=v_a / (v_a + v_s), + frac_action_ci=(float(np.nanpercentile(out, 2.5)), float(np.nanpercentile(out, 97.5))), + tie_at_max_per_128=float(np.mean([r[f"tie_frac_{kind}"] for r in rows]) * 128), + cv_mean=float(np.mean([r[f"cv_{kind}"] for r in rows])), + src="act_sensitivity flowhop shards, mean_a_*/var_a_* recomputed under the deployed formula") + # per stage + by = {} + for st in sorted({r["stage"] for r in rows}): + sel = [r for r in rows if r["stage"] == st] + x = np.array([r[f"var_a_{kind}"] for r in sel], float) + y = np.array([r[f"mean_a_{kind}"] for r in sel], float) + m = np.isfinite(x) & np.isfinite(y); x, y = x[m], y[m] + if len(x) < 3: + continue + A, Sv = float(x.mean()), float(y.var(ddof=1)) + by[str(st)] = dict(n=int(len(x)), var_a=A, var_s=Sv, + asi_dep=(A / Sv if Sv > 0 else float("inf")), + frac_action=A / (A + Sv)) + res["logged"][kind]["by_stage"] = by + print(f"[log] {kind}: frac_action={res['logged'][kind]['frac_action']:.4f} " + f"asi_dep={res['logged'][kind]['asi_dep']:.3f} n={len(va)}", flush=True) + + os.makedirs(os.path.dirname(a.out), exist_ok=True) + json.dump(res, open(a.out, "w"), indent=1) + print("wrote", a.out, flush=True) + + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/real/actcond_frozen.py b/rsm_rise/scripts/real/actcond_frozen.py new file mode 100644 index 0000000000000000000000000000000000000000..117588c1ef1453bcbb610d0f2530955b39c72962 --- /dev/null +++ b/rsm_rise/scripts/real/actcond_frozen.py @@ -0,0 +1,269 @@ +#!/usr/bin/env python +"""ACT_COND run 48 -- close the vintage thread at FINAL length, and fix a stale number in my own +headline. + +All four gamma dirs are frozen at 80 parts (untouched 2h+ at 00:41Z). Runs 44-47 measured them +mid-flight, so every vintage statement I shipped rests on a partial read. This reads them at final +length and settles: + (Y4) family-wide -- does run 44's -0.114 "the config is anti-goal-directed" alarm survive the + freeze, or was it vintage (a short dir with a high on-route base and no headroom)? +and repairs run 46's (Z3), which substituted the refreshed values into the LIFT headline but left +the AUC headline -- the estimand I am telling other streams to quote -- on the stale 19:46Z cache. + +Pre-registered in status/real/ACT_COND.md before submission: + (W0) loader null EXACT on lift AND auc, 2 frozen control dirs, else exit 3. + (W1) freeze proof: (name,size,mtime) snapshot before and after; a dir that moved is EXCLUDED. + (W2) all 4 frozen lifts in [-0.070,-0.020] and family mean > -0.060; any dir below -0.070 and + run 47's "mostly vintage, family-wide" is withdrawn for that cell. + (W3) |dlift| > |dauc| in >= 2 of 3 over the final 71/67/70 -> 80 window. + (W4) lift headline moves >0.001 and <0.004 and its CI STILL INCLUDES 0; the AUC headline keeps + its sign and its significance. + (W5) the run-47 sign flip (gap>0 at k=1, gap<0 at k=64) holds in >= 3 of 4 dirs. n=4: signs only. +""" +import argparse, json, os, shutil, sys, tempfile +import numpy as np + +sys.path.insert(0, "/proj/dmfexp/zwhong/rsm_rise/scripts/real") +from actcond_goal_directedness import boot_ci # noqa: E402 +from actcond_prefix import REAL, CACHE, parts_in_write_order, load_prefix, stats_for # noqa: E402 +from actcond_topk import curve_for, KLAD # noqa: E402 + +GAMMA = ["edge_s2ro_v0lit_g995_sh0of1", "edge_s2ro_v0lit_g9975_sh0of1", + "edge_s2ro_v5_g995_sh0of1", "edge_s2ro_v5_g9975_sh0of1"] +NULL_DIRS = ["edge_s2ro_v0lit_crn1_sh0of1", "edge_s2ro_v5_p0_sh0of1"] +RUN47 = "/proj/dmfexp/zwhong/rsm_rise/status/real/ACT_COND/TOPK_run47.json" +MODES = ["rsm", "permuted__rsm", "idql", "permuted__idql"] +BAND_LO, BAND_HI = -0.070, -0.020 + + +def snapshot(d): + """(name, size, mtime) of every part -- the freeze witness.""" + ep = os.path.join(d, "edge_parts") + out = {} + for f in sorted(os.listdir(ep)): + if f.startswith("ep") and f.endswith(".npz"): + st = os.stat(os.path.join(ep, f)) + out[f] = [int(st.st_size), float(st.st_mtime)] + return out + + +def argmax_lift(row, var): + return row["variants"].get(var, {}).get("rules", {}).get("argmax", {}).get("onroute_lift") + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--out", required=True) + ap.add_argument("--boot", type=int, default=20000) + ap.add_argument("--tmp", default=os.environ.get("TMPDIR", "/tmp")) + a = ap.parse_args() + rows = json.load(open(CACHE)) + cache = {r["dir"]: r for r in rows} + r47 = json.load(open(RUN47))["gamma"] + out = dict(generated=str(np.datetime64("now")), cache=CACHE, n_dirs=len(rows), boot=a.boot, + band=[BAND_LO, BAND_HI]) + tmproot = tempfile.mkdtemp(dir=a.tmp, prefix="actcond_frozen_") + + # ---------------------------------------------------------------- (W0) loader null, lift AND auc + null = [] + for name in NULL_DIRS: + files, _ = parts_in_write_order(f"{REAL}/{name}") + st = stats_for(load_prefix(f"{REAL}/{name}", files, tmproot), "rsm", B=0) + rl, ra = argmax_lift(cache[name], "rsm"), cache[name]["variants"]["rsm"].get("onroute_auc") + null.append(dict(dir=name, n_parts=len(files), + lift_mine=None if st is None else st["onroute_lift"], lift_cache=rl, + auc_mine=None if st is None else st["onroute_auc"], auc_cache=ra, + d_lift=None if st is None or rl is None else abs(st["onroute_lift"] - rl), + d_auc=None if st is None or ra is None else abs(st["onroute_auc"] - ra))) + out["W0_null"] = null + print("=== (W0) NULL: lift AND auc through the run-45 symlink loader, 2 frozen control dirs ===") + for r in null: + print(f" {r['dir']:32s} lift {r['lift_mine']} vs {r['lift_cache']} |d|={r['d_lift']}") + print(f" {'':32s} auc {r['auc_mine']} vs {r['auc_cache']} |d|={r['d_auc']}") + bad = [r for r in null if None in (r["d_lift"], r["d_auc"]) or r["d_lift"] > 0.0 or r["d_auc"] > 0.0] + out["W0_pass"] = not bad + json.dump(out, open(a.out, "w"), default=float, indent=1) + if bad: + print("[FAIL] (W0) -- no number reported.") + shutil.rmtree(tmproot, ignore_errors=True); sys.exit(3) + print(" PASS -- exact on both estimands") + + # ---------------------------------------------------------------- (W1)+(W2) the frozen read + print("\n=== (W1) freeze proof + (W2) the frozen family read ===") + frozen, moved = {}, [] + for name in GAMMA: + d = f"{REAL}/{name}" + before = snapshot(d) + files, name_eq_mtime = parts_in_write_order(d) + got = load_prefix(d, files, tmproot) + rec = dict(n_parts=len(files), name_order_eq_mtime=bool(name_eq_mtime)) + for mode in MODES: + st = stats_for(got, mode, B=(a.boot if mode == "rsm" else 0)) + rec[mode] = None if st is None else dict( + n_dec=st["n_dec"], n_cand=st["n_cand"], n_mixed=st["n_mixed"], + base=st["onroute_base"], lift=st["onroute_lift"], auc=st["onroute_auc"], + n_tied_at_max=st["n_tied_at_max"], lift_ci=st.get("onroute_lift_ci")) + # top-k curve, for (W5) + if got is not None: + O, A, P, E, S, Lm, nk = got + N = O.shape[1] + ks = [k for k in KLAD if k < N] + [N] + rec["ks"] = ks + rec["curves"] = {} + for mode in MODES: + if mode in S: + cv = curve_for(S[mode], O.astype(float), ks) + if cv is not None: + rec["curves"][mode] = [float(v) for v in cv[0]] + after = snapshot(d) + rec["froze_during_read"] = (before == after) + rec["n_parts_before"] = len(before); rec["n_parts_after"] = len(after) + rec["run47"] = r47.get(name, {}).get("now") + rec["cache_lift"] = argmax_lift(cache[name], "rsm") + rec["cache_auc"] = cache[name]["variants"]["rsm"].get("onroute_auc") + if not rec["froze_during_read"]: + moved.append(name) + frozen[name] = rec + out["frozen"] = frozen + out["W1_moved"] = moved + out["W1_pass"] = not moved + stable = [n for n in GAMMA if frozen[n]["froze_during_read"]] + print(f" parts stable during the read: {len(stable)}/4 moved: {moved or 'none'}") + print(f" {'dir':34s} {'parts':>5s} {'dec':>5s} {'base':>8s} {'lift47':>9s} {'liftNOW':>9s} " + f"{'auc47':>7s} {'aucNOW':>7s} {'tied':>6s}") + for n in GAMMA: + r = frozen[n]; rs = r["rsm"]; p47 = r["run47"] or {} + print(f" {n:34s} {r['n_parts']:5d} {rs['n_dec']:5d} {rs['base']:8.4f} " + f"{p47.get('lift', float('nan')):+9.4f} {rs['lift']:+9.4f} " + f"{p47.get('auc', float('nan')):7.4f} {rs['auc']:7.4f} {rs['n_tied_at_max']:6.3f}") + lifts = [frozen[n]["rsm"]["lift"] for n in stable] + inband = [n for n in stable if BAND_LO <= frozen[n]["rsm"]["lift"] <= BAND_HI] + below = [n for n in stable if frozen[n]["rsm"]["lift"] < BAND_LO] + out["W2"] = dict(n_stable=len(stable), lifts={n: frozen[n]["rsm"]["lift"] for n in stable}, + n_in_band=len(inband), below_band=below, + family_mean_lift=float(np.mean(lifts)) if lifts else None, + cache_family_mean_lift=float(np.mean([frozen[n]["cache_lift"] for n in stable]))) + out["W2_pass"] = bool(len(inband) == len(stable) and np.mean(lifts) > -0.060) + print(f" (W2) in band [{BAND_LO},{BAND_HI}]: {len(inband)}/{len(stable)} below band: {below or 'none'}") + print(f" family mean lift {out['W2']['family_mean_lift']:+.5f} " + f"(cache said {out['W2']['cache_family_mean_lift']:+.5f}; run 44 alarm -0.114) " + f"PASS={out['W2_pass']}") + json.dump(out, open(a.out, "w"), default=float, indent=1) + + # ---------------------------------------------------------------- (W3) the final growth window + grew = [n for n in stable if (frozen[n]["run47"] or {}).get("n_dec") not in (None, frozen[n]["rsm"]["n_dec"])] + w3 = [] + for n in grew: + p = frozen[n]["run47"]; c = frozen[n]["rsm"] + dl, da = abs(c["lift"] - p["lift"]), abs(c["auc"] - p["auc"]) + w3.append(dict(dir=n, dlift=dl, dauc=da, ratio=(dl / da) if da > 0 else None, + calmer=bool(da < dl))) + out["W3"] = dict(n_grew=len(w3), n_calmer=sum(r["calmer"] for r in w3), per_dir=w3) + out["W3_pass"] = bool(sum(r["calmer"] for r in w3) >= 2) + print(f"\n=== (W3) final growth window, {len(w3)} dirs that grew since run 47 ===") + for r in w3: + print(f" {r['dir']:34s} |dlift| {r['dlift']:.4f} |dauc| {r['dauc']:.4f} " + f"ratio {r['ratio'] if r['ratio'] is None else round(r['ratio'], 2)} calmer={r['calmer']}") + print(f" (W3) AUC calmer in {out['W3']['n_calmer']}/{len(w3)} PASS={out['W3_pass']}") + + # ---------------------------------------------------------------- (W4) the headline, both units + L = {r["dir"]: argmax_lift(r, "rsm") for r in rows} + PL = {r["dir"]: argmax_lift(r, "permuted__rsm") for r in rows} + AU = {r["dir"]: r["variants"].get("rsm", {}).get("onroute_auc") for r in rows} + PA = {r["dir"]: r["variants"].get("permuted__rsm", {}).get("onroute_auc") for r in rows} + AI = {r["dir"]: r["variants"].get("idql", {}).get("onroute_auc") for r in rows} + PI = {r["dir"]: r["variants"].get("permuted__idql", {}).get("onroute_auc") for r in rows} + + def headline(vmap, pmap, seed): + ds = [d for d in cache if vmap.get(d) is not None] + v = np.array([vmap[d] for d in ds]) + cs = [d for d in ds if pmap.get(d) is not None] + c = np.array([vmap[d] - pmap[d] for d in cs]) + return dict(n=len(ds), mean=float(v.mean()), ci=boot_ci(v, a.boot, seed), + n_contrib=len(cs), mean_contrib=float(c.mean()), + ci_contrib=boot_ci(c, a.boot, seed + 1), + frac_pos=float((c > 0).mean()), + excludes_zero=bool(boot_ci(c, a.boot, seed + 1)[0] > 0 + or boot_ci(c, a.boot, seed + 1)[1] < 0)) + + sub_l, sub_pl, sub_a, sub_pa, sub_ai, sub_pi = dict(L), dict(PL), dict(AU), dict(PA), dict(AI), dict(PI) + for n in stable: + r = frozen[n] + for mode, dl, da in (("rsm", sub_l, sub_a), ("permuted__rsm", sub_pl, sub_pa), + ("idql", None, sub_ai), ("permuted__idql", None, sub_pi)): + if r.get(mode): + if dl is not None: + dl[n] = r[mode]["lift"] + da[n] = r[mode]["auc"] + lift_before, lift_after = headline(L, PL, 10), headline(sub_l, sub_pl, 12) + auc_before, auc_after = headline(AU, PA, 14), headline(sub_a, sub_pa, 16) + # paired idql-rsm gap in AUC units, before and after + def gap(ar, pr, ai_, pi_, seed): + ds = [d for d in cache if None not in (ar.get(d), pr.get(d), ai_.get(d), pi_.get(d))] + g = np.array([(ai_[d] - pi_[d]) - (ar[d] - pr[d]) for d in ds]) + return dict(n=len(ds), mean=float(g.mean()), ci=boot_ci(g, a.boot, seed), + frac_pos=float((g > 0).mean())) + out["W4"] = dict(lift_before=lift_before, lift_after=lift_after, + d_mean_lift=lift_after["mean"] - lift_before["mean"], + d_mean_contrib_lift=lift_after["mean_contrib"] - lift_before["mean_contrib"], + auc_before=auc_before, auc_after=auc_after, + d_mean_contrib_auc=auc_after["mean_contrib"] - auc_before["mean_contrib"], + gap_auc_before=gap(AU, PA, AI, PI, 20), + gap_auc_after=gap(sub_a, sub_pa, sub_ai, sub_pi, 22), + n_substituted=len(stable)) + out["W4_lift_still_includes_zero"] = bool(not lift_after["excludes_zero"]) + out["W4_auc_keeps_significance"] = bool(auc_after["excludes_zero"] + and np.sign(auc_after["mean_contrib"]) == np.sign(auc_before["mean_contrib"])) + print(f"\n=== (W4) THE 149-DIR HEADLINE WITH {len(stable)} FROZEN DIRS SUBSTITUTED ===") + print(" LIFT units") + print(f" per-dir mean lift {lift_before['mean']:+.5f} {lift_before['ci']} -> " + f"{lift_after['mean']:+.5f} {lift_after['ci']} d={out['W4']['d_mean_lift']:+.5f}") + print(f" contribution vs perm {lift_before['mean_contrib']:+.5f} {lift_before['ci_contrib']} -> " + f"{lift_after['mean_contrib']:+.5f} {lift_after['ci_contrib']} " + f"d={out['W4']['d_mean_contrib_lift']:+.5f} excludes 0: " + f"{lift_before['excludes_zero']} -> {lift_after['excludes_zero']}") + print(" AUC units (run 46 never substituted these -- they were the stale 19:46Z cache)") + print(f" contribution vs perm {auc_before['mean_contrib']:+.5f} {auc_before['ci_contrib']} -> " + f"{auc_after['mean_contrib']:+.5f} {auc_after['ci_contrib']} " + f"d={out['W4']['d_mean_contrib_auc']:+.5f} excludes 0: " + f"{auc_before['excludes_zero']} -> {auc_after['excludes_zero']}") + gb, ga = out["W4"]["gap_auc_before"], out["W4"]["gap_auc_after"] + print(f" paired gap idql-rsm {gb['mean']:+.5f} {gb['ci']} -> {ga['mean']:+.5f} {ga['ci']}") + print(f" (W4) lift CI still includes 0: {out['W4_lift_still_includes_zero']} " + f"AUC keeps sign+significance: {out['W4_auc_keeps_significance']}") + json.dump(out, open(a.out, "w"), default=float, indent=1) + + # ---------------------------------------------------------------- (W5) sign flip at final length + w5 = [] + for n in stable: + r = frozen[n] + cur = r.get("curves", {}) + if not all(m in cur for m in MODES): + continue + ks = r["ks"] + + def g(k): + if k not in ks: + return None + i = ks.index(k) + return (cur["idql"][i] - cur["permuted__idql"][i]) - (cur["rsm"][i] - cur["permuted__rsm"][i]) + g1, g64 = g(1), g(64) + w5.append(dict(dir=n, gap_k1=g1, gap_k64=g64, + flip=bool(g1 is not None and g64 is not None and g1 > 0 > g64), + curve={str(k): g(k) for k in ks})) + nflip = sum(r["flip"] for r in w5) + out["W5"] = dict(n=len(w5), n_flip=nflip, per_dir=w5) + out["W5_pass"] = bool(nflip >= 3) + print(f"\n=== (W5) does run 47's sign flip survive at final length? ({len(w5)} frozen dirs) ===") + for r in w5: + print(f" {r['dir']:34s} gap(k=1) {r['gap_k1']:+.5f} gap(k=64) {r['gap_k64']:+.5f} " + f"flip={r['flip']}") + print(f" (W5) flip in {nflip}/{len(w5)} PASS={out['W5_pass']} (n=4: signs only, no p-value)") + + shutil.rmtree(tmproot, ignore_errors=True) + json.dump(out, open(a.out, "w"), default=float, indent=1) + print(f"\n[out] {a.out}") + + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/real/actcond_goal_directedness.py b/rsm_rise/scripts/real/actcond_goal_directedness.py new file mode 100644 index 0000000000000000000000000000000000000000..c9dc8181a945b4d24192757fb09c905f1f001242 --- /dev/null +++ b/rsm_rise/scripts/real/actcond_goal_directedness.py @@ -0,0 +1,522 @@ +#!/usr/bin/env python +"""ACT_COND run 39 -- does the RSM pick actions LEADING TO THE GOAL STATE, within the candidate cloud? + +Run 38 measured within-cloud selection against `err_first` = cm distance to the LOGGED action, and +found the RSM's pick sub-chance (0.4197 vs a permuted null of 0.4955). It shipped with one caveat at +full strength: *a value function is not an imitator, so preferring a candidate that makes MORE progress +than the logged action is legitimate and reads as sub-chance here*, and `scores.npz` stores no candidate +actions, so the two readings could not be separated. + +They can. `/edge_parts/ep*.npz` -- written by the same scorer run, `scorer_openloop.py:336` -- has +carried the raw geometry all along: + + cand_disp_mm [n_anchor, N, 3] candidate displacement over the edge horizon, base frame, mm + logged_disp_mm [n_anchor, 3] the logged action's displacement over the SAME horizon + onroute [n_anchor, N] bool: does this candidate head down an ON-ROUTE edge + cls [n_anchor, N] which available edge the candidate's direction matches (-1 = still) + score_ [n_anchor, N] the same scores scores.npz aggregates + +`onroute` is the estimand this stream has been missing. It is assigned by the cosine of the candidate's +own direction against the edge direction fields (`scorer_openloop.py:617-624`) and it NEVER REFERENCES +THE LOGGED ACTION, so it is completely free of run 38's imitator caveat. It is also literally the +owner's question -- "sensitive enough to action to pick actions leading to goal state". + +Three families of estimand, per (dir, score mode): + + A. GOAL-DIRECTEDNESS (caveat-free). onroute rate of the PICK vs the cloud's own base rate (`lift`), + and the within-decision Mann-Whitney AUC of score for onroute vs off-route candidates. The AUC + uses the whole ranking, so it has far more power than the argmax alone. Only decisions with a + MIXED cloud (0 < n_onroute < N) can discriminate, and only those are counted. + + B. PROGRESS DECOMPOSITION (attributes run 38's deficit). With u = logged_disp/|logged_disp|, + along = c.u and perp = |c - along*u|. A pick that is far from the logged action because it + travels FURTHER in the logged direction is the legitimate reading; one that is far because it + goes SIDEWAYS is the defect reading. Reported as rank-pct of the pick under `along` (chance .5), + under `-perp`, under `-err`, plus the mm offsets vs the cloud mean. + + C. NULLS. `permuted:*` is a within-row shuffle: same score distribution, zero correspondence to + anything, so it must land at lift 0 / AUC .5 on every estimand above. + +Ties are handled exactly as in run 38: every "pick" statistic is the EXPECTATION over the tied-at-max +set under uniform tie-break, because argmax on a tied vector returns index 0, which is not a +measurement. `_rank_parts` is lifted verbatim from `actcond_sensitivity_pays.py` (run 38), where it was +cross-checked against `scipy.stats.rankdata` at max abs diff 0.0. + +Injected candidates (indices >= n_proposer) are DROPPED: they are planted with known provenance and +would turn a within-cloud question into run 33's between-route question, which is already answered. +""" +import argparse, json, os, glob +from pathlib import Path +import numpy as np + +ROOT = "/proj/dmfexp/zwhong/rsm_rise" +TIE_RTOL, TIE_ATOL = 1e-6, 1e-12 + + +# ---------------------------------------------------------------- ranks (verbatim from run 38) +def _rank_parts(A): + """Vectorised ranks along axis 1 -> (avg, first, last), all 0-based. + + `first` = number of entries strictly LESS than this value; `last` = N-1-(number strictly greater). + `avg` is scipy `rankdata` minus 1. Validated against scipy in run 38 at max abs diff 0.0. + """ + A = np.asarray(A, float) + D, N = A.shape + order = np.argsort(A, axis=1, kind="stable") + As = np.take_along_axis(A, order, axis=1) + idx = np.broadcast_to(np.arange(N, dtype=float), (D, N)) + startflag = np.ones((D, N), bool); startflag[:, 1:] = As[:, 1:] != As[:, :-1] + first_s = np.maximum.accumulate(np.where(startflag, idx, -np.inf), axis=1) + endflag = np.ones((D, N), bool); endflag[:, :-1] = As[:, 1:] != As[:, :-1] + last_s = np.minimum.accumulate(np.where(endflag, idx, np.inf)[:, ::-1], axis=1)[:, ::-1] + avg_s = 0.5 * (first_s + last_s) + avg = np.empty((D, N)); first = np.empty((D, N)); last = np.empty((D, N)) + np.put_along_axis(avg, order, avg_s, axis=1) + np.put_along_axis(first, order, first_s, axis=1) + np.put_along_axis(last, order, last_s, axis=1) + return avg, first, last + + +def rank_pct_high(X): + """fraction of the OTHER candidates with a strictly SMALLER value (higher value = better).""" + N = X.shape[1] + return _rank_parts(X)[1] / max(N - 1, 1) + + +def rank_pct_low(X): + """fraction of the OTHER candidates with a strictly LARGER value (lower value = better). + + Same estimand run 38 used for err, so the `-err` column here is directly comparable to it. + """ + N = X.shape[1] + return ((N - 1.0) - _rank_parts(X)[2]) / max(N - 1, 1) + + +def tie_mask(S): + mx = S.max(axis=1, keepdims=True) + return np.abs(S - mx) <= TIE_RTOL * np.maximum(np.abs(mx), 1e-12) + TIE_ATOL + + +def pick_expect(tied, V): + """expectation of V over the tied-at-max set, per decision.""" + n = tied.sum(axis=1) + return (V * tied).sum(axis=1) / np.maximum(n, 1) + + +def auc_rows(S, pos): + """within-decision Mann-Whitney AUC of S for pos vs ~pos, ties counted 0.5. NaN if not mixed.""" + avg, _, _ = _rank_parts(S) + r = avg + 1.0 # 1-based tie-averaged ranks + npos = pos.sum(axis=1).astype(float) + nneg = pos.shape[1] - npos + spos = (r * pos).sum(axis=1) + out = (spos - npos * (npos + 1.0) / 2.0) / np.maximum(npos * nneg, 1e-300) + return np.where((npos > 0) & (nneg > 0), out, np.nan) + + +def boot_ci(v, B, seed, lo=2.5, hi=97.5): + v = np.asarray(v, float); v = v[np.isfinite(v)] + if len(v) < 3: + return None + rng = np.random.default_rng(seed) + m = np.nanmean(v[rng.integers(0, len(v), size=(B, len(v)))], axis=1) + return [float(np.percentile(m, lo)), float(np.percentile(m, hi))] + + +# ---------------------------------------------------------------- the estimands +def goal_stats(S, O, A, P, E, B=1000, seed=0): + """S score [D,N]; O onroute bool [D,N]; A along mm; P perp mm; E err-to-logged mm.""" + S = np.asarray(S, float) + ok = np.isfinite(S).all(1) + if ok.sum() < 3: + return None + S, O, A, P, E = S[ok], O[ok], A[ok], P[ok], E[ok] + D, N = S.shape + tied = tie_mask(S) + ntied = tied.sum(axis=1) + + base = O.mean(axis=1) # cloud onroute base rate, per decision + pick_or = pick_expect(tied, O.astype(float)) + mixed = (base > 0) & (base < 1) # only a mixed cloud can discriminate + auc = auc_rows(S, O) + + rp_along = pick_expect(tied, rank_pct_high(A)) + rp_perp = pick_expect(tied, rank_pct_low(P)) + rp_err = pick_expect(tied, rank_pct_low(E)) + d_along = pick_expect(tied, A - A.mean(axis=1, keepdims=True)) + d_perp = pick_expect(tied, P - P.mean(axis=1, keepdims=True)) + d_err = pick_expect(tied, E - E.mean(axis=1, keepdims=True)) + + out = dict( + n_dec=int(D), n_cand=int(N), n_mixed=int(mixed.sum()), + n_tied_at_max=float(ntied.mean()), + onroute_base=float(base.mean()), + onroute_base_mixed=float(base[mixed].mean()) if mixed.any() else None, + onroute_pick=float(pick_or[mixed].mean()) if mixed.any() else None, + onroute_lift=float((pick_or - base)[mixed].mean()) if mixed.any() else None, + onroute_auc=float(np.nanmean(auc)) if np.isfinite(auc).any() else None, + rank_pct_along=float(rp_along.mean()), rank_pct_negperp=float(rp_perp.mean()), + rank_pct_negerr=float(rp_err.mean()), + d_along_mm=float(d_along.mean()), d_perp_mm=float(d_perp.mean()), d_err_mm=float(d_err.mean()), + along_cloud_mm=float(A.mean()), perp_cloud_mm=float(P.mean()), err_cloud_mm=float(E.mean()), + var_a=float(S.var(axis=1, ddof=1).mean()), + ) + if B: + if mixed.any(): + out["onroute_lift_ci"] = boot_ci((pick_or - base)[mixed], B, seed) + out["onroute_auc_ci"] = boot_ci(auc, B, seed + 1) + out["rank_pct_along_ci"] = boot_ci(rp_along, B, seed + 2) + out["rank_pct_negperp_ci"] = boot_ci(rp_perp, B, seed + 3) + out["rank_pct_negerr_ci"] = boot_ci(rp_err, B, seed + 4) + return out + + +# ---------------------------------------------------------------- loading +def load_dir(d): + """merge edge_parts/ep*.npz for one dir -> (O, A, P, E, {mode: S}) over PROPOSER candidates only.""" + parts = sorted(glob.glob(os.path.join(d, "edge_parts", "ep*.npz"))) + O = []; CD = []; LD = []; SC = {}; nprop = [] + nkeep = 0 + for f in parts: + try: + z = np.load(f, allow_pickle=True) + except Exception: + continue + if "cand_disp_mm" not in z.files or "onroute" not in z.files: + continue # empty-record episode (`if recs:` guard) + meta = json.loads(z["__meta__"].tobytes().decode()) + npz_ = np.array([int(m.get("n_proposer", z["onroute"].shape[1])) for m in meta]) + O.append(z["onroute"]); CD.append(z["cand_disp_mm"]); LD.append(z["logged_disp_mm"]) + nprop.append(npz_) + for k in z.files: + if k.startswith("score_"): + SC.setdefault(k[len("score_"):], []).append(np.asarray(z[k], float)) + nkeep += 1 + if not O: + return None + # every anchor in a dir must share N so the stack is rectangular; scorer_openloop guarantees it + Ns = {a.shape[1] for a in O} + if len(Ns) != 1: + return None + O = np.concatenate(O, 0).astype(bool) + CD = np.concatenate(CD, 0).astype(float) + LD = np.concatenate(LD, 0).astype(float) + nprop = np.concatenate(nprop, 0) + S = {} + for k, v in SC.items(): + if sum(x.shape[0] for x in v) == O.shape[0] and all(x.shape[1] == O.shape[1] for x in v): + S[k] = np.concatenate(v, 0) + if not S: + return None + # drop injected candidates: keep the leading n_proposer columns (constant within a dir by + # construction -- a varying n_proposer would mean the injection slots are not aligned, so bail) + npmin = int(nprop.min()) + if npmin < 3: + return None + if npmin < O.shape[1]: + O = O[:, :npmin]; CD = CD[:, :npmin] + S = {k: v[:, :npmin] for k, v in S.items()} + Lm = np.linalg.norm(LD, axis=1) + good = np.isfinite(Lm) & (Lm > 1e-6) & np.isfinite(CD).all(axis=(1, 2)) + if good.sum() < 3: + return None + O, CD, LD, Lm = O[good], CD[good], LD[good], Lm[good] + S = {k: v[good] for k, v in S.items()} + u = LD / Lm[:, None] # [D,3] unit logged direction + A = np.einsum("dnc,dc->dn", CD, u) # along, mm (signed) + P = np.linalg.norm(CD - A[:, :, None] * u[:, None, :], axis=2) # perp, mm + E = np.linalg.norm(CD - LD[:, None, :], axis=2) # distance to the logged disp, mm + return O, A, P, E, S, float(Lm.mean()), nkeep + + +# ---------------------------------------------------------------- selftest +def selftest(): + res = [] + + def chk(name, got, want, tol): + ok = (got is not None) and abs(float(got) - want) <= tol + res.append(dict(name=name, got=None if got is None else float(got), want=want, tol=tol, ok=bool(ok))) + print(f"[selftest] {'PASS' if ok else 'FAIL':4s} {name:38s} got={got} want={want}+-{tol}", flush=True) + + rng = np.random.default_rng(0) + D, N = 2000, 64 + O = rng.random((D, N)) < 0.6 + O[:, 0] = True; O[:, 1] = False # guarantee every decision is mixed + CD = rng.normal(0, 5, (D, N, 3)); LD = rng.normal(0, 5, (D, 3)) + Lm = np.linalg.norm(LD, axis=1); u = LD / Lm[:, None] + A = np.einsum("dnc,dc->dn", CD, u) + P = np.linalg.norm(CD - A[:, :, None] * u[:, None, :], axis=2) + E = np.linalg.norm(CD - LD[:, None, :], axis=2) + + # geometry identity: along^2 + perp^2 == |c|^2 + ident = np.abs(A ** 2 + P ** 2 - (CD ** 2).sum(2)).max() + chk("geom along^2+perp^2==|c|^2", ident, 0.0, 1e-6) + + # perfect / anti onroute scorers + g = goal_stats(O * 1.0 + 1e-3 * rng.random((D, N)), O, A, P, E, B=0) + chk("perfect onroute AUC", g["onroute_auc"], 1.0, 1e-9) + chk("perfect onroute pick rate", g["onroute_pick"], 1.0, 1e-9) + g = goal_stats(-(O * 1.0) - 1e-3 * rng.random((D, N)), O, A, P, E, B=0) + chk("anti onroute AUC", g["onroute_auc"], 0.0, 1e-9) + chk("anti onroute pick rate", g["onroute_pick"], 0.0, 1e-9) + + # independent score -> chance on everything + g = goal_stats(rng.normal(0, 1, (D, N)), O, A, P, E, B=0) + chk("indep onroute AUC", g["onroute_auc"], 0.5, 0.02) + chk("indep onroute lift", g["onroute_lift"], 0.0, 0.02) + chk("indep rank_pct_along", g["rank_pct_along"], 0.5, 0.02) + chk("indep rank_pct_negperp", g["rank_pct_negperp"], 0.5, 0.02) + chk("indep rank_pct_negerr", g["rank_pct_negerr"], 0.5, 0.02) + chk("indep d_along_mm", g["d_along_mm"], 0.0, 0.5) + + # fully tied -> every pick statistic is the cloud mean exactly + g = goal_stats(np.zeros((D, N)), O, A, P, E, B=0) + chk("tied onroute lift == 0 exactly", g["onroute_lift"], 0.0, 1e-12) + chk("tied AUC == 0.5 exactly", g["onroute_auc"], 0.5, 1e-12) + chk("tied d_along_mm == 0 exactly", g["d_along_mm"], 0.0, 1e-9) + chk("tied n_tied_at_max == N", g["n_tied_at_max"], N, 1e-9) + + # perfect `along` scorer -> rank_pct_along 1.0; perfect `-perp` -> rank_pct_negperp 1.0 + g = goal_stats(A, O, A, P, E, B=0) + chk("score==along -> rank_pct_along", g["rank_pct_along"], 1.0, 1e-9) + g = goal_stats(-P, O, A, P, E, B=0) + chk("score==-perp -> rank_pct_negperp", g["rank_pct_negperp"], 1.0, 1e-9) + g = goal_stats(-E, O, A, P, E, B=0) + chk("score==-err -> rank_pct_negerr", g["rank_pct_negerr"], 1.0, 1e-9) + + # AUC against a brute-force O(N^2) Mann-Whitney on a heavily-tied integer matrix + Ss = rng.integers(0, 4, (200, 32)).astype(float) + Os = rng.random((200, 32)) < 0.5 + Os[:, 0] = True; Os[:, 1] = False + fast = auc_rows(Ss, Os) + slow = np.empty(len(Ss)) + for i in range(len(Ss)): + p = Ss[i][Os[i]]; q = Ss[i][~Os[i]] + slow[i] = ((p[:, None] > q[None, :]).sum() + 0.5 * (p[:, None] == q[None, :]).sum()) / (len(p) * len(q)) + chk("AUC vs brute-force Mann-Whitney", np.abs(fast - slow).max(), 0.0, 1e-12) + + # rank helpers vs scipy + try: + from scipy.stats import rankdata + X = rng.integers(0, 5, (300, 40)).astype(float) + sp = np.stack([rankdata(x) - 1 for x in X]) + chk("_rank_parts avg vs scipy.rankdata", np.abs(_rank_parts(X)[0] - sp).max(), 0.0, 1e-9) + # strictly-less count from `first` + bf = np.stack([[(x < v).sum() for v in x] for x in X]).astype(float) + chk("_rank_parts first == #strictly-less", np.abs(_rank_parts(X)[1] - bf).max(), 0.0, 1e-9) + except ImportError: + res.append(dict(name="scipy", ok=True, note="scipy unavailable, cross-check skipped")) + + npass = sum(1 for r in res if r["ok"]) + print(f"[selftest] {npass}/{len(res)} PASS", flush=True) + if npass != len(res): + raise SystemExit("SELFTEST FAILED -- refusing to touch real data") + return res + + +# ---------------------------------------------------------------- aggregation +def spearman(x, y): + x = np.asarray(x, float); y = np.asarray(y, float) + m = np.isfinite(x) & np.isfinite(y) + x, y = x[m], y[m] + if len(x) < 3 or np.ptp(x) == 0 or np.ptp(y) == 0: + return None + rx = _rank_parts(x[None, :])[0][0]; ry = _rank_parts(y[None, :])[0][0] + rx = rx - rx.mean(); ry = ry - ry.mean() + den = np.sqrt((rx ** 2).sum() * (ry ** 2).sum()) + return float((rx * ry).sum() / den) if den > 0 else None + + +FAMILY = {"rsm": "rsm", "idql": "idql", "pose": "pose", "bc": "bc"} + + +def family_of(name): + if name.startswith("permuted"): + # NOT lstrip(): lstrip takes a CHARACTER SET, and "permuted__rsm".lstrip("permuted_") + # eats the leading "r" of "rsm" too. Strip the literal prefix and any separators. + return "permuted:" + family_of(name[len("permuted"):].lstrip("_")) + base = name.split("_AT_")[0].split("@")[0] + return FAMILY.get(base, base) + + +def analyse(rows, st, a): + out = dict(selftest=st, n_dirs=len(rows), generated=str(np.datetime64("now"))) + + # ---- pooled by family, decision-weighted ---- + fam = {} + for r in rows: + for name, v in r["variants"].items(): + f = family_of(name) + fam.setdefault(f, []).append(v) + tab = {} + for f, vs in sorted(fam.items()): + w = np.array([v["n_dec"] for v in vs], float) + + def wm(key, mask_none=True): + x = np.array([(v[key] if v.get(key) is not None else np.nan) for v in vs], float) + m = np.isfinite(x) + return float((x[m] * w[m]).sum() / w[m].sum()) if m.any() and w[m].sum() > 0 else None + + tab[f] = dict(n_dirs=len(vs), n_dec=int(w.sum()), + onroute_base=wm("onroute_base_mixed"), onroute_pick=wm("onroute_pick"), + onroute_lift=wm("onroute_lift"), onroute_auc=wm("onroute_auc"), + rank_pct_along=wm("rank_pct_along"), rank_pct_negperp=wm("rank_pct_negperp"), + rank_pct_negerr=wm("rank_pct_negerr"), + d_along_mm=wm("d_along_mm"), d_perp_mm=wm("d_perp_mm"), d_err_mm=wm("d_err_mm"), + n_tied_at_max=wm("n_tied_at_max"), + frac_dirs_auc_above_half=float(np.mean([ + (v["onroute_auc"] or 0.5) > 0.5 for v in vs if v.get("onroute_auc") is not None])) + if any(v.get("onroute_auc") is not None for v in vs) else None, + frac_dirs_lift_pos=float(np.mean([ + v["onroute_lift"] > 0 for v in vs if v.get("onroute_lift") is not None])) + if any(v.get("onroute_lift") is not None for v in vs) else None, + n_ci_auc_above=int(sum(1 for v in vs if v.get("onroute_auc_ci") and v["onroute_auc_ci"][0] > 0.5)), + n_ci_auc_below=int(sum(1 for v in vs if v.get("onroute_auc_ci") and v["onroute_auc_ci"][1] < 0.5)), + n_ci_lift_above=int(sum(1 for v in vs if v.get("onroute_lift_ci") and v["onroute_lift_ci"][0] > 0)), + n_ci_lift_below=int(sum(1 for v in vs if v.get("onroute_lift_ci") and v["onroute_lift_ci"][1] < 0))) + out["by_family"] = tab + + # ---- within-dir: does var_a predict GOAL-directedness? (run 38 asked this of err, not of onroute) ---- + within = [] + for r in rows: + vs = {k: v for k, v in r["variants"].items() + if family_of(k) == "rsm" and v.get("onroute_auc") is not None} + if len(vs) < 3: + continue + va = np.array([v["var_a"] for v in vs.values()]) + if va.min() <= 0 or va.max() / va.min() < 2: + continue + auc = np.array([v["onroute_auc"] for v in vs.values()]) + lift = np.array([(v["onroute_lift"] if v["onroute_lift"] is not None else np.nan) for v in vs.values()]) + within.append(dict(dir=r["dir"], n_var=len(vs), var_a_spread=float(va.max() / va.min()), + rho_varA_auc=spearman(np.log10(va), auc), + rho_varA_lift=spearman(np.log10(va), lift), + best_auc_is_max_varA=bool(np.argmax(auc) == np.argmax(va)), + auc_range=[float(auc.min()), float(auc.max())])) + rv = [w["rho_varA_auc"] for w in within if w["rho_varA_auc"] is not None] + out["within_dir_varA_vs_goal"] = dict( + n_clouds=len(within), + median_rho_varA_auc=float(np.median(rv)) if rv else None, + n_negative=int(sum(1 for v in rv if v < 0)), n_positive=int(sum(1 for v in rv if v > 0)), + n_best_is_max_varA=int(sum(1 for w in within if w["best_auc_is_max_varA"])), + clouds=sorted(within, key=lambda w: -w["var_a_spread"])[:25]) + + # ---- the proposer-widening quartet run 38 flagged ---- + quart = {r["dir"]: r for r in rows if r["dir"].startswith("edge_s2w100prop_")} + if quart: + out["proposer_quartet"] = {k: {n: {kk: v[kk] for kk in + ("n_dec", "n_mixed", "var_a", "onroute_base_mixed", "onroute_pick", + "onroute_lift", "onroute_lift_ci", "onroute_auc", "onroute_auc_ci", + "rank_pct_along", "rank_pct_negperp", "rank_pct_negerr", + "d_along_mm", "d_perp_mm", "n_tied_at_max") if kk in v} + for n, v in sorted(r["variants"].items())} + for k, r in sorted(quart.items())} + + # ---- per-dir dump for the rsm family, sorted by AUC ---- + per = [] + for r in rows: + v = r["variants"].get("rsm") + if v and v.get("onroute_auc") is not None: + per.append(dict(dir=r["dir"], n_dec=v["n_dec"], n_mixed=v["n_mixed"], + base=v["onroute_base_mixed"], auc=v["onroute_auc"], ci=v.get("onroute_auc_ci"), + lift=v["onroute_lift"], rank_along=v["rank_pct_along"], + rank_negerr=v["rank_pct_negerr"], var_a=v["var_a"])) + out["per_dir_rsm"] = sorted(per, key=lambda d: -(d["auc"] or 0)) + + # ---------- print ---------- + print("\n=== GOAL-DIRECTEDNESS by scorer family (decision-weighted) ===", flush=True) + hdr = f"{'family':18s} {'dirs':>5s} {'dec':>7s} {'base':>6s} {'pick':>6s} {'lift':>8s} {'AUC':>7s} " \ + f"{'rk_along':>9s} {'rk_-perp':>9s} {'rk_-err':>8s} {'dalong':>8s} {'dperp':>8s} {'ties':>6s}" + print(hdr); print("-" * len(hdr)) + for f, v in sorted(tab.items(), key=lambda kv: -(kv[1]["onroute_auc"] or 0)): + def g(k, w=8, p=3): + x = v[k] + return f"{x:>{w}.{p}f}" if x is not None else f"{'-':>{w}s}" + print(f"{f:18s} {v['n_dirs']:5d} {v['n_dec']:7d} {g('onroute_base',6)} {g('onroute_pick',6)} " + f"{g('onroute_lift',8,4)} {g('onroute_auc',7,4)} {g('rank_pct_along',9,4)} " + f"{g('rank_pct_negperp',9,4)} {g('rank_pct_negerr',8,4)} {g('d_along_mm',8,2)} " + f"{g('d_perp_mm',8,2)} {g('n_tied_at_max',6,1)}", flush=True) + print(f"{'':18s} CI-above/below: AUC {v['n_ci_auc_above']}/{v['n_ci_auc_below']} " + f"lift {v['n_ci_lift_above']}/{v['n_ci_lift_below']} " + f"frac dirs AUC>.5 {v['frac_dirs_auc_above_half']}", flush=True) + + w = out["within_dir_varA_vs_goal"] + print(f"\n=== within-dir: Spearman(log10 var_a, onroute AUC) over {w['n_clouds']} clouds ===") + print(f" median {w['median_rho_varA_auc']} negative {w['n_negative']} positive {w['n_positive']} " + f"best-AUC-is-max-var_a {w['n_best_is_max_varA']}/{w['n_clouds']}", flush=True) + + if "proposer_quartet" in out: + print("\n=== proposer widening quartet (identical value function, varying proposer) ===") + for d, vs in out["proposer_quartet"].items(): + v = vs.get("rsm") + if v: + print(f" {d:28s} var_a={v['var_a']:.3e} base={v['onroute_base_mixed']:.3f} " + f"pick={v['onroute_pick']:.3f} lift={v['onroute_lift']:+.4f} " + f"AUC={v['onroute_auc']:.4f} {v.get('onroute_auc_ci')}", flush=True) + + os.makedirs(Path(a.out).parent, exist_ok=True) + json.dump(out, open(a.out, "w"), indent=1, default=float) + print(f"\n[out] {a.out}", flush=True) + return out + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--glob-root", default=f"{ROOT}/status/real") + ap.add_argument("--boot", type=int, default=1000) + ap.add_argument("--reuse", action="store_true") + ap.add_argument("--out", default=f"{ROOT}/status/real/ACT_COND/GOAL_DIRECTED_run39.json") + a = ap.parse_args() + + st = selftest() + + cache = str(Path(a.out).with_suffix(".rows.json")) + if a.reuse and Path(cache).exists(): + rows = json.load(open(cache)) + print(f"[cache] reusing {len(rows)} rows", flush=True) + return analyse(rows, st, a) + + dirs = sorted({str(Path(p).parent) for p in glob.glob(os.path.join(a.glob_root, "*", "edge_parts"))}) + print(f"[scan] {len(dirs)} dirs carry edge_parts/", flush=True) + + rows = [] + for d in dirs: + try: + got = load_dir(d) + except Exception as e: + print(f"[skip] {Path(d).name}: {type(e).__name__}: {e}", flush=True) + continue + if got is None: + continue + O, A, P, E, S, Lm, nkeep = got + cfgp = Path(d) / "scorer_openloop.json" + cfg = {} + if cfgp.exists(): + try: + cfg = json.load(open(cfgp)).get("args", {}) + except Exception: + cfg = {} + row = dict(dir=Path(d).name, n_parts=nkeep, logged_disp_mm=Lm, + score_kind=cfg.get("rsm_score_kind"), temperature=cfg.get("rsm_temperature"), + beta=cfg.get("rsm_beta"), gamma=cfg.get("rsm_gamma"), policy=cfg.get("policy"), + variants={}) + for k, Sv in sorted(S.items()): + g = goal_stats(Sv, O, A, P, E, B=a.boot) + if g: + row["variants"][k] = g + if row["variants"]: + rows.append(row) + r = row["variants"].get("rsm") + if r and r.get("onroute_auc") is not None: + print(f"[dir] {Path(d).name:38s} dec={r['n_dec']:4d} mixed={r['n_mixed']:4d} " + f"base={r['onroute_base_mixed']:.3f} AUC={r['onroute_auc']:.4f} " + f"lift={r['onroute_lift']:+.4f} rk_along={r['rank_pct_along']:.3f} " + f"rk_-err={r['rank_pct_negerr']:.3f}", flush=True) + + json.dump(rows, open(cache, "w"), default=float) + print(f"[cache] {len(rows)} rows -> {cache}", flush=True) + return analyse(rows, st, a) + + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/real/actcond_headline_auc.py b/rsm_rise/scripts/real/actcond_headline_auc.py new file mode 100644 index 0000000000000000000000000000000000000000..628816b32e1c3a0b663bb7da52a6fc33b3280174 --- /dev/null +++ b/rsm_rise/scripts/real/actcond_headline_auc.py @@ -0,0 +1,158 @@ +#!/usr/bin/env python +"""ACT_COND run 46b -- reissue the ACT_COND headline in the units run 45 section 6 recommends. + +Run 45 told every stream pooling off `status/real/*/edge_parts` to quote the Mann-Whitney +`onroute_auc` rather than the argmax `onroute_lift` when dir lengths differ, and run 46 (Y2) earned +that rule cache-wide (mean |drift| 0.0572 lift vs 0.0305 auc, 1.88x; signed -0.0247 vs +0.0057, +4.33x; AUC drifts less on 78% of 124 pairs). ACT_COND's own headline is still a LIFT. This fixes +that. `onroute_auc` sits at the VARIANT level of the cache -- it needs no read-out rule, it is the +whole ranking -- so no rescan is required for the 145 unchanged dirs. + +Pre-registered in status/real/ACT_COND.md before submission: (Z1) loader null exact on 2 frozen +dirs; (Z2) the per-dir AUC-units contribution CI EXCLUDES 0 (and both sentences ship either way); +(Z3) the 4 grown dirs move the lift headline by < 0.001; (Z4) the paired idql-rsm gap in AUC units. +""" +import argparse, json, os, sys, tempfile, shutil +import numpy as np + +sys.path.insert(0, "/proj/dmfexp/zwhong/rsm_rise/scripts/real") +from actcond_goal_directedness import boot_ci # noqa: E402 +from actcond_prefix import REAL, CACHE, parts_in_write_order, load_prefix, stats_for # noqa: E402 + +GROWN = ["edge_s2ro_v0lit_g995_sh0of1", "edge_s2ro_v0lit_g9975_sh0of1", + "edge_s2ro_v5_g995_sh0of1", "edge_s2ro_v5_g9975_sh0of1"] +NULL_DIRS = ["edge_s2ro_v0lit_crn1_sh0of1", "edge_s2ro_v5_p0_sh0of1"] + + +def sign_test_p(x): + """two-sided exact sign test on the non-zero entries of x.""" + from math import comb + x = np.asarray([v for v in x if v != 0], float) + n, k = len(x), int((np.asarray(x) > 0).sum()) + if n == 0: + return None + tail = sum(comb(n, i) for i in range(0, min(k, n - k) + 1)) / 2.0 ** n + return float(min(1.0, 2 * tail)) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--out", required=True) + ap.add_argument("--boot", type=int, default=20000) + ap.add_argument("--tmp", default=os.environ.get("TMPDIR", "/tmp")) + a = ap.parse_args() + rows = json.load(open(CACHE)) + cache = {r["dir"]: r for r in rows} + out = dict(generated=str(np.datetime64("now")), cache=CACHE, n_dirs=len(rows), boot=a.boot) + + # ---------------------------------------------------------------- (Z1) loader null on AUC + tmproot = tempfile.mkdtemp(dir=a.tmp, prefix="actcond_hauc_") + null = [] + for name in NULL_DIRS: + files, _ = parts_in_write_order(f"{REAL}/{name}") + st = stats_for(load_prefix(f"{REAL}/{name}", files, tmproot), "rsm", B=0) + ref = cache[name]["variants"]["rsm"].get("onroute_auc") + null.append(dict(dir=name, mine=None if st is None else st["onroute_auc"], cache=ref, + d=None if st is None or ref is None else abs(st["onroute_auc"] - ref))) + out["Z1_null"] = null + print("=== (Z1) AUC null control through the run-45 symlink loader ===") + for r in null: + print(f" {r['dir']:32s} mine={r['mine']} cache={r['cache']} |d|={r['d']}") + bad = [r for r in null if r["d"] is None or r["d"] > 0.0] + out["Z1_pass"] = not bad + json.dump(out, open(a.out, "w"), default=float, indent=1) + if bad: + print("[FAIL] (Z1) -- no headline reported."); shutil.rmtree(tmproot, ignore_errors=True) + sys.exit(3) + print(" PASS -- exact") + + # ---------------------------------------------------------------- (Z2)/(Z4) AUC-units headline + def series(var): + return {r["dir"]: r["variants"].get(var, {}).get("onroute_auc") for r in rows} + A_rsm, A_prsm = series("rsm"), series("permuted__rsm") + A_idql, A_pidql = series("idql"), series("permuted__idql") + dirs = [d for d in cache if None not in (A_rsm[d], A_prsm[d])] + c_rsm = np.array([A_rsm[d] - A_prsm[d] for d in dirs]) + di = [d for d in cache if None not in (A_idql[d], A_pidql[d], A_rsm[d], A_prsm[d])] + c_idql = np.array([A_idql[d] - A_pidql[d] for d in di]) + gap = np.array([(A_idql[d] - A_pidql[d]) - (A_rsm[d] - A_prsm[d]) for d in di]) + hd = dict( + n_dirs_rsm=len(dirs), + auc_rsm_mean=float(np.mean([A_rsm[d] for d in dirs])), + auc_perm_mean=float(np.mean([A_prsm[d] for d in dirs])), + contrib_rsm_mean=float(c_rsm.mean()), contrib_rsm_ci=boot_ci(c_rsm, a.boot, 3), + contrib_rsm_frac_pos=float((c_rsm > 0).mean()), contrib_rsm_sign_p=sign_test_p(c_rsm), + n_dirs_idql=len(di), + contrib_idql_mean=float(c_idql.mean()), contrib_idql_ci=boot_ci(c_idql, a.boot, 4), + gap_idql_minus_rsm_mean=float(gap.mean()), gap_ci=boot_ci(gap, a.boot, 5), + gap_frac_pos=float((gap > 0).mean()), gap_sign_p=sign_test_p(gap)) + hd["Z2_excludes_zero"] = bool(hd["contrib_rsm_ci"][0] > 0 or hd["contrib_rsm_ci"][1] < 0) + out["headline_auc"] = hd + print("\n=== (Z2)/(Z4) THE ACT_COND HEADLINE IN AUC UNITS, all 149 dirs ===") + print(f" auc(rsm) mean {hd['auc_rsm_mean']:.4f} auc(permuted:rsm) mean {hd['auc_perm_mean']:.4f}") + print(f" PER-DIR CONTRIBUTION rsm {hd['contrib_rsm_mean']:+.5f} CI {hd['contrib_rsm_ci']} " + f"frac>0 {hd['contrib_rsm_frac_pos']:.3f} sign p={hd['contrib_rsm_sign_p']:.3g}") + print(f" (Z2) CI excludes 0: {hd['Z2_excludes_zero']}") + print(f" PER-DIR CONTRIBUTION idql {hd['contrib_idql_mean']:+.5f} CI {hd['contrib_idql_ci']}") + print(f" PAIRED GAP idql - rsm {hd['gap_idql_minus_rsm_mean']:+.5f} CI {hd['gap_ci']} " + f"frac>0 {hd['gap_frac_pos']:.3f} sign p={hd['gap_sign_p']:.3g} " + f"({hd['n_dirs_idql']} dirs)") + json.dump(out, open(a.out, "w"), default=float, indent=1) + + # ---------------------------------------------------------------- (Z3) do the grown dirs matter? + L = {r["dir"]: r["variants"].get("rsm", {}).get("rules", {}).get("argmax", {}).get("onroute_lift") + for r in rows} + PL = {r["dir"]: r["variants"].get("permuted__rsm", {}).get("rules", {}) + .get("argmax", {}).get("onroute_lift") for r in rows} + refresh = {} + for name in GROWN: + files, _ = parts_in_write_order(f"{REAL}/{name}") + got = load_prefix(f"{REAL}/{name}", files, tmproot) + r_ = stats_for(got, "rsm", B=0); p_ = stats_for(got, "permuted__rsm", B=0) + refresh[name] = dict(n_parts=len(files), + n_dec=None if r_ is None else r_["n_dec"], + lift=None if r_ is None else r_["onroute_lift"], + perm_lift=None if p_ is None else p_["onroute_lift"], + auc=None if r_ is None else r_["onroute_auc"], + perm_auc=None if p_ is None else p_["onroute_auc"], + cache_lift=L.get(name), cache_perm_lift=PL.get(name), + cache_auc=cache[name]["variants"]["rsm"].get("onroute_auc"), + cache_perm_auc=cache[name]["variants"]["permuted__rsm"].get("onroute_auc")) + shutil.rmtree(tmproot, ignore_errors=True) + out["grown_refresh"] = refresh + + def headline(lmap, pmap): + ds = [d for d in cache if lmap.get(d) is not None] + lv = np.array([lmap[d] for d in ds]) + cs = [d for d in ds if pmap.get(d) is not None] + cv = np.array([lmap[d] - pmap[d] for d in cs]) + return dict(n=len(ds), mean_lift=float(lv.mean()), ci_lift=boot_ci(lv, a.boot, 6), + n_contrib=len(cs), mean_contrib=float(cv.mean()), + ci_contrib=boot_ci(cv, a.boot, 7)) + before = headline(L, PL) + L2, PL2 = dict(L), dict(PL) + for k, v in refresh.items(): + if v["lift"] is not None: + L2[k] = v["lift"] + if v["perm_lift"] is not None: + PL2[k] = v["perm_lift"] + after = headline(L2, PL2) + out["Z3"] = dict(before=before, after=after, + d_mean_lift=after["mean_lift"] - before["mean_lift"], + d_mean_contrib=after["mean_contrib"] - before["mean_contrib"]) + out["Z3_pass"] = bool(abs(out["Z3"]["d_mean_lift"]) < 1e-3) + print("\n=== (Z3) DO THE 4 GROWN DIRS MOVE THE LIFT HEADLINE? ===") + for k, v in refresh.items(): + print(f" {k:32s} {v['n_dec']:5d} dec ({v['n_parts']} parts) lift " + f"{v['cache_lift']:+.4f} -> {v['lift']:+.4f} auc {v['cache_auc']:.4f} -> {v['auc']:.4f}") + print(f" per-dir mean lift {before['mean_lift']:+.5f} {before['ci_lift']} -> " + f"{after['mean_lift']:+.5f} {after['ci_lift']} d={out['Z3']['d_mean_lift']:+.5f}") + print(f" per-dir contribution {before['mean_contrib']:+.5f} {before['ci_contrib']} -> " + f"{after['mean_contrib']:+.5f} {after['ci_contrib']} d={out['Z3']['d_mean_contrib']:+.5f}") + print(f" (Z3) |d mean lift| < 0.001: {out['Z3_pass']}") + json.dump(out, open(a.out, "w"), default=float, indent=1) + print(f"\n[out] {a.out}") + + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/real/actcond_lift_reconcile.py b/rsm_rise/scripts/real/actcond_lift_reconcile.py new file mode 100644 index 0000000000000000000000000000000000000000..2958e2dcc2249a33d01e5e1ebf12dcdcaad580b2 --- /dev/null +++ b/rsm_rise/scripts/real/actcond_lift_reconcile.py @@ -0,0 +1,211 @@ +#!/usr/bin/env python +"""RUN 43 -- close the ONE unresolved identity of run 42. + +Run 42, section 1 (S1) left this open: + + "argmax vs run 39: a near-reproduction, NOT bit-identical, and the residual is unexplained. + On the matched 145 dirs run 42 gives +0.00639 against run 39's +0.0054 ... the remaining + +0.0010 in lift is a filtering/weighting difference between the run-39 and run-40 scripts + that I have not located." + +This script locates it, from the TWO ROW CACHES ONLY (no GPU, no rescan, no new rollout): + + status/real/ACT_COND/GOAL_DIRECTED_run39.rows.json (run 39, written 16:39Z) + status/real/ACT_COND/READOUT_run40.rows.json (run 40, written 17:15Z) + +Both caches store, per (dir, scorer-variant), the quantities the pooled table was built from -- +`n_dec`, `n_cand`, `n_mixed` and the argmax `onroute_lift`. So the pooled difference can be split +with NO residual into three disjoint causes: + + (C1) DIR SET -- dirs present in one cache and not the other (the edge cache is LIVE: other + streams keep writing rollout dirs, and run 40 scanned 36 minutes later). + (C2) CELL DRIFT-- dirs in both, but with a DIFFERENT number of decisions, because more + `edge_parts/ep*.npz` had landed in that same dir by 17:15Z. + (C3) SCRIPT -- cells whose (n_dec, n_cand, n_mixed) are IDENTICAL in both caches. If the + two scripts compute the same estimand, every such cell must agree BIT FOR + BIT, and (C3) must be exactly 0. + +(C3) is the assertion that matters and it FAILS LOUDLY: a non-zero per-cell difference on an +identically-shaped cell is a real scripting difference and I would have to find it. + +PRE-REGISTERED (written before the job ran, see status/real/ACT_COND.md RUN 43): + (R1) every exact-shape cell agrees to <= 1e-12 -> (C3) == 0, the scripts are the same estimand; + (R2) the +0.0010 is (C1)+(C2), i.e. DATA DRIFT between 16:39Z and 17:15Z, not a defect; + (R3) if (R1) fails I name the cells and do NOT claim the identity closed. +""" +import json, sys +import numpy as np +from pathlib import Path + +R39 = "status/real/ACT_COND/GOAL_DIRECTED_run39.rows.json" +R40 = "status/real/ACT_COND/READOUT_run40.rows.json" +OUT = "status/real/ACT_COND/LIFT_RECONCILE_run43.json" +TOL = 1e-12 + + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from actcond_goal_directedness import family_of # noqa: E402 -- the EXACT pooling rule both + # scripts used; re-implementing it here would + # be a third rule and would invalidate the test + + +def norm_key(k): + """both caches were written by the same loader, so the raw key IS the comparison key. + (Do NOT rewrite `permuted__x` -> `permuted:x` here: `family_of` is the imported run-39 rule and + it parses the double-underscore form; a rewrite would silently create a third family map.)""" + return k + + +def cells(rows, argmax): + """-> {(dir, key): dict(n_dec, n_cand, n_mixed, lift)}. argmax=True reads rules['argmax'].""" + out = {} + for r in rows: + d = r["dir"] + for k, v in r["variants"].items(): + e = v["rules"]["argmax"] if argmax else v + lift = e.get("onroute_lift") + out[(d, norm_key(k))] = dict( + n_dec=int(v["n_dec"]), n_cand=int(v["n_cand"]), n_mixed=int(v["n_mixed"]), + lift=(float(lift) if lift is not None else None)) + return out + + +def pooled(cs, fam, keys=None): + """decision-weighted pooled lift over every cell whose key maps to `fam` (both scripts' rule).""" + w, x = [], [] + for (d, k), v in cs.items(): + if family_of(k) != fam: + continue + if keys is not None and (d, k) not in keys: + continue + if v["lift"] is None: + continue + w.append(v["n_dec"]); x.append(v["lift"]) + if not w: + return None, 0, 0 + w = np.array(w, float); x = np.array(x, float) + return float((w * x).sum() / w.sum()), len(w), int(w.sum()) + + +def main(): + fam = sys.argv[1] if len(sys.argv) > 1 else "rsm" + c39 = cells(json.load(open(R39)), argmax=False) + c40 = cells(json.load(open(R40)), argmax=True) + print(f"[load] run39 {len(c39)} cells run40 {len(c40)} cells", flush=True) + + res = dict(family=fam, tol=TOL, generated=str(np.datetime64("now"))) + d39 = sorted({d for d, _ in c39}); d40 = sorted({d for d, _ in c40}) + inter = sorted(set(d39) & set(d40)) + res["dirs"] = dict(n39=len(d39), n40=len(d40), n_inter=len(inter), + only39=sorted(set(d39) - set(d40))[:20], + n_only39=len(set(d39) - set(d40)), + only40=sorted(set(d40) - set(d39))[:20], + n_only40=len(set(d40) - set(d39))) + print(f"[dirs] 39={len(d39)} 40={len(d40)} inter={len(inter)} " + f"only39={res['dirs']['n_only39']} only40={res['dirs']['n_only40']}", flush=True) + + k39 = sorted({k for _, k in c39}); k40 = sorted({k for _, k in c40}) + res["variant_keys"] = dict(run39=k39, run40=k40, + only40=sorted(set(k40) - set(k39)), + only39=sorted(set(k39) - set(k40)), + fam39=sorted({family_of(k) for k in k39}), + fam40=sorted({family_of(k) for k in k40})) + res["cells_in_family"] = dict( + run39=int(sum(1 for _, k in c39 if family_of(k) == fam)), + run40=int(sum(1 for _, k in c40 if family_of(k) == fam))) + print(f"[keys] only-in-40={res['variant_keys']['only40']} only-in-39={res['variant_keys']['only39']}", + flush=True) + print(f"[cells@{fam}] run39={res['cells_in_family']['run39']} run40={res['cells_in_family']['run40']}", + flush=True) + + both = sorted(set(c39) & set(c40)) + bothf = [c for c in both if family_of(c[1]) == fam] + exact, drift = [], [] + for c in bothf: + a, b = c39[c], c40[c] + (exact if (a["n_dec"], a["n_cand"], a["n_mixed"]) == + (b["n_dec"], b["n_cand"], b["n_mixed"]) else drift).append(c) + + # ---- (C3) THE ASSERTION: identically-shaped cells must agree bit for bit ---- + bad = [] + dmax = 0.0 + for c in exact: + a, b = c39[c]["lift"], c40[c]["lift"] + if a is None or b is None: + bad.append(dict(cell=list(c), why="lift is None", a=a, b=b)); continue + dd = abs(a - b) + dmax = max(dmax, dd) + if dd > TOL: + bad.append(dict(cell=list(c), a=a, b=b, d=dd, + n_dec=c39[c]["n_dec"], n_cand=c39[c]["n_cand"])) + res["exact_cells"] = dict(n=len(exact), max_abs_lift_diff=dmax, n_bad=len(bad), bad=bad[:20]) + print(f"[C3] exact-shape cells={len(exact)} max|dlift|={dmax:.3e} bad={len(bad)}", flush=True) + + # per-cell drift detail, largest first by |dn_dec| + dr = [] + for c in drift: + a, b = c39[c], c40[c] + dr.append(dict(dir=c[0], key=c[1], n_dec39=a["n_dec"], n_dec40=b["n_dec"], + n_cand39=a["n_cand"], n_cand40=b["n_cand"], + n_mixed39=a["n_mixed"], n_mixed40=b["n_mixed"], + lift39=a["lift"], lift40=b["lift"])) + dr.sort(key=lambda r: -abs(r["n_dec40"] - r["n_dec39"])) + res["drifted_cells"] = dict(n=len(drift), n_dec_grew=int(sum(1 for r in dr if r["n_dec40"] > r["n_dec39"])), + n_dec_shrank=int(sum(1 for r in dr if r["n_dec40"] < r["n_dec39"])), + n_cand_changed=int(sum(1 for r in dr if r["n_cand40"] != r["n_cand39"])), + top=dr[:20]) + print(f"[C2] drifted cells={len(drift)} (grew {res['drifted_cells']['n_dec_grew']}, " + f"shrank {res['drifted_cells']['n_dec_shrank']}, " + f"n_cand changed {res['drifted_cells']['n_cand_changed']})", flush=True) + + # ---- the decomposition of the pooled difference ---- + L39_all, n39c, w39 = pooled(c39, fam) + L40_all, n40c, w40 = pooled(c40, fam) + keys_both = set(bothf) + L39_both, nb39, wb39 = pooled(c39, fam, keys_both) + L40_both, nb40, wb40 = pooled(c40, fam, keys_both) + keys_ex = set(exact) + L39_ex, ne39, we39 = pooled(c39, fam, keys_ex) + L40_ex, ne40, we40 = pooled(c40, fam, keys_ex) + + res["pooled"] = dict( + run39_all=dict(lift=L39_all, n_cells=n39c, n_dec=w39), + run40_all=dict(lift=L40_all, n_cells=n40c, n_dec=w40), + run39_common_cells=dict(lift=L39_both, n_cells=nb39, n_dec=wb39), + run40_common_cells=dict(lift=L40_both, n_cells=nb40, n_dec=wb40), + run39_exact_cells=dict(lift=L39_ex, n_cells=ne39, n_dec=we39), + run40_exact_cells=dict(lift=L40_ex, n_cells=ne40, n_dec=we40), + ) + tot = (L40_all - L39_all) if (L39_all is not None and L40_all is not None) else None + c1 = (L40_all - L40_both) if (L40_all is not None and L40_both is not None) else None + c1b = (L39_both - L39_all) if (L39_all is not None and L39_both is not None) else None + c2 = (L40_both - L39_both) if (L39_both is not None and L40_both is not None) else None + c3 = (L40_ex - L39_ex) if (L39_ex is not None and L40_ex is not None) else None + res["decomposition"] = dict( + total_run40_minus_run39=tot, + C1_cellset_run40_side=c1, C1_cellset_run39_side=c1b, + C2_cell_drift_on_common=c2, C3_script_on_exact_cells=c3, + identity_residual=(None if None in (tot, c1, c1b, c2) else tot - (c1 + c1b + c2))) + print(f"[pooled] run39_all={L39_all} run40_all={L40_all} total={tot}", flush=True) + print(f"[decomp] C1(cellset 40-side)={c1} C1(39-side)={c1b} C2(drift)={c2} " + f"C3(script,exact)={c3}", flush=True) + + # ---- verdicts, loud ---- + ok_r1 = (len(bad) == 0) and (len(exact) >= 3) + res["verdict"] = dict( + R1_scripts_identical_on_exact_cells=bool(ok_r1), + R2_difference_is_data_drift=bool(ok_r1 and tot is not None and abs(tot) > 0), + n_exact=len(exact), n_drift=len(drift)) + Path(OUT).parent.mkdir(parents=True, exist_ok=True) + json.dump(res, open(OUT, "w"), indent=1, default=float) + print(f"[out] {OUT}", flush=True) + if not ok_r1: + print("[FAIL] (R1) VIOLATED -- identically-shaped cells disagree; the identity is NOT closed", + flush=True) + raise SystemExit(3) + print("[PASS] (R1) every identically-shaped cell agrees to <= 1e-12: the run-39 and run-40 " + "scripts compute the SAME argmax lift.", flush=True) + + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/real/actcond_prefix.py b/rsm_rise/scripts/real/actcond_prefix.py new file mode 100644 index 0000000000000000000000000000000000000000..1357d2d4aa9d00aeff575e4f7e7409b58f0a11ff --- /dev/null +++ b/rsm_rise/scripts/real/actcond_prefix.py @@ -0,0 +1,316 @@ +#!/usr/bin/env python +"""ACT_COND run 45 -- is a partially-written edge dir BIASED, or just SHORT? + +Run 44 split the 149-dir cache into FROZEN (145) and FILLING (4) and found the 4 filling dirs at +argmax onroute lift -0.11435 against a frozen pool of +0.00665 -- 1.3% of the decisions moving 24% +of the headline and flipping the RSM's own contribution CI across 0. It shipped with a caveat at +full strength: the 4 filling dirs are ALSO a distinct config (`edge_s2ro_{v0lit,v5}_{g995,g9975}`, +another stream's gamma ablation), so "unfrozen" is confounded with "high gamma", and -0.114 could be +a real property of those configs rather than a partial-write artefact. Run 44 said the +discriminating test was one rescan after they freeze. They have NOT frozen (newest parts 20:52Z at +20:53Z), so this run runs the test that does not need them to. + +THE TEST. Partial-write bias is a claim about the PREFIX of a dir's parts: that the episodes written +first carry a different lift from the ones written later. That is measurable inside any dir, frozen +or not, by loading only the first k parts in write order: + + lift(dir, k) for k = a ladder of part counts -> the within-dir prefix trajectory + + * On a FROZEN dir the full-length value is known, so lift(dir, k) vs lift(dir, all) measures the + bias of reading that dir short. If frozen dirs read at 200-300 decisions land near their own + 987-decision value, then reading short is UNBIASED and the filling dirs' -0.114 is their config. + * On the 4 FILLING dirs the part count has roughly doubled since the 19:46Z scan, so lift at the + current length vs lift at the scan-matched prefix is a direct before/after on the same dirs. + +The loader is NOT re-implemented. A prefix is materialised as a directory of SYMLINKS to the first +k parts and handed to run 39's `load_dir` verbatim, so the filtering rule (n_proposer truncation, +finite/length masks, rectangularity bail) is literally the same code that built the cache. A second +copy of that rule would be a third rule and would invalidate the comparison. + +NULL CONTROL (run 44's (P1), applied to this tool): on a dir whose parts have not changed since the +19:46Z scan, the FULL-prefix lift through the symlink path must reproduce +`READOUT_run43fresh.rows.json`'s `rules.argmax.onroute_lift` to <= 1e-12. If it does not, the +prefix loader is wrong and this script exits 3 without reporting a trajectory. +""" +import argparse, json, os, glob, sys, tempfile, shutil +from pathlib import Path +import numpy as np + +sys.path.insert(0, "/proj/dmfexp/zwhong/rsm_rise/scripts/real") +from actcond_goal_directedness import load_dir, goal_stats, family_of, boot_ci # noqa: E402 + +ROOT = "/proj/dmfexp/zwhong/rsm_rise" +REAL = f"{ROOT}/status/real" +CACHE = f"{REAL}/ACT_COND/READOUT_run43fresh.rows.json" + +# the 8 s2ro cells: 4 FILLING (another stream's gamma ablation, run 44's outliers) and their 4 +# FROZEN siblings, same v0lit/v5 scorer, differing only in the config suffix -- the paired control. +S2RO = ["edge_s2ro_v0lit_g995_sh0of1", "edge_s2ro_v0lit_g9975_sh0of1", + "edge_s2ro_v5_g995_sh0of1", "edge_s2ro_v5_g9975_sh0of1", + "edge_s2ro_v0lit_crn1_sh0of1", "edge_s2ro_v0lit_p0_sh0of1", + "edge_s2ro_v5_crn1_sh0of1", "edge_s2ro_v5_p0_sh0of1"] +# run 43's own worked example of prefix drift, now frozen: +0.373 at 75 dec -> +0.090 at 291. +FLOW = ["edge_AC_rise_flow4", "edge_AC_rise_flow16", "edge_AC_rise_flow32"] + + +def parts_in_write_order(d): + """parts sorted by mtime, plus whether that ordering equals load_dir's filename sort.""" + ps = glob.glob(os.path.join(d, "edge_parts", "ep*.npz")) + by_name = sorted(ps) + by_mtime = sorted(ps, key=lambda p: (os.path.getmtime(p), p)) + return by_mtime, (by_name == by_mtime) + + +def load_prefix(d, files, tmproot): + """run 39's load_dir over exactly `files`, via a symlink dir -- same code, fewer parts.""" + stage = tempfile.mkdtemp(dir=tmproot) + ep = os.path.join(stage, "edge_parts") + os.makedirs(ep) + for f in files: + os.symlink(os.path.abspath(f), os.path.join(ep, os.path.basename(f))) + try: + return load_dir(stage) + finally: + shutil.rmtree(stage, ignore_errors=True) + + +def stats_for(got, mode, B): + if got is None: + return None + O, A, P, E, S, Lm, nkeep = got + if mode not in S: + return None + return goal_stats(S[mode], O, A, P, E, B=B) + + +def ladder(n, k): + """k ascending part counts ending at n, always including n itself.""" + if n <= k: + return list(range(1, n + 1)) + xs = sorted({max(1, int(round(n * (i + 1) / k))) for i in range(k)}) + if xs[-1] != n: + xs.append(n) + return xs + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--out", required=True) + ap.add_argument("--boot", type=int, default=1000) + ap.add_argument("--rungs", type=int, default=8) + ap.add_argument("--tmp", default=os.environ.get("TMPDIR", "/tmp")) + a = ap.parse_args() + + cache = {r["dir"]: r for r in json.load(open(CACHE))} + out = dict(generated=str(np.datetime64("now")), cache=CACHE, rungs=a.rungs, boot=a.boot) + + # ---------------------------------------------------------------- 1. NULL CONTROL (X1) + # full prefix through the symlink path must reproduce the cache, on the FROZEN dirs only + # (a filling dir has grown since the scan, so a mismatch there is data, not a bug). + tmproot = tempfile.mkdtemp(dir=a.tmp, prefix="actcond_prefix_") + null = [] + frozen_for_null = ["edge_s2ro_v0lit_crn1_sh0of1", "edge_s2ro_v0lit_p0_sh0of1", + "edge_s2ro_v5_crn1_sh0of1", "edge_s2ro_v5_p0_sh0of1"] + FLOW + for name in frozen_for_null: + d = f"{REAL}/{name}" + files, name_eq_mtime = parts_in_write_order(d) + got = load_prefix(d, files, tmproot) + st = stats_for(got, "rsm", B=0) + ref = cache.get(name, {}).get("variants", {}).get("rsm", {}).get("rules", {}).get("argmax", {}) + row = dict(dir=name, n_parts=len(files), name_order_eq_mtime_order=bool(name_eq_mtime), + mine=None if st is None else st["onroute_lift"], + cache=ref.get("onroute_lift"), + n_dec_mine=None if st is None else st["n_dec"], + n_dec_cache=cache.get(name, {}).get("variants", {}).get("rsm", {}).get("n_dec")) + row["dlift"] = (None if row["mine"] is None or row["cache"] is None + else abs(row["mine"] - row["cache"])) + null.append(row) + out["null_control"] = null + bad = [r for r in null if r["dlift"] is None or r["dlift"] > 1e-12] + out["null_control_max_dlift"] = max([r["dlift"] for r in null if r["dlift"] is not None] or [None]) + out["null_control_pass"] = not bad + print("\n=== (X1) NULL CONTROL: full prefix through the symlink path vs the run43fresh cache ===") + for r in null: + print(f" {r['dir']:32s} parts={r['n_parts']:4d} dec {r['n_dec_mine']}/{r['n_dec_cache']} " + f"mine={r['mine']} cache={r['cache']} |d|={r['dlift']} " + f"name_order==mtime_order={r['name_order_eq_mtime_order']}") + if bad: + print("\n[FAIL] prefix loader does not reproduce the cache at full length -- " + "no trajectory is reported. Offenders:") + for r in bad: + print(f" {r['dir']}: mine={r['mine']} cache={r['cache']} d={r['dlift']}") + json.dump(out, open(a.out, "w"), default=float, indent=1) + shutil.rmtree(tmproot, ignore_errors=True) + sys.exit(3) + print(f" PASS -- max |dlift| = {out['null_control_max_dlift']:.3e} over {len(null)} dirs") + + # ---------------------------------------------------------------- 2. PREFIX TRAJECTORIES + traj = {} + for name in S2RO + FLOW: + d = f"{REAL}/{name}" + files, name_eq_mtime = parts_in_write_order(d) + rows = [] + for k in ladder(len(files), a.rungs): + got = load_prefix(d, files[:k], tmproot) + r = stats_for(got, "rsm", B=a.boot) + p = stats_for(got, "permuted__rsm", B=0) + if r is None: + rows.append(dict(k_parts=k, n_dec=None)); continue + rows.append(dict(k_parts=k, n_dec=r["n_dec"], n_mixed=r["n_mixed"], + base=r["onroute_base_mixed"], lift=r["onroute_lift"], + lift_ci=r.get("onroute_lift_ci"), auc=r["onroute_auc"], + perm_lift=None if p is None else p["onroute_lift"], + contrib=(None if p is None or p["onroute_lift"] is None + else r["onroute_lift"] - p["onroute_lift"]))) + print(f" [{name:32s}] k={k:4d} dec={rows[-1]['n_dec']:5d} base={rows[-1]['base']:.3f} " + f"lift={rows[-1]['lift']:+.4f} contrib={rows[-1]['contrib']}", flush=True) + traj[name] = dict(n_parts=len(files), name_order_eq_mtime_order=bool(name_eq_mtime), + rungs=rows, + cache_n_dec=cache.get(name, {}).get("variants", {}).get("rsm", {}).get("n_dec"), + cache_lift=cache.get(name, {}).get("variants", {}) + .get("rsm", {}).get("rules", {}).get("argmax", {}) + .get("onroute_lift")) + out["trajectories"] = traj + shutil.rmtree(tmproot, ignore_errors=True) + json.dump(out, open(a.out, "w"), default=float, indent=1) # partial dump: never lose a scan + + # ---------------------------------------------------------------- 3. (X2) the two calls + # (a) frozen dirs read SHORT: |lift(nearest rung to the filling dirs' length) - lift(full)| + TARGETS = (200, 300) + short = [] + for name in S2RO + FLOW: + t = traj[name] + rr = [r for r in t["rungs"] if r.get("n_dec")] + if len(rr) < 2: + continue + full = rr[-1] + for tgt in TARGETS: + if full["n_dec"] < tgt * 1.5: # a dir this short has no meaningful "short read" + continue + near = min(rr, key=lambda r: abs(r["n_dec"] - tgt)) + short.append(dict(dir=name, target_dec=tgt, n_dec_short=near["n_dec"], + lift_short=near["lift"], n_dec_full=full["n_dec"], + lift_full=full["lift"], dlift=near["lift"] - full["lift"], + base_short=near["base"], base_full=full["base"], + dbase=near["base"] - full["base"], + auc_short=near["auc"], auc_full=full["auc"], + dauc=(None if near["auc"] is None or full["auc"] is None + else near["auc"] - full["auc"]), + ci_short=near.get("lift_ci"), + ci_covers_full=(near.get("lift_ci") is not None + and near["lift_ci"][0] <= full["lift"] <= near["lift_ci"][1]))) + out["short_read_bias"] = short + print("\n=== (X2c) READING A LONG DIR SHORT: lift at ~200/300 decisions vs its own full length ===") + print(f"{'dir':32s} {'tgt':>4s} {'dec_s':>6s} {'lift_s':>9s} {'dec_f':>6s} {'lift_f':>9s} " + f"{'dlift':>9s} {'dbase':>8s} {'dauc':>8s} {'CI_s cov':>9s}") + for r in short: + print(f"{r['dir']:32s} {r['target_dec']:4d} {r['n_dec_short']:6d} {r['lift_short']:+9.4f} " + f"{r['n_dec_full']:6d} {r['lift_full']:+9.4f} {r['dlift']:+9.4f} " + f"{r['dbase']:+8.4f} {r['dauc']:+8.4f} {str(r['ci_covers_full']):>9s}") + if short: + ad = np.array([abs(r["dlift"]) for r in short]) + out["short_read_bias_summary"] = dict( + n=len(short), mean_abs_dlift=float(ad.mean()), max_abs_dlift=float(ad.max()), + mean_signed_dlift=float(np.mean([r["dlift"] for r in short])), + frac_ci_covers_full=float(np.mean([bool(r["ci_covers_full"]) for r in short])), + mean_abs_dauc=float(np.mean([abs(r["dauc"]) for r in short])), + max_abs_dauc=float(np.max([abs(r["dauc"]) for r in short])), + mean_signed_dauc=float(np.mean([r["dauc"] for r in short])), + mean_signed_dbase=float(np.mean([r["dbase"] for r in short])), + spearman_dbase_dlift=None) + sb = out["short_read_bias_summary"] + # is the short-read LIFT bias explained by the short-read BASE-RATE shift? paired, same rows. + db = np.array([r["dbase"] for r in short]); dl = np.array([r["dlift"] for r in short]) + rb = np.argsort(np.argsort(db)).astype(float); rl = np.argsort(np.argsort(dl)).astype(float) + rb -= rb.mean(); rl -= rl.mean() + sb["spearman_dbase_dlift"] = float((rb * rl).sum() / np.sqrt((rb**2).sum() * (rl**2).sum())) + print(f" LIFT: mean |d| = {sb['mean_abs_dlift']:.4f} max {sb['max_abs_dlift']:.4f} " + f"signed {sb['mean_signed_dlift']:+.4f} frac short-CI covers full " + f"{sb['frac_ci_covers_full']:.2f}") + print(f" AUC : mean |d| = {sb['mean_abs_dauc']:.4f} max {sb['max_abs_dauc']:.4f} " + f"signed {sb['mean_signed_dauc']:+.4f} <- the headroom-free estimand") + print(f" BASE: signed mean shift {sb['mean_signed_dbase']:+.4f} " + f"spearman(dbase, dlift) = {sb['spearman_dbase_dlift']:+.3f}") + + # (b) the 4 FILLING dirs: current length vs the scan-matched prefix + grew = [] + for name in S2RO[:4]: + t = traj[name] + rr = [r for r in t["rungs"] if r.get("n_dec")] + if not rr or t["cache_n_dec"] is None: + continue + near = min(rr, key=lambda r: abs(r["n_dec"] - t["cache_n_dec"])) + grew.append(dict(dir=name, n_dec_scan=t["cache_n_dec"], lift_scan=t["cache_lift"], + n_dec_now=rr[-1]["n_dec"], lift_now=rr[-1]["lift"], + ci_now=rr[-1].get("lift_ci"), + n_dec_matched=near["n_dec"], lift_matched=near["lift"], + growth=rr[-1]["n_dec"] / max(t["cache_n_dec"], 1), + still_below_m005=bool(rr[-1]["lift"] < -0.05))) + out["filling_now_vs_scan"] = grew + json.dump(out, open(a.out, "w"), default=float, indent=1) + print("\n=== (X2b) THE 4 FILLING DIRS: lift at the 19:46Z scan length vs at the current length ===") + print(f"{'dir':32s} {'dec@scan':>9s} {'lift@scan':>10s} {'dec_now':>8s} {'lift_now':>9s} " + f"{'x':>5s} {'<-0.05':>7s}") + for r in grew: + print(f"{r['dir']:32s} {r['n_dec_scan']:9d} {r['lift_scan']:+10.4f} {r['n_dec_now']:8d} " + f"{r['lift_now']:+9.4f} {r['growth']:5.2f} {str(r['still_below_m005']):>7s}") + if grew: + out["filling_verdict"] = dict( + n=len(grew), all_still_below_m005=bool(all(r["still_below_m005"] for r in grew)), + mean_lift_now=float(np.mean([r["lift_now"] for r in grew])), + mean_lift_scan=float(np.mean([r["lift_scan"] for r in grew])), + mean_growth=float(np.mean([r["growth"] for r in grew]))) + print(f" mean lift {out['filling_verdict']['mean_lift_scan']:+.4f} (scan) -> " + f"{out['filling_verdict']['mean_lift_now']:+.4f} (now, " + f"{out['filling_verdict']['mean_growth']:.2f}x longer); all still < -0.05: " + f"{out['filling_verdict']['all_still_below_m005']}") + + # ---------------------------------------------------------------- 4. (X4) base-rate confound + # the 4 filling dirs also have onroute_base ~0.72 vs ~0.59 for their frozen siblings, and lift is + # mechanically capped at 1-base. Does base rate explain lift across the whole 149-dir cache? + B_, L_, N_, NM_ = [], [], [], [] + for name, r in cache.items(): + v = r["variants"].get("rsm") + # the READOUT cache names it `onroute_base` (it IS the mixed base); goal_directedness + # names the same quantity `onroute_base_mixed`. Accept either. + b = v.get("onroute_base", v.get("onroute_base_mixed")) if v else None + if b is None: + continue + am = v["rules"]["argmax"] + if am.get("onroute_lift") is None: + continue + B_.append(b); L_.append(am["onroute_lift"]) + N_.append(v["n_dec"]); NM_.append(name) + B_, L_, N_ = np.array(B_), np.array(L_), np.array(N_) + + def spearman(x, y): + rx = np.argsort(np.argsort(x)).astype(float); ry = np.argsort(np.argsort(y)).astype(float) + rx -= rx.mean(); ry -= ry.mean() + return float((rx * ry).sum() / np.sqrt((rx ** 2).sum() * (ry ** 2).sum())) + + out["base_rate_confound"] = dict( + n_dirs=int(len(B_)), spearman_base_vs_lift=spearman(B_, L_), + pearson_base_vs_lift=float(np.corrcoef(B_, L_)[0, 1]), + spearman_ndec_vs_lift=spearman(N_.astype(float), L_), + lift_by_base_tertile=[dict( + lo=float(np.quantile(B_, q0)), hi=float(np.quantile(B_, q1)), + n=int(((B_ >= np.quantile(B_, q0)) & (B_ <= np.quantile(B_, q1))).sum()), + mean_lift=float(L_[(B_ >= np.quantile(B_, q0)) & (B_ <= np.quantile(B_, q1))].mean()), + ci=boot_ci(L_[(B_ >= np.quantile(B_, q0)) & (B_ <= np.quantile(B_, q1))], 2000, 7)) + for q0, q1 in ((0, 1 / 3), (1 / 3, 2 / 3), (2 / 3, 1.0))], + high_base_dirs=sorted([[float(b), float(l), int(n), nm] + for b, l, n, nm in zip(B_, L_, N_, NM_)], reverse=True)[:10]) + bc = out["base_rate_confound"] + print("\n=== (X4) IS THE 'FILLING' SPLIT REALLY A BASE-RATE SPLIT? 149-dir cache ===") + print(f" spearman(onroute_base, argmax lift) = {bc['spearman_base_vs_lift']:+.3f} " + f"pearson = {bc['pearson_base_vs_lift']:+.3f} " + f"spearman(n_dec, lift) = {bc['spearman_ndec_vs_lift']:+.3f}") + for t in bc["lift_by_base_tertile"]: + print(f" base in [{t['lo']:.3f},{t['hi']:.3f}] n={t['n']:3d} mean lift={t['mean_lift']:+.4f} CI={t['ci']}") + + json.dump(out, open(a.out, "w"), default=float, indent=1) + print(f"\n[out] {a.out}") + + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/real/actcond_prefix_cachewide.py b/rsm_rise/scripts/real/actcond_prefix_cachewide.py new file mode 100644 index 0000000000000000000000000000000000000000..419c43fdd31e44cd003369d3f0f84090ff42d65c --- /dev/null +++ b/rsm_rise/scripts/real/actcond_prefix_cachewide.py @@ -0,0 +1,227 @@ +#!/usr/bin/env python +"""ACT_COND run 46 -- does run 45's "quote the AUC, not the lift" rule hold over the WHOLE cache? + +Run 45 measured that reading a long edge dir SHORT is BIASED, not merely noisy: over 16 (dir, target) +pairs from 11 dirs the argmax `onroute_lift` drifted by mean |d| 0.0733 (signed -0.0448) while the +Mann-Whitney `onroute_auc` drifted by 0.0312 (signed +0.0096) -- 2.4x less -- because a short read +carries a higher onroute BASE rate (+0.098) and lift is mechanically capped at `1 - base` +(spearman(dbase, dlift) = -0.685). On that basis run 45 section 6 told EVERY stream pooling off +`status/real/*/edge_parts` to quote the AUC when dir lengths differ. + +That is a rule handed to other streams on 16 pairs from one family. This run either earns it +cache-wide or withdraws it. For each of the 149 dirs of `READOUT_run43fresh.rows.json`: + + full prefix (all parts, mtime order) -> also the NULL CONTROL against the cache + short prefix targeted at ~200 decisions + short prefix targeted at ~300 decisions + +and report mean |dlift| vs mean |dauc| over every (dir, target) pair, plus the base-rate mechanism. + +NOTHING IS RE-IMPLEMENTED. `load_dir`/`goal_stats`/`boot_ci` come from run 39, and the symlink +staging path (`load_prefix`, `parts_in_write_order`, `stats_for`) from run 45, whose (X1) null control +reproduced the cache at max |dlift| = 0.000e+00 on 7 frozen dirs. This run re-runs that null control +over every unchanged dir in the cache instead of 7. + +PRE-REGISTERED in status/real/ACT_COND.md before submission: + (Y1) null control exact (max |dlift| = 0) on every dir whose n_dec still equals the cache's; grown + dirs counted and listed separately, not treated as failures. Otherwise exit 3, no drift number. + (Y2) mean|dlift| / mean|dauc| >= 1.5 cache-wide, and |signed dauc| < |signed dlift|. BELOW 1.5 => + run 45 section 6's AUC rule is withdrawn to the family it was measured on. + (Y3) spearman(dbase, dlift) <= -0.4 and |spearman(dbase, dauc)| strictly smaller. + (Y4) edge_s2ro_v5_g995_sh0of1, the first of run 44's 4 "filling" dirs to freeze, at its full + frozen length: lift < -0.05. +""" +import argparse, json, os, sys, tempfile, shutil +import numpy as np + +sys.path.insert(0, "/proj/dmfexp/zwhong/rsm_rise/scripts/real") +from actcond_goal_directedness import boot_ci # noqa: E402 +from actcond_prefix import (REAL, CACHE, parts_in_write_order, load_prefix, # noqa: E402 + stats_for) + +TARGETS = (200, 300) +FROZEN_CHECK = "edge_s2ro_v5_g995_sh0of1" # (Y4): 80 parts, newest 21:07Z, stat'd frozen at 21:30Z + + +def spearman(x, y): + x, y = np.asarray(x, float), np.asarray(y, float) + rx = np.argsort(np.argsort(x)).astype(float); ry = np.argsort(np.argsort(y)).astype(float) + rx -= rx.mean(); ry -= ry.mean() + den = np.sqrt((rx ** 2).sum() * (ry ** 2).sum()) + return None if den == 0 else float((rx * ry).sum() / den) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--out", required=True) + ap.add_argument("--boot", type=int, default=0) # CIs are not what this run is about; keep it fast + ap.add_argument("--tmp", default=os.environ.get("TMPDIR", "/tmp")) + a = ap.parse_args() + + cache = {r["dir"]: r for r in json.load(open(CACHE))} + out = dict(generated=str(np.datetime64("now")), cache=CACHE, targets=list(TARGETS), + n_dirs_in_cache=len(cache)) + tmproot = tempfile.mkdtemp(dir=a.tmp, prefix="actcond_pfxcw_") + + # ------------------------------------------------- 1. full load per dir == the (Y1) null control + full = {} + null_rows = [] + print(f"=== full-length pass over {len(cache)} cached dirs (mtime order, symlink staging) ===", + flush=True) + for i, name in enumerate(sorted(cache)): + d = f"{REAL}/{name}" + files, name_eq_mtime = parts_in_write_order(d) + if not files: + null_rows.append(dict(dir=name, n_parts=0, status="no_parts")); continue + newest = max(os.path.getmtime(f) for f in files) + st = stats_for(load_prefix(d, files, tmproot), "rsm", B=0) + v = cache[name]["variants"].get("rsm", {}) + ref_lift = v.get("rules", {}).get("argmax", {}).get("onroute_lift") + ref_ndec = v.get("n_dec") + row = dict(dir=name, n_parts=len(files), name_order_eq_mtime_order=bool(name_eq_mtime), + newest_part_mtime=float(newest), + n_dec_mine=None if st is None else st["n_dec"], n_dec_cache=ref_ndec, + lift_mine=None if st is None else st["onroute_lift"], lift_cache=ref_lift) + row["grew"] = (row["n_dec_mine"] is not None and ref_ndec is not None + and row["n_dec_mine"] != ref_ndec) + row["dlift_vs_cache"] = (None if row["lift_mine"] is None or ref_lift is None + else abs(row["lift_mine"] - ref_lift)) + null_rows.append(row) + if st is not None: + full[name] = dict(st=st, files=files, n_parts=len(files), + name_eq_mtime=bool(name_eq_mtime), newest=float(newest)) + if (i + 1) % 25 == 0: + print(f" ... {i+1}/{len(cache)} dirs", flush=True) + + unchanged = [r for r in null_rows if r.get("grew") is False and r["dlift_vs_cache"] is not None] + grown = [r for r in null_rows if r.get("grew")] + bad = [r for r in unchanged if r["dlift_vs_cache"] > 0.0] + out["null_control"] = dict( + n_dirs=len(null_rows), n_unchanged=len(unchanged), n_grown=len(grown), + max_dlift_unchanged=(max(r["dlift_vs_cache"] for r in unchanged) if unchanged else None), + n_fail=len(bad), fails=[r["dir"] for r in bad][:20], + grown_dirs=[dict(dir=r["dir"], n_dec_cache=r["n_dec_cache"], n_dec_now=r["n_dec_mine"], + lift_cache=r["lift_cache"], lift_now=r["lift_mine"]) for r in grown], + n_name_order_ne_mtime_order=sum(1 for r in null_rows + if r.get("name_order_eq_mtime_order") is False)) + nc = out["null_control"] + print(f"\n=== (Y1) NULL CONTROL, cache-wide ===") + print(f" {nc['n_unchanged']} dirs unchanged since the 19:46Z scan, max |dlift| = " + f"{nc['max_dlift_unchanged']} fails = {nc['n_fail']}") + print(f" {nc['n_grown']} dirs GREW since the scan (listed, not failures):") + for g in nc["grown_dirs"]: + print(f" {g['dir']:36s} dec {g['n_dec_cache']} -> {g['n_dec_now']} " + f"lift {g['lift_cache']} -> {g['lift_now']}") + print(f" name-order != mtime-order in {nc['n_name_order_ne_mtime_order']} dirs " + f"(load_dir sorts by NAME; a write-order prefix differs there)") + json.dump(out, open(a.out, "w"), default=float, indent=1) # dump after every section + if bad: + print("\n[FAIL] (Y1) prefix loader disagrees with the cache on an unchanged dir -- " + "no drift number is reported.") + for r in bad[:20]: + print(f" {r['dir']}: mine={r['lift_mine']} cache={r['lift_cache']} d={r['dlift_vs_cache']}") + shutil.rmtree(tmproot, ignore_errors=True) + sys.exit(3) + + # ------------------------------------------------- 2. short reads at ~200 / ~300 decisions + pairs = [] + print(f"\n=== short-read pass: ~200 and ~300 decisions per dir ===", flush=True) + for name in sorted(full): + f = full[name] + st_full = f["st"] + nd_full, npart = st_full["n_dec"], f["n_parts"] + if st_full["onroute_lift"] is None or st_full["onroute_auc"] is None: + continue + dec_per_part = nd_full / max(npart, 1) + for tgt in TARGETS: + if nd_full < tgt * 1.5 or npart < 2: # too short for a meaningful "short read" + continue + k = int(np.clip(round(tgt / max(dec_per_part, 1e-9)), 1, npart - 1)) + st = stats_for(load_prefix(f"{REAL}/{name}", f["files"][:k], tmproot), "rsm", B=a.boot) + if st is None or st["onroute_lift"] is None or st["onroute_auc"] is None: + continue + pairs.append(dict( + dir=name, target_dec=tgt, k_parts=k, n_parts=npart, + n_dec_short=st["n_dec"], n_dec_full=nd_full, + lift_short=st["onroute_lift"], lift_full=st_full["onroute_lift"], + dlift=st["onroute_lift"] - st_full["onroute_lift"], + auc_short=st["onroute_auc"], auc_full=st_full["onroute_auc"], + dauc=st["onroute_auc"] - st_full["onroute_auc"], + base_short=st["onroute_base_mixed"], base_full=st_full["onroute_base_mixed"], + dbase=(None if st["onroute_base_mixed"] is None + or st_full["onroute_base_mixed"] is None + else st["onroute_base_mixed"] - st_full["onroute_base_mixed"]), + name_eq_mtime=f["name_eq_mtime"])) + print(f" {name:40s} full dec={nd_full:5d} parts={npart:3d} " + f"pairs={sum(1 for p in pairs if p['dir'] == name)}", flush=True) + out["pairs"] = pairs + shutil.rmtree(tmproot, ignore_errors=True) + json.dump(out, open(a.out, "w"), default=float, indent=1) + + # ------------------------------------------------- 3. (Y2) the drift comparison + if pairs: + dl = np.array([p["dlift"] for p in pairs], float) + da = np.array([p["dauc"] for p in pairs], float) + db = np.array([p["dbase"] for p in pairs if p["dbase"] is not None], float) + keep = np.array([p["dbase"] is not None for p in pairs]) + s = dict(n_pairs=len(pairs), n_dirs=len({p["dir"] for p in pairs}), + mean_abs_dlift=float(np.abs(dl).mean()), max_abs_dlift=float(np.abs(dl).max()), + mean_signed_dlift=float(dl.mean()), + mean_abs_dauc=float(np.abs(da).mean()), max_abs_dauc=float(np.abs(da).max()), + mean_signed_dauc=float(da.mean()), + ratio_abs=float(np.abs(dl).mean() / max(np.abs(da).mean(), 1e-12)), + ratio_signed=float(abs(dl.mean()) / max(abs(da.mean()), 1e-12)), + ci_abs_dlift=boot_ci(np.abs(dl), 2000, 11), + ci_abs_dauc=boot_ci(np.abs(da), 2000, 12), + frac_dir_auc_drifts_less=float(np.mean(np.abs(da) < np.abs(dl))), + mean_signed_dbase=float(db.mean()) if db.size else None, + spearman_dbase_dlift=spearman(db, dl[keep]) if db.size else None, + spearman_dbase_dauc=spearman(db, da[keep]) if db.size else None) + s["Y2_pass"] = bool(s["ratio_abs"] >= 1.5 + and abs(s["mean_signed_dauc"]) < abs(s["mean_signed_dlift"])) + s["Y3_pass"] = bool(s["spearman_dbase_dlift"] is not None + and s["spearman_dbase_dlift"] <= -0.4 + and s["spearman_dbase_dauc"] is not None + and abs(s["spearman_dbase_dauc"]) < abs(s["spearman_dbase_dlift"])) + out["drift"] = s + print("\n=== (Y2)/(Y3) SHORT-READ DRIFT, CACHE-WIDE ===") + print(f" {s['n_pairs']} (dir, target) pairs over {s['n_dirs']} dirs " + f"(run 45 had 16 pairs over 11 dirs)") + print(f" LIFT mean |d| = {s['mean_abs_dlift']:.4f} {s['ci_abs_dlift']} " + f"max {s['max_abs_dlift']:.4f} signed {s['mean_signed_dlift']:+.4f}") + print(f" AUC mean |d| = {s['mean_abs_dauc']:.4f} {s['ci_abs_dauc']} " + f"max {s['max_abs_dauc']:.4f} signed {s['mean_signed_dauc']:+.4f}") + print(f" RATIO |lift|/|auc| = {s['ratio_abs']:.2f}x signed ratio " + f"{s['ratio_signed']:.2f}x AUC drifts less on " + f"{s['frac_dir_auc_drifts_less']*100:.0f}% of pairs") + print(f" BASE signed shift {s['mean_signed_dbase']:+.4f} " + f"spearman(dbase,dlift) = {s['spearman_dbase_dlift']} " + f"spearman(dbase,dauc) = {s['spearman_dbase_dauc']}") + print(f" (Y2) {'PASS' if s['Y2_pass'] else 'FAIL -- the AUC rule is WITHDRAWN to its family'}" + f" (Y3) {'PASS' if s['Y3_pass'] else 'FAIL'}") + json.dump(out, open(a.out, "w"), default=float, indent=1) + + # ------------------------------------------------- 4. (Y4) the first frozen gamma dir + f = full.get(FROZEN_CHECK) + if f is not None: + v = cache.get(FROZEN_CHECK, {}).get("variants", {}).get("rsm", {}) + out["Y4"] = dict(dir=FROZEN_CHECK, n_parts=f["n_parts"], n_dec=f["st"]["n_dec"], + lift=f["st"]["onroute_lift"], auc=f["st"]["onroute_auc"], + base=f["st"]["onroute_base_mixed"], + n_dec_at_scan=v.get("n_dec"), + lift_at_scan=v.get("rules", {}).get("argmax", {}).get("onroute_lift"), + newest_part_mtime=f["newest"], + pass_below_m005=bool(f["st"]["onroute_lift"] < -0.05)) + y = out["Y4"] + print(f"\n=== (Y4) {FROZEN_CHECK}: the first of run 44's 4 'filling' dirs to FREEZE ===") + print(f" at the 19:46Z scan: {y['n_dec_at_scan']} dec, lift {y['lift_at_scan']}") + print(f" frozen full length: {y['n_dec']} dec ({y['n_parts']} parts), " + f"lift {y['lift']:+.4f}, auc {y['auc']:.4f}, base {y['base']:.3f}") + print(f" (Y4) predicted lift < -0.05: {'PASS' if y['pass_below_m005'] else 'FAIL'}") + + json.dump(out, open(a.out, "w"), default=float, indent=1) + print(f"\n[out] {a.out}") + + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/real/actcond_readout.py b/rsm_rise/scripts/real/actcond_readout.py new file mode 100644 index 0000000000000000000000000000000000000000..e768b70fc55dd5083a51f86e0948b317f0e59e92 --- /dev/null +++ b/rsm_rise/scripts/real/actcond_readout.py @@ -0,0 +1,496 @@ +#!/usr/bin/env python +"""ACT_COND run 40 -- the READ-OUT test. Run 39 found the information is in the RANKING and the +ARGMAX throws it away. Can a different read-out, on the SAME cached clouds, convert it? + +Run 39 (status/real/ACT_COND/GOAL_DIRECTED_run39.json) established, on `onroute` -- a per-candidate +label meaning "heads down an on-route edge" that never references the logged action: + + rsm ranking onroute AUC 0.5141 pooled / 0.5206 across 145 dirs, null 0.5013 -> signal + rsm argmax PICK onroute 59.9% -> 60.4% (lift +0.0054), d_along -2.01mm, d_perp +2.65mm + +i.e. the ordering carries a real route-level signal while the argmax lands LATERALLY. Run 39 closed by +flagging "a softer read-out (top-k + tie-break on progress) is a cheap thing for the ladder to try". +This run TESTS that claim instead of shipping it as advice. Zero GPU: `edge_parts/ep*.npz` already +carries both the per-candidate scores and the geometry, so no rollout is needed. + +READ-OUT RULES. Every rule here is DEPLOYABLE: it consumes the scores and the candidate actions and +NOTHING ELSE. None may touch `logged_disp_mm` or `onroute` -- those are the measurement, not an input. + + argmax the current read-out (expectation over the tied-at-max set). Reproduces run 39. + topk+cen gate to the top k by score, then pick the candidate whose displacement is CLOSEST + TO THE CLOUD CENTROID displacement (mean over all proposer candidates). "trust the + score to filter, trust the proposer's mode to choose among the survivors". + cen = topk+cen: the centroid pick with the score IGNORED. ** THE CONTROL. ** If a + top-k rule beats argmax but `cen` beats it too, the gain is the proposer's mode, + not the value function. + topk+med gate to the top k, then take the MEDOID of the gated set (closest to the gated + set's own mean). "consensus among the best", which unlike +cen re-centres on what + the score selected. + soft expected onroute under softmax(z/tau), z = per-decision z-scored score. tau->0 is + argmax, tau->inf is `random`. A stochastic read-out, reported in expectation. + random uniform over the cloud == the base rate. Must give lift exactly 0. + +THE HEADLINE COMPARISON IS NOT rule-vs-rule. A centroid-based rule is mechanically good at `d_perp` +(it minimises distance to the cloud mean by construction) and the proposer's mode may well be onroute +more often than a random draw -- so `lift(rule)` alone cannot say the VALUE FUNCTION did anything. The +score's contribution is the PAIRED CONTRAST at a fixed rule: + + lift(rsm, rule) - lift(permuted:rsm, rule) + +`permuted:*` is the scorer's own within-row shuffle: identical score distribution, zero correspondence. +Under it the gate is a random subset, so the contrast holds the rule's geometry exactly fixed and +isolates what the ordering bought. Run 39 verified this null lands on chance on every estimand it +touched (AUC 0.5013, lift +0.0031). + +Tie discipline is run 38/39's, unchanged: every pick statistic is the EXPECTATION over the tied-at-max +set, and a top-k gate is `S >= (k-th largest)` so it ADMITS ALL TIES AT THE BOUNDARY -- the gate size is +therefore >= k and is reported beside every number (the prob read-out ties ~37/128 on the real cache, +and a k=8 gate that is really 40 wide is a different rule). + +Injected candidates (idx >= n_proposer) are dropped, as in run 39: they are run 33's between-route +question, which is answered at 96.9%. + +`_rank_parts` / `tie_mask` / `pick_expect` / `auc_rows` / `load_dir` are lifted verbatim from +`actcond_goal_directedness.py` (run 39), where they were validated at max abs diff 0.0 against +scipy.rankdata and a brute-force Mann-Whitney. +""" +import argparse, json, os, glob +from pathlib import Path +import numpy as np + +ROOT = "/proj/dmfexp/zwhong/rsm_rise" +TIE_RTOL, TIE_ATOL = 1e-6, 1e-12 + +import sys +sys.path.insert(0, os.path.join(ROOT, "scripts", "real")) +from actcond_goal_directedness import ( # noqa: E402 -- validated run-39 primitives + _rank_parts, tie_mask, pick_expect, auc_rows, rank_pct_low, rank_pct_high, + boot_ci, load_dir, family_of, spearman, +) + +KS = [1, 2, 4, 8, 16, 32, 64] +TAUS = [0.1, 0.25, 0.5, 1.0, 2.0, 4.0] + + +# ---------------------------------------------------------------- read-out rules -> weights [D,N] +def w_argmax(S, **kw): + t = tie_mask(S).astype(float) + return t / t.sum(1, keepdims=True) + + +def w_random(S, **kw): + D, N = S.shape + return np.full((D, N), 1.0 / N) + + +def topk_gate(S, k): + """boolean gate: score >= the k-th largest, so ALL ties at the boundary are admitted.""" + D, N = S.shape + if k >= N: + return np.ones((D, N), bool) + thr = -np.partition(-S, k - 1, axis=1)[:, k - 1][:, None] + return S >= thr - (TIE_RTOL * np.maximum(np.abs(thr), 1e-12) + TIE_ATOL) + + +def w_gate_then_min(S, aux, k): + """gate to top-k by score, then pick argmin of `aux` inside the gate (tie -> uniform expectation).""" + g = topk_gate(S, k) + big = np.where(g, aux, np.inf) + mn = big.min(1, keepdims=True) + sel = big <= mn + (TIE_RTOL * np.maximum(np.abs(mn), 1e-12) + TIE_ATOL) + sel = sel & g + return sel.astype(float) / sel.sum(1, keepdims=True), g.sum(1).mean() + + +def w_softmax(S, tau): + m = S.mean(1, keepdims=True) + s = S.std(1, keepdims=True) + z = np.where(s > 1e-12, (S - m) / np.maximum(s, 1e-12), 0.0) / tau + z = z - z.max(1, keepdims=True) + e = np.exp(z) + return e / e.sum(1, keepdims=True) + + +def build_rules(S, CDcen_dist, CD): + """-> {name: (weights [D,N], mean gate size)}. Uses ONLY scores + candidate displacements.""" + D, N = S.shape + out = {} + out["argmax"] = (w_argmax(S), float(tie_mask(S).sum(1).mean())) + out["random"] = (w_random(S), float(N)) + for k in KS: + if k >= N: + continue + w, gs = w_gate_then_min(S, CDcen_dist, k) + out[f"topk{k}+cen"] = (w, float(gs)) + w, gs = w_gate_then_min(S, CDcen_dist, N) + out["cen"] = (w, float(gs)) + for k in KS: + if k <= 1 or k >= N: + continue + g = topk_gate(S, k) + # medoid of the GATED set: distance to the gated set's own mean displacement + gm = (CD * g[:, :, None]).sum(1) / np.maximum(g.sum(1), 1)[:, None] + d = np.linalg.norm(CD - gm[:, None, :], axis=2) + big = np.where(g, d, np.inf) + mn = big.min(1, keepdims=True) + sel = (big <= mn + 1e-12) & g + out[f"topk{k}+med"] = (sel.astype(float) / sel.sum(1, keepdims=True), float(g.sum(1).mean())) + for t in TAUS: + out[f"soft{t}"] = (w_softmax(S, t), float(N)) + return out + + +# ---------------------------------------------------------------- per-decision stats for one rule +def rule_stats(w, O, A, P, E, mixed, B, seed): + """every quantity is the EXPECTATION of the read-out's distribution over candidates.""" + pick_or = (w * O).sum(1) + base = O.mean(1) + d_along = (w * (A - A.mean(1, keepdims=True))).sum(1) + d_perp = (w * (P - P.mean(1, keepdims=True))).sum(1) + d_err = (w * (E - E.mean(1, keepdims=True))).sum(1) + rp_err = (w * rank_pct_low(E)).sum(1) + rp_along = (w * rank_pct_high(A)).sum(1) + lift_vec = (pick_or - base) + out = dict( + onroute_pick=float(pick_or[mixed].mean()) if mixed.any() else None, + onroute_lift=float(lift_vec[mixed].mean()) if mixed.any() else None, + d_along_mm=float(d_along.mean()), d_perp_mm=float(d_perp.mean()), d_err_mm=float(d_err.mean()), + rank_pct_negerr=float(rp_err.mean()), rank_pct_along=float(rp_along.mean()), + ) + if B and mixed.any(): + out["onroute_lift_ci"] = boot_ci(lift_vec[mixed], B, seed) + return out, lift_vec, mixed + + +def readout_table(S, O, A, P, E, CD, B=1000, seed=0): + S = np.asarray(S, float) + ok = np.isfinite(S).all(1) + if ok.sum() < 3: + return None + S, O, A, P, E, CD = S[ok], O[ok], A[ok], P[ok], E[ok], CD[ok] + D, N = S.shape + base = O.mean(1) + mixed = (base > 0) & (base < 1) + cen = CD.mean(1) + dcen = np.linalg.norm(CD - cen[:, None, :], axis=2) + + rules = build_rules(S, dcen, CD) + res = dict(n_dec=int(D), n_cand=int(N), n_mixed=int(mixed.sum()), + onroute_base=float(base[mixed].mean()) if mixed.any() else None, + onroute_auc=float(np.nanmean(auc_rows(S, O))) if mixed.any() else None, + var_a=float(S.var(1, ddof=1).mean()), rules={}) + lifts = {} + for i, (name, (w, gs)) in enumerate(sorted(rules.items())): + st, lv, mk = rule_stats(w, O, A, P, E, mixed, B, seed + 7 * i) + st["gate_size"] = gs + res["rules"][name] = st + lifts[name] = lv + # PAIRED contrast vs argmax, same decisions -- the only honest way to say "better read-out" + a0 = lifts["argmax"] + for name, lv in lifts.items(): + if name == "argmax": + continue + d = (lv - a0)[mixed] + res["rules"][name]["d_lift_vs_argmax"] = float(d.mean()) if len(d) else None + if B and len(d) >= 3: + res["rules"][name]["d_lift_vs_argmax_ci"] = boot_ci(d, B, seed + 999) + return res + + +# ---------------------------------------------------------------- selftest +def selftest(): + res = [] + + def chk(name, got, want, tol): + ok = (got is not None) and abs(float(got) - want) <= tol + res.append(dict(name=name, got=None if got is None else float(got), want=want, tol=tol, ok=bool(ok))) + print(f"[selftest] {'PASS' if ok else 'FAIL':4s} {name:44s} got={got} want={want}+-{tol}", flush=True) + + rng = np.random.default_rng(0) + D, N = 1500, 32 + O = rng.random((D, N)) < 0.6 + O[:, 0] = True; O[:, 1] = False + CD = rng.normal(0, 5, (D, N, 3)); LD = rng.normal(0, 5, (D, 3)) + Lm = np.linalg.norm(LD, axis=1); u = LD / Lm[:, None] + A = np.einsum("dnc,dc->dn", CD, u) + P = np.linalg.norm(CD - A[:, :, None] * u[:, None, :], axis=2) + E = np.linalg.norm(CD - LD[:, None, :], axis=2) + base = O.mean(1); mixed = (base > 0) & (base < 1) + cen = CD.mean(1); dcen = np.linalg.norm(CD - cen[:, None, :], axis=2) + Scont = rng.normal(0, 1, (D, N)) # continuous -> no ties + + # --- gates --- + for k in (1, 4, 8): + chk(f"gate size == k (no ties, k={k})", topk_gate(Scont, k).sum(1).mean(), k, 1e-12) + chk("gate k>=N is all-true", topk_gate(Scont, N).mean(), 1.0, 1e-12) + Sint = rng.integers(0, 4, (D, N)).astype(float) # heavy ties + g = topk_gate(Sint, 8) + bf = np.stack([(x >= np.sort(x)[::-1][7]) for x in Sint]) + chk("gate vs brute-force (heavy ties)", np.abs(g.astype(float) - bf.astype(float)).max(), 0.0, 1e-12) + chk("gate size >= k under ties", float((g.sum(1) >= 8).all()), 1.0, 1e-12) + + # --- weights are proper distributions --- + for nm, (w, _) in build_rules(Scont, dcen, CD).items(): + if abs(float(w.sum(1).mean()) - 1.0) > 1e-9 or float(w.min()) < -1e-12: + chk(f"weights are a distribution [{nm}]", w.sum(1).mean(), 1.0, 1e-9) + chk("weights sum to 1 (all rules)", 1.0, 1.0, 0.0) + + # --- identities --- + r = readout_table(Scont, O, A, P, E, CD, B=0) + chk("random lift == 0 exactly", r["rules"]["random"]["onroute_lift"], 0.0, 1e-12) + chk("random d_along == 0 exactly", r["rules"]["random"]["d_along_mm"], 0.0, 1e-9) + chk("topk1+cen == argmax (no ties)", r["rules"]["topk1+cen"]["onroute_lift"], + r["rules"]["argmax"]["onroute_lift"], 1e-12) + chk("soft0.1 ~ argmax (no ties)", r["rules"]["soft0.1"]["onroute_lift"], + r["rules"]["argmax"]["onroute_lift"], 0.02) + # cen ignores the score: identical under ANY score matrix + r2 = readout_table(rng.normal(0, 1, (D, N)), O, A, P, E, CD, B=0) + chk("cen is score-independent (lift)", r2["rules"]["cen"]["onroute_lift"], + r["rules"]["cen"]["onroute_lift"], 1e-12) + chk("cen is score-independent (d_perp)", r2["rules"]["cen"]["d_perp_mm"], + r["rules"]["cen"]["d_perp_mm"], 1e-9) + # cen == brute-force argmin distance-to-centroid + bfsel = np.zeros((D, N)); bfsel[np.arange(D), dcen.argmin(1)] = 1.0 + chk("cen == brute-force argmin d_centroid", float((bfsel * O).sum(1)[mixed].mean() - base[mixed].mean()), + r["rules"]["cen"]["onroute_lift"], 1e-12) + # softmax limits + w = w_softmax(Scont, 1e12) + chk("soft tau->inf == uniform", np.abs(w - 1.0 / N).max(), 0.0, 1e-12) + # the approach is O(spread/tau), so a FINITE tau must miss uniform by a predictable amount + w8 = w_softmax(Scont, 1e8) + chk("soft tau=1e8 off-uniform ~ 1e-9", np.abs(w8 - 1.0 / N).max(), 1.16e-9, 5e-10) + w = w_softmax(Scont, 1e-6) + chk("soft tau->0 == argmax", np.abs(w - w_argmax(Scont)).max(), 0.0, 1e-9) + + # --- an independent score must not move the pick: one DRAW, so judge it against its own SE --- + ri = readout_table(Scont, O, A, P, E, CD, B=0) + se = float(np.sqrt(0.25 / mixed.sum())) + chk("indep score argmax lift ~ 0 (2 SE)", ri["rules"]["argmax"]["onroute_lift"], 0.0, 2 * se) + chk("indep score topk8+cen == cen +- 2SE", ri["rules"]["topk8+cen"]["onroute_lift"], + ri["rules"]["cen"]["onroute_lift"], 2 * se) + + # --- oracle scorers --- + Sperf = O * 1.0 + 1e-3 * rng.random((D, N)) + r = readout_table(Sperf, O, A, P, E, CD, B=0) + chk("perfect scorer argmax pick == 1", r["rules"]["argmax"]["onroute_pick"], 1.0, 1e-9) + chk("perfect scorer topk4+cen pick == 1", r["rules"]["topk4+cen"]["onroute_pick"], 1.0, 1e-9) + chk("perfect scorer topk4+med pick == 1", r["rules"]["topk4+med"]["onroute_pick"], 1.0, 1e-9) + r = readout_table(-Sperf, O, A, P, E, CD, B=0) + chk("anti scorer argmax pick == 0", r["rules"]["argmax"]["onroute_pick"], 0.0, 1e-9) + chk("anti scorer topk4+cen pick == 0", r["rules"]["topk4+cen"]["onroute_pick"], 0.0, 1e-9) + + # --- fully tied score: every rule that gates on score sees the whole cloud --- + r = readout_table(np.zeros((D, N)), O, A, P, E, CD, B=0) + chk("tied: argmax lift == 0 exactly", r["rules"]["argmax"]["onroute_lift"], 0.0, 1e-12) + chk("tied: topk4+cen == cen", r["rules"]["topk4+cen"]["onroute_lift"], + r["rules"]["cen"]["onroute_lift"], 1e-12) + chk("tied: gate size == N", r["rules"]["topk4+cen"]["gate_size"], N, 1e-12) + + # --- paired contrast machinery --- + r = readout_table(Scont, O, A, P, E, CD, B=200) + chk("d_lift(argmax vs argmax) absent", 1.0 if "d_lift_vs_argmax" not in r["rules"]["argmax"] else 0.0, 1.0, 0.0) + dl = r["rules"]["random"]["d_lift_vs_argmax"] + chk("d_lift(random) == -lift(argmax)", dl, -r["rules"]["argmax"]["onroute_lift"], 1e-12) + ci = r["rules"]["random"]["d_lift_vs_argmax_ci"] + chk("d_lift CI brackets its mean", 1.0 if (ci[0] <= dl <= ci[1]) else 0.0, 1.0, 0.0) + + npass = sum(1 for x in res if x["ok"]) + print(f"[selftest] {npass}/{len(res)} PASS", flush=True) + if npass != len(res): + raise SystemExit("SELFTEST FAILED -- refusing to touch real data") + return res + + +# ---------------------------------------------------------------- aggregation +def analyse(rows, st, a): + out = dict(selftest=st, n_dirs=len(rows), generated=str(np.datetime64("now")), + ks=KS, taus=TAUS) + fam = {} + for r in rows: + for name, v in r["variants"].items(): + fam.setdefault(family_of(name), []).append(v) + + tab = {} + for f, vs in sorted(fam.items()): + w = np.array([v["n_dec"] for v in vs], float) + rules = sorted({k for v in vs for k in v["rules"]}) + ent = dict(n_dirs=len(vs), n_dec=int(w.sum()), + onroute_base=float(np.nansum(np.array([v["onroute_base"] or np.nan for v in vs]) * w) / w.sum()), + onroute_auc=float(np.nansum(np.array([v["onroute_auc"] or np.nan for v in vs]) * w) / w.sum()), + rules={}) + for rl in rules: + def wm(key): + x = np.array([(v["rules"][rl].get(key) if rl in v["rules"] and + v["rules"][rl].get(key) is not None else np.nan) for v in vs], float) + m = np.isfinite(x) + return float((x[m] * w[m]).sum() / w[m].sum()) if m.any() else None + per_dir_d = [v["rules"][rl].get("d_lift_vs_argmax") for v in vs + if rl in v["rules"] and v["rules"][rl].get("d_lift_vs_argmax") is not None] + ent["rules"][rl] = dict( + onroute_pick=wm("onroute_pick"), onroute_lift=wm("onroute_lift"), + d_lift_vs_argmax=wm("d_lift_vs_argmax"), + d_along_mm=wm("d_along_mm"), d_perp_mm=wm("d_perp_mm"), + rank_pct_negerr=wm("rank_pct_negerr"), rank_pct_along=wm("rank_pct_along"), + gate_size=wm("gate_size"), + n_dirs_d_pos=int(sum(1 for d in per_dir_d if d > 0)), n_dirs_d=len(per_dir_d), + d_lift_dir_ci=boot_ci(per_dir_d, 2000, 11) if len(per_dir_d) >= 3 else None, + n_ci_lift_above=int(sum(1 for v in vs if rl in v["rules"] and + v["rules"][rl].get("onroute_lift_ci") and + v["rules"][rl]["onroute_lift_ci"][0] > 0)), + n_ci_lift_below=int(sum(1 for v in vs if rl in v["rules"] and + v["rules"][rl].get("onroute_lift_ci") and + v["rules"][rl]["onroute_lift_ci"][1] < 0))) + tab[f] = ent + out["by_family"] = tab + + # ---- THE headline: score contribution = lift(rsm, rule) - lift(permuted:rsm, rule), paired by dir ---- + contrib = {} + for rl in sorted(tab.get("rsm", {}).get("rules", {}).keys()): + pairs = [] + for r in rows: + a_ = r["variants"].get("rsm") + bk = [k for k in r["variants"] if family_of(k) == "permuted:rsm"] + b_ = r["variants"][bk[0]] if len(bk) == 1 else None + if not a_ or not b_: + continue + if rl in a_["rules"] and rl in b_["rules"]: + x, y = a_["rules"][rl]["onroute_lift"], b_["rules"][rl]["onroute_lift"] + if x is not None and y is not None: + pairs.append((x - y, a_["n_dec"])) + if len(pairs) >= 3: + d = np.array([p[0] for p in pairs]); wt = np.array([p[1] for p in pairs], float) + contrib[rl] = dict(n_dirs=len(pairs), mean=float(d.mean()), + wmean=float((d * wt).sum() / wt.sum()), + ci=boot_ci(d, 2000, 23), frac_pos=float((d > 0).mean())) + out["score_contribution_vs_permuted"] = contrib + + # ---------- print ---------- + for f in ("rsm", "permuted:rsm", "idql", "permuted:idql", "bc", "pose"): + if f not in tab: + continue + v = tab[f] + print(f"\n=== READ-OUTS | family={f} dirs={v['n_dirs']} dec={v['n_dec']} " + f"base={v['onroute_base']:.4f} rankAUC={v['onroute_auc']:.4f} ===", flush=True) + hdr = (f"{'rule':14s} {'gate':>6s} {'pick':>7s} {'lift':>9s} {'d_vs_argmax':>12s} {'CI(dir)':>22s} " + f"{'+dirs':>9s} {'dalong':>7s} {'dperp':>7s} {'rk-err':>7s}") + print(hdr); print("-" * len(hdr)) + order = ["argmax"] + [f"topk{k}+cen" for k in KS if f"topk{k}+cen" in v["rules"]] + ["cen"] + \ + [f"topk{k}+med" for k in KS if f"topk{k}+med" in v["rules"]] + \ + [f"soft{t}" for t in TAUS if f"soft{t}" in v["rules"]] + ["random"] + for rl in order: + if rl not in v["rules"]: + continue + e = v["rules"][rl] + def g(k, w=7, p=4): + x = e.get(k) + return f"{x:>{w}.{p}f}" if x is not None else f"{'-':>{w}s}" + ci = e.get("d_lift_dir_ci") + cis = f"[{ci[0]:+.4f},{ci[1]:+.4f}]" if ci else "-" + print(f"{rl:14s} {g('gate_size',6,1)} {g('onroute_pick',7)} {g('onroute_lift',9,5)} " + f"{g('d_lift_vs_argmax',12,5)} {cis:>22s} " + f"{e['n_dirs_d_pos']:>4d}/{e['n_dirs_d']:<4d} {g('d_along_mm',7,2)} {g('d_perp_mm',7,2)} " + f"{g('rank_pct_negerr',7)}", flush=True) + + print("\n=== SCORE CONTRIBUTION: lift(rsm, rule) - lift(permuted:rsm, rule), paired by dir ===") + print(f"{'rule':14s} {'dirs':>5s} {'mean':>10s} {'wmean':>10s} {'CI':>24s} {'frac>0':>7s}") + for rl, c in sorted(contrib.items(), key=lambda kv: -(kv[1]['mean'])): + ci = c["ci"]; cis = f"[{ci[0]:+.5f},{ci[1]:+.5f}]" if ci else "-" + print(f"{rl:14s} {c['n_dirs']:5d} {c['mean']:+10.5f} {c['wmean']:+10.5f} {cis:>24s} " + f"{c['frac_pos']:7.3f}", flush=True) + + os.makedirs(Path(a.out).parent, exist_ok=True) + json.dump(out, open(a.out, "w"), indent=1, default=float) + print(f"\n[out] {a.out}", flush=True) + return out + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--glob-root", default=f"{ROOT}/status/real") + ap.add_argument("--boot", type=int, default=500) + ap.add_argument("--reuse", action="store_true") + ap.add_argument("--selftest-only", action="store_true") + ap.add_argument("--out", default=f"{ROOT}/status/real/ACT_COND/READOUT_run40.json") + a = ap.parse_args() + + st = selftest() + if a.selftest_only: + return + + cache = str(Path(a.out).with_suffix(".rows.json")) + if a.reuse and Path(cache).exists(): + rows = json.load(open(cache)) + print(f"[cache] reusing {len(rows)} rows", flush=True) + return analyse(rows, st, a) + + dirs = sorted({str(Path(p).parent) for p in glob.glob(os.path.join(a.glob_root, "*", "edge_parts"))}) + print(f"[scan] {len(dirs)} dirs carry edge_parts/", flush=True) + rows = [] + for d in dirs: + try: + got = load_dir(d) + except Exception as e: + print(f"[skip] {Path(d).name}: {type(e).__name__}: {e}", flush=True) + continue + if got is None: + continue + O, A, P, E, S, Lm, nkeep = got + # load_dir returns geometry but not CD; rebuild the candidate displacements it derived from + CD = None + row = dict(dir=Path(d).name, variants={}) + cdz = _reload_cd(d, O.shape) + if cdz is None: + continue + CD = cdz + for k, Sv in sorted(S.items()): + try: + r = readout_table(Sv, O, A, P, E, CD, B=a.boot) + except Exception as e: + print(f"[skip-mode] {Path(d).name}/{k}: {type(e).__name__}: {e}", flush=True) + continue + if r: + row["variants"][k] = r + if row["variants"]: + rows.append(row) + r = row["variants"].get("rsm") + if r: + am = r["rules"]["argmax"]; bk = r["rules"].get("topk8+cen", am) + print(f"[dir] {Path(d).name:36s} dec={r['n_dec']:4d} AUC={r['onroute_auc']:.4f} " + f"argmax_lift={am['onroute_lift']:+.4f} topk8+cen={bk['onroute_lift']:+.4f} " + f"cen={r['rules']['cen']['onroute_lift']:+.4f}", flush=True) + json.dump(rows, open(cache, "w"), default=float) + print(f"[cache] {len(rows)} rows -> {cache}", flush=True) + return analyse(rows, st, a) + + +def _reload_cd(d, shape): + """re-read cand_disp_mm with load_dir's EXACT filtering, so CD lines up row-for-row with O/A/P/E.""" + parts = sorted(glob.glob(os.path.join(d, "edge_parts", "ep*.npz"))) + CD = []; LD = []; nprop = [] + for f in parts: + try: + z = np.load(f, allow_pickle=True) + except Exception: + continue + if "cand_disp_mm" not in z.files or "onroute" not in z.files: + continue + meta = json.loads(z["__meta__"].tobytes().decode()) + nprop.append(np.array([int(m.get("n_proposer", z["onroute"].shape[1])) for m in meta])) + CD.append(z["cand_disp_mm"]); LD.append(z["logged_disp_mm"]) + if not CD: + return None + CD = np.concatenate(CD, 0).astype(float); LD = np.concatenate(LD, 0).astype(float) + npmin = int(np.concatenate(nprop).min()) + if npmin < CD.shape[1]: + CD = CD[:, :npmin] + Lm = np.linalg.norm(LD, axis=1) + good = np.isfinite(Lm) & (Lm > 1e-6) & np.isfinite(CD).all(axis=(1, 2)) + CD = CD[good] + if CD.shape[:2] != shape: + print(f"[skip] {Path(d).name}: CD/O shape mismatch {CD.shape[:2]} vs {shape}", flush=True) + return None + return CD + + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/real/actcond_readout_dod.py b/rsm_rise/scripts/real/actcond_readout_dod.py new file mode 100644 index 0000000000000000000000000000000000000000..4a029beab9a59242c8855a079ab5be0e491f24a8 --- /dev/null +++ b/rsm_rise/scripts/real/actcond_readout_dod.py @@ -0,0 +1,212 @@ +#!/usr/bin/env python +"""ACT_COND run 42 -- the DIFFERENCE OF DIFFERENCES that resolves run 40's (S2). + +Run 40's table gives, per read-out rule, the paired score contribution + + contrib(rule) = lift(rsm, rule) - lift(permuted:rsm, rule) + +and it is positive with a CI excluding 0 for many rules. BUT `argmax` ITSELF already has +contrib = +0.01004. So "rule R has a positive score contribution" does NOT establish that R lets the +VALUE FUNCTION buy anything MORE than the argmax read-out already buys -- which is the actual question +run 39 raised and run 40 pre-registered as (S2). The sharp estimand is the difference of differences, +paired by directory: + + DoD(rule) = contrib(rule) - contrib(argmax) + = [lift(rsm,rule) - lift(rsm,argmax)] - [lift(perm,rule) - lift(perm,argmax)] + +The second line is the useful reading and it is an EXACT algebraic identity per dir: + + d_lift_vs_argmax(rsm, rule) = d_lift_vs_argmax(perm, rule) + DoD(rule) + total raw gain = GEOMETRY part + SCORE part + +i.e. every rule's gain over argmax splits, with no residual, into what the rule's geometry buys a +scorer that carries NO information (the permuted control gets the same gate size and the same +tie-break, on a random subset) plus what the real ordering adds on top. That decomposition is the +whole answer to "is the read-out worth changing, and is it worth changing BECAUSE OF THE VALUE +FUNCTION". Selftest 1 asserts the identity to 1e-12 on the real rows, not on a toy. + +Reads ONLY the run-40 row cache (status/real/ACT_COND/READOUT_run40.rows.json). No GPU, no rollout, +no new scan. Primitives (`boot_ci`, `family_of`) are IMPORTED from the run-39/40 scripts, not copied. +""" +import argparse, json, os, sys +from pathlib import Path +import numpy as np + +ROOT = "/proj/dmfexp/zwhong/rsm_rise" +sys.path.insert(0, os.path.join(ROOT, "scripts", "real")) +from actcond_goal_directedness import boot_ci, family_of # noqa: E402 validated run-39 primitives + +FAMS = [("rsm", "permuted:rsm"), ("idql", "permuted:idql")] + + +def _pick(r, fam): + """The variant for `fam` in row r, or None if ambiguous. + + Prefer the EXACT key (`rsm`, `idql`): 12 of the 145 dirs also carry an ablation twin + (`rsm_AT_s1`, `rsm_AT_zz0dup`) that `family_of` maps to the same family, and a bare + one-key-per-family guard would silently drop those dirs -- which would make this table + incomparable with run 40's 145-dir contribution table. Fall back to a unique family match + (that is how `permuted:rsm` is found, since its key is `permuted__rsm`). + """ + if fam in r["variants"]: + return r["variants"][fam] + ks = [k for k in r["variants"] if family_of(k) == fam] + return r["variants"][ks[0]] if len(ks) == 1 else None + + +def paired(rows, fa, fb): + """[(dir, a_variant, b_variant)] for every dir carrying an unambiguous variant of each family.""" + out = [] + for r in rows: + a_, b_ = _pick(r, fa), _pick(r, fb) + if a_ is not None and b_ is not None: + out.append((r.get("dir", "?"), a_, b_)) + return out + + +def series(pairs, rule, key): + """per-dir (a_val, b_val, n_dec) where BOTH families have `rule` and `key` non-null.""" + o = [] + for _, a, b in pairs: + if rule in a["rules"] and rule in b["rules"]: + x, y = a["rules"][rule].get(key), b["rules"][rule].get(key) + if x is not None and y is not None: + o.append((x, y, float(a["n_dec"]))) + return o + + +def wmean(v, w): + v, w = np.asarray(v, float), np.asarray(w, float) + m = np.isfinite(v) + return float((v[m] * w[m]).sum() / w[m].sum()) if m.any() else None + + +def dod_table(pairs, rules, boot=4000, seed=29): + """DoD(rule) and its geometry/score decomposition, paired by dir.""" + ca = series(pairs, "argmax", "onroute_lift") + contrib_argmax = np.array([x - y for x, y, _ in ca]) + w_argmax = np.array([n for _, _, n in ca]) + out = {} + for rl in rules: + s = series(pairs, rl, "onroute_lift") + if len(s) < 3 or len(s) != len(ca): + continue # only exact, complete pairings + c = np.array([x - y for x, y, _ in s]) + w = np.array([n for _, _, n in s]) + dod = c - contrib_argmax + geo = np.array([y for _, y, _ in s]) - np.array([y for _, y, _ in ca]) # perm gain over argmax + raw = np.array([x for x, _, _ in s]) - np.array([x for x, _, _ in ca]) # rsm gain over argmax + out[rl] = dict( + n_dirs=len(s), + raw_gain=float(raw.mean()), raw_gain_w=wmean(raw, w), + geometry=float(geo.mean()), geometry_w=wmean(geo, w), + dod=float(dod.mean()), dod_w=wmean(dod, w), + dod_ci=boot_ci(dod, boot, seed), dod_frac_pos=float((dod > 0).mean()), + geometry_ci=boot_ci(geo, boot, seed + 1), + contrib=float(c.mean()), contrib_w=wmean(c, w), + max_identity_resid=float(np.abs(raw - (geo + dod)).max()), + share_score=(float(dod.mean() / raw.mean()) if abs(raw.mean()) > 1e-9 else None), + ) + return out, dict(n_dirs=len(ca), contrib_argmax=float(contrib_argmax.mean()), + contrib_argmax_w=wmean(contrib_argmax, w_argmax), + contrib_argmax_ci=boot_ci(contrib_argmax, boot, seed + 2)) + + +def family_pooled(pairs, which, rule, keys): + """pooled (n_dec-weighted) values for one family on the PAIRED dir set only.""" + o = {} + for k in keys: + v, w = [], [] + for _, a, b in pairs: + t = (a if which == "a" else b) + if rule in t["rules"] and t["rules"][rule].get(k) is not None: + v.append(t["rules"][rule][k]); w.append(float(t["n_dec"])) + o[k] = wmean(v, w) if v else None + return o + + +def selftest(pairs, tab, hdr): + res, fails = [], 0 + def chk(name, got, want, tol): + nonlocal fails + ok = (got is not None) and abs(got - want) <= tol + fails += (not ok) + res.append(dict(name=name, got=got, want=want, tol=tol, ok=bool(ok))) + print(f"[selftest] {'PASS' if ok else 'FAIL'} {name:52s} got={got} want={want}+-{tol}", flush=True) + + # 1. THE decomposition identity, asserted on the REAL rows: raw == geometry + score, per dir. + worst = max(v["max_identity_resid"] for v in tab.values()) + chk("raw_gain == geometry + DoD (per dir, real rows)", worst, 0.0, 1e-12) + # 2. argmax is the origin of the contrast by construction. + chk("DoD(argmax) == 0 exactly", tab["argmax"]["dod"], 0.0, 1e-12) + chk("geometry(argmax) == 0 exactly", tab["argmax"]["geometry"], 0.0, 1e-12) + # 3. `random` and `cen` both have zero score contribution (lift 0; score-independent), so their + # DoD must equal -contrib(argmax) EXACTLY, and must equal each other. + chk("DoD(random) == -contrib(argmax)", tab["random"]["dod"], -hdr["contrib_argmax"], 1e-12) + chk("DoD(cen) == -contrib(argmax)", tab["cen"]["dod"], -hdr["contrib_argmax"], 1e-12) + chk("DoD(cen) == DoD(random)", tab["cen"]["dod"], tab["random"]["dod"], 1e-12) + # 4. every rule is on the SAME paired dir set (no rule silently dropping dirs). + n = {v["n_dirs"] for v in tab.values()} + chk("all rules share one paired dir set", float(len(n)), 1.0, 0.0) + # 5. CIs bracket their own point estimate. + bad = sum(1 for v in tab.values() if v["dod_ci"] and not (v["dod_ci"][0] <= v["dod"] <= v["dod_ci"][1])) + chk("every DoD CI brackets its mean", float(bad), 0.0, 0.0) + # 6. topk1+cen differs from argmax ONLY through ties, so its DoD is ~0. + chk("DoD(topk1+cen) ~ 0 (ties only)", tab["topk1+cen"]["dod"], 0.0, 2e-3) + print(f"[selftest] {len(res)-fails}/{len(res)} PASS", flush=True) + return res, fails + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--rows", default=f"{ROOT}/status/real/ACT_COND/READOUT_run40.rows.json") + ap.add_argument("--out", default=f"{ROOT}/status/real/ACT_COND/READOUT_DOD_run42.json") + ap.add_argument("--boot", type=int, default=4000) + a = ap.parse_args() + + rows = json.load(open(a.rows)) + print(f"[rows] {len(rows)} dirs from {a.rows}", flush=True) + out = dict(generated=str(np.datetime64("now")), n_rows=len(rows), by_family={}) + + for fa, fb in FAMS: + pairs = paired(rows, fa, fb) + rules = sorted(set.intersection(*[set(a_["rules"]) & set(b_["rules"]) for _, a_, b_ in pairs])) + tab, hdr = dod_table(pairs, rules, a.boot) + if fa == "rsm": + st, fails = selftest(pairs, tab, hdr) + out["selftest"] = st + if fails: + print(f"[FATAL] {fails} selftest failure(s)", flush=True); sys.exit(2) + + # (S1) identity check: the argmax row on the PAIRED dir set, vs run 39. + s1 = family_pooled(pairs, "a", "argmax", ["onroute_lift", "d_along_mm", "d_perp_mm", "gate_size"]) + out["by_family"][fa] = dict(paired_with=fb, n_paired=hdr["n_dirs"], + argmax_on_paired_dirs=s1, contrib_argmax=hdr, rules=tab) + + print(f"\n=== DoD | {fa} vs {fb} | {hdr['n_dirs']} paired dirs ===", flush=True) + print(f" {fa} argmax on the PAIRED set: lift {s1['onroute_lift']:+.5f} " + f"d_along {s1['d_along_mm']:+.2f}mm d_perp {s1['d_perp_mm']:+.2f}mm", flush=True) + print(f" contrib(argmax) = lift({fa},argmax) - lift({fb},argmax) = {hdr['contrib_argmax']:+.5f} " + f"CI [{hdr['contrib_argmax_ci'][0]:+.5f},{hdr['contrib_argmax_ci'][1]:+.5f}]", flush=True) + h = (f"{'rule':14s} {'raw_gain':>9s} {'=':>1s} {'GEOMETRY':>9s} {'+':>1s} {'SCORE(DoD)':>11s} " + f"{'DoD CI(dir)':>24s} {'frac>0':>7s} {'score%':>7s}") + print(h); print("-" * len(h)) + order = (["argmax"] + [f"topk{k}+cen" for k in (1, 2, 4, 8, 16, 32, 64)] + ["cen"] + + [f"topk{k}+med" for k in (2, 4, 8, 16, 32, 64)] + + [f"soft{t}" for t in (0.1, 0.25, 0.5, 1.0, 2.0, 4.0)] + ["random"]) + for rl in order: + if rl not in tab: + continue + v = tab[rl]; ci = v["dod_ci"] + sh = f"{100*v['share_score']:6.1f}%" if v["share_score"] is not None else " -" + print(f"{rl:14s} {v['raw_gain']:+9.5f} {'=':1s} {v['geometry']:+9.5f} {'+':1s} " + f"{v['dod']:+11.5f} [{ci[0]:+.5f},{ci[1]:+.5f}]{'':>3s} {v['dod_frac_pos']:7.3f} {sh:>7s}", + flush=True) + + os.makedirs(Path(a.out).parent, exist_ok=True) + json.dump(out, open(a.out, "w"), indent=1, default=float) + print(f"\n[out] {a.out}", flush=True) + + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/real/actcond_route_asi.py b/rsm_rise/scripts/real/actcond_route_asi.py new file mode 100644 index 0000000000000000000000000000000000000000..42c8da912f7cc4037d4d5be2e09a25e3553d72f5 --- /dev/null +++ b/rsm_rise/scripts/real/actcond_route_asi.py @@ -0,0 +1,453 @@ +#!/usr/bin/env python +"""ACT_COND run 51 -- WHAT IS THE ACTION-DRIVEN VARIANCE MADE OF? + +Runs 1-4 of this stream closed Tasks 1-3: the conditioning PATH is correct (12/12 assertions) and +the value is strongly action-sensitive (ASI 0.82 logit / 0.81 prob pooled; deployed-chain 0.97 prob). +Run 50 then withdrew the control behind the headline: RANK_CTRL showed a ZERO-PARAMETER pose +heuristic scores top-1 = 1.000 on the very cell where the RSM scores 0.969, because the correct +chunk sits 27x closer in pose than the median distractor, and on the ROUTE question the same +artefact is at / below chance (route AUC 0.498 uncontrolled, 0.433 [.417,.448] pose-matched). + +So: the value is sensitive to the action, and the sensitivity does not point at the goal route. +The question nobody has measured, and the only one left that is squarely this stream's: + + Of the action-driven variance of q at a FIXED state, how much is explained by a zero-parameter + PROXIMITY feature that carries no goal information, and how much by the ROUTE direction? + +That is the ASI decomposed against the route label instead of against the logged chunk. It is a +within-anchor variance decomposition, and every quantity it needs is already in this stream's own +cache -- so it costs no GPU and re-uses no other stream's files. + +INPUT (read-only, this stream's own, written 2026-09-23 14:56Z) + status/real/logged_action_rank_G999/per_anchor.npz 96 S2 anchors x 32 candidates + scores_rsm q, the DEPLOYED chain `prob` read-out + scores_permuted_rsm the permuted-feature arm, the MEASURED zero line + route_pose_dist || candidate's FIRST absolute action pose (xyz) - ANCHOR's pose || + -- zero parameters, no downstream information whatsoever + route_margin cos_succ - cos_fail of the candidate's OWN displacement direction against + the two measured meta-action directions: the CONTINUOUS on-route-ness + route_label margin > 0, the binary route label + status/real/logged_action_rank_G999/logged_action_rank.json -- for the loud regressions + +THE ESTIMATOR. Within each anchor the state is FIXED, so the spread of q across its 32 candidates +IS the ASI numerator. Per anchor, OLS of z(q) on z(pose_dist), on z(margin), and on both: + r2_pose, r2_route, r2_both; partial_route = r2_both - r2_pose (route variance proximity + CANNOT buy); partial_pose = r2_both - r2_route. +Reported per anchor, and as a pooled within (fixed-effects) R^2 on the anchor-demeaned stack. + +WHY THE CONTROLS ARE THE POINT. An R^2 alone is unreadable without knowing what the pool's own +confound hands to a scorer for free. Four arms, two of them with ZERO parameters: + rsm the measured value + permuted the measured zero line (not the nominal 0) + -posedist a zero-parameter proximity scorer -> r2_pose MUST be 1.0 (assertion C2) + +margin a zero-parameter route scorer -> r2_route MUST be 1.0 (assertion C3) +C2 and C3 are dual power checks in the spirit of run 1's 1.097 units counterfactual: they prove the +estimator can see BOTH directions, so a near-zero partial_route on the rsm arm is a fact about the +value and not about the instrument. The two zero-parameter arms also read off the pool's own +confound in both directions, which is exactly what run 50 found the headline was missing. + +THE NULL AN R^2 IS READ AGAINST. R^2 is non-negative and upward-biased, so "the interval excludes +0" proves nothing. A pure-noise regressor inside an anchor of K candidates earns E[R^2] = 1/(K-1) += 0.0323 at K=32 by construction. Run 51's first read had r2_route = 0.0320 -- dead on that null -- +and would have shipped a significant-looking route term that is exactly noise. Every route number +is therefore printed beside BOTH the analytic null and the measured permuted arm, and the headline +comparison is the PAIRED rsm-minus-permuted difference on identical anchors, never rsm-vs-zero. + +STATISTICS. All 96 anchors come from FIVE validation episodes, so the honest resampling unit is the +EPISODE, not the anchor (the source script's own docstring says anchor-level bars would be ~4x too +tight). Every headline carries a 2000-draw episode bootstrap and the per-episode breakdown, and +n_eps = 5 is printed beside every interval so nobody reads a 5-cluster CI as a 96-sample one. + +LIMITATION, STATED NOT HIDDEN. This cache holds the `prob` read-out only; `logit` would need a GPU +re-run. The Spearman companions are invariant to any monotone transform of q, so they carry over to +`logit` IF the two read-outs are monotone-related within an anchor -- which is NOT established here, +and is flagged in the JSON rather than assumed. + +FAILS LOUDLY. Nothing downstream is computed unless the input reproduces the published headline: +top1_argmax 0.96875 and route AUC 0.49790579652984107 for rsm|S2, plus the permuted arm's 0.0625 / +0.48551321310684825. If the cache does not reproduce them, this script aborts with the mismatch. +""" +import argparse, json, os, sys +import numpy as np + +REQ = ("ep", "t", "stage", "scores_rsm", "scores_permuted_rsm", + "route_pose_dist", "route_margin", "route_label") + +# published cells this run must reproduce before it is allowed to compute anything new +EXPECT = {"rsm|correct|S2.top1_argmax": 0.96875, + "permuted:rsm|correct|S2.top1_argmax": 0.0625, + "rsm|S2.auc": 0.49790579652984107, + "permuted:rsm|S2.auc": 0.48551321310684825} + + +def die(msg): + print("ASSERTION FAILED: " + msg, file=sys.stderr) + sys.exit(2) + + +TIE_TOL = 1e-12 # byte-identical to logged_action_rank.py:102 + + +def auc(score, label): + """EXACT port of logged_action_rank.py:_auc -- the estimator that produced the published cell. + Mid-ranks inside RELATIVE tie groups (TIE_TOL), nan for a single-class anchor (the source + returns None there and drops it from the mean; nan + nanmean is the same thing).""" + y = np.asarray(label).astype(bool); s = np.asarray(score, np.float64) + npos, nneg = int(y.sum()), int((~y).sum()) + if npos == 0 or nneg == 0: + return np.nan + order = np.argsort(s, kind="mergesort"); r = np.empty(len(s), np.float64) + r[order] = np.arange(1, len(s) + 1) + ss = s[order] + i = 0 + while i < len(ss): + j = i + while j + 1 < len(ss) and abs(ss[j + 1] - ss[i]) <= TIE_TOL * max(1.0, abs(ss[i])): + j += 1 + if j > i: + r[order[i:j + 1]] = (i + j + 2) / 2.0 + i = j + 1 + return float((r[y].sum() - npos * (npos + 1) / 2.0) / (npos * nneg)) + + +def z(x): + x = np.asarray(x, float); sd = x.std() + return np.zeros_like(x) if sd < 1e-12 else (x - x.mean()) / sd + + +def ols_r2(y, X): + """R^2 of y on [1, X]; X is (n,k). Returns 0.0 for a degenerate design.""" + y = np.asarray(y, float) + n = len(y) + A = np.column_stack([np.ones(n)] + [np.asarray(c, float) for c in X]) + sst = float(((y - y.mean()) ** 2).sum()) + if sst < 1e-24: + return 0.0 + try: + beta, *_ = np.linalg.lstsq(A, y, rcond=None) + except np.linalg.LinAlgError: + return 0.0 + resid = y - A @ beta + return float(max(0.0, 1.0 - (resid ** 2).sum() / sst)) + + +def spearman(a, b): + a = np.asarray(a, float); b = np.asarray(b, float) + if len(a) < 3: + return np.nan + ra, rb = _rank(a), _rank(b) + if ra.std() < 1e-12 or rb.std() < 1e-12: + return np.nan + return float(np.corrcoef(ra, rb)[0, 1]) + + +def _rank(x): + order = np.argsort(x, kind="mergesort"); r = np.empty(len(x), float); s = x[order] + i = 0 + while i < len(s): + j = i + while j + 1 < len(s) and s[j + 1] == s[i]: + j += 1 + r[order[i:j + 1]] = 0.5 * (i + j) + 1.0 + i = j + 1 + return r + + +def ep_boot(per_anchor, eps, n=2000, seed=0): + """Episode-level cluster bootstrap of a per-anchor statistic. Returns mean/lo/hi/n_eps and + the per-episode means, so a 5-cluster interval can never be mistaken for a 96-sample one.""" + per_anchor = np.asarray(per_anchor, float); eps = np.asarray(eps) + ok = np.isfinite(per_anchor) + per_anchor, eps = per_anchor[ok], eps[ok] + uniq = np.unique(eps) + if len(uniq) == 0: + return {"mean": float("nan"), "lo": float("nan"), "hi": float("nan"), "n_eps": 0} + by = {int(e): per_anchor[eps == e] for e in uniq} + rng = np.random.default_rng(seed) + draws = np.empty(n) + for k in range(n): + pick = rng.choice(uniq, size=len(uniq), replace=True) + draws[k] = np.concatenate([by[int(e)] for e in pick]).mean() + return {"mean": float(per_anchor.mean()), + "lo": float(np.percentile(draws, 2.5)), "hi": float(np.percentile(draws, 97.5)), + "n_eps": int(len(uniq)), "n_anchors": int(len(per_anchor)), + "per_episode": {str(int(e)): float(v.mean()) for e, v in by.items()}} + + +def decompose(Q, P, M, eps, drop0=False, seed=0): + """Within-anchor variance decomposition of q on proximity and route direction.""" + if drop0: + Q, P, M = Q[:, 1:], P[:, 1:], M[:, 1:] + n_anch, K = Q.shape + cols = {k: np.full(n_anch, np.nan) for k in + ("r2_pose", "r2_route", "r2_both", "partial_route", "partial_pose", + "rho_pose", "rho_route", "auc_anchor")} + dq, dp, dm = [], [], [] + for i in range(n_anch): + q, p, m = z(Q[i]), z(P[i]), z(M[i]) + rp = ols_r2(q, [p]); rr = ols_r2(q, [m]); rb = ols_r2(q, [p, m]) + rb = max(rb, rp, rr) # numerical guard: nested models + cols["r2_pose"][i] = rp; cols["r2_route"][i] = rr; cols["r2_both"][i] = rb + cols["partial_route"][i] = rb - rp; cols["partial_pose"][i] = rb - rr + cols["rho_pose"][i] = spearman(Q[i], P[i]); cols["rho_route"][i] = spearman(Q[i], M[i]) + dq.append(Q[i] - Q[i].mean()); dp.append(P[i] - P[i].mean()); dm.append(M[i] - M[i].mean()) + DQ, DP, DM = map(np.concatenate, (dq, dp, dm)) + within = {"r2_pose": ols_r2(DQ, [DP]), "r2_route": ols_r2(DQ, [DM]), + "r2_both": ols_r2(DQ, [DP, DM])} + within["r2_both"] = max(within["r2_both"], within["r2_pose"], within["r2_route"]) + within["partial_route"] = within["r2_both"] - within["r2_pose"] + within["partial_pose"] = within["r2_both"] - within["r2_route"] + out = {"n_anchors": int(n_anch), "K": int(K), "within_fixed_effects": within, + "per_anchor_mean": {k: float(np.nanmean(v)) for k, v in cols.items() if k != "auc_anchor"}, + "boot": {k: ep_boot(cols[k], eps, seed=seed) + for k in ("r2_pose", "r2_route", "partial_route", "rho_pose", "rho_route")}} + return out, cols + + +def pose_matched_concordance(Q, P, M, L, eps, tol, seed=0): + """Confound differenced OUT rather than thresholded away: inside an anchor, take every candidate + PAIR whose pose_dist differs by < tol and whose route labels DIFFER, and ask how often the + higher-q candidate is the on-route one. 0.5 is chance; it is an AUC restricted to pose-matched + pairs, so the proximity feature cannot express a preference.""" + n_anch = Q.shape[0] + per = np.full(n_anch, np.nan); npairs = np.zeros(n_anch, int) + for i in range(n_anch): + q, p, l = Q[i], P[i], L[i] + a, b = np.triu_indices(len(q), 1) + keep = (np.abs(p[a] - p[b]) < tol) & (l[a] != l[b]) + if not keep.any(): + continue + ia, ib = a[keep], b[keep] + # orient each pair so ia is the on-route member + swap = l[ia] < l[ib] + ia2 = np.where(swap, ib, ia); ib2 = np.where(swap, ia, ib) + win = (q[ia2] > q[ib2]).astype(float) + 0.5 * (q[ia2] == q[ib2]) + per[i] = float(win.mean()); npairs[i] = len(ia2) + return ({"tol_m": tol, "n_anchors_used": int(np.isfinite(per).sum()), + "pairs_total": int(npairs.sum()), "pairs_per_anchor_med": float(np.median(npairs)), + "boot": ep_boot(per, eps, seed=seed)}, per) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--src", default="status/real/logged_action_rank_G999") + ap.add_argument("--out", default="status/real/ACT_COND/ROUTE_ASI_run51.json") + ap.add_argument("--seed", type=int, default=0) + a = ap.parse_args() + + npz_p = os.path.join(a.src, "per_anchor.npz") + js_p = os.path.join(a.src, "logged_action_rank.json") + for p in (npz_p, js_p): + if not os.path.exists(p): + die(f"missing input {p}") + st0 = {p: os.stat(p) for p in (npz_p, js_p)} + + d = np.load(npz_p, allow_pickle=True) + for k in REQ: + if k not in d.files: + die(f"npz is missing required key {k}; has {sorted(d.files)}") + src = json.load(open(js_p)) + + Q = np.asarray(d["scores_rsm"], float) + QP = np.asarray(d["scores_permuted_rsm"], float) + P = np.asarray(d["route_pose_dist"], float) + M = np.asarray(d["route_margin"], float) + L = np.asarray(d["route_label"], float) + eps = np.asarray(d["ep"]).astype(int) + stage = np.asarray(d["stage"]).astype(int) + + # ---- A0 shape / finiteness / stage ------------------------------------------------------- + n_anch, K = Q.shape + for nm, arr in (("scores_permuted_rsm", QP), ("route_pose_dist", P), + ("route_margin", M), ("route_label", L)): + if arr.shape != Q.shape: + die(f"A0 shape: {nm} {arr.shape} != scores_rsm {Q.shape}") + if not np.isfinite(arr).all(): + die(f"A0 finite: {nm} has {int((~np.isfinite(arr)).sum())} non-finite entries") + if not np.isfinite(Q).all(): + die("A0 finite: scores_rsm has non-finite entries") + if len(eps) != n_anch or len(stage) != n_anch: + die("A0 shape: ep/stage length does not match n_anchors") + if not (stage == 2).all(): + die(f"A0 stage: expected all S2, got {sorted(set(stage.tolist()))}") + if not set(np.unique(L).tolist()) <= {0.0, 1.0}: + die(f"A0 label: route_label is not binary, uniques {np.unique(L)[:8]}") + + # ---- A1 / A2 the loud regressions against the PUBLISHED headline --------------------------- + got = {} + got["rsm|correct|S2.top1_argmax"] = float((np.argmax(Q, axis=1) == 0).mean()) + got["permuted:rsm|correct|S2.top1_argmax"] = float((np.argmax(QP, axis=1) == 0).mean()) + # AUC convention. The source computes _auc PER ANCHOR and reports the mean over anchors + # (logged_action_rank.py:808 `vals.mean()`), NOT a pooled AUC over every (anchor, candidate) + # cell. Run 51 first asserted against the pooled one and the guard caught it: pooled and + # anchor-averaged differ by 2.0e-04 on rsm but 2.6e-02 on the permuted arm, because pooling + # mixes anchors whose score scales differ. Assert the PUBLISHED convention; record both. + pooled = {"rsm": auc(Q.ravel(), L.ravel()), "permuted:rsm": auc(QP.ravel(), L.ravel())} + anchavg = {"rsm": float(np.nanmean([auc(Q[i], L[i]) for i in range(n_anch)])), + "permuted:rsm": float(np.nanmean([auc(QP[i], L[i]) for i in range(n_anch)]))} + got["rsm|S2.auc"] = anchavg["rsm"]; got["permuted:rsm|S2.auc"] = anchavg["permuted:rsm"] + regression = {} + for k, want in EXPECT.items(): + g = got[k]; ok = abs(g - want) < 1e-9 + regression[k] = {"published": want, "recomputed": g, "abs_diff": abs(g - want), "pass": ok} + bad = [k for k, v in regression.items() if not v["pass"]] + if bad: + for k in bad: + print(f" {k}: published {regression[k]['published']!r} recomputed " + f"{regression[k]['recomputed']!r} |d| {regression[k]['abs_diff']:.3e}", + file=sys.stderr) + die("A1/A2 regression: this cache does not reproduce the published headline; refusing to " + "compute anything downstream off it") + print(f"[A1/A2] 4/4 published cells reproduce exactly from the cache " + f"(top1 {got['rsm|correct|S2.top1_argmax']:.5f}, route auc {got['rsm|S2.auc']:.6f})") + + # ---- the four arms -------------------------------------------------------------------- + arms = {"rsm": Q, "permuted": QP, "zero_param_posedist": -P, "zero_param_margin": M} + res = {} + cols_by_arm = {} + for name, S in arms.items(): + res[name], cols_by_arm[name] = decompose(S, P, M, eps, seed=a.seed) + res[name]["route_auc_pooled"] = auc(S.ravel(), L.ravel()) + res[name]["route_auc_anchor_avg"] = float(np.nanmean([auc(S[i], L[i]) for i in range(n_anch)])) + res[name]["route_auc_published_convention"] = res[name]["route_auc_anchor_avg"] + res[name]["route_auc_boot"] = ep_boot([auc(S[i], L[i]) for i in range(n_anch)], eps, seed=a.seed) + + # ---- C2 / C3 dual power checks: the estimator must see BOTH directions ------------------- + power = {} + c2 = res["zero_param_posedist"]["within_fixed_effects"]["r2_pose"] + c3 = res["zero_param_margin"]["within_fixed_effects"]["r2_route"] + power["C2_posedist_scorer_r2_pose"] = {"value": c2, "must_be": 1.0, "pass": abs(c2 - 1.0) < 1e-8} + power["C3_margin_scorer_r2_route"] = {"value": c3, "must_be": 1.0, "pass": abs(c3 - 1.0) < 1e-8} + for k, v in power.items(): + if not v["pass"]: + die(f"{k}: a scorer that IS the feature must have R^2 = 1 within every anchor, got " + f"{v['value']!r}. The estimator is broken; no number below it is readable.") + print(f"[C2/C3] dual power checks pass: a pose-only scorer reads r2_pose = {c2:.10f}, " + f"a margin-only scorer reads r2_route = {c3:.10f}") + + # ---- the NULL an R^2 must be read against ------------------------------------------------ + # R^2 is non-negative and biased upward, so "the CI excludes 0" is not evidence of signal. A + # pure-noise regressor inside an anchor of K candidates earns E[R^2] = 1/(K-1) by construction, + # and a second regressor added to a model at R^2_1 earns E[dR^2] = (1-R^2_1)/(K-2). Both are + # printed beside every route number, and the permuted arm is carried as the MEASURED null. + r2p_mean = float(np.nanmean(cols_by_arm["rsm"]["r2_pose"])) + nulls = {"K": int(K), + "analytic_r2_one_regressor": 1.0 / (K - 1), + "analytic_partial_second_regressor": (1.0 - r2p_mean) / (K - 2), + "measured_permuted_r2_route": float(np.nanmean(cols_by_arm["permuted"]["r2_route"])), + "measured_permuted_partial_route": float(np.nanmean(cols_by_arm["permuted"]["partial_route"])), + "note": "compare r2_route and partial_route to THESE, never to 0"} + + # paired rsm - permuted on the identical anchors, episode bootstrap + paired = {k: ep_boot(cols_by_arm["rsm"][k] - cols_by_arm["permuted"][k], eps, seed=a.seed) + for k in ("r2_pose", "r2_route", "partial_route", "rho_pose", "rho_route")} + + # ---- C4 drop candidate 0 (the 27x-closer logged goal-route chunk) ------------------------- + drop0 = {} + for name in ("rsm", "permuted"): + drop0[name], _ = decompose(arms[name], P, M, eps, drop0=True, seed=a.seed) + cand0 = {"pose_dist_cand0_mean": float(P[:, 0].mean()), + "pose_dist_others_mean": float(P[:, 1:].mean()), + "ratio": float(P[:, 1:].mean() / max(P[:, 0].mean(), 1e-12)), + "label_cand0_mean": float(L[:, 0].mean())} + + # ---- the confound differenced out, rather than thresholded away -------------------------- + conc, conc_perm, conc_paired = {}, {}, {} + for t in (0.02, 0.05, 0.10): + key = f"tol_{t}".replace(".", "p") + conc[key], per_r = pose_matched_concordance(Q, P, M, L, eps, t, seed=a.seed) + conc_perm[key], per_p = pose_matched_concordance(QP, P, M, L, eps, t, seed=a.seed) + # PAIRED on the identical pair set: the permuted arm is the MEASURED zero line, and it is + # NOT at 0.5 here, so rsm-vs-0.5 is the wrong comparison and rsm-vs-permuted is the right one. + conc_paired[key] = ep_boot(per_r - per_p, eps, seed=a.seed) + + # ---- freeze witness: the input must not have moved under the read ------------------------ + st1 = {p: os.stat(p) for p in (npz_p, js_p)} + for p in st0: + if (st0[p].st_size, st0[p].st_mtime) != (st1[p].st_size, st1[p].st_mtime): + die(f"input {p} changed under the read (size/mtime witness)") + + out = { + "run": 51, "stream": "ACT_COND", "question": + "of the action-driven variance of q at a FIXED state, how much is a zero-parameter " + "proximity feature and how much is the route direction", + "src": {"npz": os.path.abspath(npz_p), "json": os.path.abspath(js_p), + "npz_size": st0[npz_p].st_size, "npz_mtime": st0[npz_p].st_mtime}, + "cell": {"stage": "S2", "n_anchors": int(n_anch), "K": int(K), + "n_episodes": int(len(np.unique(eps))), + "readout": "prob (deployed chain); logit NOT in this cache, would need a GPU re-run", + "pool_desc": src.get("pool_desc"), "beta": src.get("beta"), "gamma": src.get("gamma"), + "rsm_ckpt": src.get("rsm_ckpt")}, + "regression_vs_published": regression, + "power_checks": power, + "auc_conventions": {"pooled": pooled, "anchor_avg": anchavg, + "note": "the published route_metric AUC is the ANCHOR-AVERAGED " + "convention (logged_action_rank.py:808); the pooled number is " + "recorded beside it and is NOT the published one"}, + "arms": res, + "drop_cand0": {"why": "candidate 0 is the logged goal-route chunk and sits far closer in " + "pose than any distractor; if the route signal lives only in it, the " + "decomposition collapses when it is removed", + "cand0_pose": cand0, "arms": drop0}, + "nulls": nulls, + "paired_rsm_minus_permuted": paired, + "pose_matched_concordance": {"rsm": conc, "permuted": conc_perm, "paired": conc_paired, + "note": "within-anchor candidate pairs with |d pose_dist| < tol " + "and DIFFERENT route labels; 0.5 is chance"}, + "limitations": [ + "prob read-out only; logit is not in this cache and is not extrapolated to here", + "5 episodes -> every interval is a 5-cluster episode bootstrap, n_eps printed beside it", + "this is the FORWARD candidate pool run 50 flagged as confounded; quantifying that " + "confound is the point of the zero-parameter arms, but the numbers are about THIS pool", + ], + } + os.makedirs(os.path.dirname(a.out), exist_ok=True) + tmp = a.out + ".tmp" + with open(tmp, "w") as f: + json.dump(out, f, indent=1, sort_keys=False) + os.replace(tmp, a.out) + + # ---- console table ----------------------------------------------------------------------- + print(f"\nS2, {n_anch} anchors from {len(np.unique(eps))} episodes, K={K}, prob read-out") + print(f"{'arm':22s} {'r2_pose':>9s} {'r2_route':>9s} {'r2_both':>9s} {'partial_route':>14s} " + f"{'rho_pose':>9s} {'rho_route':>10s} {'routeAUC':>9s}") + for name in ("rsm", "permuted", "zero_param_posedist", "zero_param_margin"): + w = res[name]["within_fixed_effects"]; pa = res[name]["per_anchor_mean"] + print(f"{name:22s} {w['r2_pose']:9.4f} {w['r2_route']:9.4f} {w['r2_both']:9.4f} " + f"{w['partial_route']:14.4f} {pa['rho_pose']:9.4f} {pa['rho_route']:10.4f} " + f"{res[name]['route_auc_anchor_avg']:9.4f}") + b = res["rsm"]["boot"] + print(f"\nrsm, episode bootstrap (n_eps={b['r2_pose']['n_eps']}):") + for k in ("r2_pose", "r2_route", "partial_route", "rho_pose", "rho_route"): + print(f" {k:14s} {b[k]['mean']:+.4f} [{b[k]['lo']:+.4f}, {b[k]['hi']:+.4f}]") + print(f"\nNULLS for a within-anchor R^2 at K={K}: analytic one-regressor " + f"{nulls['analytic_r2_one_regressor']:.4f}, analytic partial-second " + f"{nulls['analytic_partial_second_regressor']:.4f}; measured permuted r2_route " + f"{nulls['measured_permuted_r2_route']:.4f}, partial_route " + f"{nulls['measured_permuted_partial_route']:.4f}") + print("paired rsm - permuted, per anchor, episode bootstrap (n_eps=5):") + for k, v in paired.items(): + star = "" if (v["lo"] <= 0.0 <= v["hi"]) else " <- excludes 0" + print(f" {k:14s} {v['mean']:+.4f} [{v['lo']:+.4f}, {v['hi']:+.4f}]{star}") + print(f"\ncandidate 0 pose {cand0['pose_dist_cand0_mean']:.4f} m vs distractors " + f"{cand0['pose_dist_others_mean']:.4f} m ({cand0['ratio']:.1f}x)") + print(f"drop cand0, rsm: r2_pose {drop0['rsm']['within_fixed_effects']['r2_pose']:.4f} " + f"r2_route {drop0['rsm']['within_fixed_effects']['r2_route']:.4f} " + f"partial_route {drop0['rsm']['within_fixed_effects']['partial_route']:.4f}") + print("\npose-matched pair concordance (0.5 = chance):") + for t, v in conc.items(): + bb = v["boot"] + print(f" rsm {t:9s} {bb['mean']:+.4f} [{bb['lo']:+.4f}, {bb['hi']:+.4f}] " + f"pairs {v['pairs_total']:6d} anchors {v['n_anchors_used']}") + for t, v in conc_perm.items(): + bb = v["boot"] + print(f" permuted {t:9s} {bb['mean']:+.4f} [{bb['lo']:+.4f}, {bb['hi']:+.4f}] " + f"pairs {v['pairs_total']:6d} anchors {v['n_anchors_used']}") + for t, v in conc_paired.items(): + star = "" if (v["lo"] <= 0.0 <= v["hi"]) else " <- excludes 0" + print(f" PAIRED {t:9s} {v['mean']:+.4f} [{v['lo']:+.4f}, {v['hi']:+.4f}]{star}") + print(f"\nwrote {a.out}") + + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/real/actcond_route_asi_multi.py b/rsm_rise/scripts/real/actcond_route_asi_multi.py new file mode 100644 index 0000000000000000000000000000000000000000..bae7452cc7aeae9a49636cfcd275f93dce990eb3 --- /dev/null +++ b/rsm_rise/scripts/real/actcond_route_asi_multi.py @@ -0,0 +1,490 @@ +#!/usr/bin/env python +"""ACT_COND run 52 -- IS THE PROXIMITY DOMINANCE A PROPERTY OF THE VALUE, OR OF THE POOL? + +Run 51 decomposed the action-driven variance of q at a FIXED state against a ZERO-PARAMETER proximity +feature and against the route direction, on this stream's own 96-anchor / 5-episode S2 cache, and found +r2_pose 0.2845 (paired vs permuted +0.3055 [+0.2706,+0.3435]) with r2_route indistinguishable from the +permuted control. It then named its own open item: that is ONE pool, ONE stage, FIVE episodes. Run 51 +estimated that answering it needed a packed GPU job. That estimate was wrong: the RANK_CTRL stream has +920 cached scoring pools under status/real/rankctrl/, and their per_anchor.npz carry exactly the arrays +this decomposition consumes -- for SEVEN scorers, 50 anchor episodes, several pool constructions and +several checkpoints. So the generalisation is a CPU re-read of someone else's already-paid-for forward +pass. Nothing here is re-scored and nothing of theirs is written. + +WHAT MOVES AND WHAT IS HELD FIXED. All three cells use checkpoint R_M/ckpt_s100000.pt -- the SAME +checkpoint as this stream's logged_action_rank_G999 -- so only the pool moves: + NGK127_base_FfailA forward, K=127, 1050 anchors, S2 my cell at 10x episodes, 4x K + NG_st_base_FfailA_st forward, K=31, 2006 anchors, S2 same K as mine -> K is not it + NG_ne_base_RevCook_ne reverse (cand0 = cook chunk from ANOTHER episode, own ep dropped), + K=31, 2041 anchors, S0 + S2 pool construction, and stage + +THE ESTIMATOR is byte-identical in intent to run 51's: within an anchor the state is FIXED, so the spread +of a scorer across its candidates IS the ASI numerator; per anchor, OLS of z(score) on z(pose_dist), on +z(margin), and on both -> r2_pose, r2_route, partial_route = r2_both - r2_pose. Pooled as a within +(fixed-effects) R^2 on the anchor-demeaned stack and as a per-anchor mean with an EPISODE cluster +bootstrap. Here the bootstrap has 50 clusters, not 5, so every interval is roughly 3x tighter than run +51's -- which is the first real chance for run 51's null results to be falsified. + +THE NULL AN R^2 IS READ AGAINST, AND WHY K MATTERS NOW. R^2 is non-negative and upward-biased; a +pure-noise regressor inside an anchor of K candidates earns E[R^2] = 1/(K-1). That is 0.0323 at K=31 but +0.0079 at K=127, so an R^2 threshold is NOT comparable across these caches and no number below is read +against a fixed constant. Every route quantity prints beside the analytic null AND the measured permuted +arm, and every headline is the PAIRED rsm-minus-permuted difference on identical anchors. + +THE ARMS. All seven scorers the caches carry (rsm, permuted:rsm, rsm_d1, bc, knn, reward, vheur) plus two +ZERO-PARAMETER arms: -pose_dist (must read r2_pose = 1, power check C2) and +margin (must read +r2_route = 1, power check C3). The seven-scorer sweep is the actual test of the run-51 question: if bc / +knn / reward also show proximity dominance on the identical pool, the confound is the POOL's; if some +scorer finds route variance the RSM does not, the pool DOES support route discrimination and the RSM is +failing to use it. + +FAILS LOUDLY, AND AGAINST SOMEBODY ELSE'S NUMBERS. Run 51 asserted against four hardcoded constants of +its own. Here the regression is source-agnostic: for EVERY (scorer, stage) cell the source JSON +publishes, top1_argmax and the route auc are recomputed from the npz with the exact ported _auc (relative +TIE_TOL = 1e-12, anchor-averaged per logged_action_rank.py:808) and must agree exactly. That is ~14-28 +cells per cache, computed by me, checked against numbers RANK_CTRL published -- a stronger test than +checking my own arithmetic against itself. If a cache does not reproduce, this script refuses to compute +anything downstream off that cache. +""" +import argparse, json, os, sys, time +import numpy as np + +TIE_TOL = 1e-12 # byte-identical to logged_action_rank.py:102 + +CELLS = [ + # --- run 52: POOL varies, checkpoint held fixed at R_M/ckpt_s100000.pt + ("NGK127_base_FfailA", "forward K=127, 1050 anchors, S2"), + ("NG_st_base_FfailA_st", "forward K=31 settle 200-400, 2006 anchors, S2"), + ("NG_ne_base_RevCook_ne", "reverse cand0=cook (other episode), K=31, 2041 anchors, S0+S2"), + # --- run 52b: the symmetric control. POOL held fixed, CHECKPOINT varies. Without this, "the + # quantity moves with the pool" is not a distinguishing statement -- it has to move LESS with + # the checkpoint on the same pool, or the pool attribution is unearned. + ("NG_ne_v0_RevCook_ne", "ckpt-control: same reverse cook pool, R_M_ft_v0"), + ("NG_ne_v1_RevCook_ne", "ckpt-control: same reverse cook pool, R_M_ft_v1"), + ("NG_ne_ntv1_RevCook_ne", "ckpt-control: same reverse cook pool, R_M_ft_v1_nt"), + ("NG_st_v0_FfailA_st", "ckpt-control: same forward settle pool, R_M_ft_v0"), + ("NG_st_v0lit_FfailA_st", "ckpt-control: same forward settle pool, R_M_ft_v0lit"), +] + + +def die(msg): + print("ASSERTION FAILED: " + msg, file=sys.stderr) + sys.exit(2) + + +def auc(score, label): + """EXACT port of logged_action_rank.py:_auc. Mid-ranks inside RELATIVE tie groups; nan for a + single-class anchor (the source returns None and drops it from the mean; nanmean is the same).""" + y = np.asarray(label).astype(bool); s = np.asarray(score, np.float64) + npos, nneg = int(y.sum()), int((~y).sum()) + if npos == 0 or nneg == 0: + return np.nan + order = np.argsort(s, kind="mergesort"); r = np.empty(len(s), np.float64) + r[order] = np.arange(1, len(s) + 1) + ss = s[order] + i = 0 + while i < len(ss): + j = i + while j + 1 < len(ss) and abs(ss[j + 1] - ss[i]) <= TIE_TOL * max(1.0, abs(ss[i])): + j += 1 + if j > i: + r[order[i:j + 1]] = (i + j + 2) / 2.0 + i = j + 1 + return float((r[y].sum() - npos * (npos + 1) / 2.0) / (npos * nneg)) + + +def z(x): + x = np.asarray(x, float); sd = x.std() + return np.zeros_like(x) if sd < 1e-12 else (x - x.mean()) / sd + + +def ols_r2(y, X): + y = np.asarray(y, float); n = len(y) + A = np.column_stack([np.ones(n)] + [np.asarray(c, float) for c in X]) + sst = float(((y - y.mean()) ** 2).sum()) + if sst < 1e-24: + return 0.0 + try: + beta, *_ = np.linalg.lstsq(A, y, rcond=None) + except np.linalg.LinAlgError: + return 0.0 + resid = y - A @ beta + return float(max(0.0, 1.0 - (resid ** 2).sum() / sst)) + + +def _rank(x): + order = np.argsort(x, kind="mergesort"); r = np.empty(len(x), float); s = x[order] + i = 0 + while i < len(s): + j = i + while j + 1 < len(s) and s[j + 1] == s[i]: + j += 1 + r[order[i:j + 1]] = 0.5 * (i + j) + 1.0 + i = j + 1 + return r + + +def spearman(a, b): + a = np.asarray(a, float); b = np.asarray(b, float) + if len(a) < 3: + return np.nan + ra, rb = _rank(a), _rank(b) + if ra.std() < 1e-12 or rb.std() < 1e-12: + return np.nan + return float(np.corrcoef(ra, rb)[0, 1]) + + +def ep_boot(per_anchor, eps, n=2000, seed=0): + """Episode-level cluster bootstrap of a per-anchor statistic. Vectorised: resampling whole + clusters and taking the size-weighted mean of their means is exactly the mean of the concatenated + resample, so this is the same estimator run 51 used, not an approximation of it.""" + per_anchor = np.asarray(per_anchor, float); eps = np.asarray(eps) + ok = np.isfinite(per_anchor) + per_anchor, eps = per_anchor[ok], eps[ok] + uniq = np.unique(eps) + if len(uniq) == 0: + return {"mean": float("nan"), "lo": float("nan"), "hi": float("nan"), "n_eps": 0, + "n_anchors": 0, "per_episode": {}} + sums = np.array([per_anchor[eps == e].sum() for e in uniq], float) + cnts = np.array([(eps == e).sum() for e in uniq], float) + rng = np.random.default_rng(seed) + pick = rng.integers(0, len(uniq), size=(n, len(uniq))) + draws = sums[pick].sum(1) / cnts[pick].sum(1) + return {"mean": float(per_anchor.mean()), + "lo": float(np.percentile(draws, 2.5)), "hi": float(np.percentile(draws, 97.5)), + "n_eps": int(len(uniq)), "n_anchors": int(len(per_anchor)), + "per_episode": {str(int(e)): float(s / c) for e, s, c in zip(uniq, sums, cnts)}} + + +def decompose(S, P, M, eps, drop0=False, seed=0, boot=True): + """Within-anchor variance decomposition of a scorer on proximity and route direction.""" + if drop0: + S, P, M = S[:, 1:], P[:, 1:], M[:, 1:] + n_anch, K = S.shape + cols = {k: np.full(n_anch, np.nan) for k in + ("r2_pose", "r2_route", "r2_both", "partial_route", "rho_pose", "rho_route")} + dq, dp, dm = np.empty_like(S), np.empty_like(P), np.empty_like(M) + for i in range(n_anch): + q, p, m = z(S[i]), z(P[i]), z(M[i]) + rp = ols_r2(q, [p]); rr = ols_r2(q, [m]); rb = ols_r2(q, [p, m]) + rb = max(rb, rp, rr) # numerical guard: nested models + cols["r2_pose"][i] = rp; cols["r2_route"][i] = rr; cols["r2_both"][i] = rb + cols["partial_route"][i] = rb - rp + cols["rho_pose"][i] = spearman(S[i], P[i]); cols["rho_route"][i] = spearman(S[i], M[i]) + dq[i] = S[i] - S[i].mean(); dp[i] = P[i] - P[i].mean(); dm[i] = M[i] - M[i].mean() + DQ, DP, DM = dq.ravel(), dp.ravel(), dm.ravel() + within = {"r2_pose": ols_r2(DQ, [DP]), "r2_route": ols_r2(DQ, [DM]), + "r2_both": ols_r2(DQ, [DP, DM])} + within["r2_both"] = max(within["r2_both"], within["r2_pose"], within["r2_route"]) + within["partial_route"] = within["r2_both"] - within["r2_pose"] + # A scorer that is CONSTANT across the candidates of an anchor has no within-anchor rank at all; + # Spearman is then undefined for that anchor. That is not a nuisance to be nanmean'd away -- it is + # precisely the failure mode this stream exists to detect ("a value that scores STATES but cannot + # rank ACTIONS"), so it is counted and reported rather than warned about. + flat = int((S.std(axis=1) < 1e-12).sum()) + pam = {} + for k, v in cols.items(): + ok = np.isfinite(v) + pam[k] = float(v[ok].mean()) if ok.any() else None + out = {"n_anchors": int(n_anch), "K": int(K), "within_fixed_effects": within, + "per_anchor_mean": pam, + "degenerate": {"n_anchors_scorer_constant_within_anchor": flat, + "frac": float(flat) / max(n_anch, 1), + "n_anchors_rho_undefined": int((~np.isfinite(cols["rho_pose"])).sum())}} + if boot: + out["boot"] = {k: ep_boot(cols[k], eps, seed=seed) + for k in ("r2_pose", "r2_route", "partial_route", "rho_pose", "rho_route")} + return out, cols + + +def pose_matched_concordance(S, P, M, L, eps, tol, seed=0): + """The confound DIFFERENCED OUT rather than thresholded away: inside an anchor, every candidate + PAIR whose pose_dist differs by < tol and whose route labels DIFFER; how often is the higher-scored + one the on-route one? 0.5 is chance, and proximity cannot express a preference inside such a pair.""" + n_anch = S.shape[0] + per = np.full(n_anch, np.nan); npairs = np.zeros(n_anch, int) + a, b = np.triu_indices(S.shape[1], 1) + for i in range(n_anch): + q, p, l = S[i], P[i], L[i] + keep = (np.abs(p[a] - p[b]) < tol) & (l[a] != l[b]) + if not keep.any(): + continue + ia, ib = a[keep], b[keep] + swap = l[ia] < l[ib] + ia2 = np.where(swap, ib, ia); ib2 = np.where(swap, ia, ib) + win = (q[ia2] > q[ib2]).astype(float) + 0.5 * (q[ia2] == q[ib2]) + per[i] = float(win.mean()); npairs[i] = len(ia2) + return ({"tol_m": tol, "n_anchors_used": int(np.isfinite(per).sum()), + "pairs_total": int(npairs.sum()), + "pairs_per_anchor_med": float(np.median(npairs)), + "boot": ep_boot(per, eps, seed=seed)}, per) + + +def key_of(scorer): + return "scores_" + scorer.replace(":", "_") + + +def regression_check(src_json, d, stage, scorers, stages_ok): + """Source-agnostic loud regression: recompute EVERY published (scorer, stage) cell from the npz.""" + got, want, rows = {}, {}, [] + by = src_json.get("by", {}) or {} + rm = src_json.get("route_metric", {}) or {} + L = np.asarray(d["route_label"], float) + for sc in scorers: + S = np.asarray(d[key_of(sc)], float) + for st in stages_ok: + sel = stage == st + tag = f"S{st}" + k1 = f"{sc}|correct|{tag}" + if k1 in by and "top1_argmax" in by[k1]: + rows.append((k1 + ".top1_argmax", float(by[k1]["top1_argmax"]), + float((np.argmax(S[sel], axis=1) == 0).mean()))) + k2 = f"{sc}|{tag}" + pub = rm.get(k2) or (by.get(k2) if isinstance(by.get(k2), dict) else None) + if pub is not None and "auc" in pub: + idx = np.flatnonzero(sel) + rows.append((k2 + ".auc", float(pub["auc"]), + float(np.nanmean([auc(S[i], L[i]) for i in idx])))) + out = {} + bad = [] + for name, w, g in rows: + ok = abs(g - w) < 1e-9 + out[name] = {"published": w, "recomputed": g, "abs_diff": abs(g - w), "pass": ok} + if not ok: + bad.append((name, w, g)) + return out, bad, len(rows) + + +def run_cell(dirname, note, root, seed, tols): + src = os.path.join(root, dirname) + npz_p, js_p = os.path.join(src, "per_anchor.npz"), os.path.join(src, "logged_action_rank.json") + for p in (npz_p, js_p): + if not os.path.exists(p): + die(f"missing input {p}") + st0 = {p: (os.stat(p).st_size, os.stat(p).st_mtime) for p in (npz_p, js_p)} + + d = np.load(npz_p, allow_pickle=True) + sj = json.load(open(js_p)) + scorers = [s for s in sj["scorers"] if key_of(s) in d.files] + if "rsm" not in scorers or "permuted:rsm" not in scorers: + die(f"{dirname}: need both rsm and permuted:rsm, have {scorers}") + + P = np.asarray(d["route_pose_dist"], float) + M = np.asarray(d["route_margin"], float) + L = np.asarray(d["route_label"], float) + eps = np.asarray(d["ep"]).astype(int) + stage = np.asarray(d["stage"]).astype(int) + n_anch, K = P.shape + + # ---- A0 shape, and STAGE-AWARE finiteness ------------------------------------------------ + # Run 52's first submission (LSF 1909238, exit 2) died here, correctly: NG_ne_base_RevCook_ne has + # route_margin non-finite on exactly its 1050 S0 anchors (33600 = 1050 x 32 cells), i.e. that cache + # carries NO route direction at S0 -- the meta-direction it would be measured against does not exist + # there. The honest handling is not to nan-drop silently and not to abort the whole cache, but to + # DROP the affected stage, record how many cells and why, and refuse only if nothing survives. A + # non-finite SCORE is a different matter and still aborts. + for nm in [key_of(s) for s in scorers] + ["route_pose_dist"]: + arr = np.asarray(d[nm], float) + if arr.shape != (n_anch, K): + die(f"{dirname} A0 shape: {nm} {arr.shape} != {(n_anch, K)}") + if not np.isfinite(arr).all(): + die(f"{dirname} A0 finite: {nm} has {int((~np.isfinite(arr)).sum())} non-finite entries") + for nm, arr in (("route_margin", M), ("route_label", L)): + if arr.shape != (n_anch, K): + die(f"{dirname} A0 shape: {nm} {arr.shape} != {(n_anch, K)}") + stages_all = sorted(set(stage.tolist())) + stages_ok, dropped = [], {} + for st in stages_all: + sel = stage == st + nbad = int((~np.isfinite(M[sel])).sum()) + int((~np.isfinite(L[sel])).sum()) + if nbad: + dropped[f"S{st}"] = {"n_anchors": int(sel.sum()), "n_nonfinite_cells": nbad, + "why": "route_margin/route_label are not defined at this stage in " + "this cache, so the route half of the decomposition has no " + "regressor; the stage is dropped, not nan-filled"} + continue + lv = set(np.unique(L[sel]).tolist()) + if not lv <= {0.0, 1.0}: + die(f"{dirname} A0 label: route_label not binary at S{st}, uniques {sorted(lv)[:8]}") + stages_ok.append(st) + if not stages_ok: + die(f"{dirname}: no stage has a finite route_margin/route_label; nothing is computable here") + if dropped: + print(f"[A0] {dirname}: stages dropped for missing route direction: " + + ", ".join(f"{k} ({v['n_anchors']} anchors)" for k, v in dropped.items())) + + # ---- A1 the loud regression, against RANK_CTRL's published cells -------------------------- + reg, bad, n_cells = regression_check(sj, d, stage, scorers, stages_ok) + if bad: + for name, w, g in bad: + print(f" {dirname} {name}: published {w!r} recomputed {g!r} |d| {abs(g-w):.3e}", + file=sys.stderr) + die(f"{dirname}: {len(bad)}/{n_cells} published cells do NOT reproduce from the npz; refusing " + f"to compute anything downstream off this cache") + print(f"[A1] {dirname}: {n_cells}/{n_cells} published cells reproduce exactly") + + arms = {s: np.asarray(d[key_of(s)], float) for s in scorers} + arms["zero_param_posedist"] = -P + arms["zero_param_margin"] = M + + per_stage = {} + for st in stages_ok: + sel = stage == st + tag = f"S{st}" + Ps, Ms, Ls, es = P[sel], M[sel], L[sel], eps[sel] + res, cols = {}, {} + for name, S in arms.items(): + res[name], cols[name] = decompose(S[sel], Ps, Ms, es, seed=seed) + aucs = [auc(S[sel][i], Ls[i]) for i in range(sel.sum())] + res[name]["route_auc_anchor_avg"] = float(np.nanmean(aucs)) + res[name]["route_auc_boot"] = ep_boot(aucs, es, seed=seed) + + # C2 / C3 dual power checks: the estimator must see BOTH directions on THIS cache + c2 = res["zero_param_posedist"]["within_fixed_effects"]["r2_pose"] + c3 = res["zero_param_margin"]["within_fixed_effects"]["r2_route"] + power = {"C2_posedist_scorer_r2_pose": {"value": c2, "pass": abs(c2 - 1.0) < 1e-8}, + "C3_margin_scorer_r2_route": {"value": c3, "pass": abs(c3 - 1.0) < 1e-8}} + for k, v in power.items(): + if not v["pass"]: + die(f"{dirname} {tag} {k}: a scorer that IS the feature must read R^2 = 1 within every " + f"anchor, got {v['value']!r}; the estimator is broken and no number is readable") + + # paired scorer - permuted on the IDENTICAL anchors + paired = {} + for name in arms: + if name == "permuted:rsm": + continue + paired[name] = {k: ep_boot(cols[name][k] - cols["permuted:rsm"][k], es, seed=seed) + for k in ("r2_pose", "r2_route", "partial_route", "rho_pose", "rho_route")} + + r2p = float(np.nanmean(cols["rsm"]["r2_pose"])) + nulls = {"K": int(K), + "analytic_r2_one_regressor": 1.0 / (K - 1), + "analytic_partial_second_regressor": (1.0 - r2p) / (K - 2), + "measured_permuted_r2_route": float(np.nanmean(cols["permuted:rsm"]["r2_route"])), + "measured_permuted_partial_route": + float(np.nanmean(cols["permuted:rsm"]["partial_route"])), + "note": "compare r2_route and partial_route to THESE, never to 0; the analytic null " + "is K-dependent so R^2 is NOT comparable across caches with different K"} + + # drop candidate 0 -- run 51's mechanism test + drop0 = {} + for name in ("rsm", "permuted:rsm"): + drop0[name], _ = decompose(arms[name][sel], Ps, Ms, es, drop0=True, seed=seed, boot=False) + cand0 = {"pose_dist_cand0_mean": float(Ps[:, 0].mean()), + "pose_dist_others_mean": float(Ps[:, 1:].mean()), + "ratio": float(Ps[:, 1:].mean() / max(Ps[:, 0].mean(), 1e-12)), + "label_cand0_mean": float(Ls[:, 0].mean())} + + # the confound differenced out + conc, conc_perm, conc_paired = {}, {}, {} + for t in tols: + kk = f"tol_{t}".replace(".", "p") + conc[kk], per_r = pose_matched_concordance(arms["rsm"][sel], Ps, Ms, Ls, es, t, seed=seed) + conc_perm[kk], per_p = pose_matched_concordance(arms["permuted:rsm"][sel], Ps, Ms, Ls, es, + t, seed=seed) + conc_paired[kk] = ep_boot(per_r - per_p, es, seed=seed) + + per_stage[tag] = {"n_anchors": int(sel.sum()), "n_episodes": int(len(np.unique(es))), + "arms": res, "power_checks": power, "nulls": nulls, + "paired_minus_permuted": paired, + "drop_cand0": {"cand0_pose": cand0, "arms": drop0}, + "pose_matched_concordance": {"rsm": conc, "permuted": conc_perm, + "paired": conc_paired}} + + st1 = {p: (os.stat(p).st_size, os.stat(p).st_mtime) for p in (npz_p, js_p)} + for p in st0: + if st0[p] != st1[p]: + die(f"input {p} changed under the read (size/mtime freeze witness)") + + return {"dir": dirname, "note": note, "src": {"npz": os.path.abspath(npz_p), + "npz_size": st0[npz_p][0], "npz_mtime": st0[npz_p][1]}, + "cell": {k: sj.get(k) for k in ("arm", "K", "n_anchors", "n_anchor_episodes", "anchor_split", + "distractor_source", "pool_desc", "label", "pose_match", + "beta", "gamma", "rsm_ckpt", "reverse_cand0", + "reverse_drop_own")}, + "scorers": scorers, "stages_dropped": dropped, + "regression_vs_published": reg, + "n_regression_cells": n_cells, "per_stage": per_stage} + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--root", default="status/real/rankctrl") + ap.add_argument("--out", default="status/real/ACT_COND/ROUTE_ASI_run52.json") + ap.add_argument("--seed", type=int, default=0) + ap.add_argument("--only", default="") + a = ap.parse_args() + tols = (0.02, 0.05, 0.10) + + cells = [c for c in CELLS if (not a.only or c[0] in a.only.split(","))] + out = {"run": 52, "stream": "ACT_COND", + "question": "run 51 measured the proximity/route decomposition of the action-driven variance " + "on ONE pool, ONE stage, FIVE episodes. Is the proximity dominance a property of " + "the VALUE or of that POOL?", + "inputs_are": "RANK_CTRL's caches under status/real/rankctrl, READ-ONLY, freeze-witnessed. " + "Nothing is re-scored; this is a re-read of their forward pass.", + "checkpoint_held_fixed": "R_M/ckpt_s100000.pt in all three cells, the same checkpoint as this " + "stream's logged_action_rank_G999", + "cells": {}} + for dirname, note in cells: + t0 = time.time() + out["cells"][dirname] = run_cell(dirname, note, a.root, a.seed, tols) + print(f"[cell] {dirname} done in {time.time()-t0:.1f}s") + + out["limitations"] = [ + "prob read-out throughout; these caches do not hold a logit read-out and it is not extrapolated to", + "the analytic R^2 null is 1/(K-1): 0.0079 at K=127, 0.0323 at K=31. R^2 magnitudes are NOT " + "comparable across the two K's; only the paired-vs-permuted differences are", + "S0 appears only in the reverse cache; S1 and S3 are in none of the three and are not claimed", + "these are RANK_CTRL's pools and RANK_CTRL's scorer implementations; this stream verified them " + "only to the extent that every published (scorer, stage) cell reproduces from the npz", + ] + os.makedirs(os.path.dirname(a.out), exist_ok=True) + tmp = a.out + ".tmp" + with open(tmp, "w") as f: + json.dump(out, f, indent=1, sort_keys=False) + os.replace(tmp, a.out) + + # ---- console tables ---------------------------------------------------------------------- + for dirname, cell in out["cells"].items(): + print(f"\n================ {dirname} -- {cell['note']}") + print(f" pool: {cell['cell']['pool_desc']}") + for tag, ps in cell["per_stage"].items(): + K = ps["nulls"]["K"] + print(f"\n --- {tag}: {ps['n_anchors']} anchors / {ps['n_episodes']} episodes, K={K}, " + f"analytic R^2 null 1/(K-1) = {ps['nulls']['analytic_r2_one_regressor']:.4f}") + print(f" {'arm':22s} {'r2_pose':>8s} {'r2_route':>9s} {'partial':>8s} {'rho_pose':>9s} " + f"{'rho_route':>10s} {'routeAUC':>9s} | {'PAIRED r2_pose':>22s} {'PAIRED r2_route':>22s}") + for name, r in ps["arms"].items(): + w = r["within_fixed_effects"]; pa = r["per_anchor_mean"] + pr = ps["paired_minus_permuted"].get(name) + if pr: + p1 = f"{pr['r2_pose']['mean']:+.3f}[{pr['r2_pose']['lo']:+.3f},{pr['r2_pose']['hi']:+.3f}]" + p2 = f"{pr['r2_route']['mean']:+.3f}[{pr['r2_route']['lo']:+.3f},{pr['r2_route']['hi']:+.3f}]" + else: + p1 = p2 = "(reference arm)" + rp = " n/a" if pa['rho_pose'] is None else f"{pa['rho_pose']:9.4f}" + rr = " n/a" if pa['rho_route'] is None else f"{pa['rho_route']:10.4f}" + flg = "" if not r["degenerate"]["n_anchors_scorer_constant_within_anchor"] else \ + f" [CONSTANT within anchor in {r['degenerate']['frac']*100:.1f}% of anchors]" + print(f" {name:22s} {w['r2_pose']:8.4f} {w['r2_route']:9.4f} " + f"{w['partial_route']:8.4f} {rp} {rr} " + f"{r['route_auc_anchor_avg']:9.4f} | {p1:>22s} {p2:>22s}{flg}") + c0 = ps["drop_cand0"]["cand0_pose"]; d0 = ps["drop_cand0"]["arms"]["rsm"]["within_fixed_effects"] + print(f" cand0 pose {c0['pose_dist_cand0_mean']:.4f} m vs others " + f"{c0['pose_dist_others_mean']:.4f} m ({c0['ratio']:.1f}x), cand0 route label mean " + f"{c0['label_cand0_mean']:.3f}") + print(f" drop cand0, rsm: r2_pose {d0['r2_pose']:.4f} r2_route {d0['r2_route']:.4f} " + f"partial {d0['partial_route']:.4f}") + print(" pose-matched pair concordance, PAIRED rsm - permuted (0 = no difference):") + for t, v in ps["pose_matched_concordance"]["paired"].items(): + star = "" if (v["lo"] <= 0.0 <= v["hi"]) else " <- excludes 0" + npair = ps["pose_matched_concordance"]["rsm"][t]["pairs_total"] + print(f" {t:9s} {v['mean']:+.4f} [{v['lo']:+.4f}, {v['hi']:+.4f}] " + f"pairs {npair}{star}") + print(f"\nwrote {a.out}") + + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/real/actcond_sensitivity_pays.py b/rsm_rise/scripts/real/actcond_sensitivity_pays.py new file mode 100644 index 0000000000000000000000000000000000000000..1a47ad07382dc23c79bbfd9f1bd3e9579f156e8e --- /dev/null +++ b/rsm_rise/scripts/real/actcond_sensitivity_pays.py @@ -0,0 +1,474 @@ +#!/usr/bin/env python +""" +ACT_COND run 38 -- DOES SENSITIVITY PAY? Joining var_a to selection quality. + +WHY THIS EXISTS +--------------- +The owner's mandate for this stream, verbatim: "All we need is for the network to be sensitive +enough to action to pick actions leading to goal state." Runs 1-35 answered "is it sensitive" +(yes, 12/12 assertions). Run 36 measured how much of the score is action-driven on the DEPLOYED +cloud. Run 37 retired `frac_action` as non-portable and replaced it with `var_a` at fixed +read-out, plus a width law (`var_a ~ width^1.5-2`). + +NONE of those touch the word ENOUGH. `var_a` is a variance; it says the score moves when the +action moves, not that it moves in the direction of the goal. A value function could have large +`var_a` and rank candidates at chance. This run joins my variance column to the SELECTION-QUALITY +column that already exists in the same files, and asks the only question that makes `var_a` +decision-relevant: does more action-driven variance buy better action picking, and how much? + +ESTIMANDS (all per (dir, value-function variant), from `scores.npz` alone, zero GPU) +----------------------------------------------------------------------------------- +Ground truth per candidate is `err_first` [D, N]: cm distance between that candidate's FIRST +action xyz and the logged ground-truth action xyz (`scorer_openloop.py:596`). Lower = closer to +the logged (expert / goal-route) action. + + * sel_rank_pct -- for each decision, the argmax-scored candidate's rank among the N by err + (fraction of candidates with STRICTLY WORSE err), averaged over the tied-at- + max set so the number is the expectation under a uniform random tie-break + (an argmax on a tied vector picks index 0, which is not a measurement). + Chance = 0.5. This is the same estimand as `scorer_openloop.py:606`. + * sel_regret_cm -- mean over decisions of (mean err over the tied-at-max set) - min err. + Chance-level picking has regret = mean err - min err; 0 is oracle. + * rho_score_err -- within-decision Spearman(score, -err_first), averaged over decisions. Uses + the whole ranking, not just the top pick, so it has far more power than + sel_rank_pct on the same data. + * var_a, var_s, tie@max -- unchanged from run 37, same `decomp`. + +THE CONFOUND, AND THE CONTRAST THAT IS FREE OF IT +------------------------------------------------- +Across dirs, a wider candidate cloud raises `var_a` (run 37's law) AND makes the err spread larger, +which can make ranking easier for an unrelated reason. So the pooled across-dir regression is +REPORTED BUT NOT LOAD-BEARING. The load-bearing contrast is WITHIN a dir: dirs that carry several +`score_rsm@` arrays have the IDENTICAL decisions, the IDENTICAL candidates and therefore +the IDENTICAL `err_first` -- every bit of difference between variants is the value function. Run +37 found 15 such clouds with >=3 RSM variants and a 39x spread in `var_a`. If more `var_a` buys +better picking, the within-dir Spearman between log10(var_a) and sel_rank_pct / rho_score_err is +positive across those clouds. + +NULLS, both already in the file and neither invented for this run +----------------------------------------------------------------- + * `score_permuted_*` -- a within-row shuffle, so it has the SAME var_a by construction (run 37 + integrity check: median permuted/original var_a = 1.0000) but no correspondence to err. It is + therefore the exact null for THIS statistic even though it was NOT a null for frac_action: + equal variance, zero information. Expect sel_rank_pct ~ 0.5, rho ~ 0. + * `score_idql` -- the RISE/IQL critic, the documented instance of "scores STATES but cannot rank + ACTIONS". + +PRE-REGISTRATION, written before the job was submitted (git-less repo; this header is the record) +------------------------------------------------------------------------------------------------- + (P1) permuted sel_rank_pct in [0.47, 0.53] and |rho| < 0.03. If not, the statistic or the file + is broken and NOTHING else in this run may be read. + (P2) RSM sel_rank_pct > 0.5 and rho_score_err > 0 pooled. Runs 1-35 + the 96.9% logged top-1 + make this near-certain; it is here as a floor, not as news. + (P3) THE ACTUAL TEST -- within-dir Spearman(log10 var_a, rho_score_err) > 0 in a clear majority + of the >=3-variant clouds. I am NOT confident in this one. The live alternative is that + `var_a` and ranking quality are ORTHOGONAL at fixed cloud: a checkpoint can be loud and + wrong. If that is what comes back, then run 37's width law -- and every `var_a` number this + stream has published, including the recommendation I gave the ladder -- describes a quantity + that does not predict the thing anyone cares about, and I have to say so in those words. + (P4) If (P3) fires, the dose curve (mean sel_rank_pct by var_a decile) answers ENOUGH with a + number: the var_a at which sel_rank_pct clears 0.55. +""" +import argparse, json, os +from pathlib import Path +import numpy as np + +ROOT = "/proj/dmfexp/zwhong/rsm_rise" +POOL_SCORE_KIND = "prob" +POOL_TEMPERATURE = 25.0 + + +def ckpt_tag(p): + if not p: + return None + p = str(p) + for anchor in ("/runs/", "/ckpt/", "/checkpoints/"): + if anchor in p: + p = p.split(anchor, 1)[1] + return "/".join(Path(p).parts[-2:]) + + +def decomp(S, B=0, seed=0): + """S [D, N] -> within/between variance decomposition + ties. Same formula as run 37.""" + S = np.asarray(S, dtype=np.float64) + if S.ndim != 2 or S.shape[1] < 2: + return None + ok = np.isfinite(S).all(1) + S = S[ok] + D, N = S.shape + if D < 3: + return None + per_var = S.var(axis=1, ddof=1) + per_mu = S.mean(axis=1) + va = float(per_var.mean()) + vs = float(per_mu.var(ddof=1)) + mx = S.max(axis=1, keepdims=True) + tie = (np.abs(S - mx) <= 1e-6 * np.maximum(np.abs(mx), 1e-12) + 1e-12).mean(axis=1) + return dict(n_dec=int(D), n_cand=int(N), var_a=va, var_s=vs, + tie_at_max_per_N=float(tie.mean() * N), + score_mean=float(S.mean()), score_min=float(S.min()), score_max=float(S.max())) + + +def _rank_parts(A): + """Vectorised ranks along axis 1. + + Returns (avg, first, last): `avg` is the tie-averaged 0-based rank (scipy `rankdata` minus 1), + `first`/`last` are the 0-based positions of the first and last element of each tie group in + ascending order, scattered back to the original column order. `last` gives the count of + strictly-greater elements for free (N - 1 - last), which is how the err rank-pct is computed + without ever forming an [N, N] comparison matrix. + """ + A = np.asarray(A, float) + D, N = A.shape + order = np.argsort(A, axis=1, kind="stable") + As = np.take_along_axis(A, order, axis=1) + idx = np.broadcast_to(np.arange(N, dtype=float), (D, N)) + startflag = np.ones((D, N), bool) + startflag[:, 1:] = As[:, 1:] != As[:, :-1] + first_s = np.maximum.accumulate(np.where(startflag, idx, -np.inf), axis=1) + endflag = np.ones((D, N), bool) + endflag[:, :-1] = As[:, 1:] != As[:, :-1] + last_s = np.minimum.accumulate(np.where(endflag, idx, np.inf)[:, ::-1], axis=1)[:, ::-1] + avg_s = 0.5 * (first_s + last_s) + avg = np.empty((D, N)); first = np.empty((D, N)); last = np.empty((D, N)) + np.put_along_axis(avg, order, avg_s, axis=1) + np.put_along_axis(first, order, first_s, axis=1) + np.put_along_axis(last, order, last_s, axis=1) + return avg, first, last + + +def _rank_axis1(A): + return _rank_parts(np.asarray(A, float))[0] + + +def selection_quality(S, E, B=1000, seed=0): + """Joint stats between a score matrix S [D,N] and err_first E [D,N] (lower err = better). + + sel_rank_pct : expected rank-pct of the PICKED candidate under uniform tie-break at the max. + sel_regret_cm: expected (err of pick) - (best err in the cloud), cm. + rho_score_err: mean within-decision Spearman(score, -err). + """ + S = np.asarray(S, float); E = np.asarray(E, float) + if S.shape != E.shape or S.ndim != 2 or S.shape[1] < 3: + return None + ok = np.isfinite(S).all(1) & np.isfinite(E).all(1) + S, E = S[ok], E[ok] + D, N = S.shape + if D < 3: + return None + # --- tie-aware pick --- + mx = S.max(axis=1, keepdims=True) + tied = np.abs(S - mx) <= 1e-6 * np.maximum(np.abs(mx), 1e-12) + 1e-12 # [D,N] bool + ntied = tied.sum(axis=1) + # rank-pct of each candidate by err: fraction of OTHERS with strictly worse (larger) err. + # `last` is the final position of that err value in ascending order, so the number of + # candidates with strictly larger err is N - 1 - last. Exact, and O(N log N) not O(N^2). + _, _, e_last = _rank_parts(E) + worse = (N - 1.0) - e_last + rank_pct = worse / max(N - 1, 1) # [D,N], chance 0.5 + per_dec_rank = (rank_pct * tied).sum(axis=1) / np.maximum(ntied, 1) + best = E.min(axis=1) + per_dec_regret = (E * tied).sum(axis=1) / np.maximum(ntied, 1) - best + chance_regret = E.mean(axis=1) - best + # --- full-ranking Spearman, within decision --- + rs = _rank_axis1(S) + re = _rank_axis1(-E) + rs = rs - rs.mean(axis=1, keepdims=True) + re = re - re.mean(axis=1, keepdims=True) + num = (rs * re).sum(axis=1) + den = np.sqrt((rs ** 2).sum(axis=1) * (re ** 2).sum(axis=1)) + per_dec_rho = np.where(den > 0, num / np.maximum(den, 1e-300), np.nan) + out = dict(n_dec=int(D), n_cand=int(N), + sel_rank_pct=float(per_dec_rank.mean()), + sel_regret_cm=float(per_dec_regret.mean()), + chance_regret_cm=float(chance_regret.mean()), + oracle_gap_cm=float((E.mean(axis=1) - best).mean()), + rho_score_err=float(np.nanmean(per_dec_rho)), + n_tied_at_max=float(ntied.mean()), + err_sd_within=float(E.std(axis=1, ddof=1).mean()), + err_mean=float(E.mean())) + if B: + rng = np.random.default_rng(seed) + idx = rng.integers(0, D, size=(B, D)) + out["sel_rank_pct_ci"] = [float(np.percentile(per_dec_rank[idx].mean(axis=1), 2.5)), + float(np.percentile(per_dec_rank[idx].mean(axis=1), 97.5))] + rb = np.nanmean(per_dec_rho[idx], axis=1) + out["rho_score_err_ci"] = [float(np.nanpercentile(rb, 2.5)), + float(np.nanpercentile(rb, 97.5))] + return out + + +def spearman(x, y): + x = np.asarray(x, float); y = np.asarray(y, float) + m = np.isfinite(x) & np.isfinite(y) + x, y = x[m], y[m] + if len(x) < 3 or np.ptp(x) == 0 or np.ptp(y) == 0: + return float("nan") + rx = _rank_axis1(x[None, :])[0]; ry = _rank_axis1(y[None, :])[0] + rx = rx - rx.mean(); ry = ry - ry.mean() + d = np.sqrt((rx ** 2).sum() * (ry ** 2).sum()) + return float(rx @ ry / d) if d > 0 else float("nan") + + +def ols(x, y): + x = np.asarray(x, float); y = np.asarray(y, float) + m = np.isfinite(x) & np.isfinite(y) + x, y = x[m], y[m] + n = len(x) + if n < 4 or x.std() == 0: + return None + xc, yc = x - x.mean(), y - y.mean() + b = float(xc @ yc / (xc @ xc)) + a = float(y.mean() - b * x.mean()) + resid = y - (a + b * x) + s2 = float(resid @ resid) / max(n - 2, 1) + se = float(np.sqrt(s2 / (xc @ xc))) if (xc @ xc) > 0 else float("nan") + r = float(xc @ yc / np.sqrt((xc @ xc) * (yc @ yc))) if (yc @ yc) > 0 else float("nan") + return dict(n=n, slope=b, intercept=a, se=se, r=r, + ci=[b - 1.96 * se, b + 1.96 * se]) + + +def partial_spearman(y, x, z): + """Spearman(y, x) controlling for z, via ranks + residualisation.""" + y = np.asarray(y, float); x = np.asarray(x, float); z = np.asarray(z, float) + m = np.isfinite(y) & np.isfinite(x) & np.isfinite(z) + if m.sum() < 5: + return float("nan") + ry = _rank_axis1(y[m][None, :])[0] + rx = _rank_axis1(x[m][None, :])[0] + rz = _rank_axis1(z[m][None, :])[0] + def resid(v): + f = ols(rz, v) + return v - (f["intercept"] + f["slope"] * rz) if f else v - v.mean() + return spearman(resid(ry), resid(rx)) + + +def selftest(): + """FAIL LOUDLY. Every claim in this run rests on selection_quality(); prove it on cases whose + answer is known by hand before it is pointed at a single real file.""" + rng = np.random.default_rng(0) + D, N = 40, 16 + E = rng.random((D, N)) * 10.0 + ok = [] + + def chk(name, got, want, tol): + good = abs(got - want) <= tol + ok.append((name, float(got), float(want), bool(good))) + print(f"[selftest] {'PASS' if good else 'FAIL'} {name}: {got:.6f} (want {want} +-{tol})", + flush=True) + + r = selection_quality(-E, E, B=0) # perfect scorer + chk("perfect.rank_pct", r["sel_rank_pct"], 1.0, 1e-12) + chk("perfect.rho", r["rho_score_err"], 1.0, 1e-12) + chk("perfect.regret", r["sel_regret_cm"], 0.0, 1e-12) + r = selection_quality(E, E, B=0) # exactly anti-correlated + chk("anti.rank_pct", r["sel_rank_pct"], 0.0, 1e-12) + chk("anti.rho", r["rho_score_err"], -1.0, 1e-12) + r = selection_quality(np.zeros((D, N)), E, B=0) # fully tied -> must be exactly chance + chk("tied.rank_pct", r["sel_rank_pct"], 0.5, 1e-12) + chk("tied.n_tied", r["n_tied_at_max"], N, 1e-12) + chk("tied.regret_is_chance", r["sel_regret_cm"] - r["chance_regret_cm"], 0.0, 1e-12) + r = selection_quality(rng.random((4000, N)), rng.random((4000, N)) * 10, B=0) + chk("indep.rank_pct", r["sel_rank_pct"], 0.5, 0.02) # independent -> chance + chk("indep.rho", r["rho_score_err"], 0.0, 0.02) + # ranks must match scipy exactly, ties included + try: + from scipy.stats import rankdata + A = rng.integers(0, 4, size=(7, 11)).astype(float) # heavy ties on purpose + mine = _rank_parts(A)[0] + 1.0 + theirs = np.stack([rankdata(row) for row in A]) + chk("rankdata.maxabsdiff", np.abs(mine - theirs).max(), 0.0, 1e-12) + except ImportError: + print("[selftest] scipy absent, rankdata cross-check skipped", flush=True) + bad = [o for o in ok if not o[3]] + if bad: + raise SystemExit(f"SELFTEST FAILED: {bad}") + print(f"[selftest] all {len(ok)} assertions passed", flush=True) + return ok + + +def analyse(rows, n_dirs, st, a): + """Everything downstream of the npz scan. Split out so --reuse re-runs it in seconds + instead of re-reading 236 npz files after a bug in the aggregation.""" + res = dict(n_dirs_scanned=n_dirs, n_rows=len(rows), rows=rows, + selftest=[dict(name=n, got=g, want=w, passed=p) for n, g, w, p in st]) + + # ---------------- P1/P2: pooled family means (the nulls) ---------------- + fam = {} + for r in rows: + if r["score_kind"] != POOL_SCORE_KIND or r["temperature"] != POOL_TEMPERATURE: + continue + for name, v in r["variants"].items(): + base = name.split("@")[0] + if base.startswith("permuted_"): + key = "permuted:" + base[len("permuted_"):].split("@")[0] + elif base.startswith("rsm"): + key = "rsm" + else: + key = base + fam.setdefault(key, []).append(v) + res["families"] = { + k: dict(n=len(vs), + sel_rank_pct=float(np.mean([v["sel_rank_pct"] for v in vs])), + sel_rank_pct_sd=float(np.std([v["sel_rank_pct"] for v in vs])), + rho=float(np.mean([v["rho_score_err"] for v in vs])), + rho_sd=float(np.std([v["rho_score_err"] for v in vs])), + regret_cm=float(np.mean([v["sel_regret_cm"] for v in vs])), + chance_regret_cm=float(np.mean([v["chance_regret_cm"] for v in vs])), + var_a_median=float(np.median([v["var_a"] for v in vs]))) + for k, vs in sorted(fam.items())} + + # ------------- P3: WITHIN-DIR, value function at FIXED cloud (load-bearing) ------------- + within = [] + for r in rows: + vs = {k: v for k, v in r["variants"].items() + if (k == "rsm" or k.startswith("rsm@")) and not k.startswith("permuted")} + if len(vs) < 3: + continue + names = sorted(vs) + va = [vs[n]["var_a"] for n in names] + rk = [vs[n]["sel_rank_pct"] for n in names] + rh = [vs[n]["rho_score_err"] for n in names] + if min(va) <= 0: + continue + within.append(dict(dir=r["dir"], n_variants=len(names), + spread_cfg_cm=r["spread_cfg_cm"], + var_a_ratio=float(max(va) / min(va)), + rho_varA_rank=spearman(np.log10(va), rk), + rho_varA_rho=spearman(np.log10(va), rh), + rank_span=[float(min(rk)), float(max(rk))], + rho_span=[float(min(rh)), float(max(rh))], + best_by_varA_is_best_by_rho=bool( + names[int(np.argmax(va))] == names[int(np.argmax(rh))]))) + def _summ(key): + v = np.array([w[key] for w in within], float) + v = v[np.isfinite(v)] + if v.size == 0: + return None + return dict(n=int(v.size), median=float(np.median(v)), mean=float(v.mean()), + n_pos=int((v > 0).sum()), n_neg=int((v < 0).sum())) + res["within_dir"] = dict(clouds=within, + summary_varA_vs_rank=_summ("rho_varA_rank"), + summary_varA_vs_rho=_summ("rho_varA_rho"), + n_best_varA_is_best_rho=int(sum(w["best_by_varA_is_best_by_rho"] + for w in within))) + + # ------------- across-dir regression (reported, NOT load-bearing: width confound) ------- + pool = [(r, r["variants"]["rsm"]) for r in rows + if "rsm" in r["variants"] and r["score_kind"] == POOL_SCORE_KIND + and r["temperature"] == POOL_TEMPERATURE and r["variants"]["rsm"]["var_a"] > 0] + if len(pool) >= 6: + lva = np.array([np.log10(v["var_a"]) for _, v in pool]) + lw = np.array([np.log10(max(v["err_sd_within"], 1e-6)) for _, v in pool]) + rk = np.array([v["sel_rank_pct"] for _, v in pool]) + rh = np.array([v["rho_score_err"] for _, v in pool]) + res["across_dir"] = dict( + n=len(pool), + ols_rank_on_log_var_a=ols(lva, rk), + ols_rho_on_log_var_a=ols(lva, rh), + spearman_rank_var_a=spearman(lva, rk), + spearman_rho_var_a=spearman(lva, rh), + partial_rho_var_a_given_width=partial_spearman(rh, lva, lw), + partial_rank_var_a_given_width=partial_spearman(rk, lva, lw), + spearman_rho_width=spearman(lw, rh)) + # ------------- P4: the dose curve, var_a decile -> selection quality ------------- + qs = np.quantile(lva, np.linspace(0, 1, 6)) + bins = [] + for i in range(5): + m = (lva >= qs[i]) & (lva <= qs[i + 1] if i == 4 else lva < qs[i + 1]) + if m.sum() < 2: + continue + bins.append(dict(bin=i, n=int(m.sum()), + var_a_median=float(10 ** np.median(lva[m])), + sel_rank_pct=float(rk[m].mean()), + rho=float(rh[m].mean()))) + res["dose_curve"] = bins + + os.makedirs(Path(a.out).parent, exist_ok=True) + json.dump(res, open(a.out, "w"), indent=2, default=float) + print(f"[done] wrote {a.out}", flush=True) + print(json.dumps(res["families"], indent=2, default=float), flush=True) + print(json.dumps({k: v for k, v in res["within_dir"].items() if k != "clouds"}, + indent=2, default=float), flush=True) + print(json.dumps(res.get("across_dir", {}), indent=2, default=float), flush=True) + print(json.dumps(res.get("dose_curve", []), indent=2, default=float), flush=True) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--glob-root", default=f"{ROOT}/status/real") + ap.add_argument("--boot", type=int, default=1000) + ap.add_argument("--reuse", action="store_true", + help="reuse the cached per-dir scan instead of re-reading every npz") + ap.add_argument("--out", default=f"{ROOT}/status/real/ACT_COND/SENS_PAYS_run38.json") + a = ap.parse_args() + + st = selftest() + + cache = str(Path(a.out).with_suffix(".rows.json")) + if a.reuse and Path(cache).exists(): + rows = json.load(open(cache)) + print(f"[cache] reusing {len(rows)} rows from {cache}", flush=True) + return analyse(rows, len(rows), st, a) + + dirs = sorted({p.parent for p in Path(a.glob_root).glob("*/scores.npz")}) + print(f"[scan] {len(dirs)} dirs carry scores.npz", flush=True) + + rows = [] + for d in dirs: + cfg_p = d / "scorer_openloop.json" + if not cfg_p.exists(): + continue + try: + cfg = json.load(open(cfg_p)) + z = np.load(d / "scores.npz") + except Exception as e: + print(f"[skip] {d.name}: unreadable ({e})", flush=True) + continue + if "err_first" not in z.files: + print(f"[skip] {d.name}: no err_first", flush=True) + continue + E = z["err_first"] + if E.ndim != 2 or E.shape[0] < 3 or E.shape[1] < 3: + print(f"[skip] {d.name}: err_first shape {E.shape}", flush=True) + continue + args_ = cfg.get("args", cfg) + row = dict(dir=d.name, + ckpt=ckpt_tag(args_.get("rsm_ckpt")), hop=ckpt_tag(args_.get("rsm_hop_ckpt")), + beta=args_.get("rsm_beta"), gamma=args_.get("rsm_gamma"), + mode=args_.get("rsm_mode"), depth=args_.get("rsm_depth"), + score_kind=args_.get("rsm_score_kind"), + temperature=args_.get("rsm_temperature"), + policy=args_.get("policy"), stride=args_.get("stride"), + spread_cfg_cm=args_.get("candidate_spread_xyz_cm"), + valid_for_results=args_.get("valid_for_results"), + variants={}) + for k in z.files: + if not k.startswith("score_"): + continue + name = k[len("score_"):] + S = z[k] + if S.shape != E.shape: + continue + dc = decomp(S) + sq = selection_quality(S, E, B=a.boot) + if dc is None or sq is None: + continue + row["variants"][name] = {**dc, **sq} + if row["variants"]: + rows.append(row) + r = row["variants"].get("rsm") + if r: + print(f"[dir] {d.name:34s} ck={str(row['ckpt']):26s} " + f"var_a={r['var_a']:.3e} rank%={r['sel_rank_pct']:.3f} " + f"rho={r['rho_score_err']:+.3f} nvar={len(row['variants'])}", flush=True) + + os.makedirs(Path(a.out).parent, exist_ok=True) + cache = str(Path(a.out).with_suffix(".rows.json")) + json.dump(rows, open(cache, "w"), default=float) + print(f"[cache] per-dir scan dumped to {cache} ({len(rows)} rows)", flush=True) + return analyse(rows, len(dirs), st, a) + + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/real/actcond_spread_law.py b/rsm_rise/scripts/real/actcond_spread_law.py new file mode 100644 index 0000000000000000000000000000000000000000..68ba49672d2a183afde218f45382af1c284c00d8 --- /dev/null +++ b/rsm_rise/scripts/real/actcond_spread_law.py @@ -0,0 +1,381 @@ +#!/usr/bin/env python +"""ACT_COND run 37 -- DOES THE ACTION-DRIVEN SHARE TRACK THE CLOUD, OR THE VALUE FUNCTION? + +WHY THIS EXISTS -- IT IS A FALSIFICATION TEST OF MY OWN RUN-36 HEADLINE. +Run 36 concluded: at read-out only ~2.8 % of the RSM's score variance is action-driven, "not +because conditioning is broken, but because the 128 candidates it is asked to rank are nearly the +same action", i.e. the binding constraint is the PROPOSER and not the value function. The evidence +was a dose-response over FOUR hand-built candidate sets, all scored by ONE checkpoint +(R_M/ckpt_s100000). Four points on one value function is not enough to attribute the effect to the +cloud rather than to that checkpoint, and I should not let my own claim stand on it. + +The corpus already contains the controlled version of that test, at zero new GPU: + * ~231 EDGE dirs carry per-candidate scores (`scorer_openloop.py:722`), spanning ~25 distinct RSM + checkpoints and a logged `candidate_spread_xyz_cm` from 0.16 cm to 23.5 cm -- a ~145x range in + how wide a cloud the read-out was handed. + * A subset of dirs carry SEVERAL `score_rsm@` arrays computed on the IDENTICAL cloud: + same decisions, same 128 candidates, same read-out, DIFFERENT value function. + +So the two explanations separate cleanly, and this script computes both contrasts under one formula: + + CONTRAST A -- VALUE FUNCTION AT FIXED CLOUD. Within one dir, across every value function scored + on it (score_rsm, score_rsm@ft_*, score_idql). States, candidates and read-out are held exactly + fixed by construction, so ALL of the spread in var_a here is attributable to the value function. + This is the clean one: no confound is even possible. + + CONTRAST B -- CLOUD AT (NEAR-)FIXED VALUE FUNCTION. Across dirs sharing a checkpoint / beta / + gamma / read-out, regress log10(var_a) on log10(cloud width). Reported BOTH against the logged + config field `candidate_spread_xyz_cm` and against an empirical width computed from the same + npz (`err_first` within-decision sd), because a regressor read out of the file beats one read + out of a config header. + + PREDICTION REGISTERED BEFORE LOOKING (this is the point of writing it here): + if run 36's attribution is right, B's slope is clearly positive and A's spread is small relative + to the range B covers. If instead A's spread rivals B's, then the value function moves this + statistic as much as the cloud does, run 36 OVER-ATTRIBUTED to the proposer, and I have to say + so in those words. + +THE ESTIMAND is run 36's, unchanged, so the two runs are directly comparable: + var_a = mean over decisions of the variance over the N candidates at that decision (action-driven) + var_s = variance over decisions of the per-decision mean score (state-driven) + frac_action = var_a / (var_a + var_s) +var_a is the unit-comparable quantity ACROSS dirs only when the read-out matches, because `prob` and +`logit` are different scales; every pooled statistic below is therefore restricted to +rsm_score_kind == 'prob' and rsm_temperature == 25.0, and the filter is recorded in the output. +frac_action additionally depends on the DECISION SET through var_s, so where dirs differ in their +decision set frac_action is reported but var_a is the one carrying the argument -- the same caveat +run 36 put on its own headline row. + +`score_permuted_*` shuffles scores to candidates WITHIN a decision, so it preserves within-row +variance up to the per-episode re-seed. It is NOT a control for this statistic; as in run 36 it is +carried only as a file-integrity check and is never pooled. +""" +import argparse, json, math, os, re, sys +from pathlib import Path +import numpy as np + +ROOT = "/proj/dmfexp/zwhong/rsm_rise" + +# read-out fields that must match for var_a to be comparable across dirs +POOL_SCORE_KIND = "prob" +POOL_TEMPERATURE = 25.0 + + +def decomp(S, B=2000, seed=0): + """S [D, N] -> within/between variance decomposition + ties, dropping non-finite rows.""" + S = np.asarray(S, dtype=np.float64) + if S.ndim != 2 or S.shape[1] < 2: + return None + ok = np.isfinite(S).all(1) + S = S[ok] + D, N = S.shape + if D < 3: + return None + per_var = S.var(axis=1, ddof=1) + per_mu = S.mean(axis=1) + va = float(per_var.mean()) + vs = float(per_mu.var(ddof=1)) + denom = va + vs + # ties at the max, same tolerance as run 36 / act_sensitivity + mx = S.max(axis=1, keepdims=True) + tie = (np.abs(S - mx) <= 1e-6 * np.maximum(np.abs(mx), 1e-12) + 1e-12).mean(axis=1) + out = dict(n_dec=int(D), n_cand=int(N), var_a=va, var_s=vs, + asi_dep=(va / vs if vs > 0 else float("inf")), + frac_action=(va / denom if denom > 0 else float("nan")), + tie_at_max_per_N=float(tie.mean() * N), + cv_mean=float(np.mean(S.std(axis=1, ddof=1) / + np.maximum(np.abs(per_mu), 1e-12))), + score_mean=float(S.mean()), score_min=float(S.min()), score_max=float(S.max())) + # bootstrap over DECISIONS (the sampling unit), vectorised + if B: + rng = np.random.default_rng(seed) + idx = rng.integers(0, D, size=(B, D)) + a_b = per_var[idx].mean(axis=1) + m_b = per_mu[idx] + s_b = m_b.var(axis=1, ddof=1) + d_b = a_b + s_b + fr = np.where(d_b > 0, a_b / np.where(d_b > 0, d_b, 1.0), np.nan) + out["frac_action_ci"] = [float(np.nanpercentile(fr, 2.5)), + float(np.nanpercentile(fr, 97.5))] + out["var_a_ci"] = [float(np.nanpercentile(a_b, 2.5)), + float(np.nanpercentile(a_b, 97.5))] + return out + + +def err_width(E): + """Empirical cloud width from err_first [D, N]: mean over decisions of the within-decision sd.""" + E = np.asarray(E, dtype=np.float64) + if E.ndim != 2 or E.shape[1] < 2: + return None + ok = np.isfinite(E).all(1) + E = E[ok] + if E.shape[0] < 3: + return None + return dict(err_sd_within=float(E.std(axis=1, ddof=1).mean()), + err_mean=float(E.mean()), + err_range_within=float((E.max(axis=1) - E.min(axis=1)).mean())) + + +def ols(x, y): + """Plain OLS slope/intercept/r with a t-based CI on the slope. Returns None if degenerate.""" + x = np.asarray(x, float); y = np.asarray(y, float) + m = np.isfinite(x) & np.isfinite(y) + x, y = x[m], y[m] + n = len(x) + if n < 4 or x.std() == 0: + return None + xc, yc = x - x.mean(), y - y.mean() + b = float(xc @ yc / (xc @ xc)) + a = float(y.mean() - b * x.mean()) + resid = y - (a + b * x) + dof = n - 2 + se = math.sqrt(float(resid @ resid) / dof / float(xc @ xc)) if dof > 0 else float("nan") + r = float(xc @ yc / math.sqrt(float(xc @ xc) * float(yc @ yc))) if yc @ yc > 0 else float("nan") + # 95% normal approx (n is 5-40 here; reported as approximate and labelled) + return dict(n=int(n), slope=b, intercept=a, r=r, r2=r * r, se=se, + slope_ci_approx=[b - 1.96 * se, b + 1.96 * se]) + + +def spearman(x, y): + x = np.asarray(x, float); y = np.asarray(y, float) + m = np.isfinite(x) & np.isfinite(y) + x, y = x[m], y[m] + if len(x) < 4: + return float("nan") + rx = np.argsort(np.argsort(x)).astype(float) + ry = np.argsort(np.argsort(y)).astype(float) + rx -= rx.mean(); ry -= ry.mean() + d = math.sqrt(float(rx @ rx) * float(ry @ ry)) + return float(rx @ ry / d) if d > 0 else float("nan") + + +def ckpt_tag(p): + if not p: + return None + return os.path.basename(os.path.dirname(p)) + "/" + os.path.basename(p) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--glob-root", default=f"{ROOT}/status/real") + ap.add_argument("--boot", type=int, default=2000) + ap.add_argument("--out", default=f"{ROOT}/status/real/ACT_COND/SPREAD_LAW_run37.json") + a = ap.parse_args() + + dirs = sorted({p.parent for p in Path(a.glob_root).glob("*/scores.npz")}) + print(f"[scan] {len(dirs)} dirs carry scores.npz", flush=True) + + rows = [] + for d in dirs: + cfg_p = d / "scorer_openloop.json" + if not cfg_p.exists(): + continue + try: + cfg = json.load(open(cfg_p)) + except Exception as e: + print(f"[skip] {d.name}: config unreadable ({e})", flush=True) + continue + args_ = cfg.get("args", cfg) + try: + z = np.load(d / "scores.npz") + except Exception as e: + print(f"[skip] {d.name}: npz unreadable ({e})", flush=True) + continue + + row = dict(dir=d.name, + ckpt=ckpt_tag(args_.get("rsm_ckpt")), + hop=ckpt_tag(args_.get("rsm_hop_ckpt")), + beta=args_.get("rsm_beta"), gamma=args_.get("rsm_gamma"), + mode=args_.get("rsm_mode"), depth=args_.get("rsm_depth"), + score_kind=args_.get("rsm_score_kind"), + temperature=args_.get("rsm_temperature"), + particles=args_.get("rsm_particles"), + policy=args_.get("policy"), stride=args_.get("stride"), + n_cand_cfg=args_.get("n_cand"), n_dec_cfg=args_.get("n_decisions"), + spread_cfg_cm=args_.get("candidate_spread_xyz_cm"), + valid_for_results=args_.get("valid_for_results"), + values={}, permuted={}) + + if "err_first" in z.files: + row["err"] = err_width(z["err_first"]) + + for k in z.files: + if not k.startswith("score_"): + continue + name = k[len("score_"):] + dc = decomp(z[k], B=a.boot) + if dc is None: + continue + if name.startswith("permuted_"): + row["permuted"][name[len("permuted_"):]] = dc + else: + row["values"][name] = dc + if row["values"]: + rows.append(row) + print(f"[dir] {d.name:34s} ck={str(row['ckpt']):28s} " + f"spread={row['spread_cfg_cm']} nval={len(row['values'])} " + f"rsm_fa={row['values'].get('rsm', {}).get('frac_action', float('nan')):.4f}", + flush=True) + + res = dict(n_dirs_scanned=len(dirs), n_rows=len(rows), + pool_filter=dict(score_kind=POOL_SCORE_KIND, temperature=POOL_TEMPERATURE), + rows=rows, contrast_A=[], contrast_B={}, integrity=[]) + + # ---------------- CONTRAST A: value function at FIXED cloud ---------------- + # Same dir => same decisions, same candidates, same read-out. Any spread in var_a here is + # caused by the value function alone. No confound is possible by construction. + # RESTRICTED TO THE RSM FAMILY ON PURPOSE. My first pass excluded only `idql` and so pooled + # `bc` and `pose`, which are on entirely different scales (bc scores are log-likelihoods, + # mean ~ -772, var_a ~ 1.4e7). That produced a meaningless 4.8e9x "ratio" on the edge_INJRBB_* + # rows. var_a is only comparable within one scoring scale, so A compares value functions of + # the SAME kind; idql/bc/pose are carried alongside as separate, clearly-labelled fields. + for r in rows: + vals = {k: v for k, v in r["values"].items() if k == "rsm" or k.startswith("rsm@")} + if len(vals) < 3: + continue + va = {k: v["var_a"] for k, v in vals.items()} + fa = {k: v["frac_action"] for k, v in vals.items()} + lo_k = min(va, key=va.get); hi_k = max(va, key=va.get) + entry = dict(dir=r["dir"], n_values=len(vals), spread_cfg_cm=r["spread_cfg_cm"], + n_dec=vals[hi_k]["n_dec"], + var_a_min=va[lo_k], var_a_min_key=lo_k, + var_a_max=va[hi_k], var_a_max_key=hi_k, + var_a_ratio=(va[hi_k] / va[lo_k] if va[lo_k] > 0 else float("inf")), + frac_action_min=min(fa.values()), frac_action_max=max(fa.values()), + per_value={k: dict(var_a=va[k], frac_action=fa[k]) for k in sorted(vals)}) + for other in ("idql", "bc", "pose"): + if other in r["values"]: + entry[f"{other}_var_a_NOT_COMPARABLE_SCALE"] = r["values"][other]["var_a"] + entry[f"{other}_frac_action"] = r["values"][other]["frac_action"] + res["contrast_A"].append(entry) + + # ---------------- CONTRAST B: cloud width at (near-)fixed value function ---------------- + pool = [r for r in rows + if r["score_kind"] == POOL_SCORE_KIND + and r["temperature"] is not None + and abs(float(r["temperature"]) - POOL_TEMPERATURE) < 1e-9 + and "rsm" in r["values"]] + + def fit_block(block, label, xkey): + xs, ys, fas = [], [], [] + for r in block: + x = (r.get("spread_cfg_cm") if xkey == "cfg" + else (r.get("err") or {}).get("err_sd_within")) + y = r["values"]["rsm"]["var_a"] + if x is None or not np.isfinite(x) or x <= 0 or not np.isfinite(y) or y <= 0: + continue + xs.append(math.log10(x)); ys.append(math.log10(y)) + fas.append(r["values"]["rsm"]["frac_action"]) + if len(xs) < 4: + return None + f = ols(xs, ys) + if f is None: + return None + f.update(label=label, x=xkey, spearman=spearman(xs, ys), + x_log10_range=[min(xs), max(xs)], y_log10_range=[min(ys), max(ys)], + frac_action_range=[min(fas), max(fas)]) + return f + + for xkey in ("cfg", "err"): + res["contrast_B"][xkey] = dict(pooled=fit_block(pool, "ALL pooled (prob, T=25)", xkey), + by_ckpt=[]) + groups = {} + for r in pool: + groups.setdefault((r["ckpt"], r["beta"], r["gamma"], r["mode"], r["depth"]), []).append(r) + for key, block in sorted(groups.items(), key=lambda kv: -len(kv[1])): + if len(block) < 5: + continue + f = fit_block(block, str(key), xkey) + if f: + f["group"] = dict(ckpt=key[0], beta=key[1], gamma=key[2], mode=key[3], depth=key[4]) + res["contrast_B"][xkey]["by_ckpt"].append(f) + + # ------- CONTRAST C: what actually sets var_s, i.e. the denominator of frac_action ------- + # Run 36 led with frac_action (deployed 0.028 vs logged 0.493). frac_action = var_a/(var_a+var_s) + # and var_s is the between-DECISION variance, so it is a property of the EVALUATION PROTOCOL -- + # how much of the episode's progress range the decision set sweeps -- not of the value function. + # Split the pool on var_s and report what distinguishes the two families. + lo = [r for r in pool if r["values"]["rsm"]["var_s"] < 1e-3] + hi = [r for r in pool if r["values"]["rsm"]["var_s"] > 1e-2] + res["contrast_C"] = {} + for lbl, grp in (("low_var_s", lo), ("high_var_s", hi)): + if not grp: + continue + v = [r["values"]["rsm"] for r in grp] + res["contrast_C"][lbl] = dict( + n=len(grp), + var_s_median=float(np.median([x["var_s"] for x in v])), + var_a_median=float(np.median([x["var_a"] for x in v])), + frac_action_median=float(np.median([x["frac_action"] for x in v])), + n_dec_median=float(np.median([x["n_dec"] for x in v])), + n_dec_range=[int(min(x["n_dec"] for x in v)), int(max(x["n_dec"] for x in v))], + score_mean_median=float(np.median([x["score_mean"] for x in v])), + score_span=[float(min(x["score_min"] for x in v)), + float(max(x["score_max"] for x in v))], + spread_median_cm=float(np.nanmedian([r["spread_cfg_cm"] or np.nan for r in grp])), + example_dirs=[r["dir"] for r in grp[:6]]) + + # ---------------- integrity: permuted preserves within-row variance ---------------- + for r in rows: + for k, v in r["permuted"].items(): + if k in r["values"] and r["values"][k]["var_a"] > 0: + res["integrity"].append(dict(dir=r["dir"], value=k, + ratio=v["var_a"] / r["values"][k]["var_a"])) + + os.makedirs(os.path.dirname(a.out), exist_ok=True) + json.dump(res, open(a.out, "w"), indent=1, default=float) + + # ---------------- printed summary ---------------- + print("\n" + "=" * 100) + print("CONTRAST A -- value function at FIXED cloud (same decisions, candidates, read-out)") + print("=" * 100) + for e in sorted(res["contrast_A"], key=lambda e: -e["n_values"]): + print(f"{e['dir']:30s} nval={e['n_values']:3d} spread={e['spread_cfg_cm']} " + f"var_a {e['var_a_min']:.4e} ({e['var_a_min_key']}) -> {e['var_a_max']:.4e} " + f"({e['var_a_max_key']}) ratio={e['var_a_ratio']:.2f}x " + f"frac_action {e['frac_action_min']:.4f}-{e['frac_action_max']:.4f}") + if res["contrast_A"]: + rr = [e["var_a_ratio"] for e in res["contrast_A"] if np.isfinite(e["var_a_ratio"])] + print(f"\n A summary: {len(rr)} clouds with >=3 value functions; " + f"var_a max/min ratio median={np.median(rr):.2f}x range=[{min(rr):.2f}, {max(rr):.2f}]x") + + print("\n" + "=" * 100) + print("CONTRAST B -- log10(var_a) vs log10(cloud width), prob read-out, T=25") + print("=" * 100) + for xkey in ("cfg", "err"): + xl = ("config candidate_spread_xyz_cm" if xkey == "cfg" + else "empirical err_first within-decision sd") + print(f"\n-- regressor: {xl}") + p = res["contrast_B"][xkey]["pooled"] + if p: + print(f" POOLED n={p['n']:3d} slope={p['slope']:+.3f} " + f"CI~[{p['slope_ci_approx'][0]:+.3f},{p['slope_ci_approx'][1]:+.3f}] " + f"r={p['r']:+.3f} r2={p['r2']:.3f} spearman={p['spearman']:+.3f} " + f"xrange(dec)={p['x_log10_range'][1] - p['x_log10_range'][0]:.2f}") + for f in res["contrast_B"][xkey]["by_ckpt"]: + g = f["group"] + print(f" {str(g['ckpt']):26s} b={g['beta']} g={g['gamma']} {g['mode']}/{g['depth']} " + f"n={f['n']:3d} slope={f['slope']:+.3f} r={f['r']:+.3f} " + f"spearman={f['spearman']:+.3f}") + + if res.get("contrast_C"): + print("\n" + "=" * 100) + print("CONTRAST C -- var_s (the frac_action denominator) is set by the EVALUATION PROTOCOL") + print("=" * 100) + for lbl, c in res["contrast_C"].items(): + print(f" {lbl:12s} n={c['n']:3d} var_s={c['var_s_median']:.3e} var_a={c['var_a_median']:.3e} " + f"frac_action={c['frac_action_median']:.4f} n_dec={c['n_dec_median']:.0f} " + f"{c['n_dec_range']} score_mean={c['score_mean_median']:.4f} " + f"span={c['score_span']} spread={c['spread_median_cm']:.3f}cm") + + if res["integrity"]: + ratios = np.array([e["ratio"] for e in res["integrity"]], float) + ratios = ratios[np.isfinite(ratios)] + print(f"\n[integrity] permuted/original var_a over {len(ratios)} arrays: " + f"median={np.median(ratios):.4f} p05={np.percentile(ratios, 5):.4f} " + f"p95={np.percentile(ratios, 95):.4f} (construction predicts ~1.0)") + print("\nwrote", a.out, flush=True) + + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/real/actcond_topk.py b/rsm_rise/scripts/real/actcond_topk.py new file mode 100644 index 0000000000000000000000000000000000000000..a095007c3f51e7f6179ca7a21a8ab373f460ed9a --- /dev/null +++ b/rsm_rise/scripts/real/actcond_topk.py @@ -0,0 +1,318 @@ +#!/usr/bin/env python +"""ACT_COND run 47 -- WHERE in the ranking does idql's advantage over the RSM live? + +Run 46 section 8 found the paired per-dir gap `contrib(idql) - contrib(rsm)` is + +0.02061 [+0.01202,+0.02926] in ARGMAX onroute-lift units (sign p=4.9e-3) + +0.00094 [-0.01056,+0.01234] in whole-ranking AUC units (sign p=4.9e-2) +and *interpreted* that as "idql's edge is confined to the TOP of the ranking". That was an +interpretation. This measures it: the top-k on-route lift curve, k = 1 .. N. k=1 IS the argmax +estimand, k=N is identically 0, and the Mann-Whitney AUC is a different weighting of the same +ranking -- so if the gap really lives at the top, the curve must decay in k. If it is flat, the +sentence is wrong and I withdraw it. + +TIES. Not a second rule: groups are formed in descending score with the same TIE_RTOL/TIE_ATOL that +`tie_mask` uses, so the top group IS `tie_mask`, and a group straddling k contributes its fraction -- +the expectation under uniform random tie-breaking. (C1) checks that against `goal_stats` directly. + +Pre-registered in status/real/ACT_COND.md before submission: + (C1) k=1 reproduces goal_stats' onroute_lift to <=1e-12 and k=N is exactly 0, else exit 3. + (C2) re-reading the 4 gamma dirs at run 46's part count reproduces run 46 exactly (append-only). + (C3) on the 3 still-growing dirs the base falls 3/3 and the lift moves toward 0 in >=2/3. + (C4) the paired gap is maximal at k=1, spearman over the k ladder <= -0.8, |gap| <= 0.005 by N/2. + (C5) |dauc| < |dlift| in at most 2 of the 3 growing dirs (run 46 section 4's caveat, new data). +""" +import argparse, json, os, sys, tempfile, shutil +import numpy as np + +sys.path.insert(0, "/proj/dmfexp/zwhong/rsm_rise/scripts/real") +from actcond_goal_directedness import (load_dir, goal_stats, tie_mask, boot_ci, # noqa: E402 + TIE_RTOL, TIE_ATOL) +from actcond_prefix import REAL, CACHE, parts_in_write_order, load_prefix, stats_for # noqa: E402 + +GAMMA = ["edge_s2ro_v0lit_g995_sh0of1", "edge_s2ro_v0lit_g9975_sh0of1", + "edge_s2ro_v5_g995_sh0of1", "edge_s2ro_v5_g9975_sh0of1"] +RUN46 = "/proj/dmfexp/zwhong/rsm_rise/status/real/ACT_COND/HEADLINE_AUC_run46.json" +MODES = ["rsm", "permuted__rsm", "idql", "permuted__idql"] +KLAD = [1, 2, 3, 4, 6, 8, 12, 16, 24, 32, 48, 64] + + +def sign_test_p(x): + from math import comb + x = np.asarray([v for v in np.asarray(x, float) if v != 0], float) + n, k = len(x), int((x > 0).sum()) + if n == 0: + return None + tail = sum(comb(n, i) for i in range(0, min(k, n - k) + 1)) / 2.0 ** n + return float(min(1.0, 2 * tail)) + + +def spearman(a, b): + a, b = np.asarray(a, float), np.asarray(b, float) + m = np.isfinite(a) & np.isfinite(b) + if m.sum() < 3: + return None + ra = np.argsort(np.argsort(a[m])).astype(float) + rb = np.argsort(np.argsort(b[m])).astype(float) + ra -= ra.mean(); rb -= rb.mean() + den = np.sqrt((ra * ra).sum() * (rb * rb).sum()) + return float((ra * rb).sum() / den) if den > 0 else None + + +def topk_rates(S, O, ks): + """expected on-route rate among the top-k under uniform tie-breaking, per decision. + + returns R [D, len(ks)]. Groups are chained in descending score with tie_mask's tolerance, so + the leading group equals tie_mask(S) exactly and k=1 reproduces goal_stats' pick_expect. + """ + S = np.asarray(S, float); O = np.asarray(O, float) + D, N = S.shape + R = np.empty((D, len(ks)), float) + order = np.argsort(-S, axis=1, kind="stable") + for d in range(D): + s = S[d, order[d]]; o = O[d, order[d]] + # group boundaries: a new group starts where the score drops below the group leader's tol + lead = s[0] + gid = np.empty(N, int) + g = 0 + for j in range(N): + if s[j] < lead - (TIE_RTOL * max(abs(lead), 1e-12) + TIE_ATOL): + g += 1; lead = s[j] + gid[j] = g + ng = g + 1 + cnt = np.bincount(gid, minlength=ng).astype(float) + hit = np.bincount(gid, weights=o, minlength=ng) + cum = np.concatenate([[0.0], np.cumsum(cnt)]) + for i, k in enumerate(ks): + kk = min(k, N) + # whole groups fully inside k, plus the fraction of the straddling group + full = cum[1:] <= kk + tot = float((hit * full).sum()) + j = int(full.sum()) + if j < ng and cum[j] < kk: + tot += hit[j] * (kk - cum[j]) / cnt[j] + R[d, i] = tot / kk + return R + + +def curve_for(S, O, ks): + """top-k lift per k over MIXED decisions only -- the estimand goal_stats' onroute_lift uses. + + The finite-row filter is goal_stats' own (`ok = isfinite(S).all(1)`), applied before base/mixed, + or (C1) would compare two different decision sets. + """ + S = np.asarray(S, float) + ok = np.isfinite(S).all(1) + if ok.sum() < 3: + return None + S, O = S[ok], np.asarray(O, float)[ok] + base = O.mean(axis=1) + mixed = (base > 0) & (base < 1) + if not mixed.any(): + return None + R = topk_rates(S, O, ks) + return (R[mixed] - base[mixed, None]).mean(axis=0), int(mixed.sum()) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--out", required=True) + ap.add_argument("--boot", type=int, default=20000) + ap.add_argument("--tmp", default=os.environ.get("TMPDIR", "/tmp")) + a = ap.parse_args() + rows = json.load(open(CACHE)) + cache = {r["dir"]: r for r in rows} + out = dict(generated=str(np.datetime64("now")), cache=CACHE, n_dirs=len(rows), klad=KLAD) + + # ------------------------------------------------------------------ the curve, all dirs + print(f"=== loading {len(rows)} dirs and building top-k curves ===", flush=True) + per_dir = {} + c1 = [] + for i, r in enumerate(rows): + name = r["dir"] + got = load_dir(f"{REAL}/{name}") + if got is None: + continue + O, A, P, E, S, Lm, nkeep = got + N = O.shape[1] + ks = [k for k in KLAD if k < N] + [N] + rec = dict(n_cand=int(N), ks=ks, curves={}) + for mode in MODES: + if mode not in S: + continue + cv = curve_for(S[mode], O.astype(float), ks) + if cv is None: + continue + lift_k, nmix = cv + rec["curves"][mode] = dict(lift_k=[float(v) for v in lift_k], n_mixed=nmix) + # (C1) k=1 must equal goal_stats' onroute_lift; k=N must be exactly 0 + st = goal_stats(S[mode], O.astype(bool), A, P, E, B=0) + ref = None if st is None else st["onroute_lift"] + rec["curves"][mode]["n_tied_at_max"] = None if st is None else st["n_tied_at_max"] + rec["curves"][mode]["onroute_auc"] = None if st is None else st["onroute_auc"] + rec["curves"][mode]["onroute_base"] = None if st is None else st["onroute_base"] + c1.append(dict(dir=name, mode=mode, k1=float(lift_k[0]), ref=ref, + d1=None if ref is None else abs(float(lift_k[0]) - ref), + kN=float(lift_k[-1]))) + if rec["curves"]: + per_dir[name] = rec + if (i + 1) % 25 == 0: + print(f" {i+1}/{len(rows)} dirs", flush=True) + + bad1 = [c for c in c1 if c["d1"] is None or c["d1"] > 1e-12 or abs(c["kN"]) > 1e-12] + out["C1"] = dict(n_checked=len(c1), + max_d_k1=max((c["d1"] for c in c1 if c["d1"] is not None), default=None), + max_abs_kN=max((abs(c["kN"]) for c in c1), default=None), + n_fail=len(bad1), examples=bad1[:5]) + out["C1_pass"] = not bad1 + print("\n=== (C1) NULL: k=1 == goal_stats onroute_lift, k=N == 0 ===") + print(f" checked {len(c1)} (dir,mode); max |d(k=1)| = {out['C1']['max_d_k1']:.3e} " + f"max |lift(k=N)| = {out['C1']['max_abs_kN']:.3e} failures {len(bad1)}") + json.dump(out, open(a.out, "w"), default=float, indent=1) + if bad1: + for c in bad1[:5]: + print(f" [FAIL] {c['dir']} {c['mode']} k1={c['k1']} ref={c['ref']} kN={c['kN']}") + print("[FAIL] (C1) -- no curve reported."); sys.exit(3) + print(" PASS") + + # ------------------------------------------------------------------ (C4) the paired gap in k + # a common k grid: k values present in every dir (all dirs share N? not guaranteed -- use the + # ladder entries that are < min N, plus the per-dir N endpoint reported separately) + Nmin = min(v["n_cand"] for v in per_dir.values()) + grid = [k for k in KLAD if k < Nmin] + print(f"\n=== (C4) paired top-k gap, {len(per_dir)} dirs, N in " + f"[{Nmin}, {max(v['n_cand'] for v in per_dir.values())}], grid {grid} + N/2 + N ===") + + def liftk(name, mode, k): + v = per_dir[name]["curves"].get(mode) + if v is None: + return None + ks = per_dir[name]["ks"] + if k not in ks: + return None + return v["lift_k"][ks.index(k)] + + tab = [] + for k in grid: + g, cr, ci_, ln = [], [], [], [] + for name in per_dir: + lr, pr = liftk(name, "rsm", k), liftk(name, "permuted__rsm", k) + li, pi = liftk(name, "idql", k), liftk(name, "permuted__idql", k) + if None not in (lr, pr): + cr.append(lr - pr) + if None not in (li, pi): + ci_.append(li - pi) + if None not in (lr, pr, li, pi): + g.append((li - pi) - (lr - pr)) + g, cr, ci_ = np.array(g), np.array(cr), np.array(ci_) + tab.append(dict(k=k, n_gap=len(g), gap=float(g.mean()), gap_ci=boot_ci(g, a.boot, k), + gap_frac_pos=float((g > 0).mean()), gap_sign_p=sign_test_p(g), + contrib_rsm=float(cr.mean()), contrib_idql=float(ci_.mean()), + n_rsm=len(cr), n_idql=len(ci_))) + out["C4_table"] = tab + print(f" {'k':>4} {'n':>4} {'contrib_rsm':>12} {'contrib_idql':>13} {'GAP':>10} " + f"{'95% CI':>26} {'frac>0':>7} {'sign p':>9}") + for t in tab: + print(f" {t['k']:>4} {t['n_gap']:>4} {t['contrib_rsm']:>+12.5f} {t['contrib_idql']:>+13.5f} " + f"{t['gap']:>+10.5f} [{t['gap_ci'][0]:+.5f},{t['gap_ci'][1]:+.5f}] " + f"{t['gap_frac_pos']:>7.3f} {t['gap_sign_p']:>9.3g}") + gaps = [t["gap"] for t in tab] + sp = spearman(grid, gaps) + out["C4"] = dict(spearman_k_gap=sp, gap_k1=gaps[0], argmax_is_max=bool(gaps[0] == max(gaps)), + grid=grid) + # half-N and full-N endpoints, per dir (N differs), reported separately + for tag, frac in (("half", 0.5), ("full", 1.0)): + g = [] + for name in per_dir: + k = max(1, int(round(per_dir[name]["n_cand"] * frac))) + lr, pr = liftk(name, "rsm", k), liftk(name, "permuted__rsm", k) + li, pi = liftk(name, "idql", k), liftk(name, "permuted__idql", k) + if None not in (lr, pr, li, pi): + g.append((li - pi) - (lr - pr)) + if g: + g = np.array(g) + out["C4"][f"gap_{tag}N"] = dict(n=len(g), mean=float(g.mean()), + ci=boot_ci(g, a.boot, 99), frac_pos=float((g > 0).mean())) + out["C4_pass"] = bool(sp is not None and sp <= -0.8 and out["C4"]["argmax_is_max"]) + print(f" spearman(k, gap) = {sp} argmax is the max: {out['C4']['argmax_is_max']} " + f"(C4 decay) pass={out['C4_pass']}") + for tag in ("half", "full"): + v = out["C4"].get(f"gap_{tag}N") + if v: + print(f" gap at k = {tag} N: {v['mean']:+.5f} {v['ci']} (n={v['n']})") + # tie structure beside it + nt = [v["curves"]["rsm"]["n_tied_at_max"] for v in per_dir.values() + if v["curves"].get("rsm", {}).get("n_tied_at_max") is not None] + out["tie_structure"] = dict(n=len(nt), mean_tied_at_max=float(np.mean(nt)), + median=float(np.median(nt)), max=float(np.max(nt)), + mean_n_cand=float(np.mean([v["n_cand"] for v in per_dir.values()]))) + print(f" TIES beside it: mean tied-at-max {out['tie_structure']['mean_tied_at_max']:.2f} of " + f"{out['tie_structure']['mean_n_cand']:.1f} candidates (median " + f"{out['tie_structure']['median']:.1f}, max {out['tie_structure']['max']:.0f})") + json.dump(out, open(a.out, "w"), default=float, indent=1) + + # ------------------------------------------------------------------ (C2)/(C3)/(C5) gamma dirs + r46 = json.load(open(RUN46))["grown_refresh"] + tmproot = tempfile.mkdtemp(dir=a.tmp, prefix="actcond_topk_") + gam = {} + for name in GAMMA: + d = f"{REAL}/{name}" + files, name_eq_mtime = parts_in_write_order(d) + now = stats_for(load_prefix(d, files, tmproot), "rsm", B=0) + k46 = int(r46[name]["n_parts"]) + back = stats_for(load_prefix(d, files[:k46], tmproot), "rsm", B=0) + gam[name] = dict( + n_parts_now=len(files), n_parts_run46=k46, name_order_eq_mtime=bool(name_eq_mtime), + now=None if now is None else dict(n_dec=now["n_dec"], lift=now["onroute_lift"], + auc=now["onroute_auc"], base=now["onroute_base"]), + replay46=None if back is None else dict(n_dec=back["n_dec"], lift=back["onroute_lift"], + auc=back["onroute_auc"], + base=back["onroute_base"]), + run46=dict(n_dec=r46[name]["n_dec"], lift=r46[name]["lift"], auc=r46[name]["auc"])) + shutil.rmtree(tmproot, ignore_errors=True) + out["gamma"] = gam + + print("\n=== (C2) APPEND-ONLY NULL: re-read at run 46's part count must reproduce run 46 ===") + c2fail = [] + for n, v in gam.items(): + if v["replay46"] is None: + c2fail.append(n); print(f" {n:32s} replay FAILED to load"); continue + dl = abs(v["replay46"]["lift"] - v["run46"]["lift"]) + da = abs(v["replay46"]["auc"] - v["run46"]["auc"]) + dn = v["replay46"]["n_dec"] - v["run46"]["n_dec"] + if dl > 1e-12 or da > 1e-12 or dn != 0: + c2fail.append(n) + print(f" {n:32s} {v['n_parts_run46']:>3} parts dn_dec={dn:+d} |dlift|={dl:.3e} |dauc|={da:.3e}") + out["C2_pass"] = not c2fail + print(f" (C2) append-only: pass={out['C2_pass']}" + (f" FAILED {c2fail}" if c2fail else "")) + + print("\n=== (C3)/(C5) the gamma trajectory, run 46 (21:37Z) -> now ===") + grew = [n for n, v in gam.items() if v["n_parts_now"] > v["n_parts_run46"]] + base_down = lift_toward0 = auc_calmer = 0 + print(f" {'dir':32s} {'parts':>9} {'dec':>11} {'base':>17} {'lift':>19} {'auc':>17}") + for n, v in gam.items(): + if v["now"] is None or v["replay46"] is None: + continue + b0, b1 = v["replay46"]["base"], v["now"]["base"] + l0, l1 = v["run46"]["lift"], v["now"]["lift"] + a0, a1 = v["run46"]["auc"], v["now"]["auc"] + if n in grew: + base_down += int(b1 < b0) + lift_toward0 += int(abs(l1) < abs(l0)) + auc_calmer += int(abs(a1 - a0) < abs(l1 - l0)) + print(f" {n:32s} {v['n_parts_run46']:>4}->{v['n_parts_now']:<4} " + f"{v['run46']['n_dec']:>5}->{v['now']['n_dec']:<5} {b0:>8.4f}->{b1:<8.4f} " + f"{l0:>+9.4f}->{l1:<+9.4f} {a0:>8.4f}->{a1:<8.4f}") + out["C3"] = dict(n_grew=len(grew), grew=grew, base_fell=base_down, lift_toward_zero=lift_toward0) + out["C3_pass"] = bool(len(grew) > 0 and base_down == len(grew) + and lift_toward0 >= max(1, int(np.ceil(2 * len(grew) / 3)))) + out["C5"] = dict(n_grew=len(grew), auc_calmer=auc_calmer) + out["C5_pass"] = bool(auc_calmer <= max(0, len(grew) - 1)) + print(f" grew: {len(grew)} base fell in {base_down}/{len(grew)} lift moved toward 0 in " + f"{lift_toward0}/{len(grew)} (C3) pass={out['C3_pass']}") + print(f" (C5) AUC calmer than lift in {auc_calmer}/{len(grew)} pass={out['C5_pass']}") + json.dump(out, open(a.out, "w"), default=float, indent=1) + print(f"\n[out] {a.out}") + + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/real/actcond_topk_figure.py b/rsm_rise/scripts/real/actcond_topk_figure.py new file mode 100644 index 0000000000000000000000000000000000000000..995580e334a2b4553b20ba646ee84a386e14f926 --- /dev/null +++ b/rsm_rise/scripts/real/actcond_topk_figure.py @@ -0,0 +1,161 @@ +#!/usr/bin/env python +"""ACT_COND (gen_q#278) -- the one figure this stream contributes. + +Top-k goal-directedness contribution of the RSM vs the IQL/idql critic over the +149-dir ranking cache, at FROZEN edge_parts length (run 48b). + +Panel A: per-dir mean contribution vs the paired permuted-feature control, for + each value function, as a function of the top-k cut. +Panel B: the paired gap (idql - rsm) with its 95% CI, which is the quantity that + crosses zero at k ~ 12. + +Reads status/real/ACT_COND/TOPK_run48frozen.json (written by actcond_topk.py). +Writes a PNG + a markdown table. Fails loudly: asserts the source's own null +checks passed and that every field it plots is present. +""" +import argparse, json, os, sys + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--src", default="status/real/ACT_COND/TOPK_run48frozen.json") + ap.add_argument("--out", default="status/real/ACT_COND/fig/topk_contribution") + a = ap.parse_args() + + import matplotlib + matplotlib.use("Agg") + import matplotlib.pyplot as plt + print("matplotlib", matplotlib.__version__, file=sys.stderr) + + d = json.load(open(a.src)) + # fail loudly if the source run's own null check did not pass + assert d["C1_pass"] is True, f"source C1 null check FAILED: {d['C1']}" + assert d["n_dirs"] == 149, d["n_dirs"] + rows = d["C4_table"] + assert rows, "empty C4_table" + for r in rows: + for f in ("k", "gap", "gap_ci", "gap_sign_p", "contrib_rsm", "contrib_idql"): + assert f in r, f"row k={r.get('k')} missing {f}" + assert r["n_gap"] == r["n_rsm"] == r["n_idql"] == 149, r + + k = [r["k"] for r in rows] + rsm = [r["contrib_rsm"] for r in rows] + idql = [r["contrib_idql"] for r in rows] + gap = [r["gap"] for r in rows] + lo = [r["gap_ci"][0] for r in rows] + hi = [r["gap_ci"][1] for r in rows] + sp = [r["gap_sign_p"] for r in rows] + + # validated categorical slots 1 and 2 (light surface #fcfcfb) + C_RSM, C_IDQL = "#2a78d6", "#eb6834" + SURFACE = "#fcfcfb" + INK, INK2, MUTED = "#0b0b0b", "#52514e", "#8a8983" + + fig, (ax, bx) = plt.subplots( + 2, 1, figsize=(7.6, 6.6), sharex=True, + gridspec_kw=dict(height_ratios=[1.35, 1.0], hspace=0.16)) + fig.patch.set_facecolor(SURFACE) + + for s in (ax, bx): + s.set_facecolor(SURFACE) + s.set_xscale("log", base=2) + s.grid(True, which="major", color=MUTED, alpha=0.22, lw=0.8) + s.set_axisbelow(True) + for side in ("top", "right"): + s.spines[side].set_visible(False) + for side in ("left", "bottom"): + s.spines[side].set_color(MUTED) + s.spines[side].set_linewidth(0.8) + s.tick_params(colors=INK2, labelsize=9, length=3, width=0.8) + + # ---- Panel A: the two contribution curves ------------------------------- + ax.plot(k, idql, color=C_IDQL, lw=2.0, marker="o", ms=5.5, mew=1.6, + mec=SURFACE, label="IQL critic (idql)", zorder=3) + ax.plot(k, rsm, color=C_RSM, lw=2.0, marker="o", ms=5.5, mew=1.6, + mec=SURFACE, label="RSM", zorder=3) + ax.axhline(0, color=MUTED, lw=1.0, zorder=1) + + # selective direct labels: each series' peak, plus the RSM's argmax value + i_i = max(range(len(k)), key=lambda j: idql[j]) + i_r = max(range(len(k)), key=lambda j: rsm[j]) + ax.annotate(f"peak +{idql[i_i]:.4f} @ k={k[i_i]}", (k[i_i], idql[i_i]), + textcoords="offset points", xytext=(9, 2), + color=INK2, fontsize=8.5, ha="left", va="center") + ax.annotate(f"peak +{rsm[i_r]:.4f} @ k={k[i_r]}, 1.9x its own argmax", + (k[i_r], rsm[i_r]), xytext=(5.0, 0.0042), textcoords="data", + color=INK2, fontsize=8.5, ha="left", va="center", + arrowprops=dict(arrowstyle="-", color=MUTED, lw=0.9, + shrinkA=2, shrinkB=4)) + ax.set_xlim(0.85, 82) + + ax.set_ylabel("contribution vs permuted-feature control\n(per-dir mean, AUC units)", + color=INK2, fontsize=9.5) + ax.set_title("Top-k goal-directedness: the RSM overtakes the IQL critic past k$\\approx$12", + color=INK, fontsize=12, loc="left", pad=10) + leg = ax.legend(frameon=False, fontsize=9.5, loc="lower left", ncol=1, + borderaxespad=0.6, handletextpad=0.6) + for t in leg.get_texts(): + t.set_color(INK2) + + # ---- Panel B: the paired gap with its 95% CI ---------------------------- + bx.fill_between(k, lo, hi, color=C_IDQL, alpha=0.16, lw=0, zorder=2, + label="95% CI") + bx.plot(k, gap, color=INK, lw=2.0, marker="o", ms=5.5, mew=1.6, + mec=SURFACE, zorder=4, label="gap = idql $-$ RSM") + bx.axhline(0, color=MUTED, lw=1.2, zorder=1) + + # significance markers, never colour-alone: filled ring + a footnote + for j, p in enumerate(sp): + if p < 0.05: + bx.plot([k[j]], [gap[j]], marker="o", ms=10, mfc="none", + mec=INK, mew=1.4, zorder=5) + + # the crossing, named in words not by colour + bx.annotate("idql ahead at the argmax", (1.0, 0.0285), textcoords="data", + color=INK2, fontsize=8.5, ha="left", va="center") + bx.annotate("RSM ahead: sign p 0.022 / 0.0031 / 9.8e-4\nat k = 32 / 48 / 64", + (9.0, 0.0175), textcoords="data", + color=INK2, fontsize=8.5, ha="left", va="center") + + bx.set_xlabel("top-k cut", color=INK2, fontsize=9.5) + bx.set_ylabel("paired gap (idql $-$ RSM)", color=INK2, fontsize=9.5) + bx.set_xticks(k) + bx.set_xticklabels([str(x) for x in k]) + bx.minorticks_off() + leg2 = bx.legend(frameon=False, fontsize=9.5, loc="lower left", ncol=1, + borderaxespad=0.6, handletextpad=0.6) + for t in leg2.get_texts(): + t.set_color(INK2) + + fig.text(0.008, 0.012, + "149 dirs, frozen edge_parts length; contribution is paired per dir against a permuted-feature control. " + "Ringed points: sign test p < 0.05.\n" + "Ties at the max: 1.0018 of 156.3 candidates (median 1.000, worst 1.017). " + "spearman(k, gap) = -0.923. Source: TOPK_run48frozen.json", + color=MUTED, fontsize=7.6, va="bottom") + fig.subplots_adjust(left=0.135, right=0.975, top=0.918, bottom=0.145) + + os.makedirs(os.path.dirname(a.out), exist_ok=True) + png = a.out + ".png" + fig.savefig(png, dpi=200, facecolor=SURFACE) + print("wrote", png) + + # the table view the accessibility pass requires + md = a.out + ".md" + with open(md, "w") as f: + f.write("# Top-k goal-directedness contribution (ACT_COND, gen_q#278)\n\n") + f.write("149 dirs, frozen `edge_parts` length. Contribution is the per-dir mean against a\n" + "paired permuted-feature control, in AUC units. Source: `TOPK_run48frozen.json`.\n\n") + f.write("| k | contrib RSM | contrib idql | gap (idql-RSM) | 95% CI | frac>0 | sign p |\n") + f.write("|---|---|---|---|---|---|---|\n") + for r in rows: + f.write(f"| {r['k']} | {r['contrib_rsm']:+.5f} | {r['contrib_idql']:+.5f} | " + f"{r['gap']:+.5f} | [{r['gap_ci'][0]:+.4f}, {r['gap_ci'][1]:+.4f}] | " + f"{r['gap_frac_pos']:.3f} | {r['gap_sign_p']:.2g} |\n") + f.write(f"\nspearman(k, gap) = {d['C4']['spearman_k_gap']:.3f}. " + f"Ties at the max: {d['tie_structure']['mean_tied_at_max']:.4f} of " + f"{d['tie_structure']['mean_n_cand']:.1f} candidates " + f"(median {d['tie_structure']['median']:.3f}, worst {d['tie_structure']['max']:.3f}).\n") + print("wrote", md) + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/real/actcond_vintage.py b/rsm_rise/scripts/real/actcond_vintage.py new file mode 100644 index 0000000000000000000000000000000000000000..4eed587efab20e6005303e0287391660d5f7107d --- /dev/null +++ b/rsm_rise/scripts/real/actcond_vintage.py @@ -0,0 +1,285 @@ +#!/usr/bin/env python +"""ACT_COND run 44 -- how RELIABLE are the goal-directedness numbers I keep handing out? + +Run 43 proved the two pooling scripts are the SAME ESTIMAND (max |dlift| = 0.000e+00 on every +identically-shaped cell) and that the whole run39->run40 drift was DATA VINTAGE: dirs of the LIVE +edge cache that were still being written while I measured them. Run 43's fresh rescan then moved +the headline AGAIN (rsm argmax +0.00693 -> +0.00563) on only +4 dirs. That leaves two things open, +and this script closes both. CPU only: it reads the two row caches and `edge_parts` MTIMES. + +PRE-REGISTERED in status/real/ACT_COND.md RUN 44, before this ran: + + (P1) NULL CONTROL ON THE RECONCILE TOOL. Decompose run40 -> run43fresh into + (C1) cell set / (C2) cell drift / (C3) script. BOTH scans came from the SAME unmodified + `actcond_readout.py` (only --out differed), so (C3) MUST be 0.000e+00. A non-zero (C3) here + means the reconcile tool itself is broken and run 43's conclusion is void -> EXIT 3. + Run 43 had no such null control; this is it. + + (P2) THE QUOTING RULE. FROZEN = newest `edge_parts/*.npz` mtime is >= --freeze-min minutes before + the scan; FILLING otherwise. Pool the rsm argmax lift on each subset with a per-dir bootstrap + CI. Call: FROZEN lands ABOVE the all-dirs +0.00563, in [+0.006, +0.012]. If it lands BELOW, + I report that and stop claiming filling dirs bias the pool downward. + + (P3) THE PAIRED FORM of run 42 section 5's cross-stream claim. `contrib_fam(d) = lift(fam,d) - + lift(permuted:fam,d)` is defined per dir for BOTH families on the SAME dir, so + contrib_idql(d) - contrib_rsm(d) is PAIRED and must be tested paired, not by eyeballing two + marginal CIs. CI excludes 0 and positive -> the claim stands in its strong form. CI includes + 0 -> the claim was an artefact of comparing two marginal CIs and I retract it. + +Nothing here touches the action-conditioning path: Tasks 1-3 stay closed either way. +""" +import argparse, json, os, sys, glob, time +from pathlib import Path +import numpy as np + +ROOT = "/proj/dmfexp/zwhong/rsm_rise" +sys.path.insert(0, os.path.join(ROOT, "scripts", "real")) +from actcond_goal_directedness import boot_ci, family_of # noqa: E402 run-39 primitives +from actcond_readout_dod import _pick, series, paired, wmean # noqa: E402 run-42 primitives + +TOL = 1e-12 + + +# ---------------------------------------------------------------- (P1) vintage decomposition +def cells(rows): + """-> {(dir, key): dict(n_dec, n_cand, n_mixed, lift)} for the argmax rule.""" + out = {} + for r in rows: + for k, v in r["variants"].items(): + e = v["rules"].get("argmax", {}) + lift = e.get("onroute_lift") + out[(r["dir"], k)] = dict(n_dec=int(v["n_dec"]), n_cand=int(v["n_cand"]), + n_mixed=int(v["n_mixed"]), + lift=(float(lift) if lift is not None else None)) + return out + + +def pooled(cs, fam, only=None): + """decision-weighted pooled argmax lift over cells of family `fam` (run-39 pooling rule).""" + w, x = [], [] + for (d, k), v in cs.items(): + if family_of(k) != fam or v["lift"] is None: + continue + if only is not None and (d, k) not in only: + continue + w.append(v["n_dec"]); x.append(v["lift"]) + if not w: + return None, 0, 0 + w = np.asarray(w, float); x = np.asarray(x, float) + return float((w * x).sum() / w.sum()), len(w), int(w.sum()) + + +def decompose(a, b, fam): + """pooled(b) - pooled(a) split with no residual into cell-set / drift / script.""" + ka, kb = set(a), set(b) + both = ka & kb + same = {k for k in both if (a[k]["n_dec"], a[k]["n_cand"], a[k]["n_mixed"]) + == (b[k]["n_dec"], b[k]["n_cand"], b[k]["n_mixed"])} + drift = both - same + pa, na, da = pooled(a, fam) + pb, nb, db = pooled(b, fam) + # C1: pooled over the SHARED cells only, a-vintage vs a-vintage-restricted + pa_sh, _, _ = pooled(a, fam, only=both) + pb_sh, _, _ = pooled(b, fam, only=both) + c1 = (pa_sh - pa) + (pb - pb_sh) # what the non-shared cells contribute on both sides + c2 = pb_sh - pa_sh # shared cells: drift (same-shape cells contribute 0 + # by construction IF the scripts agree -- (P1)) + worst, worst_cell = 0.0, None + for k in same: + if a[k]["lift"] is None or b[k]["lift"] is None: + continue + dd = abs(b[k]["lift"] - a[k]["lift"]) + if dd > worst: + worst, worst_cell = dd, k + drift_rows = [] + for k in sorted(drift, key=lambda z: -abs((b[z]["lift"] or 0) - (a[z]["lift"] or 0))): + if family_of(k[1]) != fam: + continue + drift_rows.append(dict(dir=k[0], key=k[1], n_dec=[a[k]["n_dec"], b[k]["n_dec"]], + lift=[a[k]["lift"], b[k]["lift"]])) + return dict( + fam=fam, + pooled_a=pa, pooled_b=pb, total=(pb - pa), + n_cells=[na, nb], n_dec=[da, db], + n_cells_all=[len(ka), len(kb)], n_shared=len(both), n_same_shape=len(same), + n_drifted=len(drift), n_only_a=len(ka - kb), n_only_b=len(kb - ka), + C1_cell_set=c1, C2_cell_drift=c2, + C3_script_max_abs_dlift=worst, C3_script_worst_cell=(list(worst_cell) if worst_cell else None), + residual=(pb - pa) - (c1 + c2), + drift_cells=drift_rows[:12], + ) + + +# ---------------------------------------------------------------- (P2) frozen vs filling +def newest_mtime(d): + fs = glob.glob(os.path.join(ROOT, "status", "real", d, "edge_parts", "*.npz")) + return (max(os.path.getmtime(f) for f in fs), len(fs)) if fs else (None, 0) + + +def subset_pool(rows, dirs, fam, perm, boot, seed): + """decision-weighted pooled argmax lift over `dirs`, plus a per-dir bootstrap CI and contrib.""" + v, w, c = [], [], [] + for r in rows: + if r["dir"] not in dirs: + continue + a = _pick(r, fam) + if a is None or a["rules"].get("argmax", {}).get("onroute_lift") is None: + continue + v.append(a["rules"]["argmax"]["onroute_lift"]); w.append(float(a["n_dec"])) + p = _pick(r, perm) + if p is not None and p["rules"].get("argmax", {}).get("onroute_lift") is not None: + c.append(v[-1] - p["rules"]["argmax"]["onroute_lift"]) + if not v: + return dict(n_dirs=0) + v = np.asarray(v, float); w = np.asarray(w, float); c = np.asarray(c, float) + return dict(n_dirs=len(v), n_dec=int(w.sum()), + lift_w=float((v * w).sum() / w.sum()), lift_mean=float(v.mean()), + lift_ci=boot_ci(v, boot, seed), frac_pos=float((v > 0).mean()), + contrib_n=len(c), + contrib_mean=(float(c.mean()) if len(c) else None), + contrib_ci=(boot_ci(c, boot, seed + 1) if len(c) else None)) + + +# ---------------------------------------------------------------- (P3) paired cross-family test +def paired_contrib(rows, boot, seed): + """per-dir contrib_idql(d) - contrib_rsm(d); PAIRED, same dir on both sides.""" + dif, cr, ci_, w, names = [], [], [], [], [] + for r in rows: + got = {} + for fam, perm in (("rsm", "permuted:rsm"), ("idql", "permuted:idql")): + a, p = _pick(r, fam), _pick(r, perm) + if a is None or p is None: + break + xa = a["rules"].get("argmax", {}).get("onroute_lift") + xp = p["rules"].get("argmax", {}).get("onroute_lift") + if xa is None or xp is None: + break + got[fam] = (xa - xp, float(a["n_dec"])) + if len(got) != 2: + continue + cr.append(got["rsm"][0]); ci_.append(got["idql"][0]) + dif.append(got["idql"][0] - got["rsm"][0]); w.append(got["rsm"][1]); names.append(r["dir"]) + d = np.asarray(dif, float); w = np.asarray(w, float) + nz = d[np.abs(d) > 1e-15] + k = int((nz > 0).sum()) + # exact two-sided sign test, p = 2*P(X >= k) under Binom(len(nz), 0.5) + from math import comb + n = len(nz) + tail = sum(comb(n, i) for i in range(min(k, n - k), -1, -1)) / (2.0 ** n) if n else 1.0 + return dict( + n_dirs=len(d), + contrib_rsm_mean=float(np.mean(cr)), contrib_rsm_ci=boot_ci(np.asarray(cr, float), boot, seed), + contrib_idql_mean=float(np.mean(ci_)), contrib_idql_ci=boot_ci(np.asarray(ci_, float), boot, seed + 1), + paired_diff_mean=float(d.mean()), paired_diff_w=wmean(d, w), + paired_diff_ci=boot_ci(d, boot, seed + 2), + frac_pos=float((d > 0).mean()), n_nonzero=n, n_pos=k, + sign_test_p=float(min(1.0, 2.0 * tail)), + ratio_of_means=(float(np.mean(ci_) / np.mean(cr)) if abs(np.mean(cr)) > 1e-12 else None), + ) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--rows_a", default=f"{ROOT}/status/real/ACT_COND/READOUT_run40.rows.json") + ap.add_argument("--rows_b", default=f"{ROOT}/status/real/ACT_COND/READOUT_run43fresh.rows.json") + ap.add_argument("--scan_time_b", default="2026-09-24T19:46:11") + ap.add_argument("--freeze_min", type=float, default=30.0) + ap.add_argument("--boot", type=int, default=4000) + ap.add_argument("--seed", type=int, default=44) + ap.add_argument("--out", default=f"{ROOT}/status/real/ACT_COND/VINTAGE_run44.json") + a = ap.parse_args() + + A = json.load(open(a.rows_a)); B = json.load(open(a.rows_b)) + res = dict(generated=time.strftime("%Y-%m-%dT%H:%M:%S"), rows_a=a.rows_a, rows_b=a.rows_b, + n_rows=[len(A), len(B)], freeze_min=a.freeze_min) + + # ---- (P1) + ca, cb = cells(A), cells(B) + res["P1_decompose"] = {f: decompose(ca, cb, f) for f in ("rsm", "idql")} + bad = [f for f, d in res["P1_decompose"].items() if d["C3_script_max_abs_dlift"] > TOL] + res["P1_null_control_ok"] = (len(bad) == 0) + + # ---- (P2) + t_scan = time.mktime(time.strptime(a.scan_time_b, "%Y-%m-%dT%H:%M:%S")) + cut = t_scan - a.freeze_min * 60.0 + froz, fill, miss, ages = set(), set(), set(), {} + for r in B: + m, n = newest_mtime(r["dir"]) + if m is None: + miss.add(r["dir"]); continue + ages[r["dir"]] = dict(age_min=round((t_scan - m) / 60.0, 1), n_parts=n) + (froz if m <= cut else fill).add(r["dir"]) + res["P2_frozen"] = dict( + n_frozen=len(froz), n_filling=len(fill), n_no_parts=len(miss), + filling_dirs=sorted(fill), + frozen=subset_pool(B, froz, "rsm", "permuted:rsm", a.boot, a.seed), + filling=subset_pool(B, fill, "rsm", "permuted:rsm", a.boot, a.seed + 10), + all_dirs=subset_pool(B, froz | fill | miss, "rsm", "permuted:rsm", a.boot, a.seed + 20), + frozen_idql=subset_pool(B, froz, "idql", "permuted:idql", a.boot, a.seed + 30), + all_idql=subset_pool(B, froz | fill | miss, "idql", "permuted:idql", a.boot, a.seed + 40), + age_min_quantiles={q: float(np.quantile([v["age_min"] for v in ages.values()], q)) + for q in (0.0, 0.25, 0.5, 0.75, 1.0)} if ages else None, + ) + + # ---- (P3) + res["P3_paired"] = paired_contrib(B, a.boot, a.seed + 50) + res["P3_paired_run40cache"] = paired_contrib(A, a.boot, a.seed + 50) + + Path(a.out).parent.mkdir(parents=True, exist_ok=True) + json.dump(res, open(a.out, "w"), indent=1) + + # ------------------------------------------------------------------ report + print("== (P1) VINTAGE DECOMPOSITION run40.rows -> run43fresh.rows (SAME script, null control)") + for f, d in res["P1_decompose"].items(): + print(" %-5s pooled %+.6f -> %+.6f total %+.7f cells %d->%d dec %d->%d" + % (f, d["pooled_a"], d["pooled_b"], d["total"], d["n_cells"][0], d["n_cells"][1], + d["n_dec"][0], d["n_dec"][1])) + print(" (C1) cell set %+.7f (C2) drift %+.7f residual %+.1e" + % (d["C1_cell_set"], d["C2_cell_drift"], d["residual"])) + print(" (C3) SCRIPT max |dlift| on %d identically-shaped cells = %.3e [%s]" + % (d["n_same_shape"], d["C3_script_max_abs_dlift"], + "PASS" if d["C3_script_max_abs_dlift"] <= TOL else "FAIL")) + print(" cells only in a: %d only in b: %d drifted: %d" + % (d["n_only_a"], d["n_only_b"], d["n_drifted"])) + for r in d["drift_cells"][:6]: + print(" %-34s %-16s n_dec %5d -> %5d lift %+.4f -> %+.4f" + % (r["dir"], r["key"], r["n_dec"][0], r["n_dec"][1], + (r["lift"][0] if r["lift"][0] is not None else float('nan')), + (r["lift"][1] if r["lift"][1] is not None else float('nan')))) + print("\n== (P2) FROZEN (last edge_parts write >= %.0f min before the scan) vs FILLING" + % a.freeze_min) + p2 = res["P2_frozen"] + print(" n_frozen %d n_filling %d n_no_parts %d age_min quantiles %s" + % (p2["n_frozen"], p2["n_filling"], p2["n_no_parts"], p2["age_min_quantiles"])) + for nm in ("frozen", "filling", "all_dirs", "frozen_idql", "all_idql"): + s = p2[nm] + if not s.get("n_dirs"): + print(" %-12s (empty)" % nm); continue + print(" %-12s n=%3d dec=%6d lift_w %+.5f mean %+.5f CI[%+.5f,%+.5f] fpos %.2f contrib %s" + % (nm, s["n_dirs"], s["n_dec"], s["lift_w"], s["lift_mean"], s["lift_ci"][0], + s["lift_ci"][1], s["frac_pos"], + ("%+.5f CI[%+.5f,%+.5f]" % (s["contrib_mean"], s["contrib_ci"][0], s["contrib_ci"][1])) + if s.get("contrib_mean") is not None else "-")) + if p2["filling_dirs"]: + print(" filling: " + ", ".join(p2["filling_dirs"][:10]) + + (" ..." if len(p2["filling_dirs"]) > 10 else "")) + print("\n== (P3) PAIRED contrib_argmax: idql(d) - rsm(d), same dir") + for nm in ("P3_paired", "P3_paired_run40cache"): + p = res[nm] + print(" %-22s n=%d rsm %+.5f CI[%+.5f,%+.5f] idql %+.5f CI[%+.5f,%+.5f]" + % (nm, p["n_dirs"], p["contrib_rsm_mean"], p["contrib_rsm_ci"][0], p["contrib_rsm_ci"][1], + p["contrib_idql_mean"], p["contrib_idql_ci"][0], p["contrib_idql_ci"][1])) + print(" %-22s PAIRED diff %+.5f CI[%+.5f,%+.5f] fpos %.3f sign-test p=%.2e ratio %.2fx" + % ("", p["paired_diff_mean"], p["paired_diff_ci"][0], p["paired_diff_ci"][1], + p["frac_pos"], p["sign_test_p"], + p["ratio_of_means"] if p["ratio_of_means"] else float('nan'))) + print("\nwrote", a.out) + if not res["P1_null_control_ok"]: + print("FAIL: (P1) null control violated for %s -- the reconcile tool is not trustworthy " + "and run 43's conclusion must be re-opened." % bad) + sys.exit(3) + print("(P1) null control PASSES: same script, same numbers, to the last bit.") + + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/real/add_hdf5_attrs.py b/rsm_rise/scripts/real/add_hdf5_attrs.py new file mode 100644 index 0000000000000000000000000000000000000000..e748d52cb5a26ab8d0dbbae61f7cda4778db4c2e --- /dev/null +++ b/rsm_rise/scripts/real/add_hdf5_attrs.py @@ -0,0 +1,16 @@ +#!/usr/bin/env python +"""Add the provenance attrs the sim stack reads (create_model_metadata: data.attrs['dataset_id']) to the cooking hdf5s.""" +import h5py, uuid, json, sys +ROOT = "/proj/dmfexp/zwhong/rsm_rise" +files = sys.argv[1:] or [f"{ROOT}/data/raw/cooking_v5_expert_suboptimal.hdf5", + f"{ROOT}/data/derived/cooking_v5_expert_suboptimal_expert.hdf5", + f"{ROOT}/data/derived/cooking_v5_expert_suboptimal_suboptimal.hdf5"] +for p in files: + with h5py.File(p, "r+") as f: + a = f["data"].attrs + if "dataset_id" not in a: + a["dataset_id"] = str(uuid.uuid5(uuid.NAMESPACE_URL, "rsm_rise/" + p.split("/")[-1])) + a.setdefault("env_name", json.dumps(["RSMCookingReal"])); a.setdefault("env_type", json.dumps(["real"])) + a.setdefault("dataset_type", json.dumps(["play"])); a.setdefault("creator", json.dumps(["jmarangola"])) + a.setdefault("is_test", json.dumps([False])) + print(p, "dataset_id =", a["dataset_id"], "n_demos", len(f["data"])) diff --git a/rsm_rise/scripts/real/add_segment_labels.py b/rsm_rise/scripts/real/add_segment_labels.py new file mode 100644 index 0000000000000000000000000000000000000000..9363d0527b587492792e7fbf2bbf227f59ad60f5 --- /dev/null +++ b/rsm_rise/scripts/real/add_segment_labels.py @@ -0,0 +1,71 @@ +#!/usr/bin/env python +"""Add PER-FRAME segment/edge labels to the real cache, and report segment-length structure. + +The cache builder stores only per-episode route/segment counts. The successor-model sanity check +needs per-FRAME segment ids so NN-L1 can be split into "same segment" vs "a later segment" +(= across a subgoal/stitch boundary). Written as extra files so the existing cache is untouched: + seg.i16.npy [N] int16 annotation.segment_index + edge_from.i16.npy [N] int16 annotation.edge_from + edge_to.i16.npy [N] int16 annotation.edge_to + SEGMENTS.json per-route / per-segment length statistics +""" +import json +from pathlib import Path +from collections import defaultdict +import numpy as np +import pyarrow.parquet as pq + +ROOT = Path("/proj/dmfexp/zwhong/rsm_rise/data/real/rsm_cooking_v5") +CACHE = Path("/proj/dmfexp/zwhong/rsm_rise/cache/real_cooking_v5") +info = json.loads((ROOT / "meta/info.json").read_text()) +n_ep, cs, dp = int(info["total_episodes"]), int(info["chunks_size"]), info["data_path"] + +seg, ef, et, lens, routes = [], [], [], [], [] +seglen = defaultdict(list) # (route, segment) -> lengths +edgelen = defaultdict(list) # (from,to) -> lengths +for i in range(n_ep): + t = pq.read_table(ROOT / dp.format(episode_chunk=i // cs, episode_index=i), + columns=["annotation.segment_index", "annotation.edge_from", + "annotation.edge_to", "annotation.route_index"]).to_pandas() + s = np.asarray(t["annotation.segment_index"], np.int64).ravel() + a = np.asarray(t["annotation.edge_from"], np.int64).ravel() + b = np.asarray(t["annotation.edge_to"], np.int64).ravel() + r = int(np.asarray(t["annotation.route_index"]).ravel()[0]) + seg.append(s.astype(np.int16)); ef.append(a.astype(np.int16)); et.append(b.astype(np.int16)) + lens.append(len(s)); routes.append(r) + for v in np.unique(s): + seglen[(r, int(v))].append(int((s == v).sum())) + for k in dict.fromkeys(zip(a.tolist(), b.tolist())): + m = (a == k[0]) & (b == k[1]) + edgelen[k].append(int(m.sum())) + +seg = np.concatenate(seg); ef = np.concatenate(ef); et = np.concatenate(et) +N = len(seg) +m = np.load(CACHE / "meta.npz", allow_pickle=True) +assert int(m["n_frames"]) == N, (int(m["n_frames"]), N) +assert (np.asarray(lens) == m["ep_len"]).all(), "episode lengths disagree with the cache" +np.save(CACHE / "seg.i16.npy", seg) +np.save(CACHE / "edge_from.i16.npy", ef) +np.save(CACHE / "edge_to.i16.npy", et) +print(f"[seg] wrote per-frame labels for {N} frames, {n_ep} episodes") + +rep = {"per_route_segment": {}, "per_edge": {}} +print("\n[seg] SEGMENT LENGTHS (rows), by route and segment index:") +for (r, s_), v in sorted(seglen.items()): + v = np.asarray(v) + rep["per_route_segment"][f"route{r}_seg{s_}"] = { + "n_eps": len(v), "min": int(v.min()), "median": float(np.median(v)), + "max": int(v.max()), "mean": float(v.mean())} + print(f"[seg] route {r} seg {s_}: n={len(v):3d} min={v.min():5d} " + f"median={np.median(v):7.1f} max={v.max():5d}") +print("\n[seg] SEGMENT LENGTHS by directed edge (this is the unit one successor hop would have to span):") +for k, v in sorted(edgelen.items()): + v = np.asarray(v) + rep["per_edge"][f"{k[0]}->{k[1]}"] = { + "n_eps": len(v), "min": int(v.min()), "median": float(np.median(v)), + "max": int(v.max()), "mean": float(v.mean())} + print(f"[seg] {k[0]}->{k[1]}: n={len(v):3d} min={v.min():5d} median={np.median(v):7.1f} " + f"max={v.max():5d} -> beta needed to span the median in ONE hop at eps=0.02: " + f"{np.exp(np.log(0.02)/np.median(v)):.4f}") +(CACHE / "SEGMENTS.json").write_text(json.dumps(rep, indent=2)) +print(f"\n[seg] wrote {CACHE/'SEGMENTS.json'}") diff --git a/rsm_rise/scripts/real/anchor_clamp_census.py b/rsm_rise/scripts/real/anchor_clamp_census.py new file mode 100644 index 0000000000000000000000000000000000000000..6ce787ffb02fac1ec86500c068e195bfab46e850 --- /dev/null +++ b/rsm_rise/scripts/real/anchor_clamp_census.py @@ -0,0 +1,83 @@ +"""SUCC_DEBUG run 10: the BRACKET-VALIDITY census for every per-hop column in hop_bearing.py / +chain_reach.py. + +Both scripts take the logged reference frame at nominal time t_h = min(t_anchor + h/(1-beta), t_goal). +The `min` is a CLAMP: once h/(1-beta) exceeds the anchor-to-goal span, t_h stops advancing, so + * STAY_step(h) = ||zL_{h-1} - zL_h|| -> 0 and any ratio against it diverges, + * the logged step direction is the zero vector and cos_step -> 0 by construction, not by fact. +That is exactly what the beta=0.99 rows show at h>=12 (ratios ~3e8, cos 0.000). A column is only a +measurement where the clamp has not bitten, so this prints, per beta and hop, the fraction of anchors +whose logged reference frame has stopped moving. Read every per-hop number with this table next to +it. No model is loaded; this is anchor arithmetic only. +""" +import argparse, json, os, sys +import numpy as np + +RSM = "/proj/dmfexp/zwhong/projs/issue_resolver_richardrl/gen_q_rsm/rsm_libero" +ROOT = "/proj/dmfexp/zwhong/rsm_rise" +sys.path.insert(0, RSM) +GOAL_PATH = "2->3->4" +HOP_GRID = [1, 2, 4, 8, 12, 16] + +ap = argparse.ArgumentParser() +ap.add_argument("--cache", default=f"{ROOT}/cache/real_cooking_v5") +ap.add_argument("--hdf5", default=f"{ROOT}/data/raw/cooking_v5_expert_suboptimal.hdf5") +ap.add_argument("--betas", default="0.95,0.99") +ap.add_argument("--anchors", type=int, default=200) +ap.add_argument("--max-hops", type=int, default=16) +ap.add_argument("--eval-seed", type=int, default=1234) +ap.add_argument("--out", required=True) +a = ap.parse_args() + +import h5py +from data import LiberoRSMData + +d = LiberoRSMData(a.cache, chunk=8, k_success=10, seed=0, stratify_success=False, + in_ram=False, reward_mode="dense") +tr = set(int(x) for x in d.train_eps) +_meta = np.load(os.path.join(a.cache, "meta.npz"), allow_pickle=True) +src2ep = {str(s): i for i, s in enumerate(_meta["ep_src"])} +eps_l = [] +with h5py.File(a.hdf5, "r") as f: + g = f["data"] + for k in g: + if str(g[k].attrs.get("path", "")) != GOAL_PATH: + continue + ei = int(g[k].attrs["episode_index"]) + e = src2ep.get(f"episode_{ei:06d}") + if e is None or e not in tr: + continue + ef = g[k]["annot"]["edge_from"][()] + lo, hi = int(d.ep_from[e]), int(d.ep_to[e]) + n = min(len(ef), hi - lo) + i2 = np.where(ef[:n] == 2)[0]; i3 = np.where(ef[:n] == 3)[0] + if len(i2) < 8 or len(i3) < 1: + continue + eps_l.append({"ep": e, "s2": lo + i2, "s3_entry": lo + int(i3[0]), "s4": hi - 1}) + +rng = np.random.default_rng(a.eval_seed) # SAME construction/seed as hop_bearing.py +res = {"n_goal_train_eps": len(eps_l), "anchors": a.anchors, "hop_grid": HOP_GRID, "betas": {}} +print(f"{len(eps_l)} train goal-route episodes") +print("frac of anchors whose LOGGED reference frame has stopped advancing (clamped at the goal).") +print("A per-hop column is a measurement only where this is small; at 1.000 the bracket is zero and") +print("every ratio/cosine against it is an artifact.") +print(f"{'beta':>6}{'hop_f':>7}{'span_med':>10} | " + "".join(f"h{h:<6}" for h in HOP_GRID)) +for beta in [float(x) for x in a.betas.split(",")]: + hop = 1.0 / (1.0 - beta) + an = [eps_l[int(rng.integers(len(eps_l)))] for _ in range(a.anchors)] + at = np.array([x["s2"][int(rng.integers(len(x["s2"])))] for x in an], np.int64) + a4 = np.array([x["s4"] for x in an], np.int64) + span = a4 - at + row = {} + for h in HOP_GRID: + th1 = np.minimum(at + int(round((h - 1) * hop)), a4) + th = np.minimum(at + int(round(h * hop)), a4) + row[str(h)] = {"frac_step_clamped": float(np.mean(th == th1)), + "frac_past_goal": float(np.mean(at + h * hop >= a4))} + res["betas"][str(beta)] = {"hop_frames": hop, "span_median": float(np.median(span)), + "span_mean": float(np.mean(span)), "per_hop": row} + print(f"{beta:>6}{hop:>7.0f}{np.median(span):>10.0f} | " + + "".join(f"{row[str(h)]['frac_step_clamped']:<7.3f}" for h in HOP_GRID)) +tmp = a.out + f".tmp.{os.getpid()}" +json.dump(res, open(tmp, "w"), indent=1); os.replace(tmp, a.out) +print(f"wrote {a.out}") diff --git a/rsm_rise/scripts/real/anchor_consistency.py b/rsm_rise/scripts/real/anchor_consistency.py new file mode 100644 index 0000000000000000000000000000000000000000..f6d26e305d1851bc69a0d8bd22fe8e351f4f8590 --- /dev/null +++ b/rsm_rise/scripts/real/anchor_consistency.py @@ -0,0 +1,297 @@ +#!/usr/bin/env python +"""AUG_SUCC (gen_q#279) run 21: DOES THE AUGMENTATION HAVE A REPRODUCIBLE PER-ANCHOR SIGNAL? + +Run 20 established the two facts this script exists to reconcile: + * paired delta vs the un-augmented baseline is positive on every seed (pooled +0.277 +- 0.074), + so the augmentation RELIABLY moves the model off the anti-goal pathology; + * pooled frac(goal rank pct > 0.5) = 0.486 +- 0.124, i.e. AT CHANCE, so it does NOT install + goal-direction. The per-seed gates scatter widely (0.585 / 0.372 / 0.378 / ...). + +Those two are compatible with two very different worlds, and the stream's next GPU spend depends +entirely on which one we are in: + + WORLD A -- REAL BUT MIS-CENTRED. The augmentation reproducibly ranks the SAME anchors high and + the SAME anchors low; the seeds differ only in overall level. Then there IS goal-direction + signal in the augmentation, it is simply not strong enough to push the average past 0.5, and + amplifying it (augmented fraction, threshold, longer training) is a reasonable bet. Seed + averaging is then a legitimate estimator rather than an averaging-away of noise. + + WORLD B -- TRAINING NOISE. Which anchors come out above 0.5 is re-drawn by each seed. Then no + threshold search and no extra seed will help, because there is nothing to amplify, and the + honest conclusion is that the reverse anchor needs the conditioning path (ACT_COND) or genuine + on-policy counterfactuals rather than any re-labelling of the existing corpus. + +THE STATISTIC. M is (n_anchors x n_seeds) of the goal chunk's rank percentile. Consistency is the +mean PAIRWISE correlation between seed columns (Pearson and Spearman, all C(n,2) pairs). + +THE NULL IS THE WHOLE POINT, and it is NOT r=0. 37 anchors sit in only 5 episodes, and anchors +inside one episode share a state, so ANY two models that are merely both on-manifold will agree at +the episode level and manufacture a large positive r that has nothing to do with the augmentation. +So the null here is an EPISODE-BLOCKED permutation: within each seed column, permute the anchors +WITHIN their own episode, which destroys anchor-level agreement while preserving every episode-level +effect exactly. p is the fraction of permutations whose mean pairwise r reaches the observed one. +Reported alongside: the same correlation on the EPISODE-DEMEANED matrix (each episode's mean removed +per seed), which is the episode-free effect size, and a variance decomposition of M. + +Pooling is refused unless the seeds are proved to have been scored on identical candidates, by the +same deterministic scores_bc/scores_pose bit-identity test the aggregate tool uses. + +--selftest runs the tool on constructed matrices with known answers and exits. +""" +import argparse, json, os, sys +import numpy as np +from scipy import stats + +ROOT = "/proj/dmfexp/zwhong/rsm_rise" +RK = f"{ROOT}/status/real/rankctrl" + + +def rank_pct(S, col=0): + tgt = S[:, col] + oth = np.delete(S, col, axis=1) + return ((oth < tgt[:, None]).sum(1) + 0.5 * (oth == tgt[:, None]).sum(1)) / oth.shape[1] + + +def cands_match(za, zb): + ok, seen = True, [] + for k in ("scores_bc", "scores_pose"): + if k in za.keys() and k in zb.keys(): + A, B = np.asarray(za[k]), np.asarray(zb[k]) + if A.shape != B.shape or not np.allclose(A, B): + ok = False + seen.append(k) + return (ok and bool(seen)), seen + + +def mean_pairwise(M, kind="pearson"): + """mean correlation over all C(n_seeds,2) column pairs. A column with zero variance makes its + pairs undefined; those pairs are dropped and counted rather than silently becoming nan.""" + n = M.shape[1] + vals, dropped = [], 0 + for i in range(n): + for j in range(i + 1, n): + a, b = M[:, i], M[:, j] + if a.std() < 1e-12 or b.std() < 1e-12: + dropped += 1 + continue + r = stats.pearsonr(a, b)[0] if kind == "pearson" else stats.spearmanr(a, b)[0] + if not np.isfinite(r): + dropped += 1 + continue + vals.append(float(r)) + if not vals: + return float("nan"), 0, dropped + return float(np.mean(vals)), len(vals), dropped + + +def episode_demean(M, ep): + D = M.astype(float).copy() + for e in np.unique(ep): + m = ep == e + D[m] -= D[m].mean(0, keepdims=True) + return D + + +def blocked_perm_null(M, ep, kind="pearson", n=2000, seed=0): + """permute anchors WITHIN episode, independently per seed column.""" + rng = np.random.default_rng(seed) + groups = [np.where(ep == e)[0] for e in np.unique(ep)] + out = np.empty(n) + for b in range(n): + P = np.empty_like(M, dtype=float) + for g in groups: + for c in range(M.shape[1]): + P[g, c] = M[rng.permutation(g), c] + out[b] = mean_pairwise(P, kind)[0] + return out + + +def analyse(M, ep, tag, nperm, out): + res = {} + for kind in ("pearson", "spearman"): + r, npairs, dropped = mean_pairwise(M, kind) + null = blocked_perm_null(M, ep, kind, n=nperm) + null = null[np.isfinite(null)] + p = float((null >= r).mean()) if null.size else float("nan") + nm, ns = float(null.mean()), float(null.std()) + sig = (r - nm) / ns if ns > 0 else float("nan") + res[kind] = dict(r=r, n_pairs=npairs, dropped_pairs=dropped, + null_mean=nm, null_sd=ns, sigma_vs_null=float(sig), p_ge=p) + print(f"[{tag}] mean pairwise {kind:8s} r = {r:+.4f} " + f"episode-blocked null {nm:+.4f} +-{ns:.4f} " + f"({sig:+.2f} sigma, p(null>=obs) = {p:.4f}) pairs={npairs} dropped={dropped}") + out[tag] = res + return res + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--base-cell", default="JUNC_feat_t45_c0p5") + ap.add_argument("--seeds", nargs="+", type=int, default=[0, 1, 2, 3, 4]) + ap.add_argument("--cells", nargs="+", default=[], + help="explicit cell names, INSTEAD of base_cell+seeds. Use this to ask the " + "cross-THRESHOLD version of the same question (do t42.5/t45/t50/t55 at one " + "seed agree about which anchors are goal-ranked?). The columns are then " + "thresholds rather than seeds and every printed label reads accordingly; " + "the statistic, the episode-blocked null and the candidate-alignment " + "refusal are all unchanged.") + ap.add_argument("--suffix", default="val31") + ap.add_argument("--nperm", type=int, default=2000) + ap.add_argument("--out", default=f"{ROOT}/status/real/augsucc/t45_anchor_consistency.json") + ap.add_argument("--selftest", action="store_true") + a = ap.parse_args() + + if a.selftest: + return selftest(a.nperm) + + per_seed, missing = [], [] + cells = a.cells if a.cells else [f"{a.base_cell}_s{s}" for s in a.seeds] + labels = a.cells if a.cells else a.seeds + for s, cell in zip(labels, cells): + p = f"{RK}/{cell}__R{a.suffix}/per_anchor.npz" + if not os.path.exists(p): + missing.append(cell); continue + z = np.load(p, allow_pickle=True) + per_seed.append(dict(seed=s, cell=cell, z=z, gv=rank_pct(z["scores_rsm"], 0), ep=z["ep"])) + out = dict(base_cell=a.base_cell, seeds=[d["seed"] for d in per_seed], + missing=missing, nperm=a.nperm) + if missing: + print(f"[warn] missing cells (partial read): {missing}") + if len(per_seed) < 2: + print("[refused] fewer than 2 seeds present; consistency is undefined") + out["refused"] = "fewer than 2 seeds" + json.dump(out, open(a.out, "w"), indent=2); return 0 + + ref = per_seed[0] + ok = True; bad = [] + for d in per_seed[1:]: + if not np.array_equal(d["ep"], ref["ep"]): + ok = False; bad.append((d["cell"], "ep")); continue + m, seen = cands_match(d["z"], ref["z"]) + if not (m and seen): + ok = False; bad.append((d["cell"], "cands")) + out["cands_aligned_across_seeds"] = bool(ok); out["misaligned"] = bad + if not ok: + print(f"[refused] seeds not scored on identical candidates: {bad}") + out["refused"] = "candidates not aligned" + json.dump(out, open(a.out, "w"), indent=2); return 0 + + ep = ref["ep"] + M = np.stack([d["gv"] for d in per_seed], axis=1) + out["n_anchors"], out["n_seeds"] = int(M.shape[0]), int(M.shape[1]) + out["per_seed_gate"] = [float(x) for x in M.mean(0)] + print(f"[data] M = {M.shape[0]} anchors x {M.shape[1]} seeds over " + f"{len(np.unique(ep))} episodes; per-seed gates " + + " ".join(f"{x:.3f}" for x in M.mean(0))) + + analyse(M, ep, "raw", a.nperm, out) + analyse(episode_demean(M, ep), ep, "episode_demeaned", a.nperm, out) + + # variance decomposition: how much of M's spread is anchor identity vs seed re-draw? + gm = M.mean() + v_anchor = float(((M.mean(1) - gm) ** 2).mean()) + v_seed = float(((M.mean(0) - gm) ** 2).mean()) + v_resid = float(((M - M.mean(1, keepdims=True) - M.mean(0, keepdims=True) + gm) ** 2).mean()) + tot = v_anchor + v_seed + v_resid + out["variance"] = dict(anchor=v_anchor, seed=v_seed, resid=v_resid, + anchor_frac=v_anchor / tot, seed_frac=v_seed / tot, + resid_frac=v_resid / tot) + print(f"[var] anchor {v_anchor:.4f} ({v_anchor/tot:.1%}) seed {v_seed:.4f} ({v_seed/tot:.1%}) " + f"resid {v_resid:.4f} ({v_resid/tot:.1%})") + + # sign stability: on how many anchors do ALL seeds agree about being above/below 0.5? + above = (M > 0.5) + unan = float(((above.all(1)) | (~above).all(1)).mean()) + exp_unan = float(np.mean([p ** M.shape[1] + (1 - p) ** M.shape[1] for p in above.mean(0)])) + out["sign"] = dict(unanimous_frac=unan, independent_expectation=exp_unan, + n_unanimous_above=int(above.all(1).sum()), + n_unanimous_below=int((~above).all(1).sum())) + print(f"[sign] anchors where ALL {M.shape[1]} seeds agree on >0.5: {unan:.3f} " + f"({out['sign']['n_unanimous_above']} above / {out['sign']['n_unanimous_below']} below " + f"of {M.shape[0]}); expectation if seeds were independent = {exp_unan:.3f}") + + # ---- THE INTERPRETATION OF A HIGH r: is the reproducible anchor structure NEW information, + # or is it the same on-manifold plausibility the stream diagnosed at the start? scores_pose is + # the ZERO-PARAMETER pose-continuity score on the SAME anchors and the SAME candidates, and it is + # deterministic (identical in every seed), so it carries no training noise at all. If the + # seed-averaged RSM per-anchor gate tracks the pose per-anchor gate, then the augmentation + # re-centred the score but created nothing the zero-parameter baseline did not already have. + # This reuses mean_pairwise/blocked_perm_null on a 2-column matrix -- the same code path the + # selftest covers -- rather than introducing a second correlation implementation. + if "scores_pose" in ref["z"].keys(): + pose_gate = rank_pct(np.asarray(ref["z"]["scores_pose"]), 0) + M2 = np.stack([M.mean(1), pose_gate], axis=1) + print("[confound] seed-averaged RSM per-anchor gate vs the ZERO-PARAMETER pose gate, " + "same anchors and candidates:") + analyse(M2, ep, "rsm_vs_pose", a.nperm, out) + analyse(episode_demean(M2, ep), ep, "rsm_vs_pose_episode_demeaned", a.nperm, out) + out["pose_gate_mean"] = float(pose_gate.mean()) + + json.dump(out, open(a.out, "w"), indent=2) + print(f"[out] {a.out}") + return 0 + + +def selftest(nperm): + """constructed matrices with KNOWN answers, run before the tool ever touches real data.""" + rng = np.random.default_rng(0) + ep = np.repeat(np.arange(5), 8)[:37] if False else np.repeat(np.arange(5), 8)[:40][:37] + ep = np.array(sorted(ep)) + n = len(ep) + fails = [] + + def chk(name, cond, detail): + print((" PASS " if cond else " FAIL ") + name + " " + detail) + if not cond: + fails.append(name) + + print("== T1: identical columns (perfect consistency) ==") + base = rng.random(n) + M = np.stack([base, base, base], 1) + r, _, _ = mean_pairwise(M) + chk("T1 r == 1", abs(r - 1.0) < 1e-9, f"r={r:.6f}") + + print("== T2: independent columns, NO episode structure -> r at the null, p large ==") + M = rng.random((n, 3)) + r, _, _ = mean_pairwise(M) + null = blocked_perm_null(M, ep, "pearson", n=nperm) + p = float((null >= r).mean()) + chk("T2 |r| small", abs(r) < 0.35, f"r={r:+.4f}") + chk("T2 p not significant", p > 0.05, f"p={p:.4f}") + + print("== T3: PURE episode structure, no anchor agreement -> null ABSORBS it, p large ==") + off = rng.random(5) * 2.0 + M = np.stack([off[ep] + rng.normal(0, .05, n) for _ in range(3)], 1) + r, _, _ = mean_pairwise(M) + null = blocked_perm_null(M, ep, "pearson", n=nperm) + p = float((null >= r).mean()) + chk("T3 raw r large (episode effect)", r > 0.8, f"r={r:+.4f}") + chk("T3 blocked null ALSO large", null.mean() > 0.8, f"null={null.mean():+.4f}") + chk("T3 p NOT significant", p > 0.05, f"p={p:.4f} <- this is the test that matters") + + print("== T4: genuine ANCHOR agreement on top of episode structure -> p significant ==") + anc = rng.normal(0, 1.0, n) + M = np.stack([off[ep] + anc + rng.normal(0, .05, n) for _ in range(3)], 1) + r, _, _ = mean_pairwise(M) + null = blocked_perm_null(M, ep, "pearson", n=nperm) + p = float((null >= r).mean()) + chk("T4 p significant", p < 0.01, f"r={r:+.4f} null={null.mean():+.4f} p={p:.4f}") + + print("== T5: episode-demeaning removes a pure episode effect ==") + M = np.stack([off[ep] + rng.normal(0, .05, n) for _ in range(3)], 1) + D = episode_demean(M, ep) + chk("T5 demeaned episode means ~0", abs(np.array([D[ep == e].mean() for e in np.unique(ep)])).max() < 1e-12, + "max |episode mean| < 1e-12") + + print("== T6: variance decomposition on a known matrix ==") + M = np.stack([anc, anc, anc], 1) # all variance is anchor, none seed + gm = M.mean() + v_a = ((M.mean(1) - gm) ** 2).mean(); v_s = ((M.mean(0) - gm) ** 2).mean() + chk("T6 seed variance == 0", v_s < 1e-20, f"v_anchor={v_a:.4f} v_seed={v_s:.3e}") + + print("\nSELFTEST " + ("PASSED" if not fails else f"FAILED: {fails}")) + return 0 if not fails else 1 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/rsm_rise/scripts/real/anchor_coverage.py b/rsm_rise/scripts/real/anchor_coverage.py new file mode 100644 index 0000000000000000000000000000000000000000..b0c81ab95bdc495028d9011f3392a25128fa3b8d --- /dev/null +++ b/rsm_rise/scripts/real/anchor_coverage.py @@ -0,0 +1,311 @@ +#!/usr/bin/env python +"""AUG_SUCC (gen_q#279) run 22: WHAT MAKES A GOOD ANCHOR, AND WERE THESE ANCHORS EVEN HELD OUT? + +Run 21 established WORLD A: the junction augmentation's per-anchor ordering on the reverse-anchor +gate is reproducible across seeds at episode-demeaned r = +0.768 (77% of all variance is anchor +identity, 5.3% is the seed), and ~42% of that reproducible signal is shared with the ZERO-PARAMETER +pose-continuity score. The gate fails because a reproducible ordering is centred on chance. + +Two questions follow, and this tool answers both in one pass. + +(A) THE SPLIT AUDIT -- unplanned, and it came first because it changes how (B) reads. + The ranking harness picks its "validation" anchors from data/derived/cooking_v5_split.json. + The RSM trainer (rsm_libero/data.py) builds its OWN split from np.random.default_rng(seed) with + val_frac=0.1, and build_junction_pairs.py reproduces that same seeded split (data.py's guard at + data.py:199 refuses a table built on any other one, so the table's train_eps IS the run's). + Those two splits are not the same object. This audit reports, per seed, how many of the + harness's validation episodes -- and specifically the 5 reverse-anchor episodes -- were TRAIN + episodes for the model being scored, and how many of the 37 anchors' own cache rows appear in + that seed's junction table as augmentation anchors. + +(B) THE COVERAGE READ. For each of the 37 reverse anchors, its augmentation DOSE: the number of + cross-route S2 partners within the trained threshold (45.0 in the feat metric), split by the + partner's route, plus the distance to the nearest goal-route S2 frame. Then: does the dose + predict the anchor's seed-averaged goal rank percentile? + * if YES and positive, coverage is the lever and densifying pairs is justified GPU spend; + * if NO, the reproducible per-anchor ordering is not delivered by local augmentation support, + and threshold/coverage search is not justified. + Controlled for the pose confound by partialling out the deterministic per-anchor pose gate, + because run 21 showed pose is the single largest identified component of that ordering. + +THE NULL is the same episode-blocked permutation run 21's selftest proved sound: 37 anchors sit in +5 episodes, so any two episode-level quantities manufacture a large r. Permuting anchors WITHIN +their own episode destroys anchor-level agreement while preserving every episode effect exactly. + +--selftest runs the statistics on constructed data with known answers and exits. +""" +import argparse, json, os, sys +import numpy as np +from scipy import stats + +ROOT = "/proj/dmfexp/zwhong/rsm_rise" +RK = f"{ROOT}/status/real/rankctrl" +GOAL_ROUTE = "2->3->4" +FAIL_ROUTE = "0->2->6" + + +def rank_pct(S, col=0): + tgt = S[:, col] + oth = np.delete(S, col, axis=1) + return ((oth < tgt[:, None]).sum(1) + 0.5 * (oth == tgt[:, None]).sum(1)) / oth.shape[1] + + +def episode_demean(v, ep): + v = np.asarray(v, float).copy() + for e in np.unique(ep): + m = ep == e + v[m] -= v[m].mean() + return v + + +def corr(x, y, kind): + if np.std(x) < 1e-12 or np.std(y) < 1e-12: + return float("nan") + r = stats.pearsonr(x, y)[0] if kind == "pearson" else stats.spearmanr(x, y)[0] + return float(r) if np.isfinite(r) else float("nan") + + +def partial(x, y, z): + """partial correlation of x,y given z (residualise both on z by OLS, then Pearson).""" + Z = np.column_stack([np.ones_like(z), z]) + rx = x - Z @ np.linalg.lstsq(Z, x, rcond=None)[0] + ry = y - Z @ np.linalg.lstsq(Z, y, rcond=None)[0] + return corr(rx, ry, "pearson") + + +def blocked_null(x, y, ep, kind="spearman", n=4000, seed=0): + """permute x WITHIN episode; y and the episode structure are untouched.""" + rng = np.random.default_rng(seed) + groups = [np.where(ep == e)[0] for e in np.unique(ep)] + out = np.empty(n) + for b in range(n): + xp = x.copy() + for g in groups: + xp[g] = x[rng.permutation(g)] + out[b] = corr(xp, y, kind) + return out[np.isfinite(out)] + + +def report(x, y, ep, tag, kind, nperm, out, two_sided=True): + r = corr(x, y, kind) + null = blocked_null(x, y, ep, kind, n=nperm) + nm, ns = float(null.mean()), float(null.std()) + sig = (r - nm) / ns if ns > 0 else float("nan") + p_hi = float((null >= r).mean()) if null.size else float("nan") + p_lo = float((null <= r).mean()) if null.size else float("nan") + p = min(1.0, 2 * min(p_hi, p_lo)) if two_sided else p_hi + out[tag] = dict(kind=kind, r=r, null_mean=nm, null_sd=ns, sigma=float(sig), + p_two_sided=p, p_ge=p_hi, n=int(len(x))) + print(f"[{tag:34s}] {kind:8s} r = {r:+.4f} blocked null {nm:+.4f} +-{ns:.4f} " + f"({sig:+.2f} sigma, p2 = {p:.4f})") + return r, p + + +# ----------------------------------------------------------------------------- selftest +def selftest(nperm): + print("=== SELFTEST (constructed data, known answers) ===") + rng = np.random.default_rng(7) + n_ep, per = 5, 8 + ep = np.repeat(np.arange(n_ep), per) + n = len(ep) + ok = True + + def chk(name, cond, detail=""): + nonlocal ok + print(f" [{'PASS' if cond else 'FAIL'}] {name} {detail}") + ok &= bool(cond) + + # T1 identical -> r = 1, and the blocked null cannot reach it + x = rng.normal(size=n); o = {} + r, p = report(x, x, ep, "T1_identical", "spearman", nperm, o) + chk("T1 identical -> r=1, p small", abs(r - 1) < 1e-9 and p < 0.01, f"r={r:.3f} p={p:.4f}") + + # T2 independent -> not significant + y = rng.normal(size=n); o = {} + r, p = report(x, y, ep, "T2_independent", "spearman", nperm, o) + chk("T2 independent -> p not significant", p > 0.05, f"r={r:.3f} p={p:.4f}") + + # T3 PURE EPISODE STRUCTURE in both: raw r is large, and the blocked null must ABSORB it + epval = rng.normal(size=n_ep) + a = epval[ep] + 1e-6 * rng.normal(size=n) + b = 2.0 * epval[ep] + 1e-6 * rng.normal(size=n) + o = {} + r, p = report(a, b, ep, "T3_pure_episode", "pearson", nperm, o) + chk("T3 pure episode -> large raw r but p not significant", + r > 0.9 and p > 0.05, f"r={r:.3f} null={o['T3_pure_episode']['null_mean']:.3f} p={p:.4f}") + + # T4 genuine anchor agreement ON TOP of episode structure -> significant + w = rng.normal(size=n) + a2 = epval[ep] + 1.0 * w + b2 = 2.0 * epval[ep] + 1.0 * w + o = {} + r, p = report(a2, b2, ep, "T4_anchor_on_episode", "pearson", nperm, o) + chk("T4 genuine anchor agreement -> p significant", p < 0.01, f"r={r:.3f} p={p:.4f}") + + # T5 partial correlation: x and y share only z -> partial ~ 0, raw large + z = rng.normal(size=n) + xx = z + 0.3 * rng.normal(size=n) + yy = z + 0.3 * rng.normal(size=n) + praw, ppar = corr(xx, yy, "pearson"), partial(xx, yy, z) + chk("T5 shared-cause partial ~ 0 while raw is large", + praw > 0.7 and abs(ppar) < 0.25, f"raw={praw:.3f} partial={ppar:.3f}") + + # T6 partial correlation matches the closed form on a known Gaussian + ptrue = partial(xx, yy, z) + rxy, rxz, ryz = corr(xx, yy, "pearson"), corr(xx, z, "pearson"), corr(yy, z, "pearson") + closed = (rxy - rxz * ryz) / np.sqrt((1 - rxz ** 2) * (1 - ryz ** 2)) + chk("T6 partial matches closed form", abs(ptrue - closed) < 1e-9, + f"{ptrue:.9f} vs {closed:.9f}") + + # T7 episode demeaning is exact + d = episode_demean(a2, ep) + chk("T7 episode demeaning exact", max(abs(d[ep == e].mean()) for e in np.unique(ep)) < 1e-12) + + print("=== SELFTEST", "ALL PASS" if ok else "FAILED", "===") + return 0 if ok else 1 + + +# ----------------------------------------------------------------------------- main +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--base-cell", default="JUNC_feat_t45_c0p5") + ap.add_argument("--seeds", nargs="+", type=int, default=[0, 1, 2, 3, 4]) + ap.add_argument("--suffix", default="val31") + ap.add_argument("--threshold", type=float, default=45.0) + ap.add_argument("--table-fmt", default=f"{ROOT}/data/derived/augsucc/junc_feat_s{{s}}.npz") + ap.add_argument("--cache", default=f"{ROOT}/cache/real_cooking_v5") + ap.add_argument("--harness-split", default=f"{ROOT}/data/derived/cooking_v5_split.json") + ap.add_argument("--nperm", type=int, default=4000) + ap.add_argument("--out", default=f"{ROOT}/status/real/augsucc/t45_anchor_coverage.json") + ap.add_argument("--selftest", action="store_true") + a = ap.parse_args() + if a.selftest: + return selftest(min(a.nperm, 1000)) + + out = dict(base_cell=a.base_cell, seeds=a.seeds, threshold=a.threshold, nperm=a.nperm) + + # ---- the 37 anchors and their per-seed goal rank percentile ------------------------------- + per_seed = [] + for s in a.seeds: + p = f"{RK}/{a.base_cell}_s{s}__R{a.suffix}/per_anchor.npz" + if not os.path.exists(p): + print(f"[warn] missing {p}"); continue + z = np.load(p, allow_pickle=True) + per_seed.append(dict(seed=s, z=z, gv=rank_pct(z["scores_rsm"], 0))) + if len(per_seed) < 2: + print("[refused] fewer than 2 seeds"); out["refused"] = "seeds"; json.dump(out, open(a.out, "w"), indent=2); return 0 + ref = per_seed[0]["z"] + ep, t = np.asarray(ref["ep"]), np.asarray(ref["t"]) + for d in per_seed[1:]: + assert np.array_equal(np.asarray(d["z"]["ep"]), ep) and np.array_equal(np.asarray(d["z"]["t"]), t), \ + "anchors differ across seeds" + G = np.stack([d["gv"] for d in per_seed], 1) # 37 x n_seeds + g_mean = G.mean(1) + pose = rank_pct(np.asarray(ref["scores_pose"]), 0) # deterministic, identical in every seed + n = len(ep) + print(f"[data] {n} anchors over {len(np.unique(ep))} episodes; seeds {[d['seed'] for d in per_seed]}; " + f"per-seed gates " + " ".join(f"{x:.3f}" for x in G.mean(0))) + out["n_anchors"], out["per_seed_gate"] = int(n), [float(x) for x in G.mean(0)] + out["anchor_eps"] = sorted(int(e) for e in np.unique(ep)) + + # ---- (A) THE SPLIT AUDIT ------------------------------------------------------------------- + hs = json.load(open(a.harness_split))["episodes"] + h_val = sorted(int(k) for k, v in hs.items() if v["split"] == "valid") + meta = np.load(f"{a.cache}/meta.npz", allow_pickle=True) + ep_from = np.asarray(meta["ep_from"]) + anchor_row = np.array([int(ep_from[e]) + int(tt) for e, tt in zip(ep, t)], np.int64) + audit = {"harness_val_eps": h_val, "n_harness_val": len(h_val)} + print(f"\n=== (A) SPLIT AUDIT. harness validation = {len(h_val)} episodes from " + f"{os.path.basename(a.harness_split)}; anchor episodes {audit and out['anchor_eps']}") + tables = {} + for s in a.seeds: + tp = a.table_fmt.format(s=s) + if not os.path.exists(tp): + print(f"[warn] no table {tp}"); continue + tb = np.load(tp, allow_pickle=True) + tr = set(int(x) for x in tb["train_eps"]) + rows = np.asarray(tb["rows"], np.int64) + row_pos = {int(r): i for i, r in enumerate(rows)} + in_tbl = np.array([anchor_row[i] in row_pos for i in range(n)]) + rec = dict(harness_val_in_model_train=int(sum(1 for e in h_val if e in tr)), + anchor_eps_in_model_train=int(sum(1 for e in out["anchor_eps"] if e in tr)), + anchors_in_junction_table=int(in_tbl.sum())) + audit[f"s{s}"] = rec + tables[s] = dict(tb=tb, rows=rows, row_pos=row_pos, in_tbl=in_tbl) + print(f" seed {s}: {rec['harness_val_in_model_train']}/{len(h_val)} harness-val episodes were " + f"TRAIN for this model; {rec['anchor_eps_in_model_train']}/{len(out['anchor_eps'])} anchor " + f"episodes were TRAIN; {rec['anchors_in_junction_table']}/{n} anchor frames are themselves " + f"junction-table anchors") + out["split_audit"] = audit + + # ---- (B) PER-ANCHOR AUGMENTATION DOSE ------------------------------------------------------ + print(f"\n=== (B) PER-ANCHOR AUGMENTATION DOSE at threshold {a.threshold} (feat metric)") + dose = {} + for s, T in tables.items(): + tb, rows, row_pos = T["tb"], T["rows"], T["row_pos"] + routes = [str(x) for x in np.asarray(tb["routes"])] + arte = np.asarray(tb["anchor_route"], np.int64) + nbr_row, nbr_dist = np.asarray(tb["nbr_row"], np.int64), np.asarray(tb["nbr_dist"], np.float64) + gi = routes.index(GOAL_ROUTE) if GOAL_ROUTE in routes else -1 + n_any = np.full(n, -1.0); n_goal = np.full(n, -1.0) + d_near = np.full(n, np.nan); d_goal = np.full(n, np.nan) + for i in range(n): + pos = row_pos.get(int(anchor_row[i])) + if pos is None: + continue + dd, nr = nbr_dist[pos], nbr_row[pos] + fin = np.isfinite(dd) + nb_pos = np.array([row_pos.get(int(r), -1) for r in nr]) + nb_rt = np.where(nb_pos >= 0, arte[np.clip(nb_pos, 0, None)], -1) + within = fin & (dd <= a.threshold) + n_any[i] = float(within.sum()) + n_goal[i] = float((within & (nb_rt == gi)).sum()) + if fin.any(): + d_near[i] = float(dd[fin].min()) + gmask = fin & (nb_rt == gi) + if gmask.any(): + d_goal[i] = float(dd[gmask].min()) + dose[s] = dict(n_any=n_any, n_goal=n_goal, d_near=d_near, d_goal=d_goal) + cov = (n_any > 0) + print(f" seed {s}: anchors with >=1 pair within {a.threshold}: {int(cov.sum())}/{n} " + f"({cov.mean():.1%}); pairs/anchor mean {np.nanmean(np.where(n_any>=0,n_any,np.nan)):.2f} " + f"(goal-route {np.nanmean(np.where(n_goal>=0,n_goal,np.nan)):.2f}); " + f"nearest cross-route dist median {np.nanmedian(d_near):.2f}, " + f"nearest GOAL-route dist median {np.nanmedian(d_goal):.2f}") + out["dose_per_seed"] = {f"s{s}": {k: [None if not np.isfinite(x) else float(x) for x in v] + for k, v in d.items()} for s, d in dose.items()} + + # ---- (C) DOES DOSE PREDICT THE GATE? ------------------------------------------------------- + print(f"\n=== (C) DOES THE DOSE PREDICT THE ANCHOR'S GOAL RANK? (episode-demeaned, blocked null)") + st = {} + gd = episode_demean(g_mean, ep) + posed = episode_demean(pose, ep) + # average the dose across seeds (each seed has its own split/table); anchors missing in a seed + # contribute nothing to that seed's mean + for key in ("n_any", "n_goal", "d_near", "d_goal"): + stack = np.stack([np.where(dose[s][key] >= 0, dose[s][key], np.nan) if key.startswith("n_") + else dose[s][key] for s in dose], 1) + v = np.nanmean(stack, 1) if np.isfinite(stack).any() else np.full(n, np.nan) + good = np.isfinite(v) + if good.sum() < 10 or np.nanstd(v[good]) < 1e-12: + print(f" [skip] {key}: {int(good.sum())} finite, sd {np.nanstd(v[good]) if good.any() else 0:.3g}") + st[key] = dict(skipped=True, n_finite=int(good.sum())) + continue + vd = episode_demean(v[good], ep[good]) + r, p = report(vd, gd[good], ep[good], f"gate_vs_{key}", "spearman", a.nperm, st) + rp = partial(gd[good], vd, posed[good]) + st[f"gate_vs_{key}"]["partial_out_pose_pearson"] = rp + print(f" partial-out-pose pearson r = {rp:+.4f} " + f"(raw pearson {corr(vd, gd[good], 'pearson'):+.4f})") + # the pose confound itself, for the record + report(posed, gd, ep, "gate_vs_pose", "spearman", a.nperm, st) + out["stats"] = st + + os.makedirs(os.path.dirname(a.out), exist_ok=True) + json.dump(out, open(a.out, "w"), indent=2) + print(f"\nwrote {a.out}") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/rsm_rise/scripts/real/audit271_J_dino_source.py b/rsm_rise/scripts/real/audit271_J_dino_source.py new file mode 100644 index 0000000000000000000000000000000000000000..af5686f73364f28065ee5c2f6d698d294604d71b --- /dev/null +++ b/rsm_rise/scripts/real/audit271_J_dino_source.py @@ -0,0 +1,212 @@ +"""gen_q #271, check J: is the DELIVERED reward head reproducible by a reader whose DINOv2 +SOURCE comes from GitHub instead of from this training tree? + +WHY THIS IS NOT COVERED BY A..I. Everything #271 published about R(z) -- the S4-vs-S6 AUC, the +junction split, the stitching number, every row of rise_stack/CHECKPOINTS.md -- was measured with +the DINOv2 *source* in rsm_rise/cache/torch/hub/facebookresearch_dinov2_main, a torch.hub archive +of facebookresearch/dinov2@main downloaded 2026-09-18. `dino_hub_dir:` in baselines.yaml is an +absolute path on THIS cluster, so a reader never has it: rsm_real db2e0cbe makes the clean clone +fetch the source from GitHub instead, i.e. from a LATER snapshot of main. If the two snapshots +differ in the model code (or the weights URL moved), the reader's z is not the z the head was +trained on, and every R(z) number #271 reports is inapplicable to them -- silently. Checks D, H +and I verify the head's NAME, its table row and its BYTES; all three stay green under this failure, +because the checkpoint is bit-identical and only the features feeding it have changed. + +WHAT IT MEASURES. The same frames a reader actually has -- rise_stack/fixtures, the 64-frame +held-out episode-7 replay, full-resolution mp4s, decoded by the clone's own ReplayEnv -- are +featurised twice through the clone's own DinoStateFeaturiser: + local hub_dir = the training tree's archive (what #271's numbers were measured with) + github TORCH_HOME = a scratch dir, so torch.hub fetches facebookresearch/dinov2 fresh +and the DELIVERED default head (scheme A = R_M_ft_v1/ckpt_s110000.pt, which check I has already +shown is byte-identical to successor_rsm_real_A_110000.pt on the hub) is applied to both. It +reports max|dz|, max|dR(z)| in logits, the rank agreement of R over the 64 frames, and a +file-by-file sha256 diff of the two source trees to say WHY they agree or differ. + +ok = the two sources give the same z to fp tolerance AND the delivered head's logits agree to +FP_TOL_LOGIT. A mismatch is a real delivery defect, not a nuisance: it means the head on the hub +cannot reproduce its published numbers in the hands of the reader the hub copy exists for. + +Reads only. CPU. Never writes to the shared clone, the hub, or the training tree. +""" +import hashlib +import json +import os +import sys +import time +from pathlib import Path + +import numpy as np + +ROOT = Path("/proj/dmfexp/zwhong/rsm_rise") +CLONE = Path("/proj/dmfexp/zwhong/projs/rsm_real") +RSM = "/proj/dmfexp/zwhong/projs/issue_resolver_richardrl/gen_q_rsm/rsm_libero" +SCRATCH = Path("/proj/dmfexp/zwhong/scratch_reward_stitch/J_dino") + +LOCAL_HUB = ROOT / "cache/torch/hub/facebookresearch_dinov2_main" +FEAT_STATS = ROOT / "cache/real_cooking_v5/feat_stats.npz" +# The delivered default: scheme A. Kept in sync with hf_upload.REWARD_HEADS by check I. +HEAD = ROOT / "runs/real_cooking_v5/rsm/R_M_ft_v1/ckpt_s110000.pt" +HEAD_HUB_NAME = "successor_rsm_real_A_110000.pt" +FIXTURES = CLONE / "rise_stack/fixtures" +EPISODE = 7 +STATE_DIM = 1546 +# dinov2_vits14 in fp32 on CPU: the same source must be bit-identical, a different source need not +# be. 1e-4 on a standardised, z_clip-ed feature and 1e-3 on a raw logit are far below anything +# that could move an AUC, and far above CPU fp32 reassociation noise. +FP_TOL_Z = 1e-4 +FP_TOL_LOGIT = 1e-3 + + +def sha256_file(p: Path) -> str: + h = hashlib.sha256() + with open(p, "rb") as f: + for b in iter(lambda: f.read(1 << 20), b""): + h.update(b) + return h.hexdigest() + + +def tree_hashes(root: Path) -> dict: + """sha256 of every .py under root, keyed by relative path -- the model code that decides z.""" + out = {} + if not root.exists(): + return out + for p in sorted(root.rglob("*.py")): + if "__pycache__" in p.parts: + continue + out[str(p.relative_to(root))] = sha256_file(p) + return out + + +def main() -> int: + t0 = time.time() + SCRATCH.mkdir(parents=True, exist_ok=True) + sys.path.insert(0, str(CLONE)) + sys.path.insert(0, RSM) + + import torch + from rise_stack import envs as envs_mod + from rise_stack import obs as obs_mod + from rise_stack import scorers as scorers_mod + from is_ope import load_critic + + torch.set_grad_enabled(False) + out = {"utc": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), + "head": str(HEAD), "head_hub_name": HEAD_HUB_NAME, "scheme": "A", + "fixture": str(FIXTURES), "episode": EPISODE, + "local_hub": str(LOCAL_HUB), "scratch_torch_home": str(SCRATCH), + "fp_tol_z": FP_TOL_Z, "fp_tol_logit": FP_TOL_LOGIT, "failures": []} + + # ---- the reader's frames, decoded by the clone's own ReplayEnv -------------------------- # + env = envs_mod.ReplayEnv(EPISODE, str(FIXTURES / "replay_cooking_v5_ep7.hdf5"), + grip_thresh=0.052, video_root=str(FIXTURES)) + if env.full is None: + out["failures"].append("ReplayEnv fell back to 84x84 frames: the fixture mp4s were not found, " + "so this check would compare the WRONG features") + out["ok"] = False + (ROOT / "status/real/AUDIT271_J_DINO.json").write_text(json.dumps(out, indent=1)) + print(json.dumps(out, indent=1)) + return 1 + n = len(env.S) + obs_list = [env._obs(i, None) for i in range(n)] + out["n_frames"] = n + print(f"[J] {n} fixture frames decoded from the mp4s", flush=True) + + # ---- featurise twice ------------------------------------------------------------------- # + def featurise(tag: str, *, hub_dir, torch_home) -> np.ndarray: + os.environ.pop("RISE_DINO_HUB_DIR", None) # must not override what we are testing + if torch_home is None: + os.environ.pop("TORCH_HOME", None) + else: + os.environ["TORCH_HOME"] = str(torch_home) + t = time.time() + fz = scorers_mod.DinoStateFeaturiser(str(FEAT_STATS), device="cpu", crop_mode="square", + backbone="dinov2_vits14", hub_dir=hub_dir) + z = np.stack([fz(o) for o in obs_list]).astype(np.float64) + print(f"[J] {tag}: z {z.shape} in {time.time()-t:.0f}s", flush=True) + return z + + z_local = featurise("local", hub_dir=str(LOCAL_HUB), torch_home=None) + # The question is what a reader gets TODAY, so the model CODE is re-fetched every run: without + # this the scratch tree left by the previous run would be found by hub.exists() and taken as + # source=local, and the check would silently pin itself to a frozen snapshot of main instead of + # tracking it. hub/checkpoints is kept: torch.hub caches weights by FILENAME, so a source that + # names a different weights file still downloads it. + gh_src = SCRATCH / "hub" / "facebookresearch_dinov2_main" + import shutil + existed = gh_src.exists() + if existed: + shutil.rmtree(gh_src) + out["github_source_refetched_this_run"] = True + out["github_source_existed_before"] = bool(existed) + # hub_dir=None + TORCH_HOME=scratch -> the hub dir does not exist -> the GitHub path, which is + # exactly what a reader without this cluster's tree takes. + z_github = featurise("github", hub_dir=None, torch_home=SCRATCH) + + dz = np.abs(z_local - z_github) + out["z_dim"] = int(z_local.shape[1]) + out["z_max_abs_diff"] = float(dz.max()) + out["z_mean_abs_diff"] = float(dz.mean()) + out["z_bit_identical"] = bool(np.array_equal(z_local, z_github)) + out["z_scale"] = {"local_absmean": float(np.abs(z_local).mean()), + "github_absmean": float(np.abs(z_github).mean())} + + # ---- the DELIVERED head on both ------------------------------------------------------- # + enc, rew, flow, rms, cfg = load_critic(str(HEAD), STATE_DIM, 1, "cpu", data=None) + out["head_step"] = int(torch.load(str(HEAD), map_location="cpu", weights_only=False).get("step", -1)) + + def logits(z: np.ndarray) -> np.ndarray: + x = torch.from_numpy(z.astype(np.float32)) + tk = torch.zeros(len(z), dtype=torch.long) + return rew(enc(x), tk).float().reshape(-1).numpy().astype(np.float64) + + lg_local, lg_github = logits(z_local), logits(z_github) + dl = np.abs(lg_local - lg_github) + out["logit_max_abs_diff"] = float(dl.max()) + out["logit_mean_abs_diff"] = float(dl.mean()) + out["logit_range_local"] = [float(lg_local.min()), float(lg_local.max())] + out["logit_range_github"] = [float(lg_github.min()), float(lg_github.max())] + out["argmax_frame_local"] = int(lg_local.argmax()) + out["argmax_frame_github"] = int(lg_github.argmax()) + order_local, order_github = np.argsort(lg_local), np.argsort(lg_github) + out["rank_order_identical"] = bool(np.array_equal(order_local, order_github)) + out["spearman"] = float(np.corrcoef(np.argsort(order_local), np.argsort(order_github))[0, 1]) + + # ---- WHY: are the two source trees the same snapshot? --------------------------------- # + gh_hub = SCRATCH / "hub" / "facebookresearch_dinov2_main" + h_local, h_github = tree_hashes(LOCAL_HUB), tree_hashes(gh_hub) + only_local = sorted(set(h_local) - set(h_github)) + only_github = sorted(set(h_github) - set(h_local)) + differing = sorted(k for k in set(h_local) & set(h_github) if h_local[k] != h_github[k]) + out["source_trees"] = {"github_hub_dir": str(gh_hub), + "n_py_local": len(h_local), "n_py_github": len(h_github), + "only_local": only_local, "only_github": only_github, + "differing": differing, + "same_snapshot": bool(h_local and h_github and not + (only_local or only_github or differing))} + + # ---- verdict -------------------------------------------------------------------------- # + # Not vacuous: the featuriser must actually have produced features, and the github build must + # actually have fetched a tree (run 19's lesson -- an empty glob also reports "no differences"). + if not h_github: + out["failures"].append(f"the github build left no source tree at {gh_hub}: the fetch did not " + f"happen, so 'no difference' would be vacuous") + if z_local.shape != (n, STATE_DIM): + out["failures"].append(f"z_local has shape {z_local.shape}, expected {(n, STATE_DIM)}") + if out["z_max_abs_diff"] > FP_TOL_Z: + out["failures"].append(f"DINOv2 source changes the features a reader computes: " + f"max|dz|={out['z_max_abs_diff']:.3g} > {FP_TOL_Z:g} over {n} frames") + if out["logit_max_abs_diff"] > FP_TOL_LOGIT: + out["failures"].append(f"the delivered head {HEAD_HUB_NAME} gives different logits from the " + f"two sources: max|dR|={out['logit_max_abs_diff']:.3g} > {FP_TOL_LOGIT:g}; " + f"#271's published R(z) numbers do not apply to a reader") + out["ok"] = not out["failures"] + out["secs"] = round(time.time() - t0, 1) + + (ROOT / "status/real/AUDIT271_J_DINO.json").write_text(json.dumps(out, indent=1)) + print(json.dumps(out, indent=1), flush=True) + print(f"[J] {'PASS' if out['ok'] else 'FAIL'} in {out['secs']}s", flush=True) + return 0 if out["ok"] else 1 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/rsm_rise/scripts/real/audit271_L_label_provenance.py b/rsm_rise/scripts/real/audit271_L_label_provenance.py new file mode 100644 index 0000000000000000000000000000000000000000..71a3626592fbbc30a0600ce019e32d535202b52b --- /dev/null +++ b/rsm_rise/scripts/real/audit271_L_label_provenance.py @@ -0,0 +1,321 @@ +#!/usr/bin/env python +"""gen_q #271, check L: does each DELIVERED head actually carry the LABEL its name claims? + +The levels this stream has already covered, in the order the bugs appeared: + name -> file (check H, run 18) a file advertised under the wrong label + file -> bytes (check I, run 20) the hub copy differing from the cluster source + bytes -> features (check J, run 21) a reader's DINOv2 differing from ours + prose -> reality (check K, run 21) a page describing a live head as pending +Every one of them stops at the checkpoint's SURFACE. Nothing yet asks the question a consumer +actually cares about: **was `successor_rsm_real_A_110000.pt` trained on the GOAL_SEGMENT label?** +If the fine-tune launcher had been pointed at the wrong `--reward-npy`, all four checks above stay +green, every shipped page stays self-consistent, and every downloader gets a head that optimises a +reward nobody named. That is the level below, and this is the check for it. + +Two INDEPENDENT readings, because each can fail in a way the other cannot see: + + RECORDED Reconstruct the training label by instantiating the trainer's OWN data pipeline + (`LiberoRSMData`) from the checkpoint's OWN stored config -- reward_mode, reward_npy, + success_mask, k_success, success_gamma -- and hash the resulting `d.r`. This is exact + and covers the base head, whose label comes from a `reward_mode` rule rather than from + an `--reward-npy` path, so a filename comparison could not have read it at all. + + FUNCTIONAL Score every frame of the corpus with the head and take the AUC of R(z) against each + distinct label array. A reward head trained with BCE on its own label fits it far + better than any other, so the argmax over labels identifies the training target + WITHOUT trusting any recorded config. If the config says one thing and the weights + another, the weights win and this check fails loudly. + +Labels that are bit-identical on this corpus are one CLASS (measured here, not assumed: +reward_A_tosucc == reward_C_kstate == reward_v1_goaltrans, and reward_v0lit_finalS3S4 == +reward_v5_riseprov -- see the run-13 label-identity audit). A claim is satisfied by any member of +the claimed label's class, since those arrays are the same array. + +The FUNCTIONAL reading accepts a claim when the claimed label is the STRICT argmax of AUC over the +label classes AND the head's AUC on that label clears a permuted null measured on the same head. +There is no hand-set margin: AUC saturates at 1.000 on a label the head was fit on, and the classes +are nested, so a gap threshold would measure the label geometry rather than the claim. + +usage: audit271_L_label_provenance.py [--out JSON] [--n-perm K] +""" +from __future__ import annotations +import argparse, hashlib, json, sys, traceback +from pathlib import Path +import numpy as np +import torch + +ROOT = Path("/proj/dmfexp/zwhong/rsm_rise") +CLONE = Path("/proj/dmfexp/zwhong/projs/rsm_real") +CACHE = ROOT / "cache/real_cooking_v5" +RSM = "/proj/dmfexp/zwhong/projs/issue_resolver_richardrl/gen_q_rsm/rsm_libero" + +# file on the hub -> the canonical name of the label it carries. Kept in lockstep with check H's +# NAME_OF_FILE deliberately: if the two ever disagree, H and L disagree and the audit stops. +NAME_OF_FILE = { + "successor_rsm_real_A_110000.pt": "GOAL_SEGMENT", + "successor_rsm_real_A_s1_110000.pt": "GOAL_SEGMENT", + "successor_rsm_real_B_H100_110000.pt": "GOAL_WINDOW_100", + "successor_rsm_real_B_H100_s1_110000.pt": "GOAL_WINDOW_100", + "successor_rsm_real_B_H400_110000.pt": "GOAL_WINDOW_400", + "successor_rsm_real_B_H400_s1_110000.pt": "GOAL_WINDOW_400", + "successor_rsm_real_v0lit_110000.pt": "EXPERT_EPISODE", + "successor_rsm_real_v0lit_s1_110000.pt": "EXPERT_EPISODE", + "successor_rsm_real_RM_s0_100k.pt": "GOAL_EPISODE", + # Added run 22, and NOT copied from check H -- H's map has only the nine above, so the second + # base successor is a live checkpoint carrying a reward head that no check of this issue covered: + # not its label, not its bytes (I hashes the eight fine-tunes), not the name it is sold under. + # The registry's GOAL_EPISODE entry still names only the s0 file. Listing it here does not + # assert the claim, it submits the claim to both readings below. + "successor_rsm_real_RM_s1_100k.pt": "GOAL_EPISODE", +} +# The registry defers two labels to REWARD_SCHEMES.json's files map rather than naming a path. +SCHEMES_KEY_OF_NAME = {"GOAL_EPISODE": "v0_shipped", "GOAL_ARRIVAL_MARKER": "C_literal"} +# The verified listing of what is actually on the hub (written by the sha/size verification job). +# A module constant so the negative control can repoint it at a fixture instead of the real tree. +HUB_TREE = str(ROOT / "status/real/hf_tree.json") + + +def sha(a: np.ndarray) -> str: + return hashlib.sha256(np.ascontiguousarray(a, dtype=np.float32).tobytes()).hexdigest() + + +def auc(score, label): + """Rank AUC with mid-ranks for ties (same estimator as reward_head_diag.py).""" + score = np.asarray(score, np.float64).ravel() + label = np.asarray(label).ravel() > 0.5 + n1, n0 = int(label.sum()), int((~label).sum()) + if n1 == 0 or n0 == 0: + return float("nan") + order = np.argsort(score, kind="mergesort") + r = np.empty(len(score), np.float64) + r[order] = np.arange(1, len(score) + 1, dtype=np.float64) + s = score[order] + i = 0 + while i < len(s): + j = i + while j + 1 < len(s) and s[j + 1] == s[i]: + j += 1 + if j > i: + r[order[i:j + 1]] = 0.5 * (i + 1 + j + 1) + i = j + 1 + return float((r[label].sum() - n1 * (n1 + 1) / 2.0) / (n1 * n0)) + + +def label_classes(cache: Path): + """Every reward*.f32.npy in the cache, grouped into bit-identical CLASSES (measured).""" + cls, of_file = {}, {} + for p in sorted(cache.glob("reward*.f32.npy")): + a = np.load(p).astype(np.float32).ravel() + h = sha(a) + of_file[p.name] = h + cls.setdefault(h, {"sha": h, "members": [], "n_pos": int((a > 0.5).sum()), + "mean": float(a.mean()), "_a": a}) + cls[h]["members"].append(p.name) + return cls, of_file + + +def sources(): + """hub file -> (cell name, cluster source path), from hf_upload.py's own tables.""" + sys.path.insert(0, str(ROOT / "scripts/real")) + import hf_upload as U + out = {} + for name, src, dst in getattr(U, "REWARD_HEADS", []): + out[dst] = (name, Path(src)) + for kind, src, dst in getattr(U, "MANIFEST", []): + out.setdefault(dst, (kind, Path(src))) + return out + + +def claimed_npy(name: str, reg: dict, schemes: dict) -> str: + lf = str(reg["rewards"][name].get("label_file", "")) + if lf.endswith(".npy"): + return Path(lf).name + key = SCHEMES_KEY_OF_NAME.get(name) + if key and key in schemes: + return Path(schemes[key]).name + return "" + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--out", default=str(ROOT / "status/real/AUDIT271_L_LABELPROV.json")) + ap.add_argument("--cache", default=str(CACHE)) + ap.add_argument("--batch", type=int, default=16384) + ap.add_argument("--n-perm", type=int, default=5, + help="permutations of the claimed label used to measure the AUC null per head") + ap.add_argument("--perm-seed", type=int, default=20260924) + args = ap.parse_args() + sys.path.insert(0, RSM) + from data import LiberoRSMData + from model import RewardHead, IdentityEncoder + + cache = Path(args.cache) + reg = json.loads((CLONE / "rise_stack/configs/reward_names.json").read_text()) + schemes = json.loads((ROOT / "status/real/REWARD_SCHEMES.json").read_text()).get("files", {}) + cls, sha_of_file = label_classes(cache) + src = sources() + + out = {"cache": str(cache), "n_heads_expected": len(NAME_OF_FILE), + "label_classes": {h: {"members": c["members"], "n_pos": c["n_pos"], "mean": c["mean"]} + for h, c in cls.items()}, + "heads": {}, "failures": [], "ok": False} + + # the label arrays we score against, one representative per class + rep = [(h, c["members"][0], c["_a"]) for h, c in sorted(cls.items(), key=lambda kv: -kv[1]["n_pos"])] + + feats = {} # (chunk,k_success,seed) -> LiberoRSMData with features in RAM + for hub, label in sorted(NAME_OF_FILE.items()): + row = {"claims_label": label} + out["heads"][hub] = row + if hub not in src: + out["failures"].append(f"{hub}: no source in hf_upload.py") + continue + cell, p = src[hub] + row.update(cell=cell, source=str(p)) + if not p.exists(): + out["failures"].append(f"{hub}: source {p} missing") + continue + + want_npy = claimed_npy(label, reg, schemes) + want_sha = sha_of_file.get(want_npy, "") + row["claimed_label_file"] = want_npy + if not want_sha: + out["failures"].append(f"{hub}: the registry's label_file for {label} " + f"({want_npy or ''}) is not a file in the cache") + continue + row["claimed_class"] = cls[want_sha]["members"] + + c = torch.load(p, map_location="cpu", weights_only=False) + cfg = c["config"] + row["step"] = int(c.get("step", -1)) + row["cfg_reward_npy"] = str(cfg.get("reward_npy", "")) + row["cfg_reward_mode"] = str(cfg.get("reward_mode", "")) + row["cfg_weight_npy"] = str(cfg.get("weight_npy", "")) + + # ---- RECORDED: rebuild the training label through the trainer's own pipeline ---------- + key = (int(cfg["chunk"]), int(cfg["k_success"]), int(cfg["seed"])) + d = LiberoRSMData(str(cache), chunk=key[0], k_success=key[1], seed=key[2], in_ram=True, + val_frac=0.1, + reward_mode=str(cfg.get("reward_mode", "dense")), + success_mask=str(cfg.get("success_mask", "")), + success_gamma=float(cfg.get("success_gamma", 0.98)), + reward_npy=str(cfg.get("reward_npy", "")), + weight_npy=str(cfg.get("weight_npy", "")), + subgoal_dir=str(cfg.get("subgoal_dir", ""))) + r = np.asarray(d.r, np.float32).ravel() + got = sha(r) + row["trained_label_sha"] = got + row["trained_label_members"] = cls.get(got, {}).get("members", [""]) + row["trained_label_n_pos"] = int((r > 0.5).sum()) + row["recorded_match"] = bool(got == want_sha) + if not row["recorded_match"]: + out["failures"].append( + f"{hub} claims {label} ({want_npy}, {cls[want_sha]['n_pos']} positive frames) but the " + f"checkpoint's own config rebuilds a label with {row['trained_label_n_pos']} positive " + f"frames ({'/'.join(row['trained_label_members'])})") + + # ---- FUNCTIONAL: which label does the head itself fit best? -------------------------- + enc = IdentityEncoder(int(c["d_in"])).eval() + rew = RewardHead(int(c["d_lat"]), len(c["tasks"])).eval() + rew.load_state_dict(c["rew"]) + n = len(r) + logit = np.zeros(n, np.float32) + with torch.no_grad(): + for s in range(0, n, args.batch): + idx = np.arange(s, min(s + args.batch, n), dtype=np.int64) + x = torch.from_numpy(d._feat(idx)) + z = enc(x) + t0 = torch.zeros(len(idx), dtype=torch.long) + logit[idx] = rew(z, t0).float().numpy().ravel() + aucs = {} + for h, nm, a in rep: + aucs["/".join(cls[h]["members"])] = round(auc(logit, a), 4) + row["auc_vs_label"] = aucs + claimed_k = "/".join(cls[want_sha]["members"]) + ranked = sorted(aucs.items(), key=lambda kv: -kv[1]) + best_k, best_v = ranked[0] + rival_k, rival_v = ranked[1] if len(ranked) > 1 else (None, float("nan")) + if best_k == claimed_k: + runner_k, runner_v = rival_k, rival_v + else: + runner_k, runner_v = best_k, best_v + # The DECISION RULE is strict argmax, and it carries no invented constant. An earlier + # draft required the claimed label to beat the best rival by >= 0.02; that gate is + # unsatisfiable in principle and was removed once measured rather than loosened: every + # head scores AUC exactly 1.0000 on its own training label (it is fit in-sample, as + # history.json's reward_auc=1.0 already said), the estimator cannot go higher, and the + # label classes are NESTED on this corpus (B_H100 frames are a subset of B_H400's, whose + # frames are a subset of the goal episodes), so a rival can legitimately sit at 0.99 while + # the claim is exactly right. A gap threshold would therefore have measured how nested the + # labels are, not whether the head carries the label it claims. + # + # What stops strict argmax from passing trivially is the measured NULL: the same head is + # scored against `--n-perm` random permutations of its OWN claimed label. A permutation + # keeps the label's marginal and destroys its alignment with the frames, so AUC must land + # at 0.5. The claim is only accepted if the real AUC is outside the permuted band -- i.e. + # the head's separation of that label is a property of WHICH frames are positive. + rng = np.random.default_rng(args.perm_seed + abs(hash(hub)) % 10_000) + a_claim = cls[want_sha]["_a"] + perm = [auc(logit, rng.permutation(a_claim)) for _ in range(args.n_perm)] + row["perm_null_auc"] = {"draws": [round(x, 4) for x in perm], + "mean": round(float(np.mean(perm)), 4), + "max": round(float(np.max(perm)), 4)} + row["functional_best"] = best_k + row["functional_best_auc"] = best_v + row["claimed_auc"] = aucs[claimed_k] + row["margin_over_best_rival"] = round(aucs[claimed_k] - runner_v, 4) + is_argmax = bool(best_k == claimed_k and aucs[claimed_k] > runner_v) + beats_null = bool(aucs[claimed_k] > row["perm_null_auc"]["max"]) + row["strict_argmax"] = is_argmax + row["beats_permuted_null"] = beats_null + row["functional_match"] = bool(is_argmax and beats_null) + if not is_argmax: + out["failures"].append( + f"{hub} claims {label} but R(z) fits '{best_k}' at least as well " + f"(AUC {best_v:.4f} vs claimed {aucs[claimed_k]:.4f}, " + f"margin {row['margin_over_best_rival']:+.4f})") + elif not beats_null: + out["failures"].append( + f"{hub} claims {label} and is its argmax, but its AUC {aucs[claimed_k]:.4f} does " + f"not clear the permuted null (max over {args.n_perm} draws " + f"{row['perm_null_auc']['max']:.4f}) -- the separation is not about which frames " + f"are positive") + del d, enc, rew + + # COVERAGE. A per-head check that is handed its own list of heads can be made to pass by + # shortening the list -- which is exactly how successor_rsm_real_RM_s1_100k.pt stayed unchecked + # for four runs. So L reads what is actually ON THE HUB and refuses if any live successor + # checkpoint has no declared label here. + try: + tree = json.loads(Path(HUB_TREE).read_text()) + live = sorted(r["path"] for r in tree["rows"] + if r["path"].startswith("successor_rsm_real_") and r["path"].endswith(".pt")) + except Exception as e: # noqa: BLE001 + live = [] + out["failures"].append(f"could not read the hub tree to check coverage: {e}") + out["hub_live_pt"] = live + undeclared = [p for p in live if p not in NAME_OF_FILE] + out["undeclared_on_hub"] = undeclared + if undeclared: + out["failures"].append( + "live on the hub with no label declared to this check: " + ", ".join(undeclared)) + + out["n_heads_checked"] = sum(1 for v in out["heads"].values() if "functional_match" in v) + out["ok"] = (not out["failures"]) and out["n_heads_checked"] == len(NAME_OF_FILE) + Path(args.out).write_text(json.dumps(out, indent=1)) + print(json.dumps({k: v for k, v in out.items() if k != "heads"}, indent=1)) + for hub, v in sorted(out["heads"].items()): + print(f" {hub:44s} claims={v.get('claims_label','?'):16s} " + f"rec={v.get('recorded_match')} fn={v.get('functional_match')} " + f"auc={v.get('claimed_auc')} margin={v.get('margin_over_best_rival')} " + f"null_max={(v.get('perm_null_auc') or {}).get('max')}") + print(f"[L] ok={out['ok']} failures={len(out['failures'])} -> {args.out}") + return 0 if out["ok"] else 1 + + +if __name__ == "__main__": + try: + sys.exit(main()) + except Exception: + traceback.print_exc() + sys.exit(2) diff --git a/rsm_rise/scripts/real/audit271_P_artifact_record.py b/rsm_rise/scripts/real/audit271_P_artifact_record.py new file mode 100644 index 0000000000000000000000000000000000000000..4081f38396d523700c8e662f5c90afc6df0e7c9a --- /dev/null +++ b/rsm_rise/scripts/real/audit271_P_artifact_record.py @@ -0,0 +1,334 @@ +#!/usr/bin/env python +"""Check P (gen_q #271, run 28): does what a ROW SAYS about an artefact match the artefact's OWN record? + +Every check before this one reads a claim against another PAGE or against the hub LISTING: + + * O asks whether a row EXISTS for a live path, and whether its byte count is right. + * N asks whether a printed COUNT is the right count of the right class. + * I / M ask whether the BYTES and the published DIGEST match the source the uploader names. + * L asks whether a head's reward LABEL is the one its name claims. + +None of them reads the rest of the row's words. The card's two `what it is` columns assert, for 27 +rows, a SEED, a STEP, a stage (base vs fine-tune), a parent checkpoint and a sweep arm -- and every +one of those words is parsed FROM THE FILE NAME, by `hf_card_refresh_table.what_is()` and by +`hf_upload.py`'s manifest. So a mis-pointed manifest entry (one line of twelve near-identical ones +in REWARD_HEADS) would be described wrongly, consistently, by the uploader AND by the card, and +I/M would stay green: they verify that the hub bytes equal the source the manifest NAMES, never that +the manifest names the right source. + +P closes that: it reads the record each artefact keeps about ITSELF and compares it with the row. + + the successor / reward-head blobs -> `step`, `config.seed`, `config.out`, `config.reward_npy` + the pi0.5 orbax folders -> `_CHECKPOINT_METADATA` and the `assets//` path + +RULES, each reported with its own tag so a failure names its own repair: + [seed] a row's "seed N" vs the blob's `config.seed` + [step] a row's "step N" / "N steps" vs the blob's `step` + [stage] "base successor" / "reward head" / "a 10k fine-tune" vs `config.out` + the step delta + [parent] "off `RM_s_100k`" vs the blob's seed (see SCOPE) + [name] the HUB FILE NAME's own encoded seed and step vs the blob's `config.seed` / `step`. + This, not [src], is what catches the defect P was written for: if one REWARD_HEADS line + points at the wrong cell, the blob that ships under `..._B_H400_s1_...` was written by + `R_M_ft_B400` with seed 0, and [src] cannot see it -- the record is READ AT the manifest's + own source, so `config.out` agrees with the manifest by construction. The name is the + only party that still disagrees, and every word of the row is derived from it. + [src] hf_upload.py's source path for this hub file vs the blob's own `config.out` and step -- + the narrower case where a checkpoint FILE was copied out of the cell that wrote it + [ds] a folder row's dataset vs the `assets//` directory inside it + +SCOPE, stated rather than papered over -- three kinds of word have NO in-artefact record, and the +check reports them as `unverified` instead of passing them: + * a pi0.5 folder records neither its SEED, its STEP nor its sweep ARM. `_CHECKPOINT_METADATA` + holds only handler names, two timestamps and our own export note, and `params/_METADATA` is + byte-identical (23,544 B) across all twelve arms, so the parameter tree cannot tell them apart + either. Those words rest on the export directory name, at both ends, and P says so. + * the blob records the seed it TRAINED with, not the file it resumed from, so [parent] compares + the parent's seed, not the parent's identity. + * an unverified word adds 0 to `seen`, because `seen` is the guard against a vacuous pass + (run 19) and inflating it with words nothing checked would quietly disarm it. + +`p_rows_bad(rows, records, manifest)` is pure, so the negative control drives it on fixtures. +Nothing here imports hf_card_refresh_table: the generator that WROTE these words must not supply the +parser that checks them -- that shared-helper shape is how the run-26 defect shipped past a check. +""" +from __future__ import annotations +import ast +import json +import re +from pathlib import Path + +ROOT = Path("/proj/dmfexp/zwhong/rsm_rise") +BASE_STEP = 100_000 # the pre-fine-tune successor step; every #271 head is a fine-tune of it + +_SEED = re.compile(r"\bseed\s+(\d+)\b", re.I) +_STEP_A = re.compile(r"\b(?:orbax\s+)?step\s+(\d+)\b", re.I) +_STEP_B = re.compile(r"\b(\d+)\s*k?\s+steps\b", re.I) +_STEP_BK = re.compile(r"\b(\d+)k\s+steps\b", re.I) +_FT = re.compile(r"\b(\d+)k\s+fine[- ]tune\b", re.I) +_PARENT = re.compile(r"\bRM_s(\d+)_100k\b") +_FILE_CELL = re.compile(r"`([^`]+)`") + +# The hub naming convention for successor blobs, declared here so the rule is answerable for it: +# `_s_` anywhere in the stem is seed N and its ABSENCE is seed 0 (which is what the card's +# generator assumes when it writes "seed 0"); the trailing `_.pt` or `_k.pt` is the step. +_NAME_SEED = re.compile(r"_s(\d+)_") +_NAME_STEP = re.compile(r"_(\d+)(k?)\.pt$") + + +def name_claims(hub_name): + """{seed, step} the hub FILE NAME asserts. None for a field the convention cannot read.""" + m = _NAME_SEED.search(hub_name) + seed = int(m.group(1)) if m else 0 + m = _NAME_STEP.search(hub_name) + step = int(m.group(1)) * (1000 if m and m.group(2) else 1) if m else None + return {"seed": seed, "step": step} + + +# ------------------------------------------------------------------ hf_upload.py's manifest, by AST +def read_manifest(py=None): + """{hub path: local source path} from hf_upload.py, parsed as SOURCE, not imported and not regexed. + + The manifest is the thing [src] puts on trial, so it is read structurally: the three list + literals are evaluated with ROOT/RUNS/CACHE/JMETA bound to their real values and nothing else in + scope, which fails loudly on a shape this parser does not understand rather than silently + matching fewer entries the way a regex does. + """ + py = Path(py or ROOT / "scripts/real/hf_upload.py") + tree = ast.parse(py.read_text()) + env = {"ROOT": ROOT, "RUNS": ROOT / "runs", "CACHE": ROOT / "cache/real_cooking_v5", + "JMETA": ROOT / "status/real/hf_json_meta"} + + def ev(node): + if isinstance(node, ast.Constant): + return node.value + if isinstance(node, ast.Name): + return env[node.id] + if isinstance(node, ast.BinOp) and isinstance(node.op, ast.Div): + return ev(node.left) / ev(node.right) + raise ValueError(ast.dump(node)[:80]) + + out = {} + for stmt in tree.body: + if not isinstance(stmt, ast.Assign): + continue + name = getattr(stmt.targets[0], "id", None) + if name not in ("MANIFEST", "REWARD_HEADS", "PI05_DIRS"): + continue + for elt in stmt.value.elts: + parts = [ev(x) for x in elt.elts] + src, dst = parts[-2], parts[-1] + out[dst] = Path(src) + return out + + +# ------------------------------------------------------------------ what each artefact says of itself +def read_records(manifest, loader=None): + """{hub path: record}. `loader` is injected so the control can run without torch or the files.""" + recs = {} + for dst, src in sorted(manifest.items()): + name = dst.rstrip("/") + if name.endswith(".pt") and name.startswith("successor_"): + recs[dst] = _pt_record(src, loader) + elif name.startswith("pi05_"): + recs[dst] = _orbax_record(src) + return recs + + +def _pt_record(src, loader=None): + if loader is None: + import torch + def loader(p): + return torch.load(p, map_location="cpu", weights_only=False) + if not Path(src).exists(): + return {"kind": "pt", "src": str(src), "present": False} + o = loader(src) + c = o.get("config", {}) or {} + return {"kind": "pt", "src": str(src), "present": True, + "step": o.get("step"), + "seed": c.get("seed"), + "out": str(c.get("out", "")), + "reward_npy": str(c.get("reward_npy", "")), + "steps_cfg": c.get("steps")} + + +def _orbax_record(src): + src = Path(src) + r = {"kind": "orbax", "src": str(src), "present": src.exists(), + "unrecorded": ["seed", "step", "arm"]} + if not src.exists(): + return r + meta = src / "_CHECKPOINT_METADATA" + if meta.exists(): + try: + r["export_note"] = (json.loads(meta.read_text()) + .get("custom_metadata", {}).get("rsm_rise_export")) + except Exception as e: + r["export_note"] = f"(unparsed {type(e).__name__})" + ds = sorted(p for p in src.glob("assets/*/*") if p.is_dir()) + r["datasets"] = [f"{p.parent.name}/{p.name}" for p in ds] + r["param_metadata_bytes"] = ((src / "params/_METADATA").stat().st_size + if (src / "params/_METADATA").exists() else None) + return r + + +# ------------------------------------------------------------------ the pure rule set +def _steps_claimed(text): + """Every step number a `what it is` cell asserts, normalised. `10k fine-tune` is NOT one of + them -- it is a DELTA, read by [stage] -- and `10k warm start` is a delta too.""" + out = [] + for m in _STEP_A.finditer(text): + out.append(int(m.group(1))) + for m in _STEP_BK.finditer(text): + out.append(int(m.group(1)) * 1000) + for m in _STEP_B.finditer(text): + if not re.match(r"\d+k", m.group(0).strip()): + out.append(int(m.group(1))) + return sorted(set(out)) + + +def p_rows_bad(rows, records, manifest): + """rows: [(where, line, hub path, what-it-is text)]. Returns (bad, seen, unverified).""" + bad, seen, unver = [], 0, [] + + def flag(tag, where, line, path, msg): + bad.append(f"{tag} {where}:{line} `{path}`: {msg}") + + for where, line, path, text in rows: + rec = records.get(path) or records.get(path.rstrip("/")) or records.get(path.rstrip("/") + "/") + if rec is None: + continue # not an artefact P holds a record for; O owns coverage + if not rec.get("present"): + flag("[src]", where, line, path, + f"row describes an artefact whose declared source is MISSING on the cluster " + f"({rec.get('src')}) -- nothing verifies these words") + continue + + if rec["kind"] == "orbax": + for want in ("seed", "step"): + pat = _SEED if want == "seed" else _STEP_A + for m in pat.finditer(text): + unver.append(f"{where}:{line} `{path}` {want} {m.group(1)}: " + f"a pi0.5 orbax export records no {want} (name-derived at both ends)") + for tok in re.findall(r"\bsn[0-9p]+_knn[0-9p]+\b|spectral norm [0-9.]+|kNN [0-9.]+", text): + unver.append(f"{where}:{line} `{path}` arm `{tok}`: params/_METADATA is byte-identical " + f"across all arms, so the folder cannot confirm its own arm") + ds = rec.get("datasets") or [] + if ds: + seen += 1 + if not any(d.split("/")[-1] in text or d.split("/")[-1] in path for d in ds): + # the card names the corpus once per page, so only flag a POSITIVE contradiction + other = re.search(r"\brsm_cooking_v\d+\b", text) + if other and other.group(0) not in [d.split("/")[-1] for d in ds]: + flag("[ds]", where, line, path, + f"row says `{other.group(0)}`; the folder's own assets say {ds}") + continue + + # ---- a successor / reward-head blob ------------------------------------------------- + for m in _SEED.finditer(text): + seen += 1 + if rec.get("seed") is None: + unver.append(f"{where}:{line} `{path}` seed: the blob records no config.seed") + elif int(m.group(1)) != int(rec["seed"]): + flag("[seed]", where, line, path, + f"row says seed {m.group(1)}; the checkpoint's own config.seed is {rec['seed']} " + f"(source {rec['src']})") + for s in _steps_claimed(text): + seen += 1 + if s != rec.get("step"): + flag("[step]", where, line, path, + f"row says step {s}; the checkpoint records step {rec.get('step')}") + is_ft = "_ft_" in Path(rec["out"]).name + if re.search(r"\bbase successor\b|\bpre-fine-tune\b", text, re.I): + seen += 1 + if is_ft or rec.get("step") != BASE_STEP: + flag("[stage]", where, line, path, + f"row calls this a BASE successor; the blob was written by " + f"`{Path(rec['out']).name}` at step {rec.get('step')} " + f"(a base successor is a non-`_ft_` cell at step {BASE_STEP})") + elif re.search(r"\breward head\b|\bfine[- ]tune\b", text, re.I): + seen += 1 + if not is_ft: + flag("[stage]", where, line, path, + f"row calls this a reward head / fine-tune; the blob was written by " + f"`{Path(rec['out']).name}`, which is not a `_ft_` cell") + for m in _FT.finditer(text): + seen += 1 + want = int(m.group(1)) * 1000 + got = (rec.get("step") or 0) - BASE_STEP + if got != want: + flag("[stage]", where, line, path, + f"row says a {m.group(1)}k fine-tune; the blob is at step {rec.get('step')}, " + f"{got} steps past the base {BASE_STEP}") + for m in _PARENT.finditer(text): + seen += 1 + if rec.get("seed") is None: + unver.append(f"{where}:{line} `{path}` parent: no config.seed to compare") + elif int(m.group(1)) != int(rec["seed"]): + flag("[parent]", where, line, path, + f"row says it was fine-tuned off `RM_s{m.group(1)}_100k`; the blob trained with " + f"config.seed {rec['seed']} (the blob records its seed, not the file it resumed " + f"from, so this compares the parent's SEED)") + + # ---- [src]: the manifest's own claim, once per artefact, independent of any row ---------- + for dst, src in sorted(manifest.items()): + rec = records.get(dst) + if not rec or rec["kind"] != "pt" or not rec.get("present"): + continue + want = name_claims(Path(dst).name) + seen += 1 + if rec.get("seed") is not None and want["seed"] != int(rec["seed"]): + flag("[name]", "hf_upload.py", 0, dst, + f"the hub NAME says seed {want['seed']} (`_s_`, absent = 0) but the blob it ships " + f"records config.seed {rec['seed']}, written by `{Path(rec['out']).name}` -- the " + f"manifest line for this name points at the wrong cell, and every word of this " + f"file's row is derived from the name") + if want["step"] is not None and rec.get("step") is not None and want["step"] != rec["step"]: + flag("[name]", "hf_upload.py", 0, dst, + f"the hub NAME says step {want['step']} but the blob records step {rec['step']}") + seen += 1 + if Path(rec["out"]).name != Path(src).parent.name: + flag("[src]", "hf_upload.py", 0, dst, + f"manifest uploads it from `{Path(src).parent.name}/{Path(src).name}`, but the blob " + f"records config.out `{Path(rec['out']).name}` -- the manifest names the wrong cell, " + f"so every word this file's row derives from its name is about a DIFFERENT run") + m = re.search(r"ckpt_s(\d+)\.pt$", Path(src).name) + if m and int(m.group(1)) != (rec.get("step") or -1): + flag("[src]", "hf_upload.py", 0, dst, + f"manifest source file is `{Path(src).name}` but the blob records step {rec.get('step')}") + return bad, seen, unver + + +# ------------------------------------------------------------------ row extraction (both tables) +WHAT_COLS = ("what it is", "recipe") + + +def what_is_rows(pages, cols=WHAT_COLS): + """[(where, line, hub path, cell)] for every markdown row under a claim column. + + Both the `what it is` and the `recipe` columns assert a seed, a step, a stage and a parent, so + both are read; `where` names the column so a failure says which cell to repair. Columns that + are not claims about the artefact -- `bytes`, `verified` -- are O's and I/M's and stay out. + """ + rows = [] + for where, text in pages.items(): + lines = text.splitlines() + i = 0 + while i < len(lines): + head = ([c.strip() for c in lines[i].strip().strip("|").split("|")] + if lines[i].lstrip().startswith("|") else None) + picked = ([j for j, c in enumerate(head) if c.lower() in cols] if head else []) + if (head and len(head) > 1 and picked + and i + 1 < len(lines) and re.match(r"^\s*\|[\s:|-]+\|\s*$", lines[i + 1])): + j = i + 2 + while j < len(lines) and lines[j].lstrip().startswith("|"): + cells = [c.strip() for c in lines[j].strip().strip("|").split("|")] + fm = _FILE_CELL.search(cells[0]) if cells else None + for col in picked: + if fm and col < len(cells): + rows.append((f"{where} [{head[col].lower()}]", j + 1, + fm.group(1), cells[col])) + j += 1 + i = j + else: + i += 1 + return rows diff --git a/rsm_rise/scripts/real/audit271_Q_stack_record.py b/rsm_rise/scripts/real/audit271_Q_stack_record.py new file mode 100644 index 0000000000000000000000000000000000000000..53211815e3feecb7516ad92e3b487fd3af2c6139 --- /dev/null +++ b/rsm_rise/scripts/real/audit271_Q_stack_record.py @@ -0,0 +1,274 @@ +#!/usr/bin/env python +"""Check Q (gen_q #271, run 29): the RISE-STACK artefacts' own record, against the rows that describe them. + +Run 28's check P confirmed every seed/step/stage/parent word on the shipped pages against the +SUCCESSOR blobs' own `step` / `config.seed` / `config.out`, and reported two honest gaps. Q closes +the smaller one: the four artefacts P listed as "described but held by no record" -- + + rise_actor_rsm_real_s0_e3000.pth rise_actor_rsm_real_s1_e3000.pth + bc_union_rsm_real_s0_e5000.pth hop_head_rsm_real_gauss_r1.pt + +-- were outside P only because `read_records` reads a config shape these files do not have. Probed +first (run 29, `_audit271_Q_probe{,2}.py`), they turn out to record MORE than the successors do: +robomimic serialises its whole 187-leaf config into the `.pth` (`config.train.seed`, +`config.train.num_epochs`, `config.experiment.name`, `config.experiment.save.every_n_epochs`, +`algo.use_bc`), and the hop head carries `config.seed` and a top-level `round`. + +THE TRAP THE PROBE FOUND, and the reason this module exists in the shape it does. The card calls +`bc_union_rsm_real_s0_e5000.pth` "plain BC objective (`S0B`)". The blob's own `algo_name` is +**`idql`** -- for all three robomimic files alike. `scripts/run_train.sh:95` is why: `S0B` is the +SAME robomimic algo class as `S0Aidql`, with `training.use_bc=True`. So `algo_name` is the CLASS and +the OBJECTIVE is a flag, and an `[algo]` rule comparing the row's word "BC" against `algo_name` would +have failed a page that is CORRECT. That is run 28's lesson one file over (a rule can be wrong about +the artefact before the page is), and it is why Q reads `algo.use_bc` and declares `algo_name` +out of scope rather than checking the class and calling it the objective. + +RULES, each with its own tag so a failure names its own repair: + [seed] a row's "seed N" vs `config.train.seed` (robomimic) / `config.seed` (hop) + [cell] a row's backticked cell `S0B`/`S0Aidql` vs `config.experiment.name` + [obj] "plain BC" / "BC-union" / "no critic" vs `algo.use_bc == True` + "IQL critic" / "trained jointly with" vs `algo.use_bc == False` + [epochcap] a row's "epoch N" / "N epochs" vs `config.train.num_epochs` (an upper bound) and + `config.experiment.save.every_n_epochs` (N must be a multiple: robomimic could not have + written a checkpoint at any other epoch). See SCOPE -- this is a CONSTRAINT, not the + epoch itself. + [round] a hop row's "round N" and the name's `_r` vs the head's top-level `round` + [name] the hub FILE NAME's own `_s_` / `_e` vs the blob's seed, and the same epoch + constraint -- the name is the only party OUTSIDE the manifest loop, which is the one + lesson run 28 paid for: a record read AT the manifest's source agrees with the manifest + by construction, so only the name can contradict a mis-pointed line. + +SCOPE -- stated rather than papered over. Three kinds of word Q must NOT pretend to verify: + * THE EXACT EPOCH OF A CHECKPOINT IS NOT RECORDED. `config.train.num_epochs` is 5000 in all three + files, including the two the pages call "epoch 3000": it is the run's PLANNED length, not this + file's epoch, which lives only in the source file name `model_epoch_3000.pth`. A rule comparing + "3000 epochs" to `num_epochs` would fail all three correct rows. [epochcap] therefore asserts + only what the artefact can support -- N <= num_epochs and N % every_n_epochs == 0 -- and the + epoch word is ALSO listed as unverified so nobody reads a green Q as confirming it. + * `algo_name` is the class (`idql` for the BC cell too), so it is never compared to an objective + word, and Q says so in its detail line. + * "robomimic recipe", "same backbone/data" and similar prose name no field and are not claims Q + can answer; they are neither checked nor counted. + * an unverified word adds 0 to `seen` (run 19's guard against a vacuous pass). + +`q_rows_bad(rows, records, manifest)` is pure, so the negative control drives it on fixtures, and +the module does not import hf_card_refresh_table: the generator that WROTE these words must not +supply the parser that checks them (the shape that let the run-26 defect ship). +""" +from __future__ import annotations +import json +import re +from pathlib import Path + +ROOT = Path("/proj/dmfexp/zwhong/rsm_rise") + +_SEED = re.compile(r"\bseed\s+(\d+)\b", re.I) +_EPOCH_A = re.compile(r"\bepoch\s+(\d+)\b", re.I) +_EPOCH_B = re.compile(r"\b(\d+)\s+epochs\b", re.I) +_ROUND = re.compile(r"\bround\s+(\d+)\b", re.I) +_TICK = re.compile(r"`([^`]+)`") +_CELLTOK = re.compile(r"^S\d[A-Za-z0-9]*$") + +# objective words. Deliberately explicit: "BC-transformer" is the BACKBONE, not the objective, and +# must not be read as a BC claim -- the recipe cell for the IQL actor literally says +# "BC-transformer actor trained jointly with an IQL critic". +_BC_WORDS = (re.compile(r"\bplain\s+BC\b", re.I), re.compile(r"\bBC[-\s]union\b", re.I), + re.compile(r"\bBC\s+baseline\b", re.I), re.compile(r"\bno\s+critic\b", re.I), + re.compile(r"\bBC\s+objective\b", re.I)) +_IQL_WORDS = (re.compile(r"\bIQL\s+critic\b", re.I), + re.compile(r"\btrained\s+jointly\s+with\s+an?\s+IQL\b", re.I)) + +_NAME_SEED = re.compile(r"_s(\d+)_") +_NAME_EPOCH = re.compile(r"_e(\d+)\.pth?$") +_NAME_ROUND = re.compile(r"_r(\d+)\.pt$") + +# the hub names Q holds a record for; anything else stays P's or nobody's, and O owns coverage. +ROBOMIMIC = ("rise_actor_rsm_real_s0_e3000.pth", "rise_actor_rsm_real_s1_e3000.pth", + "bc_union_rsm_real_s0_e5000.pth") +HOP = ("hop_head_rsm_real_gauss_r1.pt",) + + +def read_stack_records(manifest, loader=None): + """{hub path: record} for the robomimic actors and the hop head.""" + if loader is None: + import torch + + def loader(p): + return torch.load(p, map_location="cpu", weights_only=False) + recs = {} + for dst, src in sorted(manifest.items()): + name = Path(str(dst)).name + if name in ROBOMIMIC: + recs[dst] = _robomimic_record(src, loader) + elif name in HOP: + recs[dst] = _hop_record(src, loader) + return recs + + +def _robomimic_record(src, loader): + r = {"kind": "robomimic", "src": str(src), "present": Path(src).exists()} + if not r["present"]: + return r + o = loader(src) + cfg = o.get("config") + if isinstance(cfg, str): + try: + cfg = json.loads(cfg) + except Exception as e: + r["config_error"] = f"{type(e).__name__}" + cfg = {} + cfg = cfg or {} + tr, ex, al = cfg.get("train", {}), cfg.get("experiment", {}), cfg.get("algo", {}) + r.update(seed=tr.get("seed"), num_epochs=tr.get("num_epochs"), + every_n_epochs=(ex.get("save", {}) or {}).get("every_n_epochs"), + exp_name=ex.get("name"), out_dir=str(tr.get("output_dir", "")), + use_bc=al.get("use_bc"), + # recorded and deliberately NOT used as an objective: see the module docstring + algo_name=o.get("algo_name") or cfg.get("algo_name")) + return r + + +def _hop_record(src, loader): + r = {"kind": "hop", "src": str(src), "present": Path(src).exists()} + if not r["present"]: + return r + o = loader(src) + c = o.get("config", {}) or {} + r.update(seed=c.get("seed"), round=o.get("round"), out=str(c.get("out", ""))) + return r + + +def _epochs_claimed(text): + out = [int(m.group(1)) for m in _EPOCH_A.finditer(text)] + out += [int(m.group(1)) for m in _EPOCH_B.finditer(text)] + return sorted(set(out)) + + +def _epoch_ok(n, rec): + """What the artefact CAN say about an epoch claim: (ok, why). Never 'this is the epoch'.""" + cap, every = rec.get("num_epochs"), rec.get("every_n_epochs") + if cap is not None and n > cap: + return False, (f"the run's own config.train.num_epochs is {cap}, so no checkpoint at " + f"epoch {n} can exist") + if every and n % every: + return False, (f"the run saves every {every} epochs (config.experiment.save.every_n_epochs), " + f"so epoch {n} is not an epoch it ever wrote") + return True, "" + + +def q_rows_bad(rows, records, manifest): + """rows: [(where, line, hub path, claim text)]. Returns (bad, seen, unverified).""" + bad, seen, unver = [], 0, [] + + def flag(tag, where, line, path, msg): + bad.append(f"{tag} {where}:{line} `{path}`: {msg}") + + for where, line, path, text in rows: + rec = records.get(path) or records.get(Path(str(path)).name) + if rec is None: + continue + if not rec.get("present"): + flag("[src]", where, line, path, + f"row describes an artefact whose declared source is MISSING on the cluster " + f"({rec.get('src')}) -- nothing verifies these words") + continue + + for m in _SEED.finditer(text): + if rec.get("seed") is None: + unver.append(f"{where}:{line} `{path}` seed {m.group(1)}: the blob records no seed") + continue + seen += 1 + if int(m.group(1)) != int(rec["seed"]): + flag("[seed]", where, line, path, + f"row says seed {m.group(1)}; the checkpoint's own " + f"{'config.train.seed' if rec['kind'] == 'robomimic' else 'config.seed'} is " + f"{rec['seed']} (source {rec['src']})") + + if rec["kind"] == "robomimic": + for tok in _TICK.findall(text): + if not _CELLTOK.match(tok): + continue + name = rec.get("exp_name") or "" + seen += 1 + if f"_{tok}_" not in name: + flag("[cell]", where, line, path, + f"row names cell `{tok}`; the checkpoint's own config.experiment.name is " + f"`{name}` (a cell token must match WHOLE -- `S0A` is not `S0Aidql`)") + bc = any(p.search(text) for p in _BC_WORDS) + iql = any(p.search(text) for p in _IQL_WORDS) + if bc or iql: + if rec.get("use_bc") is None: + unver.append(f"{where}:{line} `{path}` objective: the blob records no algo.use_bc") + else: + seen += 1 + if bc and iql: + flag("[obj]", where, line, path, + "row asserts BOTH a plain-BC objective and an IQL critic; the blob " + f"records algo.use_bc={rec['use_bc']} -- one of the two words is wrong") + elif bc and not rec["use_bc"]: + flag("[obj]", where, line, path, + "row calls this a plain-BC / no-critic checkpoint; the blob records " + f"algo.use_bc=False, i.e. it was trained WITH the critic objective " + f"(cell `{rec.get('exp_name')}`)") + elif iql and rec["use_bc"]: + flag("[obj]", where, line, path, + "row says it was trained jointly with an IQL critic; the blob records " + f"algo.use_bc=True, i.e. a plain BC objective (cell `{rec.get('exp_name')}`)") + for n in _epochs_claimed(text): + ok, why = _epoch_ok(n, rec) + if not ok: + seen += 1 + flag("[epochcap]", where, line, path, f"row says epoch {n}, but {why}") + else: + unver.append(f"{where}:{line} `{path}` epoch {n}: consistent with the run's own " + f"num_epochs/save cadence, but a robomimic blob does not record " + f"WHICH epoch it is -- that word rests on the source file name") + elif rec["kind"] == "hop": + for m in _ROUND.finditer(text): + if rec.get("round") is None: + unver.append(f"{where}:{line} `{path}` round {m.group(1)}: no top-level round") + continue + seen += 1 + if int(m.group(1)) != int(rec["round"]): + flag("[round]", where, line, path, + f"row says round {m.group(1)}; the head's own top-level round is {rec['round']}") + + # ---- [name]: the one party outside the manifest loop, once per artefact ------------------ + for dst in sorted(manifest): + rec = records.get(dst) + if not rec or not rec.get("present"): + continue + nm = Path(str(dst)).name + if rec["kind"] == "robomimic": + m = _NAME_SEED.search(nm) + if m and rec.get("seed") is not None: + seen += 1 + if int(m.group(1)) != int(rec["seed"]): + flag("[name]", "hf_upload.py", 0, dst, + f"the hub NAME says seed {m.group(1)} but the blob it ships records " + f"config.train.seed {rec['seed']}, from cell `{rec.get('exp_name')}` -- the " + f"manifest line for this name points at the wrong run, and every word of " + f"this file's row is derived from the name") + m = _NAME_EPOCH.search(nm) + if m: + n = int(m.group(1)) + ok, why = _epoch_ok(n, rec) + seen += 1 + if not ok: + flag("[name]", "hf_upload.py", 0, dst, + f"the hub NAME says epoch {n}, but {why}") + src_m = re.search(r"model_epoch_(\d+)\.pth$", Path(str(manifest[dst])).name) + if src_m and int(src_m.group(1)) != n: + flag("[name]", "hf_upload.py", 0, dst, + f"the hub NAME says epoch {n} but the manifest ships " + f"`{Path(str(manifest[dst])).name}` -- the file's own epoch, from the only " + f"party that records it, is {src_m.group(1)}") + elif rec["kind"] == "hop": + m = _NAME_ROUND.search(nm) + if m and rec.get("round") is not None: + seen += 1 + if int(m.group(1)) != int(rec["round"]): + flag("[name]", "hf_upload.py", 0, dst, + f"the hub NAME says round {m.group(1)} (`_r.pt`) but the head records " + f"top-level round {rec['round']}") + return bad, seen, unver diff --git a/rsm_rise/scripts/real/audit271_R_published_stats.py b/rsm_rise/scripts/real/audit271_R_published_stats.py new file mode 100644 index 0000000000000000000000000000000000000000..ce1b7d56edcc45bbfad87e8b70a9256ea7989af4 --- /dev/null +++ b/rsm_rise/scripts/real/audit271_R_published_stats.py @@ -0,0 +1,400 @@ +#!/usr/bin/env python +"""gen_q #271, run 30 -- check R: the NUMBERS a shipped page prints, against the measurement +JSON they were substituted from. + +The rung below run 29's. P and Q read what a row says about an ARTEFACT against the record the +artefact keeps about itself; every claim they cover names a file. The claims they cannot reach are +the ones that name no artefact at all: a NUMBER in prose or in a table cell -- an AUC, a bootstrap +CI, a p-value, a positive-frame count, a bold significance tick. Their witness is a JSON under +status/real/, and NO check reads it: + + * A compares the spliced block to status/real/CHECKPOINTS_reward_block.md -- the generator's + OUTPUT, not its INPUTS. Re-measure a diagnostic and the JSON moves while the block file and the + page stay as they were; A, N, O, P and Q all stay green and every printed number is stale. + * G asserts the diagnostics EXIST for every head, never that the page quotes them correctly. + +R therefore re-reads the witnesses and compares them to the page at the PRINTED precision. It does +not import the generator's formatting: a claim is checked as `|json - printed| <= half a unit in the +last printed place`, so a page that prints 0.51 and a page that prints 0.5087 are both correct +against 0.50872, and a rounding difference cannot make a correct page go red (the trap run 29's +hand-off wrote down). Counts are compared exactly. + +Claims covered, all over the same 12 pages + the HF model card the other checks sweep: + [pos] a row's `+1 frames` <- REWARD_SCHEMES.json pos_frames + [s4s6] a row's `AUC S4 vs S6 (segment)` <- REWARD_HEAD_DIAG.json auc_S4_vs_S6_segment + [junc] a row's `junction AUC R3 vs R4` <- REWARD_HEAD_DIAG.json auc_junction_R3_vs_R4 + [stitch] a row's `AUC [lo, hi] p=P` <- STITCH_SIGNIFICANCE.json by_hop["4"].heads + [screen] a row's `mean (D [lo, hi])` <- REWARD_SCREEN.json combined/first-seed heads + [tick] a bold **/checkmark/** on either of those two columns -- a SIGNIFICANCE claim in its own + right: stitch ticks iff p_boot_vs_half < 0.05, screen ticks iff beats_control + [prose] the same five-draw result stated AGAIN as prose on the model card, heads under their + FILE aliases (`B_H400` 0.5267 ... (5/5) ... (p = 0.017) ... between-draw SD of 0.0139), + including the blanket "each above chance in k/5 draws, p < 1e-3" over the heads the + sentence has already named. Read ONLY inside a sentence that names the design + ("draw-level ranking" / "five-draw replication"): the same pages print `B400` next to + 0.5402 and 0.5437 from two OTHER designs, and a proximity rule would go red on them. + [5draw] `five-draw stitching AUC X, above chance in k/5 draws (p=P) against the base head's B` + <- STITCH_DRAWS.json by_hop["4"]: mean_over_draws, n_draws_above_half, + p_draw_level_vs_half, and base's mean_over_draws + +Deliberate non-behaviours, each with a scenario in _audit271_R_selftest.py: + * a `_pending_` or `—` cell is NOT a claim: silent, and adds 0 to `seen` (run 19's guard). + * a row whose file token this module does not map is REPORTED as unmapped, never silently + skipped and never counted as seen -- an unmapped row is how a new head would hide from R. + * the file -> diagnostics-key map is R's own literal, and is cross-checked against the + generator's HEADS tuple as DATA; if the two disagree that is itself a FAIL, so R cannot + inherit a mismapping from the thing it audits. + * R reads no artefact and no hub listing; bytes, digests, sizes and names are I/M/O/P/Q's. +""" +from __future__ import annotations +import json, re +from pathlib import Path + +ROOT = Path("/proj/dmfexp/zwhong/rsm_rise") +ST = ROOT / "status/real" +CLONE = Path("/proj/dmfexp/zwhong/projs/rsm_real") + +# the 13 rows of the #271 reward-head table, by the file each one names. R's own literal; cross +# checked against the generator's HEADS below. +FILEKEY = { + "successor_rsm_real_A_110000.pt": "A", + "successor_rsm_real_A_s1_110000.pt": "A_s1", + "successor_rsm_real_RM_s0_100k.pt": "v0", + "successor_rsm_real_v0lit_110000.pt": "v0lit", + "successor_rsm_real_v0lit_s1_110000.pt": "v0lit_s1", + "successor_rsm_real_B_H100_110000.pt": "B", + "successor_rsm_real_B_H100_s1_110000.pt": "B_s1", + "successor_rsm_real_B_H400_110000.pt": "B400", + "successor_rsm_real_B_H400_s1_110000.pt": "B400_s1", + "successor_rsm_real_C_w3_110000.pt": "C3", + "successor_rsm_real_C_w3_s1_110000.pt": "C3_s1", + "successor_rsm_real_C_w10_110000.pt": "C10", + "successor_rsm_real_C_w10_s1_110000.pt": "C10_s1", +} +SCHEMEOF = { + "A": "A_to_eq_S4", "A_s1": "A_to_eq_S4", "v0": "v0_shipped_final_eq_S4", + "v0lit": "v0lit_final_in_S3_S4", "v0lit_s1": "v0lit_final_in_S3_S4", + "B": "B_window_H100", "B_s1": "B_window_H100", + "B400": "B_window_H400", "B400_s1": "B_window_H400", + "C3": "C_label_to_eq_S4", "C3_s1": "C_label_to_eq_S4", + "C10": "C_label_to_eq_S4", "C10_s1": "C_label_to_eq_S4", +} +NOT_A_CLAIM = ("_pending_", "—", "-", "") +NUM = r"[-+]?\d+(?:\.\d+)?" + + +# ------------------------------------------------------------------ precision-tolerant compare +def _dec(s: str) -> int: + s = s.strip() + return len(s.split(".")[1]) if "." in s else 0 + + +def close(printed: str, value, slack: float = 1e-12) -> bool: + """True iff `value` rounds to the number as printed, at the precision it was printed to.""" + if value is None: + return False + try: + p = float(printed) + except ValueError: + return False + return abs(float(value) - p) <= 0.5 * 10 ** (-_dec(printed)) + slack + + +# ------------------------------------------------------------------ witnesses +def load_witnesses(st: Path = ST) -> dict: + def jl(n): + q = st / n + return json.loads(q.read_text()) if q.exists() else None + sch = {s["name"]: s for s in (jl("REWARD_SCHEMES.json") or {"schemes": []})["schemes"]} + diag = (jl("REWARD_HEAD_DIAG.json") or {}).get("heads", {}) + sig = jl("STITCH_SIGNIFICANCE.json") or {} + sigh = ((sig.get("by_hop", {}) or {}).get("4") or {}).get("heads", {}) + scr = jl("REWARD_SCREEN.json") or {} + sblk = scr.get("combined") or (list(scr.get("seeds", {}).values()) or [{}])[0] + draws = jl("STITCH_DRAWS.json") or {} + h4 = (draws.get("by_hop", {}) or {}).get("4") or {} + d4 = h4.get("heads", {}) + return {"sch": sch, "diag": diag, "sig4": sigh, "screen": sblk.get("heads", {}), + "draws4": d4, "base4": (d4.get("base") or {}).get("mean_over_draws"), + "sd4": (h4.get("noise_floor") or {}).get("between_draw_sd_mean_over_heads")} + + +# ------------------------------------------------------------------ the #271 table on a page +HDR = ("stitching auc", "auc s4 vs s6") + + +def find_tables(text: str): + """Every markdown table whose header names the two #271 diagnostics columns -> its data rows. + Header-driven, so a size table or an availability table that also names a .pt cannot be read + as a reward-head row.""" + out, lines = [], text.splitlines() + for i, ln in enumerate(lines): + low = ln.lower() + if not (ln.startswith("|") and all(h in low for h in HDR)): + continue + rows, j = [], i + 2 # skip the |---| separator + while j < len(lines) and lines[j].startswith("|"): + if "---" not in lines[j]: + rows.append(lines[j]) + j += 1 + out.append(rows) + return out + + +def _cells(row: str): + return [c.strip() for c in row.strip().strip("|").split("|")] + + +def _tick(cell: str) -> bool: + return "✓" in cell + + + +# ------------------------------------------------------------------ [prose] the draw-level ranking +# The card states the five-draw result a SECOND time, as prose, with the heads under their FILE +# aliases rather than their diagnostics keys. Matching is WHOLE and backtick-delimited: `B_H100` is +# not `B_H400` and `v0lit` is not `v0lit_s1` (run 29's first-match-wins lesson, which produced the +# S0Bplain defect). +ALIAS = {"B_H400": "B400", "B_H400_s1": "B400_s1", "B_H100": "B", "B_H100_s1": "B_s1", + "v0lit": "v0lit", "v0lit_s1": "v0lit_s1", "A": "A", "A_s1": "A_s1", + "C_w3": "C3", "C_w3_s1": "C3_s1", "C_w10": "C10", "C_w10_s1": "C10_s1", + "R_M": "base", "base": "base"} + +# A prose number is only read inside a sentence that NAMES the design it belongs to. Without this +# the rule goes red on a correct page: CHECKPOINTS.md says "the top head is still `B400` at 0.5402" +# (the matched-horizon read-out) and "0.5437 (`B400`, `prob_log`)" (the functional sweep) -- both +# are head-next-to-a-number and NEITHER is a five-draw mean. Scenarios S18c/S18d hold this. +PROSE_TRIGGER = re.compile(r"draw-level ranking|five-draw replication") +PROSE_WINDOW = 700 + + +def prose_windows(text: str): + for m in PROSE_TRIGGER.finditer(text): + w = text[m.start(): m.start() + PROSE_WINDOW] + cut = w.find("\n\n") # a paragraph break ends the sentence + w = w[:cut] if cut > 0 else w + # the claim is wrapped by the page's line width, so "in 5/5\ndraws" and "`v0lit`\n0.5212" + # are the SAME claim as their unwrapped form; normalise before matching or the rule silently + # reads a third of what the sentence says (measured: 7 of 14 claims on the live card). + yield re.sub(r"\s+", " ", w) + + +def check_prose(where: str, text: str, W, bad: list) -> int: + """`alias` [(k/5)] [(p = P)] inside a five-draw sentence, plus the blanket + "each above chance in k/5 draws" and the between-draw SD. Returns the claims seen.""" + seen = 0 + pair = re.compile(rf"`([A-Za-z0-9_]+)`\s+({NUM})\s*(\((\d+)/5\))?\s*(\(p\s*=\s*({NUM})\))?") + for w in prose_windows(text): + named = [] # (key, offset) in the order the window names them + for m in pair.finditer(w): + tok, num, _kgrp, k, _pgrp, pv = m.groups() + key = ALIAS.get(tok) + if key is None: + continue + d = W["draws4"].get(key) or {} + named.append((key, m.start())) + seen += 1 + if not d: + bad.append(f"{where}[prose] {tok}: no witness in STITCH_DRAWS by_hop['4']") + continue + if not close(num, d.get("mean_over_draws")): + bad.append(f"{where}[prose] {tok}: {num} vs mean_over_draws {d.get('mean_over_draws')!r}") + if k is not None: + seen += 1 + if k != str(d.get("n_draws_above_half")): + bad.append(f"{where}[prose] {tok}: {k}/5 vs n_draws_above_half {d.get('n_draws_above_half')!r}") + if pv is not None: + seen += 1 + if not close(pv, d.get("p_draw_level_vs_half")): + bad.append(f"{where}[prose] {tok}: p {pv} vs {d.get('p_draw_level_vs_half')!r}") + + # the blanket claim: "(each above chance in 5/5 draws, p < 1e-3)" covers every head the + # window has named BEFORE it -- scoping matters, because the same window then says + # "against base `R_M` 0.4872 (0/5)". + for bm in re.finditer(rf"each above chance in (\d+)/5 draws(,\s*p\s*<\s*({NUM}(?:e-?\d+)?))?", w): + kk, _g, pth = bm.group(1), bm.group(2), bm.group(3) + heads = [h for h, off in named if off < bm.start()] + if not heads: + bad.append(f"{where}[prose] blanket '{kk}/5' claim names no head before it") + continue + for h in heads: + d = W["draws4"].get(h) or {} + seen += 1 + if str(d.get("n_draws_above_half")) != kk: + bad.append(f"{where}[prose] blanket {kk}/5 but {h} is " + f"{d.get('n_draws_above_half')!r}/5") + if pth is not None: + seen += 1 + if not (d.get("p_draw_level_vs_half") is not None + and d["p_draw_level_vs_half"] < float(pth)): + bad.append(f"{where}[prose] blanket p < {pth} but {h} is " + f"{d.get('p_draw_level_vs_half')!r}") + + for sm in re.finditer(rf"between-draw SD of ({NUM})", w): + seen += 1 + if not close(sm.group(1), W.get("sd4")): + bad.append(f"{where}[prose] between-draw SD {sm.group(1)} vs {W.get('sd4')!r}") + return seen + + +# ------------------------------------------------------------------ the claims +def check_pages(pages, W) -> dict: + """pages: [(where, text)]. Returns {seen, bad, unmapped, tables, fivedraw}.""" + seen, bad, unmapped, ntab, nfive = 0, [], [], 0, 0 + + for where, text in pages: + for rows in find_tables(text): + ntab += 1 + for row in rows: + c = _cells(row) + if len(c) < 8: + continue + files = re.findall(r"successor_rsm_real_[A-Za-z0-9_]+\.pt", c[7]) + key = FILEKEY.get(files[0]) if files else None + if key is None: + unmapped.append(f"{where}:{c[0][:40]!r}:{files[:1]}") + continue + pos, a_s4s6, a_junc, stitch, screen = c[2], c[3], c[4], c[5], c[6] + + # [pos] -- a COUNT, compared exactly + if pos not in NOT_A_CLAIM: + seen += 1 + want = (W["sch"].get(SCHEMEOF[key]) or {}).get("pos_frames") + if want is None or pos.replace(",", "") != str(want): + bad.append(f"{where}[pos] {key}: page {pos!r} vs json {want!r}") + + d = W["diag"].get(key) or {} + for tag, cell, fld in (("s4s6", a_s4s6, "auc_S4_vs_S6_segment"), + ("junc", a_junc, "auc_junction_R3_vs_R4")): + if cell in NOT_A_CLAIM: + continue + seen += 1 + m = re.fullmatch(NUM, cell) + if not m or not close(cell, d.get(fld)): + bad.append(f"{where}[{tag}] {key}: page {cell!r} vs json {d.get(fld)!r}") + + # [stitch] mean [lo, hi] p=P (+ [tick]) + if stitch not in NOT_A_CLAIM: + sg = W["sig4"].get(key) or {} + m = re.match(rf"({NUM}) \[({NUM}), ({NUM})\] p=(<1e-4|{NUM})", stitch) + seen += 1 + if not m or not sg: + bad.append(f"{where}[stitch] {key}: unparsed or no witness: {stitch!r}") + else: + g_m, g_lo, g_hi, g_p = m.groups() + ci = sg.get("auc_per_anchor_ci95") or [None, None] + if not close(g_m, sg.get("auc_per_anchor_mean")): + bad.append(f"{where}[stitch] {key}: mean {g_m} vs {sg.get('auc_per_anchor_mean')!r}") + if not (close(g_lo, ci[0]) and close(g_hi, ci[1])): + bad.append(f"{where}[stitch] {key}: ci [{g_lo}, {g_hi}] vs {ci!r}") + p = sg.get("p_boot_vs_half") + okp = (p is not None and p < 1e-4) if g_p == "<1e-4" else close(g_p, p) + if not okp: + bad.append(f"{where}[stitch] {key}: p {g_p} vs {p!r}") + seen += 1 + if _tick(stitch) != (p is not None and p < 0.05): + bad.append(f"{where}[tick] {key}: stitch tick={_tick(stitch)} but p={p!r}") + + # [screen] mean (delta [lo, hi]) (+ [tick]) + if screen not in NOT_A_CLAIM: + sc = W["screen"].get(key) or {} + m = re.match(rf"({NUM}) \(({NUM}) \[({NUM}), ({NUM})\]\)", screen) + seen += 1 + if not m or not sc: + bad.append(f"{where}[screen] {key}: unparsed or no witness: {screen!r}") + else: + g_m, g_d, g_lo, g_hi = m.groups() + ci = sc.get("ci95") or [None, None] + if not close(g_m, sc.get("oracle_rank_pct_mean")): + bad.append(f"{where}[screen] {key}: mean {g_m} vs {sc.get('oracle_rank_pct_mean')!r}") + if not close(g_d, sc.get("delta_vs_permuted")): + bad.append(f"{where}[screen] {key}: delta {g_d} vs {sc.get('delta_vs_permuted')!r}") + if not (close(g_lo, ci[0]) and close(g_hi, ci[1])): + bad.append(f"{where}[screen] {key}: ci [{g_lo}, {g_hi}] vs {ci!r}") + seen += 1 + if _tick(screen) != bool(sc.get("beats_control")): + bad.append(f"{where}[tick] {key}: screen tick={_tick(screen)} but " + f"beats_control={sc.get('beats_control')!r}") + + # [5draw] -- anywhere on the page, head taken from the last file named on the same line + pat = re.compile(rf"five-draw stitching AUC ({NUM}), above chance in (\d+)/5 draws " + rf"\(p=({NUM})\) against the base head's ({NUM})") + for mm in pat.finditer(text): + nfive += 1 + line = text[text.rfind("\n", 0, mm.start()) + 1: mm.end()] + fs = re.findall(r"successor_rsm_real_[A-Za-z0-9_]+\.pt", line) + key = FILEKEY.get(fs[-1]) if fs else None + if key is None: + unmapped.append(f"{where}:five-draw sentence naming {fs[-1:]!r}") + continue + d = W["draws4"].get(key) or {} + g_m, g_k, g_p, g_b = mm.groups() + seen += 1 + if not d: + bad.append(f"{where}[5draw] {key}: no witness in STITCH_DRAWS by_hop['4']") + continue + if not close(g_m, d.get("mean_over_draws")): + bad.append(f"{where}[5draw] {key}: mean {g_m} vs {d.get('mean_over_draws')!r}") + if g_k != str(d.get("n_draws_above_half")): + bad.append(f"{where}[5draw] {key}: k {g_k}/5 vs {d.get('n_draws_above_half')!r}") + if not close(g_p, d.get("p_draw_level_vs_half")): + bad.append(f"{where}[5draw] {key}: p {g_p} vs {d.get('p_draw_level_vs_half')!r}") + seen += 1 + if not close(g_b, W["base4"]): + bad.append(f"{where}[5draw] {key}: base head {g_b} vs {W['base4']!r}") + + seen += check_prose(where, text, W, bad) + + return {"seen": seen, "bad": bad, "unmapped": unmapped, "tables": ntab, "fivedraw": nfive} + + +# ------------------------------------------------------------------ R's map vs the generator's +def map_agrees_with_generator() -> list: + """The generator's HEADS is read as DATA (a tuple of names), never as a parser. Any + disagreement with R's own literal is a FAIL: R must not inherit a mismapping from the thing it + audits.""" + import importlib.util + p = ROOT / "scripts/real/build_checkpoints_reward_rows.py" + if not p.exists(): + return ["generator build_checkpoints_reward_rows.py not found"] + spec = importlib.util.spec_from_file_location("_b271gen", p) + mod = importlib.util.module_from_spec(spec) + spec.loader.exec_module(mod) # main() is guarded by __main__ + bad = [] + for key, _name, _form, skey, dkey, hf in mod.HEADS: + f = re.findall(r"successor_rsm_real_[A-Za-z0-9_]+\.pt", hf) + if not f: + bad.append(f"generator row {key}: no file token in {hf!r}") + continue + if FILEKEY.get(f[0]) != dkey: + bad.append(f"generator maps {f[0]} -> {dkey}, R maps it -> {FILEKEY.get(f[0])!r}") + if SCHEMEOF.get(dkey) != skey: + bad.append(f"generator maps {dkey} -> scheme {skey}, R maps it -> {SCHEMEOF.get(dkey)!r}") + return bad + + +def default_pages() -> list: + pg = (sorted((CLONE / "rise_stack").glob("*.md")) + sorted(CLONE.glob("*.md")) + + [ST / "HF_MODEL_CARD.md"]) + out = [] + for md in pg: + if md.exists(): + try: + where = str(md.relative_to(CLONE)) + except ValueError: + where = md.name + out.append((where, md.read_text())) + return out + + +def run() -> tuple: + W = load_witnesses() + res = check_pages(default_pages(), W) + res["map_bad"] = map_agrees_with_generator() + res["bad"] = res["bad"] + res["map_bad"] + return res + + +if __name__ == "__main__": + r = run() + print(json.dumps({k: v for k, v in r.items()}, indent=1)[:4000]) diff --git a/rsm_rise/scripts/real/audit271_S_foreign_stats.py b/rsm_rise/scripts/real/audit271_S_foreign_stats.py new file mode 100644 index 0000000000000000000000000000000000000000..e5907f08677a21be715dce2966fca59ad3cd377b --- /dev/null +++ b/rsm_rise/scripts/real/audit271_S_foreign_stats.py @@ -0,0 +1,229 @@ +"""Check S (run 31): the numbers a shipped page prints whose witness belongs to ANOTHER STREAM. + +The rung below R. R (run 30) covers every number whose witness is a JSON *this* stream wrote +(REWARD_SCHEMES, REWARD_HEAD_DIAG, STITCH_SIGNIFICANCE, REWARD_SCREEN, STITCH_DRAWS). The same +pages also quote the #269 / pi0.5 stream's screen: ten table rows of "spread X, oracle Y cm, +head Z", plus the prose that repeats them. Their witness is +status/real/openloop_pi05/scorer_openloop.json -- an artefact this stream does not write and +cannot regenerate. Nothing checked them: P/Q read a row's WORDS about an artefact, R only reads +witnesses it owns, and K/N/O/D read the hub, not the screen. So the #269 stream can re-run a +screen, overwrite a scorer_openloop.json, and every one of the eighteen other checks stays green +while ten shipped rows quote the superseded numbers. + +THREE THINGS THE PROBE ESTABLISHED (rr_cpu_271Sprobe31; the run-28/29/30 discipline -- probe the +witness before designing the rule, because a rule can be wrong about the witness before the page +ever is): + + 1. "head" IS NOT A FIELD. No scorer_openloop.json, and no pi05_readout/pi05_screen_stats JSON, + holds 0.598 for the default cell. `head` is DERIVED: greedy_first_mean_cm - oracle_first_mean_cm + (the headroom an ideal scorer could harvest). Verified on all ten rows before a line of this + module was written (0.4619->0.462 ... 0.5979->0.598, 30/30 exact). A rule that looked for a + `head` key would have reported ten false mismatches on a correct page. + + 2. A PROXIMITY RULE IS UNUSABLE HERE. The probe's naive pass ("any number on a line that says + pi0.5") scored 310 hits / 217 float misses on CHECKPOINTS.md alone: the hits were mostly + coincidences (1, 25, 128, 0.3) and the misses were hyperparameters (penalty 0.1, radius 1 cm), + byte counts and GiB sizes. S is therefore STRUCTURED -- it parses the screen statement by its + own grammar and reads nothing else. + + 3. THE SAME TABLE ROW CARRIES A FOREIGN DESIGN. Every row also states "Step-10000 held-out greedy + 1.044 cm first / 1.491 cm chunk, grip_acc 0.956". That is a FIT eval at training step 10000, + not the 25-episode screen, and it has no witness among these files -- the screen's own greedy + for that cell is 1.038. A rule that read "greedy" out of the row would go red on a correct + page. S is scoped to the screen statement and is deliberately SILENT on held-out greedy, + chunk, grip_acc and the knob columns (scenarios S9-S11). + +Claims covered: + [spread] "spread X" vs candidate_spread_xyz_cm + [oracle] "oracle Y cm" vs scorers.oracle.first_mean_cm + [head] "head Z" vs greedy_first_mean_cm - oracle_first_mean_cm (derived) +NOT covered, deliberately: `greedy`. The word is ambiguous between two designs in these rows -- +the risebn row's "greedy 23.453 cm" IS the screen's, but `sn0p1_knn0p03`'s "Step-10000 held-out +greedy 1.015 cm" is the FIT eval and falls INSIDE the screen window (it is written after the +screen statement on that row, unlike every other row). Measured live in run 31: a `greedy` rule +would compare 1.015 against the screen's 0.9987 and go red on a correct page. Scenario S19. + [nep] "full 25 ep"/"25 ep" vs n_episodes -- the design constant, not a result + [ncand] "over 128 candidates" vs n_cand +all compared at the PRINTED precision (|witness - printed| <= half a unit in the last printed +place), so a page that rounds cannot be made red by rounding. + +S does not read a digest, a byte count, a file list or a hub path -- those stay I/M/N/O/P/Q's. +""" +import json, re, pathlib + +ROOT = pathlib.Path("/proj/dmfexp/zwhong/rsm_rise") +ST = ROOT / "status" / "real" +CLONE = pathlib.Path("/proj/dmfexp/zwhong/projs/rsm_real") + +# --- the map, as S's OWN literals ------------------------------------------------------------- +# page folder token -> (witness directory, the openpi run/step its `policy` must name). +# S must not inherit the mapping it audits (R's lesson), so every entry is cross-checked against +# the witness's own `policy` string, which records the training run directory and step. +FOLDER2W = { + "pi05_rise_actor_rsm_real_rise_s0_29999": ("openloop_pi05rise_s0", "pi05_cooking_rise", "29999"), + "pi05_rise_actor_rsm_real_rise_s1_29999": ("openloop_pi05rise_s1", "pi05_cooking_rise", "29999"), + "pi05_rise_actor_rsm_real_riseadv_s0_29999": ("openloop_pi05riseadv_s0", "pi05_cooking_riseadv", "29999"), + "pi05_rise_actor_rsm_real_wsctrl_s0_ws9999": ("openloop_pi05wsctrl_ws9999", "pi05_cooking_wsctrl", "9999"), + "pi05_rise_actor_rsm_real_sn0p03_knn0p01_s0_ws9999": ("openloop_pi05sn0p03_knn0p01_ws9999","pi05_cooking_sn0p03_knn0p01", "9999"), + "pi05_rise_actor_rsm_real_sn0p1_knn0p03_s0_ws9999": ("openloop_pi05sn0p1_knn0p03_ws9999", "pi05_cooking_sn0p1_knn0p03", "9999"), + "pi05_rise_actor_rsm_real_sn0p1_knn0p05_s0_ws9999": ("openloop_pi05sn0p1_knn0p05_ws9999", "pi05_cooking_sn0p1_knn0p05", "9999"), + "pi05_rise_actor_rsm_real_sn0p3_knn0p01_s0_ws9999": ("openloop_pi05sn0p3_knn0p01_ws9999", "pi05_cooking_sn0p3_knn0p01", "9999"), + "pi05_rise_actor_rsm_real_sn0p3_knn0p03_s0_ws9999": ("openloop_pi05sn0p3_knn0p03_ws9999", "pi05_cooking_sn0p3_knn0p03", "9999"), + "pi05_rise_actor_rsm_real_sn1_knn0p03_s0_ws9999": ("openloop_pi05sn1_knn0p03_ws9999", "pi05_cooking_sn1_knn0p03", "9999"), + "pi05_rise_actor_rsm_real_sn1_knn0p05_s0_ws9999": ("openloop_pi05sn1_knn0p05_ws9999", "pi05_cooking_sn1_knn0p05", "9999"), + "pi05_rise_actor_rsm_real_risebn_s0_ws9999": ("openloop_pi05risebn_ws9999", "pi05_cooking_risebn", "9999"), + "pi05_bc_rsm_real_stock_s1_29999": ("openloop_pi05stock_s1", "pi05_cooking_stock", "29999"), + # The risebn diagnostic arm is named on the page by its TRAINING RUN PATH + # (`pi05_cooking_risebn/ws_s0/9999`), not by a hub folder -- it FAILS the keep rule and was + # never uploaded, so it has no hub name to be called by. Found by the run-31 self-test, which + # reported it as an unmapped screen row rather than skipping it (scenario S15). + "pi05_cooking_risebn": ("openloop_pi05risebn_ws9999", "pi05_cooking_risebn", "9999"), +} + + +def load_witnesses(root=None) -> dict: + """witness dir name -> {spread, oracle, greedy, head, n_episodes, n_cand, policy} or {'missing'}.""" + root = pathlib.Path(root) if root else ST + W = {} + for _folder, (wd, _run, _step) in FOLDER2W.items(): + j = root / wd / "scorer_openloop.json" + if not j.exists(): + W[wd] = {"missing": str(j)} + continue + try: + w = json.loads(j.read_text()) + except Exception as e: + W[wd] = {"missing": f"unreadable: {e}"} + continue + sc = w.get("scorers") or {} + o = (sc.get("oracle") or {}).get("first_mean_cm") + g = (sc.get("greedy") or {}).get("first_mean_cm") + W[wd] = { + "spread": w.get("candidate_spread_xyz_cm"), + "oracle": o, + "greedy": g, + # DERIVED -- see docstring note 1. None if either side is absent, so a truncated + # witness fails loudly rather than silently comparing against a wrong number. + "head": (g - o) if isinstance(g, (int, float)) and isinstance(o, (int, float)) else None, + "n_episodes": w.get("n_episodes"), + "n_cand": w.get("n_cand"), + "policy": w.get("policy") or "", + "tag": w.get("tag"), + } + return W + + +def map_agrees_with_witness(W: dict) -> list: + """Cross-check S's literals against each witness's OWN policy string (run dir + step). + + This is the discipline R's map_agrees_with_generator() uses and the reason the run-29/30 + probes existed: if the #269 stream re-points a directory at a different training run, the + numbers would still parse and still compare -- against the wrong cell. + """ + bad = [] + for folder, (wd, run, step) in FOLDER2W.items(): + w = W.get(wd) + if not w: + bad.append(f"map: no witness loaded for {wd}") + continue + if "missing" in w: + continue # reported by the caller as a missing witness + pol = w["policy"] + if run not in pol: + bad.append(f"map: {folder} -> {wd}, whose policy {pol[:70]!r} does not name run {run!r}") + elif not re.search(rf"/{re.escape(step)}(/|$)", pol): + bad.append(f"map: {folder} -> {wd}, whose policy {pol[:70]!r} does not end at step {step!r}") + return bad + + +def _close(witness: float, printed: str) -> bool: + """|witness - printed| <= half a unit in the last printed place (R's rule).""" + nd = len(printed.split(".")[1]) if "." in printed else 0 + return abs(float(witness) - float(printed)) <= 0.5 * (10 ** -nd) + 1e-12 + + +# --- the screen statement's grammar ----------------------------------------------------------- +# It appears in two punctuations, both live: +# "screened, full 25 ep: spread 0.317, oracle 0.478 cm, head 0.462" +# "SCREENED (25 ep, LSF 1855155): spread **0.446** / oracle **0.440** / head **0.598**" +# Scoped to a window that NAMES ITS DESIGN (the word SCREEN/screened + "ep"), which is what keeps +# the row's Step-10000 held-out-greedy sentence -- a foreign design -- out of reach (note 3). +SCREEN_WIN = re.compile(r"(?i)\bscreened?\b[^.|]{0,80}?(\d+)\s*ep\b(.{0,340})") +NUMBER = r"\*{0,2}(\d+\.\d+|\d+)\*{0,2}" +FIELDS = [("spread", re.compile(r"(?i)\bspread\s+" + NUMBER)), + ("oracle", re.compile(r"(?i)\boracle\s+" + NUMBER)), + ("head", re.compile(r"(?i)\bhead\s+" + NUMBER))] +# The row's subject appears either as a hub folder (`pi05_rise_actor_..._ws9999/`) or, for an arm +# that was never uploaded, as its training run path (`pi05_cooking_risebn/ws_s0/9999`). Both are +# the same kind of token: a backticked pi05_* name, optionally followed by a path tail. +FOLDER_TOK = re.compile(r"`(pi05_[A-Za-z0-9_]+)(?:/[A-Za-z0-9_/]*)?`") + + +def check_pages(pages, W) -> dict: + """pages: [(where, text)]. Returns {seen, bad, unmapped, rows}.""" + seen, bad, unmapped, rows = 0, [], [], 0 + for where, text in pages: + for ln, line in enumerate(text.splitlines(), 1): + if not line.lstrip().startswith("|"): + continue # table rows only (S13) + toks = FOLDER_TOK.findall(line) + m = SCREEN_WIN.search(line) + if not m: + continue + if not toks: + unmapped.append(f"{where}:{ln} screen statement with no `pi05_*` folder token") + continue + folder = toks[0] # the row's subject: its FIRST token + ent = FOLDER2W.get(folder) + if ent is None: + unmapped.append(f"{where}:{ln} row names {folder}, which S does not map") + continue + wd = ent[0] + w = W.get(wd) or {} + if "missing" in w: + bad.append(f"{where}:{ln} [witness] {folder}: {w['missing']}") + continue + rows += 1 + nep, tail = m.group(1), m.group(2) + # [nep] the design constant the row states about itself + seen += 1 + if str(w["n_episodes"]) != nep: + bad.append(f"{where}:{ln} [nep] {folder}: page {nep} ep, witness n_episodes={w['n_episodes']}") + for key, rx in FIELDS: + mm = rx.search(tail) + if not mm: + continue # a row need not state all three (S7) + printed, wv = mm.group(1), w[key] + seen += 1 + if wv is None: + bad.append(f"{where}:{ln} [{key}] {folder}: page {printed}, witness has no value") + elif not _close(wv, printed): + bad.append(f"{where}:{ln} [{key}] {folder}: page {printed}, witness {wv:.4f}") + return {"seen": seen, "bad": bad, "unmapped": unmapped, "rows": rows} + + +def default_pages() -> list: + pg = (sorted((CLONE / "rise_stack").glob("*.md")) + sorted(CLONE.glob("*.md")) + + [ST / "HF_MODEL_CARD.md"]) + out = [] + for md in pg: + if md.exists(): + try: + where = str(md.relative_to(CLONE)) + except ValueError: + where = md.name + out.append((where, md.read_text())) + return out + + +def run() -> dict: + W = load_witnesses() + res = check_pages(default_pages(), W) + res["map_bad"] = map_agrees_with_witness(W) + res["bad"] = res["bad"] + res["map_bad"] + res["n_witnesses"] = sum(1 for v in W.values() if "missing" not in v) + return res + + +if __name__ == "__main__": + print(json.dumps(run(), indent=1, default=str)[:4000]) diff --git a/rsm_rise/scripts/real/audit271_U_design_constants.py b/rsm_rise/scripts/real/audit271_U_design_constants.py new file mode 100644 index 0000000000000000000000000000000000000000..59dad43e7172fc168b4607f1efc4b5ee0549084b --- /dev/null +++ b/rsm_rise/scripts/real/audit271_U_design_constants.py @@ -0,0 +1,328 @@ +#!/usr/bin/env python +"""gen_q #271, run 33 -- check U: the DESIGN CONSTANTS a shipped page prints, against the config +the artefact recorded for ITSELF. + +The rung below R and S. R reads the printed RESULT numbers against the measurement JSON they were +substituted from; S does the same for the numbers whose witness belongs to another stream. Neither +reads the SETTINGS the measurement was taken AT -- the beta, the gamma, the particle count, N, the +flow steps, the checkpoint, the split. A page can quote the right AUC out of the right JSON and +describe it as measured at beta 0.99 when the JSON's own `config` says 0.95, and all 19 checks stay +green. Worse: two pages print a RUNNABLE COMMAND under a heading that says "Reproducing it", and a +reader who runs it gets whatever the flags say, not what the section measured. + +U has two parts, and neither guesses at a witness -- the §8 trap of run 32 (four printed numbers +with no identifiable design) is the thing to avoid: + + [recipe] a block of constants whose heading NAMES ITS CELL in backticks, resolved to a witness by + that witness's OWN `config.tag` (never by a filename guess). Every printed constant is + compared to the cell's own config field at the PRINTED precision. A constant no record + holds -- the 0.80 coverage gate is a pre-registered BAR, written in no config and no + script -- is REPORTED as `no record`, never passed and never failed (check P's rule). + + [repro] a fenced command that names a checkpoint, under a heading that prints results. U + collects every artefact of that script's shape whose recorded design equals the + command's other flags, splits them into the ones recording the COMMANDED checkpoint and + the ones carrying the SECTION'S PRINTED NUMBERS, and FAILs when those two sets are + disjoint. A witness is "of record" only if at least TWO of the section's printed + numbers match it at the printed precision: run 32's T1 probe measured single-value + matching unusable (41 files hold "5.3"), and 0.96875 is 93/96, which many arms hit. + +Deliberate non-behaviours, each with a scenario in _audit271_U_selftest.py: + * a block whose cell name resolves to NO witness is REPORTED as unanchorable, never silently + skipped -- an unanchored block is how a new recipe would hide from U. + * a constant with no config key is `no record`, not a pass (the coverage gate). + * U reads no bytes, no hub listing and no result table; those are I/M/O/P/Q/R/S's. + * the flag -> config-key map is U's own literal and is cross-checked against the witnesses that + actually record those keys; a key no witness in the corpus records is reported. +""" +from __future__ import annotations +import json, re +from collections import defaultdict +from pathlib import Path + +ROOT = Path("/proj/dmfexp/zwhong/rsm_rise") +ST = ROOT / "status/real" +CLONE = Path("/proj/dmfexp/zwhong/projs/rsm_real") + +# ---------------------------------------------------------------- literals (U's own, cross-checked) +# a printed constant -> the regex that finds it -> the config keys a witness records it under +CLAIMS = [ + ("beta", re.compile(r"\bbeta\s+([01]\.\d+)", re.I), ["rsm_beta", "beta"]), + ("gamma", re.compile(r"\bgamma\s+([01]\.\d+)", re.I), ["rsm_gamma", "gamma"]), + ("particles", re.compile(r"\b(\d+)\s+particles\b"), ["rsm_particles", "particles"]), + ("n_cand", re.compile(r"\bN\s*=\s*(\d+)\s+candidates\b"), ["n_cand"]), + ("flow_steps", re.compile(r"\b(\d+)\s+flow steps\b"), ["rsm_flow_steps", "flow_steps"]), + ("rsm_ckpt", re.compile(r"\b([A-Za-z0-9_]+/ckpt_s\d+\.pt)\b"), ["rsm_ckpt"]), + ("policy_run", re.compile(r"\b([a-z0-9_]+_s\d+/\d+)\b"), ["policy"]), + ("held_out", re.compile(r"\b(held-out split)\b"), ["held_out"]), + ("gate", re.compile(r"\(gate\s+([01]\.\d+)"), []), # a BAR: no record + ("coverage", re.compile(r"coverage\s+([01]\.\d+)"), ["@states/S0/coverage"]), + ("depth", re.compile(r"\bdepth\s+(\d+)\b"), ["rsm_depth"]), + ("temperature", re.compile(r"\btemperature\s+([\d.]+)"), ["rsm_temperature"]), +] +# a command flag -> the field the artefact records it under +FLAG2FIELD = { + "beta": "beta", "gamma": "gamma", "particles": "particles", + "n-distractor": "K", "n_distractor": "K", "rsm-ckpt": "rsm_ckpt", "rsm_ckpt": "rsm_ckpt", +} +# A repro section's numbers are read ONLY where the PROSE LABELS them. Run 32's T1 probe measured +# bare-value matching unusable (41 unrelated files hold "5.3"), and U's own first run reproduced that +# failure: scraping 21 numbers out of 40 lines of context named a JUNC_feat arm as the witness on 16 +# coincidental hits. Each entry is (field, regex); TOPLEVEL fields sit on the artefact, BYLEVEL ones +# inside by["rsm|"]. +TOPLEVEL = [ + ("n_anchors", re.compile(r"\ball (\d+) anchors\b")), + ("n_anchor_episodes", re.compile(r"\b(\d+) validation episodes\b")), + ("chance_top1", re.compile(r"\bchance of ([01]\.\d+)")), +] +BYLEVEL = [ + ("top1_tie", re.compile(r"\btop-1 ([01]\.\d+)")), + ("rank_pct_mid", re.compile(r"\brank percentile ([01]\.\d+)")), + ("ties_at_max", re.compile(r"\bTies at the maximum are ([01]\.\d+)")), + ("score_cv", re.compile(r"\bcoefficient of variation of ([01]\.\d+)")), +] +BACKTICK = re.compile(r"`([A-Za-z0-9_./-]+)`") +FLAG = re.compile(r"--([a-zA-Z][\w-]*)(?:[ =]+((?:[^\s\\]|\\.)+))?") +NUM = re.compile(r"(? 40_000_000: return None + d = json.loads(p.read_text()) + except Exception: + return None + return d if isinstance(d, dict) else None + + +def corpus(): + """(tag -> witness paths with a config block, list of (path, dict) for rank-shaped artefacts)""" + tagidx = defaultdict(list); ranks = []; ncfg = 0 + for p in sorted(ST.rglob("*.json")): + d = _load(p) + if d is None: continue + cfg = d.get("config") + if isinstance(cfg, dict): + ncfg += 1 + t = cfg.get("tag") + if isinstance(t, str) and t: + tagidx[t].append(str(p.relative_to(ROOT))) + if {"beta", "gamma", "particles", "rsm_ckpt"} <= set(d): + ranks.append((str(p.relative_to(ROOT)), d)) + return tagidx, ranks, ncfg + + +def getpath(d, spec): + cur = d + for k in spec[1:].split("/"): + if not isinstance(cur, dict) or k not in cur: return None + cur = cur[k] + return cur + + +def at_printed_precision(printed, recorded): + """R's rule: |json - printed| <= half a unit in the last printed place.""" + try: + pv = float(printed); rv = float(recorded) + except (TypeError, ValueError): + return None + dec = len(str(printed).split(".")[1]) if "." in str(printed) else 0 + return abs(pv - rv) <= 0.5 * 10 ** -dec + 1e-12 + + +def cmpval(kind, printed, recorded): + if recorded is None: return None, "no record" + if kind == "held_out": + return bool(recorded) is True, f"'held-out split' vs held_out={recorded}" + num = at_printed_precision(printed, recorded) + if num is not None: + return num, f"{printed} vs {recorded}" + ps, rs = str(printed), str(recorded) + return (ps == rs or rs.endswith(ps) or ps in rs), f"{ps!r} vs {rs!r}" + + +# ---------------------------------------------------------------- part 1: anchored recipe blocks +def blocks_of(pg): + """(start_line, body_lines, all_lines) for each fenced block and each run of >=2 indented lines.""" + try: lines = pg.read_text().splitlines() + except Exception: return [] + out = []; infence = False; cur = []; start = None + for i, ln in enumerate(lines, 1): + if ln.strip().startswith("```"): + if infence and cur: out.append((start, cur, lines)) + cur = []; infence = not infence + if infence: start = i + continue + if infence: + cur.append(ln); continue + if ln.startswith(" ") and ln.strip(): + if not cur: start = i + cur.append(ln) + else: + if len(cur) >= 2: out.append((start, cur, lines)) + cur = [] + if len(cur) >= 2: out.append((start, cur, lines)) + return out + + +def part_recipe(tagidx, res): + for pg in pages(): + for start, body, lines in blocks_of(pg): + txt = "\n".join(body) + if "--rsm-ckpt" in txt: # a reproduction command is part 2's, not a recipe block + continue + found = [(k, rx) for k, rx, _ in CLAIMS if rx.search(txt)] + if len(found) < 3: # a block with 1-2 stray numbers is not a recipe + continue + names = [] + for j in range(max(0, start - 4), start - 1): + names += BACKTICK.findall(lines[j]) + names += BACKTICK.findall(txt) + cell = next((nm for nm in names if nm in tagidx), None) + if cell is None: + res["unanchored"].append({"page": rel(pg), "line": start, + "n_constants": len(found), "names_seen": names[:6]}) + continue + wpath = tagidx[cell][0] + w = _load(ROOT / wpath) or {} + cfg = w.get("config", {}) + res["cells"].append({"page": rel(pg), "line": start, "cell": cell, "witness": wpath}) + for kind, rx, keys in CLAIMS: + m = rx.search(txt) + if not m: continue + printed = m.group(1) + recorded = used = None + for k in keys: + v = getpath(w, k) if k.startswith("@") else cfg.get(k) + if v is not None: recorded, used = v, k; break + ok, detail = cmpval(kind, printed, recorded) + item = {"kind": "recipe", "page": rel(pg), "line": start, "cell": cell, + "constant": kind, "printed": printed, "cfg_key": used, "detail": detail} + if ok is None: res["no_record"].append(item) + elif ok: res["seen"] += 1 + else: res["bad"].append(item) + if ok: res["seen_items"].append(item) + + +# ---------------------------------------------------------------- part 2: reproduction commands +def part_repro(ranks, res): + for pg in pages(): + try: lines = pg.read_text().splitlines() + except Exception: continue + for start, body, _ in blocks_of(pg): + txt = re.sub(r"\\\s*\n", " ", "\n".join(body)) + if "scripts/real/" not in txt or "--rsm-ckpt" not in txt: + continue + flags = {} + for m in FLAG.finditer(txt): + v = m.group(2) + flags[m.group(1)] = "" if (v is None or v.startswith("--")) else v.strip("'\"") + ck = flags.get("rsm-ckpt") or flags.get("rsm_ckpt") + design = {FLAG2FIELD[f]: v for f, v in flags.items() + if f in FLAG2FIELD and FLAG2FIELD[f] != "rsm_ckpt" and v != ""} + # what the SECTION says, only where the prose labels it. The window is the ENCLOSING + # level-2 section, not a fixed number of lines: U's second run took 40 lines and missed + # the headline sentence at the top of the section (the `###` the block sits under is + # "Reproducing IT", and "it" is the `##` section's experiment). + head = 0 + for j in range(start - 2, -1, -1): + if re.match(r"^#{1,2} ", lines[j]): head = j; break + ctx = "\n".join(lines[head:start - 1]) + top_claims = {f: m.group(1) for f, rx in TOPLEVEL for m in [rx.search(ctx)] if m} + by_claims = {f: m.group(1) for f, rx in BYLEVEL for m in [rx.search(ctx)] if m} + entry = {"kind": "repro", "page": rel(pg), "line": start, "commanded_ckpt": ck, + "design": design, "labelled_toplevel": top_claims, "labelled_bylevel": by_claims} + if len(by_claims) < 3: + res["unanchored"].append({**entry, "why": "the section labels fewer than 3 result numbers"}) + continue + # design match = the command's own flags AND every top-level number the prose labels + matched = [] + for path, d in ranks: + if not all(at_printed_precision(v, d.get(k)) for k, v in design.items()): continue + if not all(at_printed_precision(v, d.get(k)) for k, v in top_claims.items()): continue + matched.append((path, d)) + entry["n_design_matched"] = len(matched) + if not matched: + res["unanchored"].append({**entry, "why": "no artefact records this design"}) + continue + + def labelled_hits(d): + """the best single by["rsm|*"] dict: how many LABELLED fields it reproduces""" + best = 0 + for key, b in (d.get("by") or {}).items(): + if not (isinstance(b, dict) and key.startswith("rsm|")): continue + h = sum(1 for f, v in by_claims.items() + if f in b and at_printed_precision(v, b[f])) + best = max(best, h) + return best + + scored = [(p, labelled_hits(d)) for p, d in matched] + # a witness is "of record" only if it reproduces EVERY labelled result number the + # section prints (>=4 of them); with only 3 labelled, all 3. U's third run allowed one + # miss and 11 arms qualified -- 0.969 is 93/96 and "ties 1.00" is common, so a slack + # rule re-creates the coincidence problem run 32's T1 probe measured. + need = len(by_claims) + record = [p for p, h in scored if h >= need] + entry["best_labelled_hits"] = max((h for _, h in scored), default=0) + entry["need"] = need + entry["n_of_record"] = len(record) + entry["witness_of_record"] = record[:4] + entry["record_ckpts"] = sorted({str((_load(ROOT / p) or {}).get("rsm_ckpt")).split("/rsm/")[-1] + for p in record})[:6] + tail = ck.split("/rsm/")[-1] if ck and "/rsm/" in ck else (ck or "") + commanded = [p for p, d in matched if tail and str(d.get("rsm_ckpt", "")).endswith(tail)] + entry["commanded_witnesses"] = commanded[:4] + if not record: + res["unanchored"].append({**entry, "why": "no artefact reproduces the labelled numbers"}) + continue + if commanded and set(commanded) & set(record): + res["seen"] += 1; res["seen_items"].append(entry); continue + entry["why"] = ("the artefact(s) reproducing the section's LABELLED numbers " + f"{entry['record_ckpts']} record a DIFFERENT checkpoint than the " + f"command names ({tail})") + res["bad"].append(entry) + + +def run(): + tagidx, ranks, ncfg = corpus() + res = {"seen": 0, "seen_items": [], "bad": [], "no_record": [], "unanchored": [], "cells": []} + part_recipe(tagidx, res) + part_repro(ranks, res) + # the flag->field map, cross-checked against what the corpus actually records + # ...but only against a NON-EMPTY corpus: "no artefact records this field" is a statement + # about the corpus, and with no artefacts at all it is vacuous, not a mismapping. + unrecorded = sorted({f for f in set(FLAG2FIELD.values()) + if not any(f in d for _, d in ranks)}) if ranks else [] + res["map_fields_no_artifact_records"] = unrecorded + if unrecorded: + res["bad"].append({"kind": "map", "why": f"U names config fields no artefact records: {unrecorded}"}) + ok = not res["bad"] + detail = (f"{res['seen'] + len(res['bad']) + len(res['no_record'])} design-constant claim(s) over " + f"{len(res['cells'])} named cell(s) and the reproduction command(s) on the 12 pages + the " + f"HF card, each against the config the artefact recorded for ITSELF ({ncfg} config-bearing " + f"JSONs, {len(tagidx)} distinct config.tag, {len(ranks)} rank-shaped artefacts); compared at " + f"the printed precision; {len(res['no_record'])} constant(s) NO record holds (the coverage " + f"gate is a pre-registered bar) -- reported, not passed; {len(res['unanchored'])} block(s) " + f"U cannot anchor to a cell (reported, not counted); bad={[b.get('why') or b.get('constant') for b in res['bad']]}") + return ok, detail, res + + +if __name__ == "__main__": + ok, detail, res = run() + print(("PASS" if ok else "FAIL"), detail) + (ST / "AUDIT271_U_DESIGN.json").write_text(json.dumps(res, indent=1, default=str)) + for b in res["bad"]: + print(" BAD", json.dumps(b, default=str)[:500]) + for u in res["unanchored"]: + print(" unanchored", json.dumps(u, default=str)[:300]) + for n in res["no_record"]: + print(" no-record", json.dumps(n, default=str)[:200]) diff --git a/rsm_rise/scripts/real/audit271_V_cross_page.py b/rsm_rise/scripts/real/audit271_V_cross_page.py new file mode 100644 index 0000000000000000000000000000000000000000..08efad8b149f5fbb896442c8d973f9c125dd6770 --- /dev/null +++ b/rsm_rise/scripts/real/audit271_V_cross_page.py @@ -0,0 +1,344 @@ +#!/usr/bin/env python +"""gen_q #271, run 34 -- check V: two shipped pages stating the SAME named quantity must agree. + +The rung below R/S/U, and the one that covers this stream's blind spot. R resolves a printed +statistic to its measurement JSON; S does it for another stream's artefacts; U does it for the +design constants. All three are RESOLVERS: each takes a number on a page, finds its witness, and +compares. When there is NO witness all three go SILENT -- correctly, because inventing one is check +P's forbidden move. But silence is not absence of a defect: run 32 §4 found four numbers on a +shipped page that no artefact on disk reproduces, and could conclude nothing beyond "unwitnessed". + +V is the check that works where the resolvers cannot. If two pages state the same quantity for the +same subject, they must agree with EACH OTHER -- and that is decidable from the pages alone, with no +artefact, no hub call and no config. A number with no witness is still checkable the moment a +second page mentions it. + +Rules, each one paid for by a failure of this stream's own: + * A mention requires the quantity's NAME **and** a resolvable SUBJECT in the same sentence. Never + a bare value: run 32's T1 probe measured value-only matching unusable (41 files hold "5.3") and + run 33's first U wiring reproduced the same error on 16 coincidental hits. + * A subject that only ONE page states is NOT cross-checkable. It is REPORTED, never passed -- + a vacuous pass is how a lone wrong number would hide from V. + * Every mention becomes an INTERVAL (a point -> [v,v]; a range "0.81-0.88" -> [0.81,0.88]; a set + "0.88 / 0.86" -> [min,max]). Two mentions DISAGREE only when their intervals are DISJOINT at + the coarser of the two printed precisions. This is deliberately conservative: pages state a + quantity at different granularity (a class range vs per-arm points, S0 vs S2), and V must fire + on contradiction, not on granularity. + * The arm -> class map is V's own literal, printed in the output so it can be argued with. + * V compares pages to pages ONLY. It never opens an artefact, so it can never be right or wrong + about a witness -- the failure mode that bit runs 32 and 33. +""" +from __future__ import annotations +import json, re +from collections import defaultdict +from pathlib import Path + +ROOT = Path("/proj/dmfexp/zwhong/rsm_rise") +ST = ROOT / "status/real" +CLONE = Path("/proj/dmfexp/zwhong/projs/rsm_real") + +# ------------------------------------------------------------------ V's literals (argue with these) +# the subject an arm name belongs to. "RISE arms" is a CLASS on one page and per-arm points on +# another, so the class is what the two can be compared at. +ARM_CLASS = [ + (re.compile(r"plain\s+pi0\.5|pi0\.5\s+stock|stock\s+pi0\.5|pi05_cooking_stock|\bstock\b", + re.I), "stock"), + (re.compile(r"sn1|sn0p3|sn0p1|n512|rise_s0|RISE\s+arms?|\bRISE\b|best\s+proposer" + r"|default\s+proposer|the\s+default\s+cell", re.I), "rise_arms"), +] +# The BRANCH STATE a mention is qualified to. Added run 35, and it is a RETRACTION: run 34's V +# published a "contradiction" between FINDINGS.md:10 (0.81-0.88) and EDGE_TEST.md:145 (sn1 0.942, +# RISE 0.904) that the record does not support. Measured against the arm directories +# (_audit271_W_probe.json, from run 32's T3 read-out) the RISE-arm coverage band is +# S0 0.9038-0.9416 and S2 0.7043-0.8093 -- two states that differ by ~0.13, far more than the +# 0.005 tolerance V compares at. EDGE_TEST.md:145 matches S0 exactly; FINDINGS.md:10 is disjoint +# from S0 and sits at the S2 end. The two pages were never stating the same quantity, and V broke +# the ONE rule its own docstring sets: fire on contradiction, not on granularity. +# +# So STATE joins the subject. A mention whose state does not resolve is REPORTED, never compared -- +# the same decline-rather-than-guess discipline that the arm attribution needed after three wrong +# wirings, and that run 35's per-arm probe (_audit271_V3_probe.json: a full arm name resolves for +# 0 of 13 coverage values and 2 of 12 spread values) says the pages cannot support at arm level. +STATE_WORDS = [ + # the trailing lookahead must reject `S2.coverage` (a JSON key) but NOT `S2.` at the end of a + # sentence -- `(?![\w.])` rejected both, and the control caught it: "0.90 at S0 and 0.78 at S2." + # resolved to S0 alone instead of declining as ambiguous. `(?!\w|\.\w)` is the distinction. + (re.compile(r"\bat\s+(?:the\s+)?initial\s+state\b|\binitial\s+state\b|(?=\s*[01]?\.\d+\s+of\s+anchors", re.I), + re.compile(r"<\s*[01]?\.\d+", re.I), + re.compile(r"\bd\s*[+\u2212-]\s*\d*\.\d+", re.I), # an effect size, not a coverage + # `coverage@1 cm` is a DIFFERENT quantity (a paired delta in cm against a control), + # not the on-route direction-cluster coverage these pages gate the proposer on + re.compile(r"coverage@\s*\d+\s*cm[^.;|]*", re.I), + re.compile(r"Spearman\([^)]*\)\s*=\s*\*{0,2}[-\u2212]?\d?\.\d+", re.I), + ], + }, + "candidate_spread_mm": { + "name": re.compile(r"\bspread\b", re.I), + "band": (0.1, 100.0), + # only a number the page itself marks as millimetres, either directly or as the left half + # of a "6.8 / 6.5 mm" pair + "value": re.compile(r"(? ...<=TRAIL_GAP chars ending in 'for'/'on'... (tried FIRST) + P1 ...<=LEAD_GAP chars, no other subject... + Returns the class, or None (reported, never guessed).""" + for q, _e, c in subs: + if q >= end and q - end <= TRAIL_GAP and TRAIL_PREP.search(text[end:q]): + return c + before = [(q, e, c) for q, e, c in subs if q <= pos] + if before: + _q, e, c = before[-1] + if pos - e <= LEAD_GAP: + return c + return None + + +def run(): + mentions = defaultdict(list) # (quantity, subject) -> per-mention records + unattributed = [] # a value near a quantity name that V cannot assign a subject + for p in pages(): + if not p.exists(): continue + for ln, raw in units(p.read_text(errors="replace")): + for qname, spec in QUANTITIES.items(): + if not spec["name"].search(raw): continue + text = blank(raw, spec["kill"]) + namespans = [(m.start(), m.end()) for m in spec["name"].finditer(text)] + if not namespans: continue + subs = subject_positions(text) + lo, hi = spec["band"] + # "0.81-0.88" is ONE claim, so both halves are attributed from the range's start -- + # otherwise the far end of a range falls outside LEAD_GAP and only half survives + ranges = [(m.start(), m.end()) for m in RANGE.finditer(text)] + for m in spec["value"].finditer(text): + tok = next((g for g in m.groups() if g), None) + if tok is None: continue + try: v = float(tok) + except ValueError: continue + if not (lo <= v <= hi): continue + if not near_name(m.start(), namespans): continue + rec = {"page": rel(p), "line": ln, "quantity": qname, "value": v, + "token": tok, "dec": decimals(tok), + "sent": text[max(0, m.start() - 90):m.start() + 40].strip()} + a, b = m.start(), m.end() + for ra, rb in ranges: + if ra <= a and b <= rb: a, b = ra, rb; break + subj = attribute(a, b, text, subs) + st = state_of(text) + rec["state"] = st + if subj is None: + unattributed.append(rec) + else: + # (quantity, class, STATE) -- an unqualified mention keeps state None and + # can only ever be compared to another unqualified mention of the same + # subject, never to one the page pins to a state. + mentions[(qname, subj, st)].append(rec) + + bad, reported, agreed = [], [], [] + for (qname, subj, st), recs in sorted(mentions.items(), key=lambda kv: str(kv[0])): + bypage = defaultdict(list) + for r in recs: bypage[r["page"]].append(r) + if qname not in ADJUDICATE: + reported.append({"quantity": qname, "subject": subj, "state": st, + "pages": sorted(bypage), + "values": sorted({r["value"] for r in recs}), + "why": "extracted and reported; not adjudicated at class granularity"}) + continue + if qname in STATE_DEPENDENT and st is None: + reported.append({"quantity": qname, "subject": subj, "state": None, + "pages": sorted(bypage), + "values": sorted({r["value"] for r in recs}), + "why": "state-dependent quantity stated with NO branch state on " + "either page -- not cross-checkable (S0 and S2 differ by " + "~0.13 on the same arm, 26x V's tolerance)"}) + continue + if len(bypage) < 2: + reported.append({"quantity": qname, "subject": subj, "state": st, + "pages": sorted(bypage), + "values": sorted({r["value"] for r in recs}), + "why": "stated on one page only -- not cross-checkable"}) + continue + # A page's claim about a subject is the SPAN of everything it states for it. A span, not + # each value on its own: the pages state a quantity at different granularity (a class range + # on one page, per-arm points on another, S0 vs S2), and V must fire on contradiction, not + # on granularity. Disjoint spans are the only thing no reading can reconcile. + spans = {pg: (min(r["value"] for r in rs), max(r["value"] for r in rs), + max(r["dec"] for r in rs)) for pg, rs in bypage.items()} + pgs = sorted(spans) + conflict = False + for i in range(len(pgs)): + for j in range(i + 1, len(pgs)): + a, b = spans[pgs[i]], spans[pgs[j]] + tol = 0.5 * 10 ** -min(a[2], b[2]) # the COARSER printed precision + if a[1] + tol < b[0] or b[1] + tol < a[0]: + conflict = True + bad.append( + f"{qname}[{subj}@{st or 'state-unqualified'}]: {pgs[i]} states {a[0]:g}-{a[1]:g} but {pgs[j]} states " + f"{b[0]:g}-{b[1]:g} -- disjoint at the coarser printed precision " + f"(tol {tol:g})") + if not conflict: + agreed.append({"quantity": qname, "subject": subj, "state": st, "pages": pgs, + "spans": {k: [v[0], v[1]] for k, v in spans.items()}}) + + detail = {"mentions": {f"{q}|{s}|{st or '-'}": v for (q, s, st), v in mentions.items()}, + "unattributed": unattributed, "agreed": agreed, "reported": reported, "bad": bad, + "arm_class_map": [[pat.pattern, c] for pat, c in ARM_CLASS], + "state_words": [[pat.pattern, c] for pat, c in STATE_WORDS], + "near_window": [NEAR_BEFORE, NEAR_AFTER]} + (ST / "AUDIT271_V_CROSSPAGE.json").write_text(json.dumps(detail, indent=1)) + msg = (f"{sum(len(v) for v in mentions.values())} attributed mention(s) of " + f"{len(QUANTITIES)} quantity(ies) ({len(ADJUDICATE)} adjudicated, the rest reported at " + f"class granularity) over {len(pages())} pages, grouped into " + f"{len(mentions)} (quantity, subject) pair(s); {len(agreed)} cross-checked and agree, " + f"{len(reported)} stated on one page only (reported, not passed), " + f"{len(unattributed)} value(s) V cannot attribute to a subject (reported); " + f"pages are compared ONLY to pages -- V opens no artefact; bad={bad}") + return (not bad), msg, detail + + +if __name__ == "__main__": + ok, msg, _ = run() + print(("[PASS] " if ok else "[FAIL] ") + "V_cross_page_quantity_agreement: " + msg) diff --git a/rsm_rise/scripts/real/audit271_W_ckpt_path.py b/rsm_rise/scripts/real/audit271_W_ckpt_path.py new file mode 100644 index 0000000000000000000000000000000000000000..a47942c06686e2842e519c8b35bcadffdbe119ec --- /dev/null +++ b/rsm_rise/scripts/real/audit271_W_ckpt_path.py @@ -0,0 +1,98 @@ +#!/usr/bin/env python3 +"""#271 ladder rung `W` -- a shipped reproduction command must not name a checkpoint its own section's +prose contradicts. + +WHY THIS IS A RUNG AND R1 IS NOT. Runs 39-41 prototyped three intra-page prose-vs-command rules in probe +AB. R1 (any numeric flag vs numbers near the flag's concept word) was RETIRED: run 39 read all 12 of its +live conflicts and every one was false -- these pages quote alternative invocations inline in prose on +purpose, so an inline-code span is not a claim about the fenced command. R2 (checkpoint step) and R3 +(checkpoint name) survived, and run 41's probe AC measured them over the corpus's ENTIRE history rather +than the one live snapshot: + + 112 snapshots of rise_stack/ (every commit on rise-stack-scaffold touching it) + surface .... max 1 checkpoint-path pair in ANY snapshot; histogram {0 pairs: 66, 1 pair: 46} + fired ...... 43 consecutive snapshots, 2026-09-23T13:40Z -> the fix in 97eac5be + agreed ..... the 3 snapshots since the fix (97eac5be, 9fefc57, a6c2af2) + identity ... 46 = 43 + 3, and 92 judged pair-checks = 46 snapshots x 2 rules + distinct conflict sites over all of history .... 2, i.e. ONE defect site x two rules + (rise_stack/FINDINGS.md:82 --rsm-ckpt .../R_M_ft_v0/ckpt_s110000.pt, whose own section + says R_M and 100000; found by hand in run 38 and fixed in 97eac5be) + +So over 112 snapshots and 9430 (flag,value) pairs these two rules produced ZERO false-positive sites and +caught one real defect that had sat in the shipped corpus for 43 commits. R1 over the same history +produced 945 conflicts. That is the whole case for promoting one and not the other. + +WHY IT IS PROMOTED NOW. Runs 39/40 set the criterion "promote when the corpus carries >=3 checkpoint-path +claims AND R2/R3 have been silent across 3 moved runs". AC decided both halves by measurement: + * the ">=3 claims" half is UNSATISFIABLE BY WAITING -- 112 commits and the surface has never exceeded 1, + so runs 39-41 were blocked on a state history says does not occur. Retired as a criterion. + * the "3 moved runs" half is ALREADY SATISFIED retrospectively -- the 3 post-fix commits are 3 distinct + moved snapshots on which both rules agree with zero conflicts. It needed no further waiting; the + evidence was in git the whole time. + +SURFACE 0 IS A NON-PASS, DELIBERATELY. The ladder's standing convention (P/Q/R/S/U/V) is that a check +whose extraction silently stops must not pass by claiming nothing, so `ok` requires a non-empty surface. +AC measured that red as reachable -- 66 of 112 snapshots carry no checkpoint-path pair at all -- and it +means "the bottleneck test's reproduction command has left the shipped corpus", a coverage loss worth a +red on a reproducibility deliverable, NOT a formula defect. The detail line says which of the two it is. + +The rules are IMPORTED from scripts/real/_audit271_AB_probe.py, never restated here: a second copy would +let the rung and the probe that measured it drift apart, which is the failure this probe family exists to +catch. Control: scripts/real/audit271_W_selftest.py. +""" +from __future__ import annotations +import importlib.util +from pathlib import Path + +ROOT = Path("/proj/dmfexp/zwhong/rsm_rise") +RULES = ("R2_checkpoint_step", "R3_checkpoint_name") + + +def _ab(): + spec = importlib.util.spec_from_file_location("ab_rules", ROOT / "scripts/real/_audit271_AB_probe.py") + m = importlib.util.module_from_spec(spec) + spec.loader.exec_module(m) + return m + + +def judge(texts): + """texts: [(where, text)]. Returns (conflicts, surface, stats).""" + ab = _ab() + conflicts, surface, stats = [], [], {"agree": 0, "conflict": 0, "silent": 0} + for where, text in texts: + con, st = ab.judge_page(where, text) + conflicts += [c for c in con if c["rule"] in RULES] + for r in ("R2", "R3"): + for k in ("agree", "conflict", "silent"): + stats[k] += st[f"{r}_{k}"] + # the surface these two rules can see at all: a (flag,value) pair whose value is a ckpt_s path + for _head, rows in ab.sections(text): + for lno, cmd in ab.commands(rows): + if not cmd.strip() or cmd.strip().startswith("#"): + continue + for flag, val in ab.pairs(cmd): + if ab.CKPT_STEP.search(val): + surface.append({"page": where, "line": lno, "flag": flag, "value": val}) + return conflicts, surface, stats + + +def run(): + ab = _ab() + texts = [(where, md.read_text(errors="replace")) for where, md in ab.pages() if md.is_file()] + conflicts, surface, stats = judge(texts) + if not surface: + return (False, "surface 0: no shipped page carries a checkpoint-path reproduction command " + "(coverage loss, not a formula defect; AC: 66/112 historical snapshots were also 0)", + {"conflicts": conflicts, "surface": surface, "stats": stats}) + if conflicts: + w = "; ".join(f"{c['page']}:{c['line']} {c['rule']} {c['flag']} {c['value']}" for c in conflicts[:4]) + return (False, f"{len(conflicts)} checkpoint claim(s) contradicted by their own section's prose: {w}", + {"conflicts": conflicts, "surface": surface, "stats": stats}) + return (True, f"{len(surface)} checkpoint-path claim(s) on {len({s['page'] for s in surface})} page(s), " + f"all agreeing with their own section's prose (R2/R3 agree={stats['agree']}, conflict=0)", + {"conflicts": conflicts, "surface": surface, "stats": stats}) + + +if __name__ == "__main__": + ok, detail, _ = run() + print(f"[{'PASS' if ok else 'FAIL'}] W: {detail}") diff --git a/rsm_rise/scripts/real/audit271_W_selftest.py b/rsm_rise/scripts/real/audit271_W_selftest.py new file mode 100644 index 0000000000000000000000000000000000000000..941e0eeaede67210654f545ab1638b2c72665a0e --- /dev/null +++ b/rsm_rise/scripts/real/audit271_W_selftest.py @@ -0,0 +1,110 @@ +#!/usr/bin/env python3 +"""Control for #271 ladder rung `W` (scripts/real/audit271_W_ckpt_path.py). + +A rung is worth nothing until something shows it can FAIL. Scenario 1 is the real pre-fix blob taken from +git (`97eac5be^:rise_stack/FINDINGS.md`), never written to the tree, so the positive control is a defect +that actually shipped rather than one invented to be caught. Scenario 2 is the same page after the fix and +must be clean. The rest are the shapes W must LEAVE ALONE -- above all scenario 5, the inline-code hazard +that scored R1's precision at 0.00 in run 39 and got it retired: these pages quote alternative invocations +inline in prose on purpose, so W must not read an inline-code span as a claim about the fenced command. + +Writes status/real/AUDIT271_W_SELFTEST.json. Exits 1 if any scenario fails. +""" +from __future__ import annotations +import json, subprocess, sys +from pathlib import Path + +sys.path.insert(0, "/proj/dmfexp/zwhong/rsm_rise/scripts/real") +from audit271_W_ckpt_path import judge # noqa: E402 + +CLONE = Path("/proj/dmfexp/zwhong/projs/rsm_real") +OUT = Path("/proj/dmfexp/zwhong/rsm_rise/status/real/AUDIT271_W_SELFTEST.json") + + +def blob(ref): + r = subprocess.run(["git", "-C", str(CLONE), "show", ref], capture_output=True, text=True) + return r.stdout if r.returncode == 0 else None + + +def P(head, prose, cmd): + return f"## {head}\n\n{prose}\n\n```bash\n{cmd}\n```\n" + + +CK = "runs/real_cooking_v5/rsm" +SCEN = [] + +# 1/2 -- the real defect and the real fix, from git history. +SCEN.append(("real_prefix_blob_CONFLICTS", blob("97eac5be^:rise_stack/FINDINGS.md"), "conflict")) +SCEN.append(("real_postfix_blob_CLEAN", blob("97eac5be:rise_stack/FINDINGS.md"), "clean")) + +# 3 -- synthetic: step disagrees with the prose of its own section. +SCEN.append(("synth_step_conflict", P( + "The bottleneck test", + "We score with the successor R_M at 100000 steps.", + f"python scorer.py --rsm-ckpt {CK}/R_M/ckpt_s110000.pt"), "conflict")) + +# 4 -- synthetic: name disagrees, step agrees. +SCEN.append(("synth_name_conflict", P( + "The bottleneck test", + "We score with the successor R_M at 100000 steps.", + f"python scorer.py --rsm-ckpt {CK}/R_M_ft_v0/ckpt_s100000.pt"), "conflict")) + +# 5 -- THE HAZARD THAT RETIRED R1. The prose deliberately quotes a DIFFERENT invocation inline; the fenced +# command is the section's own. W must stay clean. +SCEN.append(("hazard_inline_code_alt_invocation", P( + "The bottleneck test", + "We score with R_M at 100000 steps. For the ablation we reran it at " + f"`--rsm-ckpt {CK}/R_M_ft_v0/ckpt_s110000.pt`, which moved the number by 0.003.", + f"python scorer.py --rsm-ckpt {CK}/R_M/ckpt_s100000.pt"), "clean")) + +# 6 -- agreement, the ordinary case. +SCEN.append(("synth_agrees", P( + "The bottleneck test", + "We score with the successor R_M at 100000 steps.", + f"python scorer.py --rsm-ckpt {CK}/R_M/ckpt_s100000.pt"), "clean")) + +# 7 -- prose makes NO checkpoint claim: W must go silent, not guess (check P's forbidden move). +SCEN.append(("silent_when_prose_makes_no_claim", P( + "The bottleneck test", + "The command below reproduces the table.", + f"python scorer.py --rsm-ckpt {CK}/R_M/ckpt_s100000.pt"), "silent")) + +# 8 -- no checkpoint path at all: zero surface, and W must not manufacture a judgement. +SCEN.append(("no_surface", P( + "Latency", "We measured 117.3 ms at batch 16.", "python bench.py --openpi-batch 16"), "no_surface")) + +# 9 -- a placeholder path must not be judged (AB.pairs drops it). +SCEN.append(("placeholder_not_judged", P( + "Quickstart", "Point it at your own successor, e.g. R_M at 100000.", + "python scorer.py --rsm-ckpt /path/to/ckpt_s110000.pt"), "no_surface")) + +res, fails = [], [] +for name, text, want in SCEN: + if text is None: + res.append({"scenario": name, "want": want, "got": "BLOB_MISSING", "ok": False}) + fails.append(name) + continue + con, surf, st = judge([(f"scenario/{name}", text)]) + if not surf: + got = "no_surface" + elif con: + got = "conflict" + elif st["silent"] and not st["agree"]: + got = "silent" + else: + got = "clean" + ok = got == want + res.append({"scenario": name, "want": want, "got": got, "ok": ok, + "n_surface": len(surf), "stats": st, + "conflicts": [f"{c['rule']} {c['flag']} {c['value']}" for c in con]}) + if not ok: + fails.append(name) + print(f"[{'ok ' if ok else 'FAIL'}] {name}: want={want} got={got} surface={len(surf)} {st}") + +d = {"probe": "W_selftest", "issue": 271, "n": len(SCEN), "n_pass": len(SCEN) - len(fails), + "all_pass": not fails, "failed": fails, "scenarios": res, + "note": "scenario 1/2 are the real pre-fix and post-fix blobs from git, not invented defects; " + "scenario 5 is the inline-code hazard that retired rule R1 in run 39."} +OUT.write_text(json.dumps(d, indent=1)) +print(f"[W selftest] {d['n_pass']}/{d['n']} all_pass={d['all_pass']} -> {OUT}") +sys.exit(0 if not fails else 1) diff --git a/rsm_rise/scripts/real/audit271_W_selftest.sh b/rsm_rise/scripts/real/audit271_W_selftest.sh new file mode 100644 index 0000000000000000000000000000000000000000..f41c8c67408c1778f3ddbcd9eaa2f627c928198d --- /dev/null +++ b/rsm_rise/scripts/real/audit271_W_selftest.sh @@ -0,0 +1,4 @@ +#!/usr/bin/env bash +set -euo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +exec python3 scripts/real/audit271_W_selftest.py diff --git a/rsm_rise/scripts/real/audit271_consistency.py b/rsm_rise/scripts/real/audit271_consistency.py new file mode 100644 index 0000000000000000000000000000000000000000..e9ac695a7d566d5d31862ef884e216cc2afbf335 --- /dev/null +++ b/rsm_rise/scripts/real/audit271_consistency.py @@ -0,0 +1,1408 @@ +#!/usr/bin/env python +"""gen_q #271, run 17: a NO-DRIFT audit of the delivered artefacts. No new measurement, no GPU. + +#271 is closed and the deliverables were completed at run 6 and reconciled with the applied gate at +run 16. This script exists so that "complete" is re-established from the sources every run instead of +being asserted from a status file. Every check below compares a SHIPPED artefact against the thing it +was generated from; anything that no longer matches is a drift and is reported as FAIL. + + A the #271 block spliced into rise_stack/CHECKPOINTS.md == the generator's output today + B the rsm_real clone: on rise-stack-scaffold, clean, in sync with origin + C rise_stack/configs/baselines.yaml keys (rsm_reward, the two selection keys, the ckpt paths on disk) + D the Hugging Face repo tree <-> the CHECKPOINTS table: every live successor_rsm_real_* reward head + has a row, and every row naming a file has that file live + E PR jmarangola/rsm_real#1's LIVE body: every splice marker present and in order + F the LIVE model card on the hub: the generated #271 block present, and every live head named in it + G the diagnostics matrix: every head in the table has its four #271 diagnostics in the JSONs + H (run 18) the canonical-name -> CHECKPOINT FILE map: configs/reward_names.json's hugging_face + fields agree with scripts/real/hf_upload.py and the live hub, and no page in rise_stack puts a + reward NAME next to a file that carries a DIFFERENT label. Added after another stream's registry + attached successor_rsm_real_A_110000.pt (= R_M_ft_v1 = GOAL_SEGMENT) to the name GOAL_EPISODE and + the error spread into WHAT_TO_LOAD.md and FINDINGS.md. + + I (run 20; widened at run 23) the CONTENT of every live successor checkpoint: the hub's LFS sha256 + against the sha256 of the cluster checkpoint hf_upload.py names as its source. A, D and H all + reason about names; this is the only check that reads the bytes a reader downloads. Its file + list is the HUB's, not the uploader's, so a public checkpoint outside REWARD_HEADS -- the two + BASE successors, from MANIFEST -- cannot sit outside the check, and any live .pt with no + declared cluster source is a FAIL. + M (run 23) the DIGEST a shipped page prints, against the digest the hub serves. I compares hub to + cluster and K reads availability prose; neither reads the sha256 the model card publishes for a + downloader to compare their own file against. + + N (run 24) the COUNTS a shipped page prints, against the record they are computed from and + against each other. M reads one digest of one file; every SUMMARY claim on these pages is a + COUNT, and a count is substituted from a record, so it goes stale when the record is rewritten + by a narrower run while the prose around it keeps the wide run's scope. + + O (run 26) the per-file SIZE TABLE a shipped page prints, against the live hub listing it + describes: every printed byte count and `(N files)`, every row naming a file that is still + there, and -- the defect it was written against -- every live top-level path having a row at + all. The card's table described four pi05_ params folders on a hub carrying twelve; the other + eight (99.5 GiB, public) were named nowhere, and a row that does not exist is invisible to + every check that reads names, bytes, digests or counts. + + P (run 28) what a row SAYS about an artefact, against the record the ARTEFACT KEEPS ABOUT + ITSELF. O asks whether a row exists and its bytes are right; N whether a count is right; + I/M/L whether the bytes, the digest and the reward label are right. None of them reads the + rest of the row's words -- the seed, the step, the stage, the parent, the sweep arm -- and all + of those are parsed FROM THE FILE NAME, by the card's generator and by hf_upload.py's manifest + alike. P reads `step` / `config.seed` / `config.out` out of each successor blob and the + `assets//` path out of each pi0.5 export, and says plainly which words (a pi0.5 + folder's seed, step and arm) no record can confirm. See audit271_P_artifact_record.py. + + R (run 30) the printed STATISTICS, against the measurement JSON they came from. P and Q + cover claims that NAME an artefact; a number names none, and check A compares the spliced + block to the generator's OUTPUT file rather than to its inputs, so a re-measured JSON leaves + every AUC, CI, p-value, frame count and bold tick on the pages stale with every other check + green. Compared at the printed precision so rounding cannot make a correct page red. + See audit271_R_published_stats.py. + +Writes status/real/AUDIT271_RUN17.json. Exits 1 if any check FAILs. +""" +from __future__ import annotations +import json, os, re, subprocess, sys, urllib.request +from pathlib import Path + +ROOT = Path("/proj/dmfexp/zwhong/rsm_rise") +ST = ROOT / "status/real" +CLONE = Path("/proj/dmfexp/zwhong/projs/rsm_real") +OUT = ST / "AUDIT271_RUN17.json" +REPO = os.environ.get("RR_HF_REPO", "rli14/rsm_cooking_v5_checkpoints") +sys.path.insert(0, str(ROOT / "scripts/real")) + +R: dict = {"checks": {}} + + +def rec(key, ok, detail): + R["checks"][key] = {"ok": bool(ok), "detail": detail} + print(f"[{'PASS' if ok else 'FAIL'}] {key}: {detail}", flush=True) + + +def gh_token(): + line = (Path.home() / ".git-credentials").read_text() + m = re.search(r"https://richardrl:([^@]*)@", line) + return m.group(1) + + +def gh_get(url, tok): + req = urllib.request.Request(url, headers={"Authorization": f"token {tok}", + "Accept": "application/vnd.github+json"}) + return json.load(urllib.request.urlopen(req)) + + +# ---------------------------------------------------------------- A: the generated block +def check_A(): + rc = subprocess.run([str(ROOT / "scripts/real/run_env.sh"), + str(ROOT / "scripts/real/build_checkpoints_reward_rows.py")], + capture_output=True, text=True) + if rc.returncode != 0: + rec("A_block_regenerates", False, f"generator rc={rc.returncode}: {rc.stderr[-300:]}") + return + fresh = (ST / "CHECKPOINTS_reward_block.md").read_text() + # the generator writes the markers into its own output; the clone holds them once, around the + # splice, so the comparable quantity is the text BETWEEN them on both sides. + fm = re.search(r"\n(.*?)", fresh, re.S) + if fm: + fresh = fm.group(1) + live = (CLONE / "rise_stack/CHECKPOINTS.md").read_text() + m = re.search(r"\n(.*?)", live, re.S) + if not m: + rec("A_block_matches_clone", False, "markers not found in CHECKPOINTS.md") + return + same = m.group(1).strip() == fresh.strip() + rec("A_block_matches_clone", same, + f"regenerated {len(fresh)} B vs spliced {len(m.group(1))} B; identical={same}") + + +# ---------------------------------------------------------------- B: the clone +def check_B(): + def g(*a): + return subprocess.run(["git", "-C", str(CLONE)] + list(a), + capture_output=True, text=True).stdout.strip() + br = g("rev-parse", "--abbrev-ref", "HEAD") + # run 18: the clone is SHARED and every stream runs python in it, so untracked bytecode caches + # appear constantly. They are a build artefact, not drift -- "dirty" must mean a tracked file + # changed or a real untracked file was added, or the check cries wolf on __pycache__. + IGNORE = re.compile(r"^\?\? .*(__pycache__/|\.pyc$|\.pyo$)") + raw = [ln for ln in g("status", "--porcelain").splitlines() if ln.strip()] + dirty = [ln for ln in raw if not IGNORE.match(ln)] + ignored = len(raw) - len(dirty) + subprocess.run(["git", "-C", str(CLONE), "fetch", "-q", "origin", "rise-stack-scaffold"], + capture_output=True, text=True) + local, remote = g("rev-parse", "HEAD"), g("rev-parse", "origin/rise-stack-scaffold") + ok = br == "rise-stack-scaffold" and not dirty and local == remote + rec("B_clone_in_sync", ok, + f"branch={br} clean={not dirty} (ignored {ignored} bytecode-cache entries) " + f"HEAD={local[:8]} origin={remote[:8]}" + + (f" dirty={dirty[:5]}" if dirty else "")) + R["clone_head"] = local + + +# ---------------------------------------------------------------- C: baselines.yaml +def check_C(): + y = (CLONE / "rise_stack/configs/baselines.yaml").read_text() + want = {"rsm_reward": "A", "rsm_reward_ckpt_hf": "successor_rsm_real_A_110000.pt"} + got, bad = {}, [] + for k, v in want.items(): + m = re.search(rf"^\s*{k}:\s*(\S+)", y, re.M) + got[k] = m.group(1) if m else None + if got[k] != v: + bad.append(f"{k}={got[k]} (want {v})") + m = re.search(r"^\s*rsm_reward_stitching_best:\s*(\S+)", y, re.M) + got["rsm_reward_stitching_best"] = m.group(1) if m else "ABSENT" + if got["rsm_reward_stitching_best"] not in ("null", "ABSENT"): + bad.append(f"stitching_best={got['rsm_reward_stitching_best']} (want null)") + m = re.search(r"^\s*rsm_reward_ckpt:\s*(\S+)", y, re.M) + ck = Path(m.group(1)) if m else None + if ck is None or not ck.exists(): + bad.append(f"rsm_reward_ckpt missing on disk: {ck}") + R["baselines"] = got + rec("C_baselines_keys", not bad, "; ".join(bad) if bad else f"{got}, ckpt on disk") + + +# ---------------------------------------------------------------- D: hub tree <-> table +def check_D(): + from huggingface_hub import HfApi + from hf_upload import REWARD_HEADS + api = HfApi(token=os.environ.get("HF_TOKEN") or os.environ.get("HUGGING_FACE_HUB_TOKEN")) + live = {e.path for e in api.list_repo_tree(REPO, repo_type="model", recursive=True) + if getattr(e, "size", None) is not None and not hasattr(e, "tree_id")} + live_heads = sorted(p for p in live if p.startswith("successor_rsm_real_") + and p not in ("successor_rsm_real_RM_s0_100k.pt",)) + block = (ST / "CHECKPOINTS_reward_block.md").read_text() + named = {dst for _, _, dst in REWARD_HEADS} + rows_naming = {d for d in named if d in block} + # every live reward head must appear in the table + orphan_files = [p for p in live_heads if p in named and p not in rows_naming] + # A row may name a head that was trained but deliberately NOT uploaded (it fails the gate); + # run 16 made that note per head. What must never happen is a row naming a file as though it + # were downloadable when it is not, so the note is what the check keys on. + def declared_absent(dst): + i = block.find(dst) + return "not uploaded" in block[i:i + 400] + ghost_rows = [d for d in rows_naming if d not in live and not declared_absent(d)] + R["rows_declared_not_uploaded"] = sorted(d for d in rows_naming + if d not in live and declared_absent(d)) + ok = not orphan_files and not ghost_rows + R["hub_reward_heads_live"] = [p for p in live_heads if p in named] + rec("D_hub_matches_table", ok, + f"{len(R['hub_reward_heads_live'])} reward heads live, all with rows; " + f"orphan_files={orphan_files} ghost_rows={ghost_rows}") + + +# ---------------------------------------------------------------- E: PR #1 body +def check_E(): + tok = gh_token() + pr = gh_get("https://api.github.com/repos/jmarangola/rsm_real/pulls/1", tok) + body = pr["body"] or "" + marks = re.findall(r"", body) + nums = [int(m[1:]) for m in marks if re.fullmatch(r"s\d+", m)] + # the invariant: begin ... (s_k, s_k_end) strictly nested and increasing ... end. + # Sections (1)-(4) predate the marker convention and are inside the begin block unmarked, so a + # count is NOT the check -- the structure is. + want = ["begin"] + [x for k in nums for x in (f"s{k}", f"s{k}end")] + ["end"] + ok = (marks == want and nums == sorted(nums) and len(nums) == len(set(nums)) and len(nums) >= 1 + and "" in body) + R["pr1_body_bytes"] = len(body) + R["pr1_sections"] = nums + rec("E_pr1_markers_ordered", ok, + f"body={len(body)} B, marked sections={nums}, begin/end nesting ok={ok}") + + +# ---------------------------------------------------------------- F: the live model card +def check_F(): + from huggingface_hub import hf_hub_download + p = hf_hub_download(REPO, "README.md", repo_type="model", + token=os.environ.get("HF_TOKEN") or os.environ.get("HUGGING_FACE_HUB_TOKEN")) + card = Path(p).read_text() + missing = [d for d in R.get("hub_reward_heads_live", []) if d not in card] + has_block = "" in card + rec("F_card_describes_live_heads", has_block and not missing, + f"card={len(card)} B, 271 block={has_block}, live heads not named in card={missing}") + + +# ---------------------------------------------------------------- G: the diagnostics matrix +def check_G(): + diag = json.loads((ST / "REWARD_HEAD_DIAG.json").read_text())["heads"] + draws = json.loads((ST / "STITCH_DRAWS.json").read_text()) + screen = json.loads((ST / "REWARD_SCREEN.json").read_text())["combined"]["heads"] + alias = {"base": "base_R_M"} + import build_checkpoints_reward_rows as B + gaps = [] + for name, _disp, _f, _sch, dk, _hf in B.HEADS: + d_key = alias.get(dk, dk) + if d_key not in diag and dk not in diag: + gaps.append(f"{name}:diag") + if dk not in draws["heads"]: + gaps.append(f"{name}:stitch") + if d_key not in screen and dk not in screen: + gaps.append(f"{name}:screen") + rec("G_diagnostics_complete", not gaps, + f"{len(B.HEADS)} table heads; diag+stitch+screen present for all; gaps={gaps}") + + +# ---------------------------------------------------------------- H: the name -> file map (run 18) +# The registry names LABELS; the hub holds FILES. This check is the one that catches a file being +# advertised under the wrong label -- a consumer acting on it downloads a head trained on a different +# reward, which no other check here would notice. `default_for_planning` is deliberately NOT audited: +# which name is the planning default is the owner's call (#271), not an invariant. +NAME_OF_FILE = { # file on the hub -> the canonical name of the label it carries + "successor_rsm_real_A_110000.pt": "GOAL_SEGMENT", + "successor_rsm_real_A_s1_110000.pt": "GOAL_SEGMENT", + "successor_rsm_real_B_H100_110000.pt": "GOAL_WINDOW_100", + "successor_rsm_real_B_H100_s1_110000.pt": "GOAL_WINDOW_100", + "successor_rsm_real_B_H400_110000.pt": "GOAL_WINDOW_400", + "successor_rsm_real_B_H400_s1_110000.pt": "GOAL_WINDOW_400", + "successor_rsm_real_v0lit_110000.pt": "EXPERT_EPISODE", + "successor_rsm_real_v0lit_s1_110000.pt": "EXPERT_EPISODE", + "successor_rsm_real_RM_s0_100k.pt": "GOAL_EPISODE", + # run 22: live on the hub, same label as s0, verified by check L (both readings). + "successor_rsm_real_RM_s1_100k.pt": "GOAL_EPISODE", +} + + +def _says(text, label): + """True iff `text` names the canonical label `label` as a whole token. + + Substring matching would let GOAL_SEGMENT_CONTRASTIVE stand in for GOAL_SEGMENT, which is + exactly the confusion this check exists to catch. + """ + return re.search(rf"(? cell is hf_upload.py's table. + import hf_upload as U + table = getattr(U, "REWARD_HEADS", None) or getattr(U, "HEADS", None) or [] + up = {dst: str(src) for _cell, src, dst in table} + if not up: + txt = (ROOT / "scripts/real/hf_upload.py").read_text() + up = {m[2]: m[1] for m in re.findall( + r'\("([^"]+)",\s*RUNS / "([^"]+)",\s*"([^"]+)"\)', txt)} + # a name may legitimately have more than one training cell: GOAL_EPISODE is both the base + # successor's own provenance head (cell R_M) and its 10k fine-tune (R_M_ft_v0). + cells_of_name = {"GOAL_SEGMENT": {"R_M_ft_v1"}, "GOAL_EPISODE": {"R_M_ft_v0", "R_M"}, + "EXPERT_EPISODE": {"R_M_ft_v0lit"}, "GOAL_WINDOW_100": {"R_M_ft_B"}, + "GOAL_WINDOW_400": {"R_M_ft_B400"}} + for fname, name in NAME_OF_FILE.items(): + src = up.get(fname) + if src is None: # not in the reward-head upload table at all + continue + cells = cells_of_name.get(name, set()) + stem = src.split("/")[-2] if "/" in src else src + if cells and stem not in cells and stem.removesuffix("_s1") not in cells: + bad.append(f"hf_upload maps {fname} <- {src}, but the name {name} is cell(s) " + f"{sorted(cells)}") + # H2 -- the registry's hugging_face field must not name a file that carries a different label. + reg = json.loads((CLONE / "rise_stack/configs/reward_names.json").read_text()) + bad += h2_registry_bad(reg) + # H3 -- no markdown line a consumer reads puts a name next to a file carrying a different label. + # The run-18 bug lived in rise_stack/{WHAT_TO_LOAD,FINDINGS}.md. The clone's ROOT pages + # (QUICKSTART.md, README.md) are the same class of page -- they tell a reader which file to + # download -- and another stream edits them (ce58f6b1 touched QUICKSTART.md), so they are audited + # too. Labels are paths relative to the clone, so the two README.md cannot be confused. + pages = (sorted((CLONE / "rise_stack").glob("*.md")) + sorted(CLONE.glob("*.md")) + + [ST / "HF_MODEL_CARD.md"]) + for md in pages: + try: + where = str(md.relative_to(CLONE)) + except ValueError: + where = md.name + for i, ln in enumerate(md.read_text().splitlines(), 1): + for fname, carries in NAME_OF_FILE.items(): + if fname not in ln or carries in ln: + # naming the label the file actually carries is the correct statement, and a line + # may name a second label to contrast with it -- that is how the corrections read. + continue + others = [o for o in set(NAME_OF_FILE.values()) - {carries} if o in ln] + if others: + bad.append(f"{where}:{i} names {others} on a line holding {fname}, which " + f"carries {carries}, and never names {carries}") + rec("H_name_to_file_map", not bad, + f"{len(NAME_OF_FILE)} file->label pairs checked against hf_upload.py, reward_names.json " + f"and {len(pages)} pages (rise_stack/*.md + the clone's root *.md + the HF card); " + f"bad={bad[:6]}") + + +# ------------------------------------------------- I: the BYTES on the hub, not just the names +def declared_pt_sources(): + """hub filename -> the cluster checkpoint the uploader says it came from. + + BOTH uploader lists: REWARD_HEADS (the eight #271 fine-tunes) and MANIFEST, which is where the + two BASE successors live (successor_rsm_real_RM_s{0,1}_100k.pt, the GOAL_EPISODE provenance + heads). A module function so the control can repoint it without touching hf_upload. + """ + import hf_upload + want = {dst: Path(src) for _n, src, dst in hf_upload.REWARD_HEADS} + for _group, src, dst in hf_upload.MANIFEST: + if dst.startswith("successor_rsm_real_") and dst.endswith(".pt"): + want.setdefault(dst, Path(src)) + return want + + +def hub_live_pt(api): + """path -> RepoFile for every live successor_rsm_real_*.pt, with sizes and LFS metadata.""" + live = [e.path for e in api.list_repo_tree(REPO, repo_type="model", recursive=True) + if getattr(e, "size", None) is not None and not hasattr(e, "tree_id") + and e.path.startswith("successor_rsm_real_") and e.path.endswith(".pt")] + return {f.path: f for f in api.get_paths_info(REPO, sorted(live), repo_type="model", expand=True)} + + +def check_I(): + """Every live reward head's CONTENT == the cluster checkpoint the uploader says it is. + + D and H establish the name -> file map from the uploader's source, the registry and the pages; + neither reads a byte of what is actually on the hub. A re-upload from the wrong source, a + truncated transfer, or a later overwrite would leave every name check passing while a reader + downloads a head trained on a different reward -- the run-18 failure mode, one level down. + Hub side: RepoFile.lfs.sha256 (HF stores the sha256 of the contents as the LFS/Xet object id). + Local side: hashlib over hf_upload.REWARD_HEADS' source path. Same comparison + scripts/real/hf_verify_sha.py made once by hand at run 6/16; this runs it every audit. + """ + import hashlib + from huggingface_hub import HfApi + api = HfApi(token=os.environ.get("HF_TOKEN") or os.environ.get("HUGGING_FACE_HUB_TOKEN")) + want = declared_pt_sources() + live = hub_live_pt(api) + # COVERAGE IS A CHECK, NOT AN INPUT (the lesson of run 22's check L). Until run 23 this check + # hashed hf_upload.REWARD_HEADS and nothing else, so the two BASE successors -- which come from + # MANIFEST, are public, and carry GOAL_EPISODE -- had never had a byte read. A per-file check + # handed its own list passes by shortening the list, so the list is now the HUB's. + uncovered = [p for p in live if p not in want] + rows, bad = [], [] + for dst in sorted(set(live) & set(want)): # only the checkpoints that are actually live + src, f = want[dst], live[dst] + hub = getattr(getattr(f, "lfs", None), "sha256", None) + if hub is None: + bad.append(f"{dst}: live but carries no LFS sha256, so its content cannot be verified") + continue + if not src.exists(): + bad.append(f"{dst}: live on the hub but its source {src} is gone from the cluster") + continue + h = hashlib.sha256() + with open(src, "rb") as fh: + for b in iter(lambda: fh.read(1 << 24), b""): + h.update(b) + loc = h.hexdigest() + rows.append({"path": dst, "hub_sha256": hub, "local_sha256": loc, "match": hub == loc, + "bytes": getattr(f, "size", None), "src": str(src)}) + if hub != loc: + bad.append(f"{dst}: hub {hub[:12]} != {src.parent.name}/{src.name} {loc[:12]}") + R["hub_content_rows"] = rows + R["hub_content_uncovered"] = uncovered + # The two failure modes report apart: a byte mismatch is a wrong file, an uncovered file is a + # public checkpoint this check cannot speak for. Both fail the check. + if uncovered: + bad.append("live on the hub with no declared cluster source: " + ", ".join(uncovered)) + # bool(rows) so that an empty hub, or a listing that matched nothing, is a FAIL and not a + # vacuous pass -- the lesson of run 19's widened glob. + rec("I_hub_bytes_match_source", not bad and bool(rows), + f"{len(rows)}/{len(live)} live successor checkpoints hashed on both sides, " + f"{sum(r['match'] for r in rows)} identical; mismatches={bad[:4]}") + + +def m_digest_bad(pages, hub_sha): + """M: every sha256 a SHIPPED PAGE prints must be the digest the hub actually serves. + + Pure function of {page label: text} and {hub path: lfs sha256}, so the control can feed fixtures. + + The level below K. I compares the hub against the cluster; K reads the prose around a filename + for availability. Neither reads the DIGEST a page prints -- and the model card prints one per + checkpoint, under the sentence "everything here is live and content-verified", which is exactly + what a downloader checks their own file against. Re-upload a head from a different source and + the card's digest goes stale while I stays green, because I never reads the card. + + Only a token introduced by the word "sha256" counts: a bare hex run on a line is as likely to be + a git commit, and flagging those would make the check noise. + """ + bad, seen = [], 0 + for where, text in pages.items(): + for i, ln in enumerate(text.splitlines(), 1): + digs = re.findall(r"sha256[^0-9a-f]{0,4}([0-9a-f]{8,64})", ln, re.I) + if not digs: + continue + # LONGEST EXTENSION FIRST. With `pt|pth` the alternation matched ".pt" inside ".pth", + # so `rise_actor_rsm_real_s0_e3000.pth` parsed as `...e3000.pt`, was not a hub path, and + # its published digest was silently skipped -- three 3.2 GB actor checkpoints unchecked + # while the check reported PASS. Found by counting M's claims against the card's rows. + files = [f for f in re.findall( + r"[A-Za-z0-9_./-]+\.(?:safetensors|json|npy|pth|pt)\b", ln) if f in hub_sha] + if not files: + continue + for f in files: + hub = hub_sha[f] + for d in digs: + seen += 1 + if hub is None: + bad.append(f"{where}:{i} prints a sha256 for {f}, which carries no LFS " + f"digest on the hub") + elif not hub.startswith(d.lower()): + bad.append(f"{where}:{i} prints sha256 {d} for {f}, but the hub serves " + f"{hub[:len(d)]}") + return bad, seen + + +def check_M(): + from huggingface_hub import HfApi + api = HfApi(token=os.environ.get("HF_TOKEN") or os.environ.get("HUGGING_FACE_HUB_TOKEN")) + files = [e.path for e in api.list_repo_tree(REPO, repo_type="model", recursive=True) + if getattr(e, "size", None) is not None and not hasattr(e, "tree_id")] + hub_sha = {} + for i in range(0, len(files), 100): + for f in api.get_paths_info(REPO, files[i:i + 100], repo_type="model", expand=True): + hub_sha[f.path] = getattr(getattr(f, "lfs", None), "sha256", None) + pages = {} + for md in (sorted((CLONE / "rise_stack").glob("*.md")) + sorted(CLONE.glob("*.md")) + + [ST / "HF_MODEL_CARD.md"]): + try: + where = str(md.relative_to(CLONE)) + except ValueError: + where = md.name + pages[where] = md.read_text() + bad, seen = m_digest_bad(pages, hub_sha) + R["published_digests_checked"] = seen + # seen>0: a page set that prints no digest at all must not pass silently -- run 19's lesson. + rec("M_published_digests_match_hub", not bad and seen > 0, + f"{seen} published sha256 claims over {len(pages)} pages checked against " + f"{sum(v is not None for v in hub_sha.values())} LFS digests on the hub; bad={bad[:4]}") + + +def check_J(): + """The DELIVERED head still reproduces its published R(z) for a READER, whose DINOv2 source + comes from GitHub and not from this training tree. + + A..I all reason about names, rows, bytes and configs. Every one of them stays green if the + FEATURES change underneath a bit-identical checkpoint -- and they can: `dino_hub_dir:` in + baselines.yaml is an absolute path on this cluster, so a reader never has it and rsm_real + db2e0cbe makes the clean clone fetch facebookresearch/dinov2 from GitHub, i.e. a later + snapshot of main than the 2026-09-18 archive every #271 number was measured with. A source + that changed the model code would make the hub copy of the head unable to reproduce its own + published numbers in the hands of the reader it exists for. + + Run as a SUBPROCESS: J rewrites TORCH_HOME and sys.path to build two backbones, which must not + leak into the other checks. See scripts/real/audit271_J_dino_source.py; its negative control is + scripts/real/_audit271_J_selftest.py. + """ + import subprocess + r = subprocess.run([str(ROOT / "scripts/real/_audit271_J.sh")], + capture_output=True, text=True, timeout=1800) + jf = ROOT / "status/real/AUDIT271_J_DINO.json" + if not jf.exists(): + rec("J_reader_features_match", False, + f"check J wrote no result (rc={r.returncode}); tail={r.stdout[-300:]!r}") + return + d = json.loads(jf.read_text()) + R["reader_feature_rows"] = {k: d.get(k) for k in + ("n_frames", "z_max_abs_diff", "z_bit_identical", + "logit_max_abs_diff", "rank_order_identical", "head_hub_name", + "github_source_refetched_this_run")} + st = d.get("source_trees", {}) + rec("J_reader_features_match", bool(d.get("ok")), + f"{d.get('n_frames')} fixture frames through both DINOv2 sources: max|dz|=" + f"{d.get('z_max_abs_diff')}, {d.get('head_hub_name')} max|dR|={d.get('logit_max_abs_diff')}, " + f"source trees {st.get('n_py_local')}/{st.get('n_py_github')} .py files " + f"same_snapshot={st.get('same_snapshot')}; failures={d.get('failures')}") + + +# ------------------------- K: a page's PROSE about a head's availability vs the hub tree +# The pages a reader is sent to name checkpoint files in sentences. A..J check the files, the +# rows, the bytes and the features; none reads whether the SENTENCE around a filename still tells +# the truth about whether that file can be downloaded. Found by hand at run 21: REWARDS.md +# described scheme C as "not published yet -- in training" while all four C heads had been trained +# to step 110000 and were absent from the hub by DECISION (no C head beats its permuted control) -- +# which CHECKPOINTS.md:419-422 stated correctly, per file, at the same time. A reader following +# REWARDS.md would have waited for an upload that was never coming. +PENDING_PHRASES = ("not published yet", "not yet published", "in training", "still training", + "upload pending", "not yet uploaded", "coming soon") +NOT_LIVE_MARKERS = ("not uploaded", "not on the hub", "not published", "deliberately not") + + +def check_K(): + """For every `successor_rsm_real_*.pt` mentioned on a shipped page: if the file is NOT live on + the hub the sentence must say so, and if it IS live the sentence must not describe it as pending. + + Deliberately narrow -- it reads availability only, the one property of a head that a reader acts + on and that changes without the page changing. It is NOT a general prose check. + """ + pages = (sorted((CLONE / "rise_stack").glob("*.md")) + sorted(CLONE.glob("*.md")) + + [ST / "HF_MODEL_CARD.md"]) + live = set(R.get("hub_reward_heads_live") or []) + if not live: + rec("K_availability_prose_matches_hub", False, + "the live-head set is empty (check D did not run or the hub listing failed), so every " + "verdict here would be vacuous") + return + declared = set(R.get("rows_declared_not_uploaded") or []) + bad, seen = [], 0 + for md in pages: + try: + where = str(md.relative_to(CLONE)) + except ValueError: + where = md.name + for i, ln in enumerate(md.read_text().splitlines(), 1): + for fname in set(re.findall(r"successor_rsm_real_[A-Za-z0-9_]+\.pt", ln)): + if fname not in live and fname not in declared: + continue # not a #271 reward head this check knows about + seen += 1 + low = ln.lower() + if fname in live: + hit = [ph for ph in PENDING_PHRASES if ph in low] + if hit: + bad.append(f"{where}:{i} calls {fname} {hit} but it is LIVE on the hub") + else: + if not any(m in low for m in NOT_LIVE_MARKERS): + bad.append(f"{where}:{i} names {fname} with no mark that it is NOT " + f"downloadable (it is declared but not on the hub)") + # K2 -- a pending phrase that names NO file. K1 above is keyed on a filename, and the run-21 + # bug had none: REWARDS.md's scheme-C row put "not published yet -- in training" in the FILE + # column, so the stale claim was the whole cell. On #271's own pages every reward head is + # trained, so a pending phrase there is stale by construction unless it names a specific head + # that genuinely is not (and then K1 judges it). Restricted to these pages on purpose: another + # stream's page may legitimately say "in training" about work that is not a reward head. + own = [CLONE / "rise_stack/REWARDS.md", CLONE / "rise_stack/REWARD_NAMES.md", + CLONE / "rise_stack/CHECKPOINTS.md", ST / "HF_MODEL_CARD.md"] + n2 = 0 + for md in own: + if not md.exists(): + bad.append(f"{md.name} is missing, so K2 cannot read it") + continue + n2 += 1 + try: + where = str(md.relative_to(CLONE)) + except ValueError: + where = md.name + for i, ln in enumerate(md.read_text().splitlines(), 1): + low = ln.lower() + hit = [ph for ph in PENDING_PHRASES if ph in low] + if hit and not re.search(r"successor_rsm_real_[A-Za-z0-9_]+\.pt", ln): + bad.append(f"{where}:{i} claims {hit} without naming any head; every #271 reward " + f"head is trained, so this tells a reader to wait for nothing") + rec("K_availability_prose_matches_hub", not bad and seen > 0 and n2 == len(own), + f"{seen} checkpoint mentions over {len(pages)} pages checked against {len(live)} live + " + f"{len(declared)} declared-not-uploaded heads, plus {n2} of this issue's own pages swept " + f"for pending claims that name no head; bad={bad[:6]}") + + +# --------------------- L: the head's LABEL provenance -- does the file carry the reward it claims? +# H checks name -> file, I checks file -> bytes, J checks bytes -> features, K checks prose -> +# availability. All four stop at the checkpoint's SURFACE. None of them asks whether +# successor_rsm_real_A_110000.pt was TRAINED on the GOAL_SEGMENT label: point the fine-tune +# launcher at the wrong --reward-npy and every one of them stays green while every downloader gets +# a head that optimises a reward nobody named. L reads the level below, twice and independently: +# it rebuilds each head's training label from the checkpoint's own config through the trainer's own +# data pipeline (which also covers the base head, whose label comes from a reward_mode rule and not +# from a path), and it scores the corpus with the head to see which label R(z) actually fits best. +# Run as a SUBPROCESS: L needs the RSM venv's interpreter (torch + the rsm_libero package). +# Its negative control is scripts/real/_audit271_L_selftest.py. +def check_L(): + import subprocess + r = subprocess.run([str(ROOT / "scripts/real/_audit271_L.sh")], + capture_output=True, text=True, timeout=3600) + lf = ROOT / "status/real/AUDIT271_L_LABELPROV.json" + if not lf.exists(): + rec("L_head_label_provenance", False, + f"check L wrote no result (rc={r.returncode}); tail={r.stdout[-300:]!r}") + return + d = json.loads(lf.read_text()) + heads = d.get("heads", {}) + R["label_provenance_rows"] = { + k: {kk: v.get(kk) for kk in ("claims_label", "recorded_match", "functional_match", + "claimed_auc", "margin_over_best_rival")} + for k, v in heads.items()} + n_rec = sum(1 for v in heads.values() if v.get("recorded_match")) + n_fn = sum(1 for v in heads.values() if v.get("functional_match")) + margins = [v["margin_over_best_rival"] for v in heads.values() + if isinstance(v.get("margin_over_best_rival"), (int, float))] + rec("L_head_label_provenance", bool(d.get("ok")), + f"{d.get('n_heads_checked')}/{d.get('n_heads_expected')} delivered heads: " + f"recorded label matches for {n_rec}, R(z) fits the claimed label best for {n_fn} " + f"(min margin over the best rival label {min(margins):+.4f})" if margins else + f"{d.get('n_heads_checked')} heads; failures={d.get('failures')}") + if d.get("failures"): + R.setdefault("label_provenance_failures", d["failures"]) + + +# ---------------------------------------------------------------- N: counts vs their record +_N_WORDNUM = {"one": 1, "two": 2, "three": 3, "four": 4, "five": 5, "six": 6, "seven": 7, + "eight": 8, "nine": 9, "ten": 10, "eleven": 11, "twelve": 12} + + +def _n_int(s): + s = (s or "").strip().lower().replace(",", "") + return int(s) if s.isdigit() else _N_WORDNUM.get(s) + + +def _n_sentences(text): + """Sentences with the line wrapping removed. + + Every count claim on these pages spans a line break (`**8 of\\nthose 356 objects ...`), so the + page is unwrapped per paragraph before splitting. Split on `;` or a period followed by + WHITESPACE -- the run-23 H2 rule, which does not cut `.gitattributes`, `86fca39.` or + `successor_..._110000.pt` in half the way a bare `[;.]` split does. + """ + out = [] + for para in re.split(r"\n\s*\n", text): + s = re.sub(r"\s+", " ", para).strip() + if s: + out += [p.strip() for p in re.split(r";|(?<=\.)\s+", s) if p.strip()] + return out + + +# ---------------------------------------------------------------- [inv]: the INVENTORY level +# Run 26 repaired the card's per-file TABLE (check O) and, in doing so, exposed the level below the +# counts N already read. N's [count]/[cover]/[scope] all read the HASHING paragraph -- "N of those +# M objects have been hashed", "the twelve pi05_ params folders". Two other live sentences print a +# count of ARTEFACTS ("three params folders", "five reward heads"), and no rule read either: on a +# hub carrying twelve pi05_ folders and eight fine-tuned heads, both were wrong, directly above a +# table that (now) lists all twenty. An inventory count is not the hashing paragraph's count and +# not a table row; it is a claim about WHAT THE REPO HOLDS, and it goes stale on every upload. +# +# The hard part is not the number, it is the DENOMINATOR: "five reward heads" is wrong on a hub with +# 8 fine-tuned heads + 2 base successors, but so is "ten", which is the count of a DIFFERENT class +# (every successor_*.pt). So class membership is defined here, once, as a path convention, and the +# failure message names the classes the printed number WOULD have been right for -- a reader fixing +# it has to choose a denominator, and the check is what tells them the choice exists. +# +# This classifier is deliberately INDEPENDENT of hf_card_refresh_table.what_is(), which composes the +# same distinction for the table's `what it is` column: the generator and its auditor reading the +# same helper is how the 8-of-356 sentence shipped past a check that "verified" it (run 25 doc). +_N_INV_CLASSES = ( + # phrase (regex, matched case-insensitively) -> class key + (r"(?:pi0\.5\s+|pi05_\s+)?params?\s+folders?", "params folder"), + (r"reward\s+heads?", "reward head"), + (r"base\s+successors?", "base successor"), + (r"successor\s+checkpoints?", "successor checkpoint"), +) +# "successors" on its own is NOT a class: the shipped pages say "8.3 successor queries per chain" +# and "one successor draw", where the number is a rate, not an inventory. A check that fires on +# those is the run-23 H false positive again, and the count it would print is meaningless. + + +def _n_inventory(tree_paths): + """Live member lists of the artefact classes a page makes inventory claims about. + + {class key: [top-level hub path]}, from the tree record alone, so the control can feed a + fixture tree. The conventions, all of them documented by the files themselves: + * a pi0.5 params export is a top-level DIRECTORY named pi05_* + * a fine-tuned reward head is successor_rsm_real_[_s1]_.pt + * a BASE successor is the pre-fine-tune checkpoint, successor_rsm_real_RM_s_100k.pt -- + the `_RM_s_` infix is what separates it from a head, and check L's label map carries + the same split (run 22 named both base successors as its coverage gap). + """ + tops = sorted({p.split("/")[0] + ("/" if "/" in p else "") for p in tree_paths}) + pi05 = [p for p in tops if p.endswith("/") and p.startswith("pi05_")] + succ = [p for p in tops if re.match(r"^successor_rsm_real_.*\.pt$", p)] + base = [p for p in succ if re.search(r"_RM_s\d+_", p)] + return {"params folder": pi05, + "sweep params folder": [p for p in pi05 + if re.search(r"_(?:sn[0-9p]+_knn[0-9p]+|wsctrl)_", p)], + "reward head": [p for p in succ if p not in base], + "base successor": base, + "successor checkpoint": succ} + + +def _n_inventory_bad(where, s, inv, skip_spans): + """[inv] over one sentence -> (failures, claims read). + + `skip_spans` are character ranges another rule already owns. The claim COUNT is the number of + number+class pairs actually read, never the number of times a class word occurs: run 19's + lesson is that `seen` is what stops a vacuous pass, so inflating it with unnumbered prose would + quietly disarm that guard. + """ + out, claims = [], 0 + for pat, key in _N_INV_CLASSES: + rx = (r"(? 3 else ''}{also}") + return out, claims + + +def n_count_claims_bad(pages, records): + """N: a COUNT a shipped page prints, against the record it is computed from, and against the + scope that same sentence claims for it. + + The level below M. M reads a DIGEST -- one file, one string, and a wrong one is a typo or a + re-upload. Nothing read a COUNT, and a count is the form every SUMMARY claim on these pages + takes ("the tree is N files", "N of those M objects have been hashed"). A count is more + fragile than a digest precisely because it is SUBSTITUTED from a record: regenerate the page + while the record it reads was last written by a NARROWER run and the number silently becomes + that narrower run's, while every clause written for the wide run stays put. That is the bug + this check was written against, and it is on the live model card: run 16 said `123 of those 354 + objects have been hashed ... (the 124th is .gitattributes)`, which closes; run 21 re-substituted + `8 of those 356` from an `hf_verify_sha.py --group reward` record and left behind both the + ordinal and "That includes every binary *inside* the four pi0.5 params folders" -- for which the + 8-row record holds not one row. The count UNDERSTATES the work done and the scope OVERSTATES + what was read, in one sentence, and D/F/I/K/M are all green on it. + + Pure function of {page label: text} and {record name: parsed json}, so the control can feed + fixtures instead of the live files. Four rules that must report APART, because a reader fixes + them differently: + [tree] a live claim about the repo's size -> hf_tree.json n_files / total_human + [count] "N of those M objects have been hashed" -> rows in hf_sha.json, and M vs n_files + [arith] an ordinal in the SAME sentence as that count -> must close against N with no record + [cover] "N of those M objects are verified/checked" -> rows that MATCHED, and M vs n_files + [scope] what the sentence says the hashing COVERS -> folders the record has rows for, + and the folder COUNT the page asserts + vs the folders the TREE record lists + [rev] the revision a page pins its verification to -> the revision the record was taken at + [inv] an INVENTORY count -- "N params folders", -> the members of that CLASS in the tree + "N reward heads" -- i.e. what the repo HOLDS record, with the classes the printed + number WOULD have been right for + + Run 25 added [cover] and made [scope] two-sided, both against defects found on the live card + while repairing the one above. [count] reads only "hashed", and the honest paragraph prints + TWO counts -- 206 objects carry an LFS sha256 and were hashed, 149 small members carry none and + are compared by size -- so the wider claim ("355 of those 356 objects are verified") was a + number no rule read; that is the same uncovered level one step out. [scope] fired only when + the record covered FEWER folders than the page claimed, so "the four pi0.5 params folders" on a + hub that now holds TWELVE of them was a definite description the record contradicts, and the + one-sided rule was structurally unable to see it. + + Only PRESENT-TENSE claims about the current tree are read. A dated snapshot claim ("27 files + under this folder, repo total 354 files ... verified on the hub 2026-09-22, + `pi05_hub_files_run23.txt`") is history, it was true when written, and flagging it is exactly + the run-23 H false positive -- a check that fires on a correct page trains everyone to ignore + the audit. A sentence carrying a date or a `*_run.txt/json` snapshot name is therefore + skipped by [tree]. + """ + tree = records.get("hf_tree") or {} + sha_rows = [r for r in ((records.get("hf_sha") or {}).get("rows") or []) if isinstance(r, dict)] + n_hashed = sum(1 for r in sha_rows if r.get("mode") == "sha256") + n_matched = sum(1 for r in sha_rows if r.get("match") is True) + tree_paths = list((tree.get("tree") or {}).keys()) + inv = _n_inventory(tree_paths) + bad, seen = [], 0 + + for where, text in pages.items(): + sents = _n_sentences(text) + # the [scope] rule only applies to the paragraph that makes a hashing claim + page_hashes = any(re.search(r"\bof (?:those )?[\d,]+ (?:objects|files)\b.{0,90}?" + r"(?:have been|were|are) (?:hashed|sha256-)", s, re.I) + for s in sents) + for s in sents: + historic = bool(re.search(r"20\d\d-\d\d-\d\d|_run\d+\.(?:txt|json)", s)) + + m = re.search(r"\btree is\b\D{0,12}([\d,]+) files,\s*([\d.]+)\s*(GiB|GB|MiB|TiB)", s, re.I) + if m and not historic: + seen += 1 + n, human = _n_int(m.group(1)), f"{m.group(2)} {m.group(3)}" + if tree.get("n_files") != n: + bad.append(f"[tree] {where}: the page says the tree is {n} files, the record " + f"hf_tree.json was taken with n_files={tree.get('n_files')}") + rec_human = re.sub(r"\s+", " ", str(tree.get("total_human", ""))).strip() + if rec_human and rec_human.lower() != human.lower(): + bad.append(f"[tree] {where}: the page says {human}, the record says {rec_human}") + + m = m_hashed = re.search(r"([\d,]+) of (?:those )?([\d,]+) (?:objects|files)\b.{0,90}?" + r"(?:have been|were|are) (?:hashed|sha256-)", s, re.I) + if m: + seen += 1 + n, tot = _n_int(m.group(1)), _n_int(m.group(2)) + if n != n_hashed: + bad.append(f"[count] {where}: the page claims {n} objects hashed, the record " + f"hf_sha.json holds {n_hashed} sha256 rows " + f"(rows cover {len({r.get('path','').split('/')[0] for r in sha_rows})} " + f"top-level paths)") + if tree.get("n_files") is not None and tot != tree.get("n_files"): + bad.append(f"[count] {where}: the page says {n} of {tot} objects, but the tree " + f"record holds {tree.get('n_files')} files") + k = re.search(r"\bthe (\d+)(?:st|nd|rd|th)\b", s) + if k and n is not None and int(k.group(1)) > n + 1: + bad.append(f"[arith] {where}: the sentence claims {n} of {tot} hashed and then " + f"says 'the {k.group(1)}th' -- that ordinal only closes if " + f"{int(k.group(1)) - 1} were hashed, so the two numbers in this one " + f"sentence come from different runs") + + # [cover]: the WIDER claim the same paragraph makes -- how many objects were checked at + # all, by any means. Deliberately a different verb set from [count]'s "hashed", and a + # different denominator in the record (rows that MATCHED, not rows in sha256 mode), so + # a page cannot satisfy one rule by borrowing the other's number. + m = re.search(r"([\d,]+) of (?:those |the )?([\d,]+) (?:objects|files)\b.{0,110}?" + r"(?:have been|were|are)\s+(?:verified|checked|compared)\b", s, re.I) + # One clause that says both ("206 of those 356 objects have been hashed and verified") + # is ONE claim and is [count]'s; only a SEPARATE pair of numbers is [cover]'s, which is + # why the guard compares the two matches' start offsets and not the sentence's words. + if m and not historic and not (m_hashed and m_hashed.start() == m.start()): + seen += 1 + n, tot = _n_int(m.group(1)), _n_int(m.group(2)) + if n != n_matched: + bad.append(f"[cover] {where}: the page claims {n} objects verified, the record " + f"hf_sha.json holds {n_matched} rows that matched their source " + f"(of {len(sha_rows)} read)") + if tree.get("n_files") is not None and tot != tree.get("n_files"): + bad.append(f"[cover] {where}: the page says {n} of {tot} objects, but the tree " + f"record holds {tree.get('n_files')} files") + + m = re.search(r"[Vv]erified at revision\s*`?([0-9a-f]{7,40})`?", s) + if m: + seen += 1 + rev = str(tree.get("revision") or "") + if not rev.startswith(m.group(1).lower()): + bad.append(f"[rev] {where}: the page pins its verification to revision " + f"{m.group(1)}, the record was taken at {rev[:12] or '(none)'}") + + scope_spans = [] + if page_hashes: + m = re.search(r"includes every\b.{0,40}?\binside\b.{0,24}?\bthe\s+([A-Za-z0-9]+)\s+" + r"([A-Za-z0-9_.]+).{0,24}?\bfolders\b", s, re.I) + if m: + scope_spans.append(m.span()) + seen += 1 + want, tokraw = _n_int(m.group(1)), m.group(2) + tok = re.sub(r"[^a-z0-9]", "", tokraw.lower()) + got = sorted({r.get("path", "").split("/")[0] for r in sha_rows + if "/" in r.get("path", "") + and tok in re.sub(r"[^a-z0-9]", "", + r.get("path", "").split("/")[0].lower())}) + if want is None or len(got) < want: + bad.append(f"[scope] {where}: the page says the hashing 'includes every " + f"... inside the {m.group(1)} {tokraw} ... folders', but the " + f"record it cites has rows inside {len(got)} such folder(s) " + f"{got[:4]}") + # The other side, and a different repair: "the four ... folders" is a definite + # description of the REPO, so it is wrong the moment a fifth lands -- even + # while the hashing still covers every one of them and the rule above is + # silent. Measured against the TREE (what is on the hub), not against the sha + # record (what was read), because those are two different claims. + on_hub = sorted({p.split("/")[0] for p in tree_paths if "/" in p + and tok in re.sub(r"[^a-z0-9]", "", + p.split("/")[0].lower())}) + if want is not None and on_hub and len(on_hub) != want and not historic: + bad.append(f"[scope] {where}: the page calls them 'the {m.group(1)} " + f"{tokraw} ... folders', but the tree record lists " + f"{len(on_hub)} such folder(s) on the hub {on_hub[:3]}" + f"{' ...' if len(on_hub) > 3 else ''}") + + # [inv]: the INVENTORY sentences -- "N params folders", "N reward heads" -- which are + # neither the hashing paragraph's counts nor a table row. Present tense only, same + # rule as [tree]/[cover]: a dated or snapshot-named sentence is history. + if not historic and inv: + hits, nclaims = _n_inventory_bad(where, s, inv, scope_spans) + seen += nclaims + bad += hits + return bad, seen + + +def check_N(): + pages = {} + for md in (sorted((CLONE / "rise_stack").glob("*.md")) + sorted(CLONE.glob("*.md")) + + [ST / "HF_MODEL_CARD.md"]): + try: + where = str(md.relative_to(CLONE)) + except ValueError: + where = md.name + pages[where] = md.read_text() + records = {} + for name in ("hf_tree", "hf_sha"): + p = ST / f"{name}.json" + records[name] = json.loads(p.read_text()) if p.exists() else {} + bad, seen = n_count_claims_bad(pages, records) + R["count_claims_checked"] = seen + if bad: + R["count_claim_failures"] = bad + # seen>0: a page set that prints no count at all must not pass vacuously (run 19's lesson, + # the same guard M carries). + rec("N_published_counts_match_record", not bad and seen > 0, + f"{seen} count/scope claims over {len(pages)} pages checked against hf_tree.json " + f"(n_files={records.get('hf_tree',{}).get('n_files')}) and hf_sha.json " + f"({sum(1 for r in (records.get('hf_sha',{}).get('rows') or []) if r.get('mode')=='sha256')}" + f" sha256 rows); bad={bad[:3]}") + + + +_O_UNIT = {"b": 1, "kib": 2 ** 10, "mib": 2 ** 20, "gib": 2 ** 30, "tib": 2 ** 40} +# Two files on the hub that a listing of the CHECKPOINTS is not wrong to leave out: the card itself, +# and the one file the Hub writes and for which there is no source. Named here rather than skipped +# silently, and printed in the check's detail, so an exemption cannot grow by accident. +_O_NOT_CONTENT = {"README.md", ".gitattributes"} + + +def _o_bytes(cell): + """The byte count and the optional `(N files)` a table cell prints, or (None, None). + + `12,441,308,391 (30 files)` -> (12441308391, 30); `96,433 total` -> (96433, None); + `148.65 GiB` -> (159609127118, None) at the printed precision; `matches source` -> (None, None). + """ + m = re.match(r"\s*([\d][\d,]*(?:\.\d+)?)\s*(B|KiB|MiB|GiB|TiB)?\b", cell) + if not m: + return None, None, None + num, unit = m.group(1).replace(",", ""), (m.group(2) or "").lower() + nf = re.search(r"\((\d+)\s+files?\)", cell) + nf = int(nf.group(1)) if nf else None + if unit: + prec = len(num.split(".")[1]) if "." in num else 0 + return float(num) * _O_UNIT[unit], nf, prec + if "." in num: # a bare decimal is not a byte count + return None, None, None + return int(num), nf, None + + +def _o_match(pat, tree): + """The hub paths a table row's backticked token names. `dir/` is a prefix, `*` is a glob.""" + if pat.endswith("/"): + return [p for p in tree if p.startswith(pat)] + if "*" in pat or "?" in pat: + import fnmatch + return [p for p in tree if fnmatch.fnmatchcase(p, pat)] + return [p for p in tree if p == pat] + + +def _o_tables(text): + """Markdown tables whose header names a BYTES column, as (header cells, [(line no, cells)]).""" + out, lines = [], text.splitlines() + i = 0 + while i < len(lines): + cells = [c.strip() for c in lines[i].strip().strip("|").split("|")] \ + if lines[i].lstrip().startswith("|") else None + if cells and len(cells) > 1 and any(re.search(r"\bbytes?\b", c, re.I) for c in cells) \ + and i + 1 < len(lines) and re.match(r"^\s*\|[\s:|-]+\|\s*$", lines[i + 1]): + rows, j = [], i + 2 + while j < len(lines) and lines[j].lstrip().startswith("|"): + rows.append((j + 1, [c.strip() for c in lines[j].strip().strip("|").split("|")])) + j += 1 + out.append((cells, rows)) + i = j + else: + i += 1 + return out + + +def o_file_table_bad(pages, tree): + """O: the per-file SIZE TABLE a shipped page prints, against the hub listing it describes. + + The level below N. M reads one digest; N reads the SUMMARY counts a page prints about the repo + as a whole. Neither reads the table that tells a downloader WHAT IS IN THE REPO and how big + each part is -- and that table is the only place a reader learns what a 12 GB folder contains. + It is maintained by hand, by whichever stream uploaded last, so it drifts in two directions: + a printed size goes stale when a file is re-uploaded, and -- the defect this was written + against -- an upload lands with NO ROW AT ALL. On the live card the table listed four pi05_ + params folders while the hub carried twelve: eight public folders of ~12 GB each, 99.5 GiB, + with nothing on the page saying what they are, under a paragraph that (correctly) says every + byte is verified. I/M/N were all green on it, because a row that does not exist prints no + name, no digest and no count. + + Pure function of {page label: text} and {hub path: bytes}, so the control can feed fixtures. + Four rules that report APART, because a reader fixes them differently: + [bytes] a row's printed size -> the summed size of the hub paths it names + [nfiles] a row's `(N files)` -> how many hub paths it names + [ghost] a row naming no live path -> deleted or renamed on the hub, still on the page + [cover] a live top-level path no row names -> an upload nobody described + + [cover] fires only on a table that CLAIMS to list the repo: its first header cell says so, or + its rows name eight or more live top-level entries (a table naming that many is a listing + whatever its header was renamed to). A three-row table of just the reward heads is not wrong + for leaving the actors out, and a check that failed it would be the run-23 H false positive in + a new costume: broad enough to fire on a true page. + """ + bad, seen, cover_tables = [], 0, 0 + top = {} + for p in tree: + top.setdefault(p.split("/")[0] + ("/" if "/" in p else ""), []).append(p) + for where, text in pages.items(): + for head, rows in _o_tables(text): + named, row_pats = set(), [] + for ln, cells in rows: + pats = re.findall(r"`([^`]+)`", cells[0]) if cells else [] + if not pats: + continue + row_pats.append((ln, cells, pats)) + for pat in pats: + named.update(_o_match(pat, tree)) + is_listing = bool(re.search(r"file|repo", head[0], re.I)) and \ + bool(re.search(r"repo|hub", " ".join(head), re.I)) + n_top = len({p.split("/")[0] for p in named}) + if n_top >= 8: + is_listing = True + for ln, cells, pats in row_pats: + hit, missing = [], [] + for pat in pats: + m = _o_match(pat, tree) + (hit.extend(m) if m else missing.append(pat)) + if missing: + seen += 1 + bad.append(f"[ghost] {where}:{ln} has a row for {missing} which is not on " + f"the hub") + if not hit: + continue + claimed, nf, prec = None, None, None + for c in cells[1:]: + claimed, nf, prec = _o_bytes(c) + if claimed is not None: + break + actual = sum(tree[p] for p in set(hit)) + if claimed is not None: + seen += 1 + ok = (abs(claimed - actual) < 0.5) if prec is None else \ + (round(claimed / _O_UNIT["gib"], prec) == + round(actual / _O_UNIT["gib"], prec)) + if not ok: + bad.append(f"[bytes] {where}:{ln} prints {claimed:,.0f} bytes for {pats}, " + f"but the hub serves {actual:,} over {len(set(hit))} file(s)") + if nf is not None: + seen += 1 + if nf != len(set(hit)): + bad.append(f"[nfiles] {where}:{ln} says {nf} files for {pats}, but the hub " + f"has {len(set(hit))}") + if not is_listing: + continue + cover_tables += 1 + for k, members in sorted(top.items()): + if k.rstrip("/") in _O_NOT_CONTENT or any(p in named for p in members): + continue + seen += 1 + bad.append(f"[cover] {where}: the hub carries `{k}` " + f"({len(members)} file(s), {sum(tree[p] for p in members):,} bytes) " + f"and this repo listing has no row for it") + return bad, seen, cover_tables + + +def check_O(): + from huggingface_hub import HfApi + api = HfApi(token=os.environ.get("HF_TOKEN") or os.environ.get("HUGGING_FACE_HUB_TOKEN")) + # The LIVE tree, not status/real/hf_tree.json: the table describes the hub, so a record that + # went stale in the same run must not be able to make this check green. + tree = {e.path: e.size for e in api.list_repo_tree(REPO, repo_type="model", recursive=True) + if getattr(e, "size", None) is not None and not hasattr(e, "tree_id")} + pages = {} + for md in (sorted((CLONE / "rise_stack").glob("*.md")) + sorted(CLONE.glob("*.md")) + + [ST / "HF_MODEL_CARD.md"]): + try: + where = str(md.relative_to(CLONE)) + except ValueError: + where = md.name + pages[where] = md.read_text() + bad, seen, ntab = o_file_table_bad(pages, tree) + R["table_claims_checked"] = seen + if bad: + R["table_claim_failures"] = bad + # seen>0: a page set whose size tables print nothing readable must not pass vacuously. + rec("O_file_table_matches_hub", not bad and seen > 0, + f"{seen} size/row claims over {len(pages)} pages against {len(tree)} live hub files " + f"({sum(tree.values()):,} bytes); {ntab} table(s) read as a repo listing, exempt from " + f"[cover]: {sorted(_O_NOT_CONTENT)}; bad={bad[:4]}") + + +def check_P(): + from audit271_P_artifact_record import (read_manifest, read_records, what_is_rows, p_rows_bad) + pages = {} + for md in (sorted((CLONE / "rise_stack").glob("*.md")) + sorted(CLONE.glob("*.md")) + + [ST / "HF_MODEL_CARD.md"]): + try: + where = str(md.relative_to(CLONE)) + except ValueError: + where = md.name + pages[where] = md.read_text() + manifest = read_manifest() + records = read_records(manifest) + rows = what_is_rows(pages) + bad, seen, unver = p_rows_bad(rows, records, manifest) + described = {r[2] for r in rows} + # the robomimic actors and the hop head moved to check Q in run 29, so P must stop reporting + # them as "held by no record". Imported as DATA (two name tuples), never as a parser: P and Q + # keep separate readers on purpose (run 26's shared-helper defect). + from audit271_Q_stack_record import ROBOMIMIC as Q_ROBO, HOP as Q_HOP + q_owned = set(Q_ROBO) | set(Q_HOP) + skipped = sorted(d for d in described + if d not in records and d.rstrip("/") not in records + and Path(d).name not in q_owned + and (d.endswith(".pt") or d.endswith(".pth") or d.startswith("pi05_"))) + R["P_claims_checked"] = seen + R["P_unverifiable"] = unver + if bad: + R["P_row_failures"] = bad + n_pt = sum(1 for r in records.values() if r["kind"] == "pt" and r.get("present")) + n_orb = sum(1 for r in records.values() if r["kind"] == "orbax" and r.get("present")) + # seen>0: a card whose claim columns stop parsing must not pass by describing nothing. + rec("P_row_words_match_artifact_record", not bad and seen > 0, + f"{seen} row/name claims over {len(rows)} claim cells on {len(pages)} pages, against " + f"{n_pt} checkpoint blobs' own step/config.seed/config.out and {n_orb} orbax exports' own " + f"assets; {len(unver)} word(s) NO record can confirm (a pi0.5 export records neither seed, " + f"step nor arm) -- reported, not passed; artefacts described but held by no record: " + f"{skipped} (the 3 robomimic actors + the hop head are check Q's since run 29); " + f"bad={bad[:4]}") + + +def check_Q(): + """The RISE-STACK artefacts' own record vs the rows that describe them (run 29). + + P reads the successor blobs' `step`/`config.seed`/`config.out` and reported four artefacts it + held no record for -- the two RISE actors, the BC-union control and the hop head. They were + outside P only because `read_records` reads a config shape they do not have: robomimic + serialises its whole 187-leaf config into the `.pth`, and the hop head carries its round. + + Q reads `algo.use_bc`, NOT `algo_name`: `algo_name` is `idql` for the BC cell too (S0B is the + same algo class with `training.use_bc=True`, run_train.sh:95), so an `[algo]` rule would have + failed the card's correct "plain BC objective (`S0B`)" row. + """ + from audit271_P_artifact_record import read_manifest, what_is_rows + from audit271_Q_stack_record import read_stack_records, q_rows_bad + pages = {} + for md in (sorted((CLONE / "rise_stack").glob("*.md")) + sorted(CLONE.glob("*.md")) + + [ST / "HF_MODEL_CARD.md"]): + try: + where = str(md.relative_to(CLONE)) + except ValueError: + where = md.name + pages[where] = md.read_text() + manifest = read_manifest() + records = read_stack_records(manifest) + rows = what_is_rows(pages) + bad, seen, unver = q_rows_bad(rows, records, manifest) + R["Q_claims_checked"] = seen + R["Q_unverifiable"] = unver + if bad: + R["Q_row_failures"] = bad + n_rb = sum(1 for r in records.values() if r["kind"] == "robomimic" and r.get("present")) + n_hop = sum(1 for r in records.values() if r["kind"] == "hop" and r.get("present")) + objs = sorted({f"{Path(k).name}:use_bc={v.get('use_bc')}" + for k, v in records.items() if v["kind"] == "robomimic" and v.get("present")}) + # seen>0 for the same reason as P: a card whose claim columns stop parsing must not pass by + # describing nothing. + rec("Q_stack_row_words_match_artifact_record", not bad and seen > 0, + f"{seen} row/name claims over {len(rows)} claim cells on {len(pages)} pages, against " + f"{n_rb} robomimic checkpoints' own config.train.seed / experiment.name / algo.use_bc " + f"({objs}) and {n_hop} hop head's own round; {len(unver)} word(s) no record can confirm " + f"(a robomimic blob records its run's num_epochs, never WHICH epoch it is) -- reported, " + f"not passed; algo_name is the CLASS (idql for the BC cell too) and is deliberately never " + f"read as an objective; bad={bad[:4]}") + + +# ---------------------------------------------------------------- R: the printed STATISTICS +def check_R(): + """(run 30) the NUMBERS a shipped page prints, against the measurement JSON they were + substituted from. P and Q read what a row says about an ARTEFACT; every claim they cover names + a file. A number names none. A compares the spliced block to the generator's OUTPUT file, not + to its INPUTS, and G asserts only that the diagnostics EXIST -- so a re-measurement that + rewrites a JSON leaves every printed AUC, CI, p-value, frame count and bold significance tick + stale while all seventeen other checks stay green. R re-reads the witnesses and compares at + the PRINTED precision (half a unit in the last printed place), so a page that rounds cannot go + red for rounding. See audit271_R_published_stats.py.""" + from audit271_R_published_stats import run as r_run + res = r_run() + bad, seen = res["bad"], res["seen"] + R["R_claims_checked"] = seen + if res["unmapped"]: + R["R_unmapped_rows"] = res["unmapped"] + if bad: + R["R_stat_failures"] = bad + # seen>0 for P's and Q's reason: a table whose cells stop parsing must not pass by claiming + # nothing. An unmapped row is REPORTED, never counted -- that is how a new head would hide. + rec("R_published_stats_match_measurement", not bad and seen > 0, + f"{seen} numeric claims over {res['tables']} #271 diagnostics table(s) and " + f"{res['fivedraw']} five-draw sentence(s) on the 12 pages + the HF card, against " + f"REWARD_SCHEMES / REWARD_HEAD_DIAG / STITCH_SIGNIFICANCE[by_hop 4] / REWARD_SCREEN / " + f"STITCH_DRAWS[by_hop 4]; compared at the printed precision, counts exactly, and the bold " + f"ticks against p<0.05 and beats_control; {len(res['unmapped'])} row(s) named a head R does " + f"not map (reported, not counted); bad={bad[:4]}") + + +def check_S(): + """(run 31) the numbers a shipped page prints whose witness belongs to ANOTHER STREAM. + + The rung below R. R covers every number whose witness is a JSON this stream wrote. The same + pages quote the #269 / pi0.5 screen -- twelve table rows of "spread X, oracle Y cm, head Z" -- + whose witness is status/real/openloop_pi05/scorer_openloop.json, an artefact this stream + neither writes nor can regenerate. Nothing read it: P/Q read a row's WORDS about an artefact, + R only reads witnesses it owns, K/N/O/D read the hub. So #269 can re-run a screen, overwrite a + scorer_openloop.json, and all eighteen other checks stay green while twelve shipped rows quote + superseded numbers. Three things the probe (rr_cpu_271Sprobe31) established before a rule was + written: `head` is not a field anywhere -- it is DERIVED, greedy - oracle; a proximity rule is + unusable (310 coincidental hits / 217 float misses on CHECKPOINTS.md alone); and the same row + carries a FOREIGN design ("Step-10000 held-out greedy"), which on one live row is written + INSIDE the screen window. See audit271_S_foreign_stats.py.""" + from audit271_S_foreign_stats import run as s_run + res = s_run() + bad, seen = res["bad"], res["seen"] + R["S_claims_checked"] = seen + if res["unmapped"]: + R["S_unmapped_rows"] = res["unmapped"] + if bad: + R["S_stat_failures"] = bad + # seen>0 for P's, Q's and R's reason: a table whose cells stop parsing must not pass by + # claiming nothing. An unmapped row is REPORTED, never counted. + rec("S_foreign_stats_match_measurement", not bad and seen > 0, + f"{seen} numeric claims over {res['rows']} pi0.5 screen row(s) on the 12 pages + the HF " + f"card, against {res['n_witnesses']} status/real/openloop_pi05*/scorer_openloop.json " + f"witness(es) owned by the #269 stream; spread/oracle direct, head DERIVED as " + f"greedy-oracle, plus the row's own 'N ep' design constant; compared at the printed " + f"precision; the map is cross-checked against each witness's own policy run+step; " + f"deliberately silent on held-out greedy/chunk/grip_acc (a different design) and on the " + f"knob columns; {len(res['unmapped'])} screen row(s) S does not map (reported, not " + f"counted); bad={bad[:4]}") + + +def check_U(): + """(run 33) the DESIGN CONSTANTS a shipped page prints, against the config the artefact + recorded for ITSELF. + + The rung below R and S. R reads the printed RESULT numbers against the measurement JSON they + were substituted from; S does the same where the witness belongs to another stream. Neither + reads the SETTINGS the measurement was taken AT -- the beta, the gamma, the particles, N, the + flow steps, the checkpoint, the split. A page can quote the right AUC out of the right JSON + and describe it as measured at beta 0.99 when the JSON's own `config` says 0.95, and all + nineteen other checks stay green. And two pages print a RUNNABLE COMMAND under a heading that + says "Reproducing it": nothing read its flags, so a reader can be handed a different + measurement than the section's. That is exactly what U found on its first live run. + + Three things the probes (rr_cpu_271Uprobe33 / U2 / U3) established before a rule was written: + 453 of 2236 status JSONs record a `config`, so the witness exists; the richest recipe on the + pages is INDENTED, not fenced (U1 read only fences and missed it); and single-value matching is + unusable for finding a witness -- U's own first wiring named a JUNC_feat arm on 16 coincidental + hits, the same failure run 32's T1 probe measured. U therefore reads only numbers the PROSE + LABELS, inside the enclosing level-2 section, and calls an artefact the witness of record only + if it reproduces EVERY labelled number. See audit271_U_design_constants.py, control + _audit271_U_selftest.py (15/15).""" + from audit271_U_design_constants import run as u_run + ok, detail, res = u_run() + R["U_constant_claims_checked"] = res["seen"] + if res["unanchored"]: + R["U_unanchored_blocks"] = res["unanchored"] + if res["no_record"]: + R["U_no_record_constants"] = res["no_record"] + if res["bad"]: + R["U_design_failures"] = res["bad"] + # seen>0 for P/Q/R/S's reason: a page whose recipe blocks stop parsing must not pass by + # claiming nothing. An unanchorable block is REPORTED, never counted. + rec("U_design_constants_match_config", ok and res["seen"] > 0, detail) + + +def check_V(): + """(run 34) two shipped pages stating the SAME named quantity must agree WITH EACH OTHER. + + The rung below R/S/U, and the one that covers this ladder's blind spot. R, S and U are all + RESOLVERS: each takes a number off a page, finds the artefact that witnesses it, and compares. + When there is NO witness all three go silent -- correctly, since inventing one is check P's + forbidden move. But silence is not absence of a defect: run 32 §4 found four numbers on a + shipped page that no artefact on disk reproduces and could conclude nothing beyond + "unwitnessed". V is what works there. If two pages state the same quantity for the same + subject they must agree, and that is decidable from the pages alone -- no artefact, no hub + call, no config. A number with no witness becomes checkable the moment a second page prints it. + + V attributes a value to an arm under exactly TWO constructions (an arm token followed within 50 + characters by the value; or the value followed within 20 by "for/on ") and DECLINES + everything else. General proximity was tried and measured wrong on four different sentence + shapes -- this is the third wiring, and the control caught all of them. Two mentions count as + a contradiction only when their page-level spans are DISJOINT at the coarser printed precision, + so V fires on contradiction rather than on granularity. `candidate_spread_mm` is extracted and + reported but NOT adjudicated: the pages state spread per arm (default 6.78, runner-up 6.50) and + V's subject is a class, which made two correct numbers look like a conflict. See + audit271_V_cross_page.py, probes _audit271_V{,2}_probe.py, control _audit271_V_selftest.py + (9/9, incl. five SILENCE scenarios).""" + from audit271_V_cross_page import run as v_run + ok, detail, res = v_run() + R["V_attributed_mentions"] = sum(len(v) for v in res["mentions"].values()) + if res["unattributed"]: + R["V_unattributed_values"] = res["unattributed"] + if res["reported"]: + R["V_not_cross_checkable"] = res["reported"] + if res["bad"]: + R["V_cross_page_conflicts"] = res["bad"] + # seen>0 for P/Q/R/S/U's reason: a check whose extraction silently stops must not pass by + # claiming nothing. An unattributable value is REPORTED, never counted as agreement. + rec("V_cross_page_quantity_agreement", ok and R["V_attributed_mentions"] > 0, detail) + + + +def check_W(): + """(run 41) a shipped reproduction command must not name a checkpoint its own section's prose + contradicts. + + The rung runs 39/40 prototyped as probe AB's rules R2/R3 and deliberately did NOT promote, because + its live surface is one (flag,value) pair and n=1 immunity buys the appearance of coverage. Run 41's + probe AC settled that by replaying AB's UNMODIFIED detector over all 112 commits of rise_stack/: + over 9430 pairs and 112 snapshots R2/R3 fired on exactly TWO distinct sites -- one defect line times + two rules -- caught the real `R_M_ft_v0/ckpt_s110000.pt` vs prose-`R_M`/`100000` defect that had + shipped for 43 consecutive commits, and agreed on all 3 snapshots since run 38 fixed it + (46 surface-carrying snapshots = 43 firing + 3 agreeing, 92 judged pair-checks = 46 x 2 rules). + Zero false-positive sites. R1 over the same history produced 945 conflicts and stays retired. + + AC also retired the OTHER half of the promotion criterion by measuring it unsatisfiable: it asked for + >=3 checkpoint-path claims, and the surface has never exceeded 1 in 112 commits, so runs 39-41 were + waiting on a state history says does not occur. Surface 0 is a non-pass by the ladder's standing + seen>0 convention (P/Q/R/S/U/V) and means the repro command left the corpus -- a coverage loss, not a + formula defect; the detail line distinguishes them. Rules imported from _audit271_AB_probe.py so the + rung cannot drift from the probe that measured it. Control: audit271_W_selftest.py (9/9, including + the real pre-fix blob from git as the positive control, and the inline-code alternative-invocation + hazard that retired R1).""" + from audit271_W_ckpt_path import run as w_run + ok, detail, res = w_run() + R["W_ckpt_path_surface"] = res["surface"] + R["W_ckpt_path_stats"] = res["stats"] + if res["conflicts"]: + R["W_ckpt_path_conflicts"] = res["conflicts"] + rec("W_ckpt_path_prose_agreement", ok, detail) + + +def main(): + for fn in (check_A, check_B, check_C, check_D, check_E, check_F, check_G, + check_H, check_I, check_J, check_K, check_L, check_M, check_N, + check_O, check_P, check_Q, check_R, check_S, check_U, check_V, + check_W): + try: + fn() + except Exception as e: # a failing check must not hide the others + rec(fn.__name__, False, f"EXCEPTION {type(e).__name__}: {e}") + R["all_pass"] = all(c["ok"] for c in R["checks"].values()) + OUT.write_text(json.dumps(R, indent=1, default=str)) + print(f"[audit] wrote {OUT} all_pass={R['all_pass']}", flush=True) + sys.exit(0 if R["all_pass"] else 1) + + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/real/aug_feasibility.py b/rsm_rise/scripts/real/aug_feasibility.py new file mode 100644 index 0000000000000000000000000000000000000000..4c1b9a9a4d894ba3b87f6a37d89c85dae5cf83de --- /dev/null +++ b/rsm_rise/scripts/real/aug_feasibility.py @@ -0,0 +1,375 @@ +"""TASK 1 (stream AUG_SUCC, gen_q#279): is RISE's state-space kNN augmentation rich enough AT THE S2 +JUNCTION of the real cooking corpus to supply the COUNTERFACTUAL (state, action) pairs the successor has +never seen -- and is the neighbourhood SMALLER than the goal-vs-failure action gap it must not destroy? + +THE DECISION THIS SCRIPT MAKES + RISE's augmentation emits (obs = anchor i, action = neighbour j's action, reward = j's reward, + next_obs = i's OWN next_obs). Two readings of that for an occupancy model: + invariant -- assert the neighbour's action leads to the ANCHOR's future occupancy. Safe ONLY if + the admitted neighbourhood is strictly smaller than the action gap between the + goal route's chunk and the failure route's chunk at the same state. + contrastive -- assert the counterfactual action carries the NEIGHBOUR's outcome/reward. + If the admitted neighbours' actions straddle the goal-vs-failure action gap, `invariant` actively + destroys the signal the reverse-anchor test needs and only `contrastive` is defensible. + +METRICS (both reported, on the same threshold ladder) + feat1546 L2 in the NORMALISED 1546-d DINO+proprio feature the successor actually trains in + (x = clip((f - mu)/sd, -10, 10), feat_stats.npz). This is the analogue of RISE's own metric: + with image observations `_extract_state_for_distance` returns flattened VISUAL FEATURES. + Also reported per-dim (L2 / sqrt(D)) so the number is dimension-free. + ee10 L2 over [xyz (m), 0.05 * rot6d] -- the metric `scripts/real/build_knn_pairs_ee.py` ships for + the real kNN, in METRES, so RISE's shipped distance_threshold 0.15 is directly comparable. + +ANCHORS the S2 frames (edge_from == 2) at --stride of the VALIDATION `2->3->4` episodes: the same 96 +anchors the reverse/forward ranking tests use. +NEIGHBOUR POOLS every frame of every OTHER episode, broken down by route, plus the S2-only slice. +CPU only; MUJOCO_GL=disable. +""" +import argparse, json, sys, collections +import numpy as np + +ROOT = "/proj/dmfexp/zwhong/rsm_rise" +GOAL_PATH = "2->3->4" +ROUTES_OF_INTEREST = ("0->2->6", "0->2->3", "0->1->3", "0->5", "2->3->4") +ROT_SCALE = 0.05 + + +def pct(a, qs=(0, 1, 5, 10, 25, 50, 75, 95, 100)): + a = np.asarray(a, np.float64) + return {f"p{q}": (float(np.percentile(a, q)) if len(a) else float("nan")) for q in qs} + + +def fmt(d): + return " ".join(f"{k}={v:.4f}" for k, v in d.items()) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--hdf5", default=f"{ROOT}/data/raw/cooking_v5_expert_suboptimal.hdf5") + ap.add_argument("--split", default=f"{ROOT}/data/derived/cooking_v5_split.json") + ap.add_argument("--cache", default=f"{ROOT}/cache/real_cooking_v5") + ap.add_argument("--feat-stats", default=f"{ROOT}/cache/real_cooking_v5/feat_stats.npz") + ap.add_argument("--stride", type=int, default=25) + ap.add_argument("--horizon", type=int, default=8) + ap.add_argument("--n-distractor", type=int, default=31) + ap.add_argument("--num-neighbors", type=int, default=15, help="RISE's per-anchor neighbour cap") + ap.add_argument("--seed", type=int, default=0) + ap.add_argument("--out", required=True) + a = ap.parse_args() + import os, h5py + os.makedirs(a.out, exist_ok=True) + rng = np.random.default_rng(a.seed) + split = json.load(open(a.split))["episodes"] + + # ---------------------------------------------------------------- features (the training metric) + from pathlib import Path + cache = Path(a.cache); st = np.load(a.feat_stats) + zf = np.load(cache / "z.f16.npy", mmap_mode="r") + pf = np.load(cache / "proprio.f32.npy", mmap_mode="r") + meta = np.load(cache / "meta.npz", allow_pickle=True) + ep_from = {int(e): int(v) for e, v in enumerate(meta["ep_from"])} + ep_len = {int(e): int(v) for e, v in enumerate(meta["ep_len"])} + D = zf.shape[1] + pf.shape[1] + mu, sd = st["mu"][:D].astype(np.float32), st["sd"][:D].astype(np.float32) + zclip = float(st["z_clip"]) if "z_clip" in st else 10.0 + N = zf.shape[0] + print(f"[aug] cache {N} frames x {D} dims; building normalised features in RAM", flush=True) + X = np.empty((N, D), np.float32) + CH = 20000 + for i in range(0, N, CH): + j = min(i + CH, N) + X[i:j] = np.clip((np.concatenate([np.asarray(zf[i:j], np.float32), + np.asarray(pf[i:j], np.float32)], 1) - mu) / sd, -zclip, zclip) + Xsq = (X.astype(np.float64) ** 2).sum(1) + P = np.asarray(pf, np.float32) + E = np.concatenate([P[:, :3], ROT_SCALE * P[:, 3:9]], 1).astype(np.float32) # EE metric, metres + Esq = (E.astype(np.float64) ** 2).sum(1) + print(f"[aug] features ready ({X.nbytes/1e9:.2f} GB)", flush=True) + + # ---------------------------------------------------------------- episode / route bookkeeping + with h5py.File(a.hdf5, "r") as f: + d = f["data"] + keys = list(d) + path = {int(k.split("_")[1]): str(d[k].attrs.get("path", "")) for k in keys} + stage, acts = {}, {} + for k in keys: + e = int(k.split("_")[1]); g = d[k] + stage[e] = g["annot"]["edge_from"][()].astype(np.int16) + acts[e] = (g["actions_raw"] if "actions_raw" in g else g["actions"])[()].astype(np.float32) + is_val = lambda e: split.get(str(e), {}).get("split") == "valid" + by_route = collections.Counter(path.values()) + print("[aug] routes: " + " ".join(f"{r}={n}" for r, n in sorted(by_route.items())), flush=True) + + def rows_of(e): + """global cache rows of episode e, clipped to both the cache length and the hdf5 length""" + L = min(ep_len[e], len(stage[e]), len(acts[e])) + return ep_from[e] + np.arange(L), L + + # anchors: S2 frames at --stride of the VALIDATION goal episodes + anchors = [] # (ep, t, global_row) + for e in sorted(path): + if path[e] != GOAL_PATH or not is_val(e): + continue + r, L = rows_of(e) + for t in range(0, L - a.horizon, a.stride): + if int(stage[e][t]) == 2: + anchors.append((e, t, int(r[t]))) + print(f"[aug] anchors: {len(anchors)} S2 frames from " + f"{len(set(x[0] for x in anchors))} validation {GOAL_PATH} episodes", flush=True) + + # neighbour pools + pools = {} + for rt in ROUTES_OF_INTEREST: + idx, meta_rows = [], [] + for e in sorted(path): + if path[e] != rt: + continue + r, L = rows_of(e) + idx.append(r[: L - a.horizon]); meta_rows.append(np.stack( + [np.full(L - a.horizon, e), np.arange(L - a.horizon), + stage[e][: L - a.horizon].astype(np.int64)], 1)) + pools[rt] = (np.concatenate(idx), np.concatenate(meta_rows)) + print(f"[aug] pool {rt}: {len(pools[rt][0])} frames", flush=True) + allrows = np.concatenate([pools[rt][0] for rt in ROUTES_OF_INTEREST]) + allmeta = np.concatenate([pools[rt][1] for rt in ROUTES_OF_INTEREST]) + + # ---------------------------------------------------------------- chunk helper + def chunk(e, t): + A = acts[e]; c = A[t:t + a.horizon] + if len(c) < a.horizon: + c = np.concatenate([c, np.repeat(c[-1:], a.horizon - len(c), 0)], 0) + return c.reshape(-1) + + CHUNK = {} + for e in sorted(path): + _, L = rows_of(e) + for t in range(0, L - a.horizon): + CHUNK[(e, t)] = None # lazily filled; avoid 180k x 80 floats up front + def ch(e, t): + v = CHUNK.get((e, t)) + if v is None: + v = chunk(e, t); CHUNK[(e, t)] = v + return v + + # ---------------------------------------------------------------- distances anchor -> pools + LADDER_FEAT = [2.0, 4.0, 6.0, 8.0, 10.0, 12.0, 15.0, 20.0, 25.0, 30.0] # L2 in the 1546-d metric + LADDER_EE = [0.02, 0.05, 0.10, 0.15, 0.20, 0.30, 0.50] # metres (RISE ships 0.15) + out = {"n_anchors": len(anchors), "D": int(D), "stride": a.stride, "horizon": a.horizon, + "num_neighbors": a.num_neighbors, "routes": dict(by_route), + "ladder_feat": LADDER_FEAT, "ladder_ee": LADDER_EE, "rot_scale": ROT_SCALE} + + ar = np.array([x[2] for x in anchors]) + Aq = X[ar].astype(np.float64); Aqsq = Xsq[ar] + Ae = E[ar].astype(np.float64); Aesq = Esq[ar] + + def dists(rows): + B = X[rows].astype(np.float64) + d2 = Aqsq[:, None] + Xsq[rows][None, :] - 2.0 * (Aq @ B.T) + Be = E[rows].astype(np.float64) + e2 = Aesq[:, None] + Esq[rows][None, :] - 2.0 * (Ae @ Be.T) + return np.sqrt(np.maximum(d2, 0)), np.sqrt(np.maximum(e2, 0)) + + # ---- 1. distance distribution to each route, all frames and S2-only ---- + out["dist"] = {} + DF, DE = {}, {} + for rt in ROUTES_OF_INTEREST: + rows, m = pools[rt] + df, de = dists(rows) + DF[rt], DE[rt] = df, de + same_ep = (m[None, :, 0] == np.array([x[0] for x in anchors])[:, None]) # exclude self-episode + dfm = np.where(same_ep, np.inf, df); dem = np.where(same_ep, np.inf, de) + s2 = m[:, 2] == 2 + rec = {"n_frames": int(len(rows)), "n_frames_S2": int(s2.sum()), + "feat_all": pct(dfm[np.isfinite(dfm)]), "ee_all": pct(dem[np.isfinite(dem)]), + "feat_min_per_anchor": pct(dfm.min(1)), "ee_min_per_anchor": pct(dem.min(1))} + if s2.any(): + sub = dfm[:, s2]; sube = dem[:, s2] + rec["feat_S2"] = pct(sub[np.isfinite(sub)]); rec["ee_S2"] = pct(sube[np.isfinite(sube)]) + rec["feat_S2_min_per_anchor"] = pct(sub.min(1)); rec["ee_S2_min_per_anchor"] = pct(sube.min(1)) + out["dist"][rt] = rec + print(f"\n[dist] anchor -> {rt} ({len(rows)} frames, {int(s2.sum())} at S2)") + print(f" feat1546 all : {fmt(rec['feat_all'])}") + print(f" feat1546 NN : {fmt(rec['feat_min_per_anchor'])} (per-anchor nearest)") + print(f" ee10(m) all : {fmt(rec['ee_all'])}") + print(f" ee10(m) NN : {fmt(rec['ee_min_per_anchor'])}") + if s2.any(): + print(f" feat1546 S2 : {fmt(rec['feat_S2'])}") + print(f" ee10(m) S2 : {fmt(rec['ee_S2'])}") + sys.stdout.flush() + + # ---- 2. neighbour COUNTS on the ladder, and the anchors covered ---- + dF_all = np.concatenate([DF[rt] for rt in ROUTES_OF_INTEREST], 1) + dE_all = np.concatenate([DE[rt] for rt in ROUTES_OF_INTEREST], 1) + same_ep_all = (allmeta[None, :, 0] == np.array([x[0] for x in anchors])[:, None]) + dF_all = np.where(same_ep_all, np.inf, dF_all) + dE_all = np.where(same_ep_all, np.inf, dE_all) + anchor_route = np.array([path[x[0]] for x in anchors]) + nb_route = np.array([path[int(e)] for e in allmeta[:, 0]]) + is_cross = (nb_route[None, :] != anchor_route[:, None]) + is_fail26 = (nb_route[None, :] == "0->2->6") + is_023 = (nb_route[None, :] == "0->2->3") + + out["counts"] = {"feat": {}, "ee": {}} + print("\n[ladder] neighbours per anchor (DIFFERENT episode; RISE also caps at num_neighbors)") + print(f"{'thr':>8}{'any/anchor':>12}{'cross/anchor':>14}{'0->2->6':>10}{'0->2->3':>10}" + f"{'anchors>=1':>12}{'anchors>=1x':>12}") + for T in LADDER_FEAT: + m = dF_all <= T + rec = {"mean_per_anchor": float(m.sum(1).mean()), + "mean_cross_route": float((m & is_cross).sum(1).mean()), + "mean_0_2_6": float((m & is_fail26).sum(1).mean()), + "mean_0_2_3": float((m & is_023).sum(1).mean()), + "frac_anchors_ge1": float((m.sum(1) >= 1).mean()), + "frac_anchors_ge1_cross": float(((m & is_cross).sum(1) >= 1).mean()), + "frac_anchors_ge1_fail26": float(((m & is_fail26).sum(1) >= 1).mean())} + out["counts"]["feat"][str(T)] = rec + print(f"{T:>8.1f}{rec['mean_per_anchor']:>12.1f}{rec['mean_cross_route']:>14.1f}" + f"{rec['mean_0_2_6']:>10.1f}{rec['mean_0_2_3']:>10.1f}" + f"{rec['frac_anchors_ge1']:>12.3f}{rec['frac_anchors_ge1_cross']:>12.3f}") + print(f"\n[ladder] same, EE metric (metres; RISE ships distance_threshold 0.15)") + print(f"{'thr(m)':>8}{'any/anchor':>12}{'cross/anchor':>14}{'0->2->6':>10}{'0->2->3':>10}" + f"{'anchors>=1':>12}{'anchors>=1x':>12}") + for T in LADDER_EE: + m = dE_all <= T + rec = {"mean_per_anchor": float(m.sum(1).mean()), + "mean_cross_route": float((m & is_cross).sum(1).mean()), + "mean_0_2_6": float((m & is_fail26).sum(1).mean()), + "mean_0_2_3": float((m & is_023).sum(1).mean()), + "frac_anchors_ge1": float((m.sum(1) >= 1).mean()), + "frac_anchors_ge1_cross": float(((m & is_cross).sum(1) >= 1).mean()), + "frac_anchors_ge1_fail26": float(((m & is_fail26).sum(1) >= 1).mean())} + out["counts"]["ee"][str(T)] = rec + print(f"{T:>8.3f}{rec['mean_per_anchor']:>12.1f}{rec['mean_cross_route']:>14.1f}" + f"{rec['mean_0_2_6']:>10.1f}{rec['mean_0_2_3']:>10.1f}" + f"{rec['frac_anchors_ge1']:>12.3f}{rec['frac_anchors_ge1_cross']:>12.3f}") + sys.stdout.flush() + + # ---- 3. ACTION distance: the gap the augmentation must not swallow ---- + # (b) the 31 failure distractors the ranking test uses: chunks from 0->5 / 0->2->6 at the same stage. + FAIL_PATHS = ("0->5", "0->2->6") + fail_pool = collections.defaultdict(list) + for e in sorted(path): + if path[e] not in FAIL_PATHS: + continue + _, L = rows_of(e) + for t in range(0, L - a.horizon, a.stride): + fail_pool[int(stage[e][t])].append((e, t)) + # the reverse-arm "goal chunk" distance too: goal-route chunks at S2 from OTHER episodes + goal_pool = collections.defaultdict(list) + for e in sorted(path): + if path[e] != GOAL_PATH: + continue + _, L = rows_of(e) + for t in range(0, L - a.horizon, a.stride): + goal_pool[int(stage[e][t])].append((e, t)) + + anchor_chunks = np.stack([ch(e, t) for e, t, _ in anchors]) + adist = lambda U, V: np.sqrt(((U - V) ** 2).sum(-1)) + + d_distract, d_goal = [], [] + for i, (e, t, _) in enumerate(anchors): + cand = [c for c in fail_pool.get(2, []) if c[0] != e] + if len(cand) >= a.n_distractor: + pick = rng.choice(len(cand), size=a.n_distractor, replace=False) + d_distract.append(adist(np.stack([ch(*cand[j]) for j in pick]), anchor_chunks[i])) + g = [c for c in goal_pool.get(2, []) if c[0] != e] + if g: + d_goal.append(adist(np.stack([ch(*c) for c in g]), anchor_chunks[i])) + d_distract = np.concatenate(d_distract) if d_distract else np.array([]) + d_goal = np.concatenate(d_goal) if d_goal else np.array([]) + out["action_gap"] = {"failure_distractors_31": pct(d_distract), + "other_goal_route_chunks": pct(d_goal), + "n_failure_pairs": int(len(d_distract)), "n_goal_pairs": int(len(d_goal))} + print("\n[action] ||a_chunk - a_anchor||, 8x10 absolute-pose chunk, raw units") + print(f" vs the 31 FAILURE distractors (the ranking test's set): {fmt(pct(d_distract))}") + print(f" vs OTHER GOAL-route chunks at S2 : {fmt(pct(d_goal))}") + # the DECISION statistic: the median failure-distractor action gap + GAP = float(np.median(d_distract)) if len(d_distract) else float("nan") + GAP25 = float(np.percentile(d_distract, 25)) if len(d_distract) else float("nan") + out["action_gap"]["median_failure_gap"] = GAP + out["action_gap"]["p25_failure_gap"] = GAP25 + + # (a) admitted neighbours' action distance, per threshold + print(f"\n[decision] median goal-vs-failure action gap = {GAP:.4f} (p25 {GAP25:.4f}).") + print(" For each state threshold: the action distance of the neighbours it ADMITS, and the") + print(" fraction of them whose action is FARTHER from the anchor's than that gap.") + print(" straddle_frac HIGH -> the neighbourhood swallows the decision -> `invariant` DESTROYS it.") + print(f"{'metric':>6}{'thr':>9}{'n_pairs':>10}{'a_p50':>9}{'a_p95':>9}{'straddle50':>12}{'straddle25':>12}") + out["straddle"] = {"feat": {}, "ee": {}} + nb_ep = allmeta[:, 0].astype(int); nb_t = allmeta[:, 1].astype(int) + for tag, Dm, ladder in (("feat", dF_all, LADDER_FEAT), ("ee", dE_all, LADDER_EE)): + for T in ladder: + m = Dm <= T + ai, bj = np.nonzero(m) + if len(ai) == 0: + out["straddle"][tag][str(T)] = {"n_pairs": 0} + print(f"{tag:>6}{T:>9.3f}{0:>10}{'-':>9}{'-':>9}{'-':>12}{'-':>12}") + continue + if len(ai) > 200000: # cap the work; uniform subsample of the pairs + sel = rng.choice(len(ai), size=200000, replace=False); ai, bj = ai[sel], bj[sel] + da = adist(np.stack([ch(int(nb_ep[j]), int(nb_t[j])) for j in bj]), anchor_chunks[ai]) + rec = {"n_pairs": int(m.sum()), "n_scored": int(len(da)), "action_dist": pct(da), + "straddle_frac_median_gap": float((da > GAP).mean()), + "straddle_frac_p25_gap": float((da > GAP25).mean())} + out["straddle"][tag][str(T)] = rec + print(f"{tag:>6}{T:>9.3f}{rec['n_pairs']:>10}{rec['action_dist']['p50']:>9.4f}" + f"{rec['action_dist']['p95']:>9.4f}{rec['straddle_frac_median_gap']:>12.3f}" + f"{rec['straddle_frac_p25_gap']:>12.3f}") + sys.stdout.flush() + + # ---- 4. RISE-faithful count: cap at num_neighbors, different trajectory, over the WHOLE corpus ---- + # (this is what the trainer would actually build, anchors = every frame, not just S2) + # THE KNOB THAT DECIDES WHETHER ANY COUNTERFACTUAL SURVIVES: RISE keeps only the k NEAREST + # different-trajectory neighbours and only then applies the threshold. At this junction the + # nearest different-episode frames are OTHER GOAL-ROUTE episodes (they are the same behaviour), + # so the cap can be entirely consumed by on-route frames and emit no counterfactual at all. + # Reported here as the route composition of the pairs the cap actually admits. + print(f"\n[rise-faithful] k={a.num_neighbors} cap FIRST (nearest different-episode frames), then the threshold") + print(f"{'metric':>7}{'thr':>9}{'pairs/anch':>12}{'cross/anch':>12}{'0->2->6/a':>11}" + f"{'cov':>7}{'cov_cross':>11}{'cov_026':>9}{'a_p50':>8}{'straddle50':>12}") + out["capped"] = {"feat": {}, "ee": {}} + for tag, Dm, ladder in (("feat", dF_all, LADDER_FEAT), ("ee", dE_all, LADDER_EE)): + ordr = np.argsort(Dm, 1)[:, :a.num_neighbors] # one sort per metric + kth = np.take_along_axis(Dm, ordr, 1) + cross_k = np.take_along_axis(is_cross, ordr, 1) + f26_k = np.take_along_axis(is_fail26, ordr, 1) + f23_k = np.take_along_axis(is_023, ordr, 1) + nb_of = np.stack([nb_ep[ordr], nb_t[ordr]], -1) # [n_anchor, k, 2] + for T in ladder: + m = kth <= T + n = m.sum(1) + ai, bj = np.nonzero(m) + if len(ai): + da = adist(np.stack([ch(int(nb_of[i, j, 0]), int(nb_of[i, j, 1])) + for i, j in zip(ai, bj)]), anchor_chunks[ai]) + ap50 = float(np.percentile(da, 50)); strad = float((da > GAP).mean()) + adist_pct = pct(da) + else: + ap50 = float("nan"); strad = float("nan"); adist_pct = {} + rec = {"mean_per_anchor": float(n.mean()), + "mean_cross_route": float((m & cross_k).sum(1).mean()), + "mean_0_2_6": float((m & f26_k).sum(1).mean()), + "mean_0_2_3": float((m & f23_k).sum(1).mean()), + "frac_anchors_ge1": float((n >= 1).mean()), + "frac_anchors_ge1_cross": float(((m & cross_k).sum(1) >= 1).mean()), + "frac_anchors_ge1_fail26": float(((m & f26_k).sum(1) >= 1).mean()), + "total_pairs": int(n.sum()), "action_dist": adist_pct, + "straddle_frac_median_gap": strad} + out["capped"][tag][str(T)] = rec + print(f"{tag:>7}{T:>9.3f}{rec['mean_per_anchor']:>12.2f}{rec['mean_cross_route']:>12.2f}" + f"{rec['mean_0_2_6']:>11.2f}{rec['frac_anchors_ge1']:>7.3f}" + f"{rec['frac_anchors_ge1_cross']:>11.3f}{rec['frac_anchors_ge1_fail26']:>9.3f}" + f"{ap50:>8.3f}{strad:>12.3f}") + sys.stdout.flush() + + json.dump(out, open(f"{a.out}/aug_feasibility.json", "w"), indent=1) + np.savez_compressed(f"{a.out}/aug_feasibility_raw.npz", + anchor_ep=np.array([x[0] for x in anchors]), + anchor_t=np.array([x[1] for x in anchors]), + d_feat_min=dF_all.min(1), d_ee_min=dE_all.min(1), + d_distract=d_distract, d_goal=d_goal) + print(f"\nwrote {a.out}/aug_feasibility.json") + + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/real/aug_fit_check.py b/rsm_rise/scripts/real/aug_fit_check.py new file mode 100644 index 0000000000000000000000000000000000000000..9ac1ce6d0a600f81f5a250179643b57e433eb008 --- /dev/null +++ b/rsm_rise/scripts/real/aug_fit_check.py @@ -0,0 +1,420 @@ +#!/usr/bin/env python3 +"""AUG_SUCC (gen_q#279) run 23 -- DID THE CONTRASTIVE AUGMENTATION LOSS GET FIT AT ALL? + +WHY THIS EXISTS. Run 22 closed the data axis: the Task-4 junction augmentation reaches 73 % of the +37 scored anchors with ~20 goal-route counterfactual actions each (~30x RISE's shipped-radius dose), +at the exact frames the gate scores, in models that trained on those frames' own episodes -- and the +goal chunk still ranks at chance. Coverage does not predict the gate (|r| <= 0.19, p >= 0.25) and the +zero-parameter pose score does (r = +0.55, p = 0.002). So more pairs is not the lever. + +That leaves exactly two readings, and they call for opposite next moves: + (a) the contrastive loss was NEVER FIT -- the model collapsed to the invariant solution and ignores + which route the action came from. Then the fix is optimisation (loss weight, capacity, the + beta band), not data, and no threshold sweep can ever help. + (b) the loss WAS fit on its own training pairs, and the failure is the READ-OUT: the chain score of + a candidate chunk does not expose the counterfactual the model learned. Then the fix is the + scoring protocol, which is a different stream's surface. + +This script decides between them, HELD-IN, in the gate's own read-out. For a junction pair +(anchor state s from route A, partner action chunk a' from route B) it compares the chain score +q(s, a_own) against q(s, a_partner) -- the same RSMScorer, chain mode, beta / gamma / particles / +temperature the gate uses, so the only thing that changes is which action is scored. + + arm GOALvsFAIL goal-route anchor, failure-route partner: win = q(s, a_own) > q(s, a_partner) + arm FAILvsGOAL failure-route anchor, goal-route partner: win = q(s, a_partner) > q(s, a_own) + <- THIS IS THE GATE'S QUESTION, asked on the training pairs themselves + arm SAMEROUTE partner from the anchor's OWN route: win = q(s, a_own) > q(s, a_partner). + The control. There is no counterfactual signal in it, so a trained model that is + merely scoring on-manifold plausibility should sit wherever this arm sits, and an + arm that does not beat it has shown nothing. + +Every arm is reported for the AUGMENTED cell AND for the un-augmented baseline on the SAME pairs, so +the number that matters is the paired delta, not the level. Bootstrap is over anchor EPISODES. +CPU only; MUJOCO_GL=disable. +""" +import argparse, collections, json, os, sys +import numpy as np + +ROOT = "/proj/dmfexp/zwhong/rsm_rise" +sys.path.insert(0, f"{ROOT}/scripts/real") + + +# ------------------------------------------------------------------ statistics (pure, selftested) +def boot_episode(eps, vals, n_boot=4000, seed=0): + """Bootstrap the mean of `vals` by resampling anchor EPISODES with replacement.""" + eps = np.asarray(eps); vals = np.asarray(vals, np.float64) + uniq = np.unique(eps) + if len(uniq) < 2 or len(vals) == 0: + return dict(mean=float(vals.mean()) if len(vals) else float("nan"), + lo=None, hi=None, se=None, n_eps=int(len(uniq))) + by = [vals[eps == e] for e in uniq] + rng = np.random.default_rng(seed) + bs = np.array([np.concatenate([by[i] for i in rng.integers(0, len(by), len(by))]).mean() + for _ in range(n_boot)]) + return dict(mean=float(vals.mean()), lo=float(np.percentile(bs, 2.5)), + hi=float(np.percentile(bs, 97.5)), se=float(bs.std()), n_eps=int(len(uniq))) + + +def arm_stats(eps, win, margin, n_boot=4000, seed=0): + """`win` in {0, .5, 1} per pair (.5 = exact tie); `margin` = q_signed difference.""" + b = boot_episode(eps, win, n_boot, seed) + m = np.asarray(margin, np.float64) + return dict(n_pairs=int(len(win)), n_anchor_eps=int(len(np.unique(eps))), + win=b["mean"], lo=b["lo"], hi=b["hi"], se=b["se"], + margin_mean=float(m.mean()) if len(m) else float("nan"), + margin_med=float(np.median(m)) if len(m) else float("nan"), + ties=float(np.mean(np.asarray(win) == 0.5)) if len(win) else float("nan")) + + +def paired_delta(eps, win_a, win_b, n_boot=4000, seed=0): + """Episode-bootstrapped delta of two arms measured on the SAME pairs (augmented - baseline).""" + d = np.asarray(win_a, np.float64) - np.asarray(win_b, np.float64) + b = boot_episode(eps, d, n_boot, seed) + return dict(delta=b["mean"], lo=b["lo"], hi=b["hi"], se=b["se"]) + + +# ------------------------------------------------------------------------------------- selftest +def selftest(): + ok = True + + def chk(name, cond, extra=""): + nonlocal ok + ok &= bool(cond) + print(f" [{'PASS' if cond else 'FAIL'}] {name} {extra}") + + rng = np.random.default_rng(0) + # T1 a perfect arm is 1.0 and a dead arm is 0.5 with a zero-width CI when every episode agrees + eps = np.repeat(np.arange(5), 20) + s = arm_stats(eps, np.ones(100), np.ones(100)) + chk("T1 perfect arm win=1, CI degenerate", abs(s["win"] - 1) < 1e-12 and s["hi"] - s["lo"] < 1e-12) + # T2 a coin arm sits at 0.5 and its CI covers 0.5 + w = (rng.random(100) < 0.5).astype(float) + s = arm_stats(eps, w, rng.normal(size=100)) + chk("T2 coin arm CI covers 0.5", s["lo"] <= 0.5 <= s["hi"], f"win={s['win']:.3f} [{s['lo']:.3f},{s['hi']:.3f}]") + # T3 ALL the variance is between episodes -> the episode bootstrap must be WIDE even though the + # pair-level sd is tiny. This is the property that makes the pair-level CI a lie. + w = np.repeat([0.0, 0.0, 1.0, 1.0, 1.0], 20).astype(float) + s = arm_stats(eps, w, np.zeros(100)) + chk("T3 between-episode variance -> wide CI", (s["hi"] - s["lo"]) > 0.5, + f"win={s['win']:.3f} [{s['lo']:.3f},{s['hi']:.3f}]") + # T4 ties count as half a win + s = arm_stats(eps, np.full(100, 0.5), np.zeros(100)) + chk("T4 all ties -> win 0.5, ties 1.0", abs(s["win"] - 0.5) < 1e-12 and abs(s["ties"] - 1.0) < 1e-12) + # T5 a paired delta of two identical arms is exactly zero with a zero CI + d = paired_delta(eps, w, w) + chk("T5 identical arms -> delta 0", abs(d["delta"]) < 1e-12 and abs(d["hi"] - d["lo"]) < 1e-12) + # T6 a paired delta recovers a known constant shift + d = paired_delta(eps, np.ones(100), np.zeros(100)) + chk("T6 paired delta recovers +1", abs(d["delta"] - 1.0) < 1e-12) + # T7 win/margin sign convention: win must be 1 exactly when the margin is positive + q_own, q_par = rng.normal(size=200), rng.normal(size=200) + win = (q_own > q_par).astype(float); mar = q_own - q_par + chk("T7 win <-> sign(margin)", np.all((win == 1.0) == (mar > 0))) + print(f" selftest {'PASS' if ok else 'FAIL'}") + return ok + + +# ------------------------------------------------------------------------------------- the tool +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--cells", nargs="+", required=True, + help="run cell names under runs/real_cooking_v5/rsm; the FIRST is the reference " + "(normally R_M, the un-augmented baseline) and every other is delta'd against it") + ap.add_argument("--table", default=f"{ROOT}/data/derived/augsucc/junc_feat_s0.npz") + ap.add_argument("--cache", default=f"{ROOT}/cache/real_cooking_v5") + ap.add_argument("--hdf5", default=f"{ROOT}/data/raw/cooking_v5_expert_suboptimal.hdf5") + ap.add_argument("--hop-ckpt", default=f"{ROOT}/runs/real_cooking_v5/hop/gauss/policy_r1.pt") + ap.add_argument("--step", type=int, default=100000) + ap.add_argument("--threshold", type=float, default=45.0) + ap.add_argument("--max-anchors", type=int, default=600, help="per arm, sampled with a fixed seed") + ap.add_argument("--pairs-per-anchor", type=int, default=3) + ap.add_argument("--beta", type=float, default=0.99) + ap.add_argument("--gamma", type=float, default=0.999) + ap.add_argument("--particles", type=int, default=16) + ap.add_argument("--temperature", type=float, default=25.0) + ap.add_argument("--chunk", type=int, default=8) + ap.add_argument("--seed", type=int, default=0) + ap.add_argument("--nboot", type=int, default=4000) + ap.add_argument("--gate-eps", type=int, nargs="*", default=[204, 223, 224, 230, 231], + help="the 5 reverse-anchor episodes; arm FAILvsGOAL is re-reported on these alone") + ap.add_argument("--out", default=f"{ROOT}/status/real/augsucc/aug_fit_check.json") + ap.add_argument("--only-arms", nargs="*", default=None, + help="score only these arms (pairs for every arm are still BUILT, because the " + "derived arms are built from FAILvsGOAL's pair list). Pure cost control; " + "it changes no pair and no statistic.") + ap.add_argument("--any-arm", action="store_true", + help="add FAILvsGOALany: the same failure anchors, but the goal-route partner " + "drawn UNIFORMLY from all goal-route S2 frames with NO proximity gate -- " + "exactly how the gate draws its candidate 0. Isolates the proximity gate " + "as the difference between the held-in pair fit and the gate.") + ap.add_argument("--swap-arm", action="store_true", + help="add FAILvsGOALswap: the same goal-route partner ACTIONS re-paired with a " + "DIFFERENT failure anchor, so the action is in distribution but this exact " + "(state, action) pair was never trained on. Separates pair memorisation " + "from a learned route-level rule.") + ap.add_argument("--selftest-only", action="store_true") + a = ap.parse_args() + + print("=== selftest (runs BEFORE the tool sees any model output)") + if not selftest(): + sys.exit("selftest FAILED -- refusing to report a measurement") + if a.selftest_only: + return + + import h5py, torch + from twin_rollout import Scorer + + T = np.load(a.table, allow_pickle=True) + rows, nbr_row, nbr_dist = T["rows"], T["nbr_row"], T["nbr_dist"] + a_route, a_ep = T["anchor_route"], T["anchor_ep"] + routes = [str(r) for r in T["routes"]] + GOAL = routes.index("2->3->4") + FAIL = routes.index("0->2->6") + print(f"[fit] table {os.path.basename(a.table)}: {len(rows)} S2 anchors, routes {routes}, " + f"GOAL={GOAL} FAIL={FAIL}, K={nbr_row.shape[1]}") + + # row -> index into the anchor table, so a partner's route and episode are known + idx_of = {int(r): i for i, r in enumerate(rows)} + + m = np.load(f"{a.cache}/meta.npz", allow_pickle=True) + ep_from, ep_len = m["ep_from"], m["ep_len"] + zf = np.load(f"{a.cache}/z.f16.npy", mmap_mode="r") + pf = np.load(f"{a.cache}/proprio.f32.npy", mmap_mode="r") + st = np.load(f"{a.cache}/feat_stats.npz") + D = zf.shape[1] + pf.shape[1] + mu, sd = st["mu"][:D].astype(np.float32), st["sd"][:D].astype(np.float32) + zclip = float(st["z_clip"]) if "z_clip" in st else 10.0 + + with h5py.File(a.hdf5, "r") as f: + d = f["data"] + acts = {int(k.split("_")[1]): (d[k]["actions_raw"] if "actions_raw" in d[k] + else d[k]["actions"])[()].astype(np.float32) for k in d} + ep_of_row = np.full(int(zf.shape[0]), -1, np.int32) + for e in acts: + ep_of_row[int(ep_from[e]):int(ep_from[e]) + int(ep_len[e])] = e + + def chunk_of(row): + """the logged chunk that STARTS at global cache row `row`, padded with its last action.""" + e = int(ep_of_row[row]); t = int(row - ep_from[e]); A = acts[e] + c = A[t:t + a.chunk] + if len(c) < a.chunk: + c = np.concatenate([c, np.repeat(c[-1:], a.chunk - len(c), 0)], 0) + return c + + def feat(row): + x = np.concatenate([np.asarray(zf[row], np.float32), np.asarray(pf[row], np.float32)]) + return np.clip((x - mu) / sd, -zclip, zclip) + + # ---- build the pair list ONCE so every cell is scored on identical pairs ------------------- + rng = np.random.default_rng(a.seed) + ARMS = {"GOALvsFAIL": (GOAL, FAIL), "FAILvsGOAL": (FAIL, GOAL), "SAMEROUTE": (None, None)} + if a.swap_arm: + # FAILvsGOALswap -- the control that separates PAIR MEMORISATION from a learned action-level + # rule. Same failure anchor, and a goal-route partner action drawn from the pool of actions + # that DO appear as training partners, but paired with a DIFFERENT failure anchor, so this + # exact (state, action) pair was never a training pair. The action is in distribution as a + # partner and the state is a training anchor; only the PAIRING is new. If the paired arm is + # ~1.0 and this one is ~0.0, the model memorised pairs and learned no rule about routes. + ARMS["FAILvsGOALswap"] = (FAIL, GOAL) + if a.any_arm: + # FAILvsGOALany -- the gate's OWN draw. logged_action_rank.py:559-563 picks candidate 0 as a + # uniform random goal-route chunk from the pool at the anchor's meta stage, with no distance + # gate at all (`eligible(gentries, gposes, lambda c: True)`). FAILvsGOAL asks the same + # question with a partner that is within `--threshold` in feature space. The ONLY difference + # between the two arms is that proximity gate, so the pair of them localises the held-in -> + # gate gap to "the transfer is local in feature space" or not. + ARMS["FAILvsGOALany"] = (FAIL, GOAL) + pairs = {k: [] for k in ARMS} # (anchor_idx, partner_idx) + ANYDIST = [] # state distance of the uniform-draw partners, for the report + for name, (ar, pr) in ARMS.items(): + cand = np.arange(len(rows)) if ar is None else np.nonzero(a_route == ar)[0] + cand = cand[rng.permutation(len(cand))] + got = 0 + for i in cand: + if got >= a.max_anchors: + break + nb, nd = nbr_row[i], nbr_dist[i] + ok = np.nonzero(np.isfinite(nd) & (nd <= a.threshold))[0] + sel = [] + for s in ok: + j = idx_of.get(int(nb[s])) + if j is None or int(a_ep[j]) == int(a_ep[i]): + continue + same = int(a_route[j]) == int(a_route[i]) + if name == "SAMEROUTE": + # the table is cross-route by construction, so the control pairs an anchor with + # another frame of its OWN route drawn at the same distance rank -- see below + continue + if (not same) and int(a_route[j]) == pr: + sel.append(j) + if name == "SAMEROUTE": + own = np.nonzero((a_route == a_route[i]) & (a_ep != a_ep[i]))[0] + if len(own) == 0: + continue + xi = feat(int(rows[i])) + sub = own[rng.permutation(len(own))[:400]] + Xs = np.stack([feat(int(rows[j])) for j in sub]) + dd = np.linalg.norm(Xs - xi[None], axis=1) + keep = sub[np.nonzero(dd <= a.threshold)[0]] + sel = list(keep[:a.pairs_per_anchor]) + if not sel: + continue + sel = list(np.asarray(sel)[rng.permutation(len(sel))[:a.pairs_per_anchor]]) + pairs[name] += [(int(i), int(j)) for j in sel] + got += 1 + if name == "FAILvsGOALswap": + src = pairs["FAILvsGOAL"] + if src: + anchors = [p[0] for p in src]; partners = [p[1] for p in src] + # derangement by rotation, then drop any pair that accidentally stays a real training + # partner of its new anchor (rotation can collide when one anchor appears twice) + sh = partners[1:] + partners[:1] + keep = [] + for i2, j2 in zip(anchors, sh): + nb2, nd2 = nbr_row[i2], nbr_dist[i2] + real = {int(nb2[t]) for t in np.nonzero(np.isfinite(nd2) & (nd2 <= a.threshold))[0]} + if int(rows[j2]) in real or int(a_ep[j2]) == int(a_ep[i2]): + continue + keep.append((int(i2), int(j2))) + pairs[name] = keep + if name == "FAILvsGOALany": + src = pairs["FAILvsGOAL"] + goal_rows = np.nonzero(a_route == GOAL)[0] + keep, anydist = [], [] + for (i2, _j) in src: + nb2, nd2 = nbr_row[i2], nbr_dist[i2] + real = {int(nb2[t]) for t in np.nonzero(np.isfinite(nd2) & (nd2 <= a.threshold))[0]} + xi = feat(int(rows[i2])) + for _try in range(20): + j2 = int(goal_rows[rng.integers(len(goal_rows))]) + if int(a_ep[j2]) == int(a_ep[i2]) or int(rows[j2]) in real: + continue + keep.append((int(i2), j2)) + anydist.append(float(np.linalg.norm(feat(int(rows[j2])) - xi))) + break + pairs[name] = keep + ANYDIST.extend(anydist) + print(f"[fit] arm {name:10s}: {len(pairs[name])} pairs over " + f"{len({p[0] for p in pairs[name]})} anchors, " + f"{len({int(a_ep[p[0]]) for p in pairs[name]})} anchor episodes", flush=True) + + # ---- score every arm with every cell, on identical pairs ----------------------------------- + lo = hi = None + with h5py.File(a.hdf5, "r") as f: + lo = np.array(json.loads(f["data"].attrs["action_min"]), np.float32) + hi = np.array(json.loads(f["data"].attrs["action_max"]), np.float32) + + out = {"table": a.table, "threshold": a.threshold, "beta": a.beta, "gamma": a.gamma, + "particles": a.particles, "temperature": a.temperature, "chunk": a.chunk, + "step": a.step, "routes": routes, "cells": {}, + "n_pairs": {k: len(v) for k, v in pairs.items()}} + if ANYDIST: + ad = np.asarray(ANYDIST, np.float64) + out["any_partner_state_dist"] = {"n": int(ad.size), "min": float(ad.min()), + "p10": float(np.percentile(ad, 10)), + "median": float(np.median(ad)), + "p90": float(np.percentile(ad, 90)), + "max": float(ad.max()), + "frac_within_threshold": float((ad <= a.threshold).mean())} + print("[fit] FAILvsGOALany partner state distance: median {:.1f} p10 {:.1f} p90 {:.1f} " + "frac <= threshold {:.1f} ({:.3g} = the paired arm's radius)" + .format(np.median(ad), np.percentile(ad, 10), np.percentile(ad, 90), + float((ad <= a.threshold).mean()), a.threshold), flush=True) + raw = {} + for cell in a.cells: + ck = f"{ROOT}/runs/real_cooking_v5/rsm/{cell}/ckpt_s{a.step}.pt" + if not os.path.exists(ck): + print(f"[fit] {cell}: no checkpoint at {ck} -- skip", flush=True) + continue + sc = Scorer("rsm", lo, hi, rsm_ckpt=ck, seed=a.seed, rsm_mode="chain", rsm_beta=a.beta, + rsm_gamma=a.gamma, rsm_particles=a.particles, rsm_dim=D, + rsm_temperature=a.temperature, rsm_hop_ckpt=a.hop_ckpt).rsm + raw[cell] = {} + for name, pl in pairs.items(): + if a.only_arms and name not in a.only_arms: + continue + q_own, q_par, ep = [], [], [] + for (i, j) in pl: + x = torch.as_tensor(feat(int(rows[i])), dtype=torch.float32, device=sc.device)[None] + A = np.stack([chunk_of(int(rows[i])), chunk_of(int(rows[j]))]) + q = np.asarray(sc.score(x, A, seed=a.seed), np.float64) + q_own.append(q[0]); q_par.append(q[1]); ep.append(int(a_ep[i])) + raw[cell][name] = dict(q_own=np.array(q_own), q_par=np.array(q_par), ep=np.array(ep), + anchor=np.array([p[0] for p in pl])) + print(f"[fit] {cell} {name}: scored {len(pl)} pairs", flush=True) + + # ---- the report ---------------------------------------------------------------------------- + def wins(name, r): + d = r["q_own"] - r["q_par"] + if name.startswith("FAILvsGOAL"): # the partner (goal-route) action is the one that should win + d = -d + w = np.where(d > 0, 1.0, np.where(d < 0, 0.0, 0.5)) + return w, d + + ref = a.cells[0] + print("\n=== held-in pair fit, chain read-out, beta={:.3g} gamma={:.4g} particles={} T={}" + .format(a.beta, a.gamma, a.particles, a.temperature)) + hdr = (f"{'cell':26s} {'arm':11s} {'pairs':>6s} {'win':>6s} {'95% CI':>16s} {'SE':>6s} " + f"{'ties':>5s} {'margin_med':>11s} {'vs ' + ref[:10]:>14s}") + print(hdr); print("-" * len(hdr)) + for cell in a.cells: + if cell not in raw: + continue + out["cells"][cell] = {} + for name in ARMS: + if name not in raw[cell]: + continue + w, d = wins(name, raw[cell][name]) + s = arm_stats(raw[cell][name]["ep"], w, d, a.nboot, a.seed) + dl = "" + if cell != ref and ref in raw: + wr, _ = wins(name, raw[ref][name]) + pd = paired_delta(raw[cell][name]["ep"], w, wr, a.nboot, a.seed) + s["delta_vs_ref"] = pd + dl = f"{pd['delta']:+.3f}+-{pd['se']:.3f}" + out["cells"][cell][name] = s + ci = "n/a" if s["lo"] is None else f"[{s['lo']:.3f},{s['hi']:.3f}]" + print(f"{cell:26s} {name:11s} {s['n_pairs']:6d} {s['win']:6.3f} {ci:>16s} " + f"{(s['se'] or float('nan')):6.3f} {s['ties']:5.2f} {s['margin_med']:11.3e} {dl:>14s}") + + # ---- the ROUTE-SIGNAL INDEX, which cancels the model's preference for the anchor's OWN action. + # If the score depends only on "is this the logged action here" and not at all on which route + # the action came from, then GOALvsFAIL = SAMEROUTE = p and FAILvsGOAL = 1 - p for the same p, + # so S = GOALvsFAIL + FAILvsGOAL - 1 = 0 whatever that own-action preference is. S > 0 is the + # only thing that means the model knows a goal-route action is the better one AT A STATE. + # The two arms sit on DIFFERENT anchor episodes, so they cannot be paired; the SE is the + # quadrature sum of the two independent episode bootstraps and is reported as such. + if "GOALvsFAIL" in out["cells"][cell] and "FAILvsGOAL" in out["cells"][cell]: + gf = out["cells"][cell]["GOALvsFAIL"]; fg = out["cells"][cell]["FAILvsGOAL"] + S = gf["win"] + fg["win"] - 1.0 + Sse = float(np.hypot(gf["se"] or np.nan, fg["se"] or np.nan)) + out["cells"][cell]["route_signal_index"] = dict(S=S, se=Sse, sigma=S / Sse if Sse else float("nan")) + print(f"{cell:26s} {'ROUTE-S':11s} {'':6s} {S:6.3f} {'+-' + format(Sse, '.3f'):>16s} " + f"{Sse:6.3f} {'':5s} {'':11s} {S / Sse if Sse else float('nan'):+.2f} sigma") + + # the gate's own anchors, every FAILvsGOAL-family arm that was scored + for _arm in [k for k in ARMS if k.startswith("FAILvsGOAL") and k in raw[cell]]: + r = raw[cell][_arm] + sel = np.isin(r["ep"], np.asarray(a.gate_eps)) + if not sel.sum(): + continue + w, d = wins(_arm, {k: (v[sel] if isinstance(v, np.ndarray) else v) + for k, v in r.items()}) + s = arm_stats(r["ep"][sel], w, d, a.nboot, a.seed) + out["cells"][cell][_arm + "@gate_eps"] = s + ci = "n/a" if s["lo"] is None else f"[{s['lo']:.3f},{s['hi']:.3f}]" + _lab = "FvG@gate" if _arm == "FAILvsGOAL" else ("FvGany@gate" if _arm.endswith("any") + else "FvGswap@gate") + print(f"{cell:26s} {_lab:11s} {s['n_pairs']:6d} {s['win']:6.3f} {ci:>16s} " + f"{(s['se'] or float('nan')):6.3f} {s['ties']:5.2f} {s['margin_med']:11.3e}") + os.makedirs(os.path.dirname(a.out), exist_ok=True) + json.dump(out, open(a.out, "w"), indent=1) + print(f"\n[fit] wrote {a.out}") + print("READ: arm FAILvsGOAL is the gate's question asked on the TRAINING pairs. ~0.5 there means " + "the contrastive loss was never fit and no amount of data or threshold can help; clearly " + ">0.5 there while the gate stays at chance means the loss WAS fit and the chain read-out " + "does not expose it. SAMEROUTE is the floor both must beat.") + + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/real/augsucc_ah_score.py b/rsm_rise/scripts/real/augsucc_ah_score.py new file mode 100644 index 0000000000000000000000000000000000000000..8490adb9abd441b433b1c6c282d70d6eb8f4a093 --- /dev/null +++ b/rsm_rise/scripts/real/augsucc_ah_score.py @@ -0,0 +1,60 @@ +#!/usr/bin/env python3 +"""AUG_SUCC run 47: score (AH) -- does (AD)'s gate-rises-with-training replicate on c0p5_s2/s3/s4? +Reads only existing logged_action_rank.json. No compute.""" +import json, os, sys +R='/proj/dmfexp/zwhong/rsm_rise/status/real/rankctrl' +def load(c): + f=os.path.join(R,c,'logged_action_rank.json') + return json.load(open(f)) if os.path.exists(f) else None +def pick(b,*cs): + for c in cs: + if c in b: return b[c] + return {} +def parse(d): + if d is None: return None + g=pick(d['by'],'rsm|goal|S2','rsm|correct|S2') + pm=pick(d['by'],'permuted:rsm|goal|S2','permuted:rsm|correct|S2') + br=g.get('boot_rank_pct_mid') or {} + return dict(rk=g.get('rank_pct'), lo=br.get('lo'), t1=g.get('top1'), perm=pm.get('rank_pct')) +def fwd(d): + if d is None: return None + g=pick(d['by'],'rsm|correct|S2','rsm|goal|S2') + return dict(t1=g.get('top1'), rk=g.get('rank_pct')) +def f(x): return ('%6.3f'%x) if isinstance(x,(int,float)) else ' n/a' +STEPS=[10000,30000,50000,70000] +print('=== (AH) gate bootLo trajectory, cap 0.50 family, 1 MC draw ===') +print('cell ' + ''.join('%9s'%('%dk'%(s//1000)) for s in STEPS) + ' 100k(3dr) |70k-10k|') +rows={} +for sd in (1,2,3,4): + cell='JUNC_feat_tinf_c0p5_s%d'%sd + los=[] + for st in STEPS: + d=load(f'{cell}__R{st}_mc0'); p=parse(d) + los.append(p['lo'] if p else None) + # 100k reference, 3 draws + ref=[] + for m in (0,1,2): + d=load(f'{cell}__R100k_mc{m}') or (load(f'{cell}__Rval31') if m==0 else None) + p=parse(d) + if p and p['lo'] is not None: ref.append(p['lo']) + delta=None + if los[0] is not None and los[3] is not None: delta=los[3]-los[0] + rows[sd]=(los,delta) + print('%-16s'%('s%d'%sd) + ''.join(' '+f(x) for x in los) + + ' '+f(sum(ref)/len(ref) if ref else None)+' '+(('%+.3f'%delta) if delta is not None else ' n/a')) +print() +print('=== Ffail top-1 trajectory (field), same checkpoints ===') +print('cell ' + ''.join('%9s'%('%dk'%(s//1000)) for s in STEPS)) +for sd in (1,2,3,4): + cell='JUNC_feat_tinf_c0p5_s%d'%sd + vs=[] + for st in STEPS: + d=load(f'{cell}__Ffail{st}_mc0'); p=fwd(d) + vs.append(p['t1'] if p else None) + print('%-16s'%('s%d'%sd) + ''.join(' '+f(x) for x in vs)) +print() +n=sum(1 for sd in (2,3,4) if rows[sd][1] is not None and abs(rows[sd][1])>=0.15) +avail=sum(1 for sd in (2,3,4) if rows[sd][1] is not None) +print('(AH) registered: at least 2 of c0p5_s{2,3,4} have |bootLo(70k)-bootLo(10k)| >= 0.15') +print(' available %d/3, exceeding 0.15: %d -> %s'%(avail,n, + 'CONFIRMED' if n>=2 else ('FALSIFIED' if avail==3 else 'PENDING'))) diff --git a/rsm_rise/scripts/real/augsucc_dose2x2.py b/rsm_rise/scripts/real/augsucc_dose2x2.py new file mode 100644 index 0000000000000000000000000000000000000000..b66a832563b03af55c4745364e27efa919dcabff --- /dev/null +++ b/rsm_rise/scripts/real/augsucc_dose2x2.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""AUG_SUCC run 48: gate-flatness vs field-peak across the WHOLE dose ladder, and the gate x field +2x2 within each dose. Reads only existing JSON.""" +import json, os, re +R='/proj/dmfexp/zwhong/rsm_rise/status/real/rankctrl' +def load(c): + f=os.path.join(R,c,'logged_action_rank.json') + return json.load(open(f)) if os.path.exists(f) else None +def pick(b,*cs): + for c in cs: + if c in b: return b[c] + return {} +def draws(cell,kind): + out=[] + for sd in (0,1,2): + d=load(f'{cell}__{kind}100k_mc{sd}') or (load(f'{cell}__{kind}val31') if sd==0 else None) + if d is None: continue + g=pick(d['by'],'rsm|goal|S2','rsm|correct|S2'); pm=pick(d['by'],'permuted:rsm|goal|S2','permuted:rsm|correct|S2') + br=g.get('boot_rank_pct_mid') or {} + out.append(dict(lo=br.get('lo'), t1=g.get('top1'), perm=pm.get('rank_pct'))) + return out +def m(xs): + xs=[x for x in xs if isinstance(x,(int,float))] + return sum(xs)/len(xs) if xs else None +pat=re.compile(r'^JUNC_feat_tinf_(c[0-9p]+)_s(\d+)__R(?:100k_mc\d|val31)$') +cells={} +for d in os.listdir(R): + mm=pat.match(d) + if mm: cells.setdefault((mm.group(1),int(mm.group(2))),f'JUNC_feat_tinf_{mm.group(1)}_s{mm.group(2)}') +cap=lambda c: float(c[1:].replace('p','.')) +by={} +for (cp,sd) in sorted(cells,key=lambda k:(cap(k[0]),k[1])): + c=cells[(cp,sd)] + G=draws(c,'R'); F=draws(c,'Ffail') + if not G: continue + lo=m([d['lo'] for d in G]); perm=m([d['perm'] for d in G]); ff=m([d['t1'] for d in F]) + by.setdefault(cp,[]).append((sd,lo,perm,ff)) +f=lambda x:('%.3f'%x) if isinstance(x,(int,float)) else ' n/a ' +print(f"{'cap':>7s} {'n':>2s} {'meanGateLo':>10s} {'gate>0.5&>perm':>14s} {'meanFfail':>9s} {'Ffail>=0.80':>11s} {'BOTH':>5s}") +tot_g=tot_f=tot_b=tot_n=0; off_f=off_n=0 +for cp in sorted(by,key=cap): + rs=by[cp]; n=len(rs) + g=sum(1 for r in rs if r[1] is not None and r[1]>0.5 and r[2] is not None and r[1]>r[2]) + fi=sum(1 for r in rs if r[3] is not None and r[3]>=0.80) + b=sum(1 for r in rs if r[1] is not None and r[1]>0.5 and r[2] is not None and r[1]>r[2] and r[3] is not None and r[3]>=0.80) + print(f"{cp:>7s} {n:2d} {f(m([r[1] for r in rs])):>10s} {('%d/%d'%(g,n)):>14s} {f(m([r[3] for r in rs])):>9s} {('%d/%d'%(fi,n)):>11s} {('%d/%d'%(b,n)):>5s}") + tot_g+=g; tot_f+=fi; tot_b+=b; tot_n+=n + if cp!='c0p5': off_f+=fi; off_n+=n +print() +print('ALL doses: n=%d gate-pass %d (%.0f%%) field-intact %d (%.0f%%) BOTH %d (%.0f%%)'%( + tot_n,tot_g,100*tot_g/tot_n,tot_f,100*tot_f/tot_n,tot_b,100*tot_b/tot_n)) +print('field-intact at cap 0.50: %d/%d = %.0f%% at every OTHER dose: %d/%d = %.0f%%'%( + tot_f-off_f, tot_n-off_n, 100*(tot_f-off_f)/(tot_n-off_n), off_f, off_n, 100*off_f/off_n)) +# Fisher exact on the 2x2 (cap0.50 vs other) x (field intact vs not) +from math import comb +a=tot_f-off_f; b2=(tot_n-off_n)-a; c2=off_f; d2=off_n-off_f +def fisher(a,b,c,d): + n=a+b+c+d; r1=a+b; c1=a+c + p0=comb(r1,a)*comb(n-r1,c1-a)/comb(n,c1) + p=0.0 + for k in range(max(0,c1-(n-r1)), min(r1,c1)+1): + pk=comb(r1,k)*comb(n-r1,c1-k)/comb(n,c1) + if pk<=p0+1e-12: p+=pk + return p +print('Fisher exact two-sided (cap0.50 vs other doses) x (field intact): p = %.4f [%d/%d vs %d/%d]'%( + fisher(a,b2,c2,d2),a,a+b2,c2,c2+d2)) +# gate flatness: mean gate lo by dose +los=[(cap(cp), m([r[1] for r in by[cp]])) for cp in sorted(by,key=cap)] +print('gate meanLo across doses 0.05..0.75: '+' '.join('%.2f:%.3f'%(c,l) for c,l in los)) +print(' range %.3f (un-augmented baseline = 0.234)'%(max(l for _,l in los)-min(l for _,l in los))) diff --git a/rsm_rise/scripts/real/augsucc_fieldgate.py b/rsm_rise/scripts/real/augsucc_fieldgate.py new file mode 100644 index 0000000000000000000000000000000000000000..1cfa0f82e1ddb3bee25edc204bae09c9d0473bec --- /dev/null +++ b/rsm_rise/scripts/real/augsucc_fieldgate.py @@ -0,0 +1,132 @@ +#!/usr/bin/env python3 +"""AUG_SUCC run 49: IS THE REVERSE GATE A FIELD-DEGRADATION PROXY? + +Why this exists, with the number that justified it. Run 48 measured the partner-scrambled control's +matched early ladder: its reverse gate is HIGHER than the deployed arm's by +0.40..+0.52 in 3 of 4 seeds +while its occupancy field is WORSE (minmse_val +0.10, 4/4). Run 49 read the 100k histories and found the +three arms line up monotonically on BOTH axes at once: + + arm minmse_val@100k minmse/staymse reverse gate bootLo + un-augmented 0.691 / 0.678 1.027 / 1.037 0.167 / 0.114 (rank_pct) + augmented 0.819 .. 0.865 1.29 .. 1.32 ~0.55 + scrambled 0.940 .. 0.966 1.46 .. 1.49 ~0.66 .. 0.96 (70k) + +i.e. the worse the occupancy field, the higher the reverse gate, across every arm this stream has +trained. If that ordering is a LAW rather than three arm labels, the stream's PASS is vacuous: the +augmentation would be passing the gate by damaging the model, not by learning goal-direction. + +The test has to be WITHIN an arm as well as across arms, because across-arm monotonicity with n=3 arms +is not evidence. This script pools every cell that has both a gate draw and a training history, and +reports spearman(field, gate) pooled and within each arm. Reads only existing JSON. No compute. +""" +import json, os, re +R='/proj/dmfexp/zwhong/rsm_rise/status/real/rankctrl' +RUNS='/proj/dmfexp/zwhong/rsm_rise/runs/real_cooking_v5/rsm' + +def load(c): + f=os.path.join(R,c,'logged_action_rank.json') + return json.load(open(f)) if os.path.exists(f) else None +def pick(b,*cs): + for c in cs: + if c in b: return b[c] + return {} +def draws(cell,kind,step='100k'): + out=[] + for sd in (0,1,2): + d=load(f'{cell}__{kind}{step}_mc{sd}') or (load(f'{cell}__{kind}val31') if sd==0 else None) + if d is None: continue + g=pick(d['by'],'rsm|goal|S2','rsm|correct|S2') + pm=pick(d['by'],'permuted:rsm|goal|S2','permuted:rsm|correct|S2') + br=g.get('boot_rank_pct_mid') or {} + out.append(dict(lo=br.get('lo'), rp=g.get('rank_pct'), t1=g.get('top1'), perm=pm.get('rank_pct'))) + return out +def m(xs): + xs=[x for x in xs if isinstance(x,(int,float))] + return sum(xs)/len(xs) if xs else None +def field(run, step=100000): + p=os.path.join(RUNS,run,'history.json') + if not os.path.exists(p): return None + h=json.load(open(p)); rows=h if isinstance(h,list) else h.get('rows',h) + best=None + for r in rows: + st=r.get('step',r.get('global_step')) + if st!=step or 'minmse_val' not in r: continue + best=r + if best is None: return None + return dict(minmse=best['minmse_val'], ratio=best['minmse_val']/best['staymse_val'], + cfm=best.get('cfm_val'), qgap=best.get('q_action_gap')) + +def spearman(xs, ys): + n=len(xs) + if n<4: return None + def rank(v): + order=sorted(range(n), key=lambda i: v[i]); rk=[0.0]*n; i=0 + while i0 and dy>0 else None + +# ---- build the cell table ------------------------------------------------- +rows=[] +# un-augmented controls: gate cells are named BASE3_, training dir is +for run in ['R_M','R_M_s1']: + G=draws('BASE3_'+run,'R'); F=draws('BASE3_'+run,'Ffail'); fl=field(run) + if G and fl: rows.append(dict(arm='unaug', cell=run, n=len(G), lo=m([d['lo'] for d in G]), + rp=m([d['rp'] for d in G]), perm=m([d['perm'] for d in G]), + ff=m([d['t1'] for d in F]), **fl)) +# augmented sweep +pat=re.compile(r'^(JUNC_feat_tinf_c[0-9p]+_s\d+)__R(?:100k_mc\d|val31)$') +seen=set() +for d in sorted(os.listdir(R)): + mm=pat.match(d) + if not mm or mm.group(1) in seen: continue + c=mm.group(1); seen.add(c) + G=draws(c,'R'); F=draws(c,'Ffail'); fl=field(c) + if G and fl: rows.append(dict(arm='aug', cell=c, n=len(G), lo=m([d['lo'] for d in G]), + rp=m([d['rp'] for d in G]), perm=m([d['perm'] for d in G]), + ff=m([d['t1'] for d in F]), **fl)) +# scramble (100k if scored, else the 70k matched point) +for s in (1,2,3,4): + c='JUNC_feat_scr_c0p5_s%d'%s + G=draws(c,'R'); step=100000 + if not G: + G=draws(c,'R','70000'); step=70000 + F=draws(c,'Ffail') or draws(c,'Ffail','70000') + fl=field(c, step) + if G and fl: rows.append(dict(arm='scr@%dk'%(step//1000), cell=c, n=len(G), lo=m([d['lo'] for d in G]), + rp=m([d['rp'] for d in G]), perm=m([d['perm'] for d in G]), + ff=m([d['t1'] for d in F]), **fl)) + +f=lambda x:('%.3f'%x) if isinstance(x,(int,float)) else ' n/a' +print('%-30s %-8s %2s %7s %7s %7s %7s %7s %7s'%('cell','arm','n','minmse','mm/sm','gateLo','gateRP','perm','Ffail')) +for r in sorted(rows, key=lambda r:(r['arm'], r['minmse'])): + print('%-30s %-8s %2d %7s %7s %7s %7s %7s %7s'%(r['cell'],r['arm'],r['n'],f(r['minmse']), + f(r['ratio']),f(r['lo']),f(r['rp']),f(r['perm']),f(r['ff']))) + +print() +def report(tag, sub): + sub=[r for r in sub if r['lo'] is not None and r['minmse'] is not None] + if len(sub)<4: print('%-34s n=%d (too few)'%(tag,len(sub))); return + xs=[r['minmse'] for r in sub] + print('%-34s n=%2d spearman(minmse, gateLo)=%s (mm/sm, gateLo)=%s (minmse, Ffail)=%s'%( + tag, len(sub), f(spearman(xs,[r['lo'] for r in sub])), + f(spearman([r['ratio'] for r in sub],[r['lo'] for r in sub])), + f(spearman(xs,[r['ff'] for r in sub if r['ff'] is not None])) if all(r['ff'] is not None for r in sub) else ' n/a')) +report('POOLED (all arms)', rows) +for a in sorted(set(r['arm'] for r in rows)): + report('within arm '+a, [r for r in rows if r['arm']==a]) +print() +print('arm means:') +for a in sorted(set(r['arm'] for r in rows)): + sub=[r for r in rows if r['arm']==a] + print(' %-9s n=%2d minmse %s mm/sm %s gateLo %s gateRP %s Ffail %s'%( + a,len(sub),f(m([r['minmse'] for r in sub])),f(m([r['ratio'] for r in sub])), + f(m([r['lo'] for r in sub])),f(m([r['rp'] for r in sub])),f(m([r['ff'] for r in sub])))) diff --git a/rsm_rise/scripts/real/augsucc_heldout_score.py b/rsm_rise/scripts/real/augsucc_heldout_score.py new file mode 100644 index 0000000000000000000000000000000000000000..702d302ab5cc72969de101b46d70656c72527f38 --- /dev/null +++ b/rsm_rise/scripts/real/augsucc_heldout_score.py @@ -0,0 +1,90 @@ +#!/usr/bin/env python3 +"""AUG_SUCC run 45: score (T)/(U) -- the leakage arms -- and (AD), the gate trajectory. +Reads only existing logged_action_rank.json files; no compute. +Draw handling: mc0 falls back to the legacy `Rval31` name (same draw, older naming), exactly as +augsucc_ladder_all.py does, so the standard arm is not silently missing seed 1.""" +import json, os +R='/proj/dmfexp/zwhong/rsm_rise/status/real/rankctrl' +def load(c): + f=os.path.join(R,c,'logged_action_rank.json') + return json.load(open(f)) if os.path.exists(f) else None +def pick(b,*cs): + for c in cs: + if c in b: return b[c] + return {} +def parse(d): + if d is None: return None + g=pick(d['by'],'rsm|goal|S2','rsm|correct|S2') + pm=pick(d['by'],'permuted:rsm|goal|S2','permuted:rsm|correct|S2') + o=pick(d['by'],'rsm|own|S2') + br=g.get('boot_rank_pct_mid') or {} + return dict(rk=g.get('rank_pct'), lo=br.get('lo'), hi=br.get('hi'), t1=g.get('top1'), + perm=pm.get('rank_pct'), own=o.get('top1'), cv=g.get('score_cv'), + ties=g.get('ties_at_max_mean') or g.get('ties_at_max'), + pose=pick(d['by'],'pose|goal|S2','pose|correct|S2').get('rank_pct'), + bc=pick(d['by'],'bc|goal|S2','bc|correct|S2').get('rank_pct')) +def cell_draws(cell, kind='R', step='100k'): + out=[] + for sd in (0,1,2): + d=load(f'{cell}__{kind}{step}_mc{sd}') + if d is None and sd==0: d=load(f'{cell}__{kind}val31') + if d is None: continue + out.append(parse(d)) + return out +def f(x): return ('%6.3f'%x) if isinstance(x,(int,float)) else ' n/a' +def mean(xs): + xs=[x for x in xs if isinstance(x,(int,float))] + return sum(xs)/len(xs) if xs else None +def survives(r): return r and r['lo'] is not None and r['lo']>0.5 and r['perm'] is not None and r['rk']>r['perm'] + +arms={'std':'JUNC_feat_tinf_c0p5_s%d','hg':'JUNC_feat_hg_c0p5_s%d','ho':'JUNC_feat_ho_c0p5_s%d'} +D={a:{s:cell_draws(p%s) for s in (1,2,3,4)} for a,p in arms.items()} +F={a:{s:cell_draws(p%s,'Ffail') for s in (1,2,3,4)} for a,p in arms.items()} + +for tag,idx in (('MATCHED mc0 only',0),('ALL DRAWS (mean)',None)): + print(f'=== (T)/(U) reverse arm, cap 0.50, seeds 1-4 -- {tag} ===') + print(f"{'cell':26s} {'nd':>2s} {'gate':>6s} {'bootLo':>6s} {'bootHi':>6s} {'perm':>6s} {'g_t1':>6s} {'ownT1':>6s} {'CV':>6s} {'ties':>6s} | {'Ffail':>6s} {'field':>8s} verdict") + agg={} + for a in ('std','hg','ho'): + for s in (1,2,3,4): + ds=D[a][s] + if not ds: print(f"{arms[a]%s:26s} MISSING"); continue + use=[ds[0]] if idx==0 else ds + r=dict(rk=mean([x['rk'] for x in use]), lo=mean([x['lo'] for x in use]), + hi=mean([x['hi'] for x in use]), perm=mean([x['perm'] for x in use]), + t1=mean([x['t1'] for x in use]), own=mean([x['own'] for x in use]), + cv=mean([x['cv'] for x in use]), ties=mean([x['ties'] for x in use])) + ff=mean([x['t1'] for x in F[a][s]]) if F[a][s] else None + health='INTACT' if (ff is not None and ff>=0.80) else ('COLLAPSE' if ff is not None else 'n/a') + sv=survives(r) + pf = sv and health=='INTACT' + agg.setdefault(a,[]).append((s,r['lo'],r['rk'],sv,pf,ff)) + print(f"{arms[a]%s:26s} {len(use):2d} {f(r['rk'])} {f(r['lo'])} {f(r['hi'])} {f(r['perm'])} {f(r['t1'])} {f(r['own'])} {f(r['cv'])} {f(r['ties'])} | {f(ff)} {health:>8s} {'SURVIVE' if sv else 'fail '}{' PASS+FIELD' if pf else ''}") + print() + for a in ('std','hg','ho'): + rows=agg.get(a,[]) + print(f"arm {a:4s}: meanBootLo={f(mean([r[1] for r in rows]))} meanGate={f(mean([r[2] for r in rows]))} survivors={sum(r[3] for r in rows)}/{len(rows)} PASS+field={sum(r[4] for r in rows)}/{len(rows)}") + lo_by={a:{r[0]:r[1] for r in agg.get(a,[])} for a in ('std','hg','ho')} + for a in ('hg','ho'): + pairs=[(s, lo_by['std'][s]-lo_by[a][s]) for s in (1,2,3,4) + if lo_by['std'].get(s) is not None and lo_by[a].get(s) is not None] + if pairs: + print(f"(U) std-{a} bootLo drop per seed: " + ' '.join(f"s{s}={d:+.3f}" for s,d in pairs) + f" mean {mean([d for _,d in pairs]):+.3f}") + print() + +print('=== (AD): gate trajectory, reverse arm (rank_pct / bootLo), 1 MC draw ===') +print(f"{'cell':26s} " + ' '.join(f"{s:>15s}" for s in ('10k','30k','50k','70k','100k'))) +for cell in ('JUNC_feat_tinf_c0p1_s0','JUNC_feat_tinf_c0p1_s1','JUNC_feat_tinf_c0p5_s1'): + cs=[] + for st in ('10000','30000','50000','70000','100k'): + ds=cell_draws(cell,'R',st); r=ds[0] if ds else None + cs.append(('%.3f/%.3f'%(r['rk'],r['lo']) if r and r['lo'] is not None else 'n/a').rjust(15)) + print(f"{cell:26s} " + ' '.join(cs)) +print() +print('matched FIELD trajectory (Ffail top-1):') +for cell in ('JUNC_feat_tinf_c0p1_s0','JUNC_feat_tinf_c0p1_s1','JUNC_feat_tinf_c0p5_s1'): + cs=[] + for st in ('10000','30000','50000','70000','100k'): + ds=cell_draws(cell,'Ffail',st); r=ds[0] if ds else None + cs.append((('%.3f'%r['t1']) if r and r['t1'] is not None else 'n/a').rjust(15)) + print(f"{cell:26s} " + ' '.join(cs)) diff --git a/rsm_rise/scripts/real/augsucc_ladder.py b/rsm_rise/scripts/real/augsucc_ladder.py new file mode 100644 index 0000000000000000000000000000000000000000..7badb37edb6cdd65cf1de3d20c7c69e5ea8b2a83 --- /dev/null +++ b/rsm_rise/scripts/real/augsucc_ladder.py @@ -0,0 +1,44 @@ +#!/usr/bin/env python3 +"""AUG_SUCC run 37: the seed-ladder joint table -- gate (3 MC draws) x field (3 draws) per cell, +with the episode-bootstrap CI on the gate's rank percentile.""" +import json, glob, os, statistics as st +R='/proj/dmfexp/zwhong/rsm_rise/status/real/rankctrl' +def load(c): + f=os.path.join(R,c,'logged_action_rank.json') + return json.load(open(f)) if os.path.exists(f) else None +def pick(b,*cs): + for c in cs: + if c in b: return b[c] + return {} +def draws(cell, kind): + out=[] + for sd in (0,1,2): + d=load(f'{cell}__{kind}100k_mc{sd}') + if d is None and sd==0: + d=load(f'{cell}__{kind}val31') # legacy name for the seed-0 draw of the first cells measured + if d is None: continue + g=pick(d['by'],'rsm|goal|S2','rsm|correct|S2') + pm=pick(d['by'],'permuted:rsm|goal|S2','permuted:rsm|correct|S2') + o=pick(d['by'],'rsm|own|S2') + br=g.get('boot_rank_pct_mid') or {} + out.append(dict(rk=g.get('rank_pct'), t1=g.get('top1'), perm=pm.get('rank_pct'), + own=o.get('top1'), cv=g.get('score_cv'), lo=br.get('lo'), hi=br.get('hi'))) + return out +def m(xs): + xs=[x for x in xs if isinstance(x,(int,float))] + return sum(xs)/len(xs) if xs else None +CELLS=[] +for dose in ('c0p25','c0p5','c0p75'): + for s in range(5): + c=f'JUNC_feat_tinf_{dose}_s{s}' + if glob.glob(os.path.join(R,c+'__R100k_mc*')) or os.path.isdir(os.path.join(R,c+'__Rval31')): + CELLS.append(c) +f=lambda x:('%6.3f'%x) if isinstance(x,(int,float)) else ' n/a' +print(f"{'cell':34s} {'nd':>2s} {'gate':>6s} {'span':>6s} {'bootLo':>6s} {'perm':>6s} {'g_t1':>6s} {'ownT1':>6s} {'CV':>6s} | {'Ffail':>6s} {'nd':>2s} {'field':>8s}") +for c in CELLS: + G=draws(c,'R'); F=draws(c,'Ffail') + gm=m([d['rk'] for d in G]); sp=(max(d['rk'] for d in G)-min(d['rk'] for d in G)) if G else None + fm_=m([d['t1'] for d in F]) + lo=m([d['lo'] for d in G]) + health='INTACT' if (fm_ is not None and fm_>=0.80) else ('COLLAPSE' if fm_ is not None else ' n/a') + print(f"{c:34s} {len(G):2d} {f(gm)} {f(sp)} {f(lo)} {f(m([d['perm'] for d in G]))} {f(m([d['t1'] for d in G]))} {f(m([d['own'] for d in G]))} {f(m([d['cv'] for d in G]))} | {f(fm_)} {len(F):2d} {health:>8s}") diff --git a/rsm_rise/scripts/real/augsucc_ladder_all.py b/rsm_rise/scripts/real/augsucc_ladder_all.py new file mode 100644 index 0000000000000000000000000000000000000000..2f9ce0f7973a18cf2f3a6f0b3cb7eaaf475355ce --- /dev/null +++ b/rsm_rise/scripts/real/augsucc_ladder_all.py @@ -0,0 +1,61 @@ +#!/usr/bin/env python3 +"""AUG_SUCC run 43: the DOSE ladder table -- every cap present under rankctrl, gate (up to 3 MC draws) +x field, with the episode-bootstrap lower bound. Same statistic as augsucc_ladder.py; only the cell +enumeration differs (all doses, seeds 0-8, instead of the hardcoded three doses).""" +import json, glob, os, re, sys +R='/proj/dmfexp/zwhong/rsm_rise/status/real/rankctrl' +def load(c): + f=os.path.join(R,c,'logged_action_rank.json') + return json.load(open(f)) if os.path.exists(f) else None +def pick(b,*cs): + for c in cs: + if c in b: return b[c] + return {} +def draws(cell, kind): + out=[] + for sd in (0,1,2): + d=load(f'{cell}__{kind}100k_mc{sd}') + if d is None and sd==0: + d=load(f'{cell}__{kind}val31') + if d is None: continue + g=pick(d['by'],'rsm|goal|S2','rsm|correct|S2') + pm=pick(d['by'],'permuted:rsm|goal|S2','permuted:rsm|correct|S2') + o=pick(d['by'],'rsm|own|S2') + br=g.get('boot_rank_pct_mid') or {} + out.append(dict(rk=g.get('rank_pct'), t1=g.get('top1'), perm=pm.get('rank_pct'), + own=o.get('top1'), cv=g.get('score_cv'), lo=br.get('lo'), hi=br.get('hi'))) + return out +def m(xs): + xs=[x for x in xs if isinstance(x,(int,float))] + return sum(xs)/len(xs) if xs else None +pat=re.compile(r'^JUNC_feat_tinf_(c[0-9p]+)_s(\d+)__R(?:100k_mc\d|val31)$') +cells={} +for d in os.listdir(R): + mm=pat.match(d) + if mm: cells.setdefault((mm.group(1),int(mm.group(2))),f'JUNC_feat_tinf_{mm.group(1)}_s{mm.group(2)}') +def capval(c): return float(c[1:].replace('p','.')) +order=sorted(cells, key=lambda k:(capval(k[0]),k[1])) +f=lambda x:('%6.3f'%x) if isinstance(x,(int,float)) else ' n/a' +# run 48: Fgoal (the on-route-distractor arm, un-augmented baseline 0.674/0.760) is now in this table. +# It was omitted through run 47 and it is the arm on which nothing in the sweep recovers baseline: +# max 0.521 / mean 0.156 over 26 cells. A table without it lets a gate win hide a forward regression, +# which is exactly what the assignment forbids. +print(f"{'cell':34s} {'nd':>2s} {'gate':>6s} {'span':>6s} {'bootLo':>6s} {'perm':>6s} {'g_t1':>6s} {'ownT1':>6s} {'CV':>6s} | {'Ffail':>6s} {'nd':>2s} {'field':>8s} | {'Fgoal':>6s} {'nd':>2s} {'vs0.72':>7s}") +bydose={} +for k in order: + c=cells[k] + G=draws(c,'R'); F=draws(c,'Ffail'); Q=draws(c,'Fgoal') + if not G: continue + gm=m([d['rk'] for d in G]); sp=(max(d['rk'] for d in G)-min(d['rk'] for d in G)) + fm_=m([d['t1'] for d in F]); lo=m([d['lo'] for d in G]) + health='INTACT' if (fm_ is not None and fm_>=0.80) else ('COLLAPSE' if fm_ is not None else ' n/a') + qm=m([d['t1'] for d in Q]) + qflag='KEPT' if (qm is not None and qm>=0.674) else ('LOST' if qm is not None else 'n/a') + print(f"{c:34s} {len(G):2d} {f(gm)} {f(sp)} {f(lo)} {f(m([d['perm'] for d in G]))} {f(m([d['t1'] for d in G]))} {f(m([d['own'] for d in G]))} {f(m([d['cv'] for d in G]))} | {f(fm_)} {len(F):2d} {health:>8s} | {f(qm)} {len(Q):2d} {qflag:>7s}") + bydose.setdefault(k[0],[]).append((k[1],lo,len(G))) +print() +print(f"{'cap':>8s} {'ncell':>5s} {'meanLo':>7s} {'minLo':>6s} {'maxLo':>6s} per-seed(ndraws)") +for cap in sorted(bydose, key=capval): + rows=bydose[cap]; los=[r[1] for r in rows if r[1] is not None] + print(f"{cap:>8s} {len(rows):5d} {f(m(los))} {f(min(los)) if los else ' n/a'} {f(max(los)) if los else ' n/a'} " + + ' '.join(f"s{s}={('%.3f'%l) if l is not None else 'n/a'}({n})" for s,l,n in rows)) diff --git a/rsm_rise/scripts/real/augsucc_noregress.py b/rsm_rise/scripts/real/augsucc_noregress.py new file mode 100644 index 0000000000000000000000000000000000000000..87c7abb06018d612ff029a09b73b0060f0a3716c --- /dev/null +++ b/rsm_rise/scripts/real/augsucc_noregress.py @@ -0,0 +1,53 @@ +#!/usr/bin/env python3 +"""AUG_SUCC run 48: per-cell no-regression audit. Does ANY cell in the 30-cell sweep hold the reverse +gate AND both forward arms against the un-augmented baseline (Ffail 0.969, Fgoal 0.677)?""" +import json, os, re +R='/proj/dmfexp/zwhong/rsm_rise/status/real/rankctrl' +def load(c): + f=os.path.join(R,c,'logged_action_rank.json') + return json.load(open(f)) if os.path.exists(f) else None +def pick(b,*cs): + for c in cs: + if c in b: return b[c] + return {} +def vals(cell,kind,sc): + o=[] + for sd in (0,1,2): + d=load(f'{cell}__{kind}100k_mc{sd}') or (load(f'{cell}__{kind}val31') if sd==0 else None) + if d: o.append(pick(d['by'],f'{sc}|goal|S2',f'{sc}|correct|S2',f'{sc}|S2')) + return o +def m(xs): + xs=[x for x in xs if isinstance(x,(int,float))] + return sum(xs)/len(xs) if xs else None +def g(cell,kind,sc,key): + if key=='boot_lo': return m([(v.get('boot_rank_pct_mid') or {}).get('lo') for v in vals(cell,kind,sc)]) + return m([v.get(key) for v in vals(cell,kind,sc)]) +pat=re.compile(r'^JUNC_feat_tinf_(c[0-9p]+)_s(\d+)__R(?:100k_mc\d|val31)$') +cells=set() +for d in os.listdir(R): + mm=pat.match(d) + if mm: cells.add((mm.group(1),int(mm.group(2)))) +cap=lambda c: float(c[1:].replace('p','.')) +f=lambda x:('%6.3f'%x) if isinstance(x,(int,float)) else ' n/a' +BASE_FF, BASE_FG = 0.969, 0.677 +print('un-augmented baseline: REVgate rank_pct 0.234 | Ffail top-1 %.3f | Fgoal top-1 %.3f'%(BASE_FF,BASE_FG)) +print('PASS_gate = bootLo>0.5 and >perm. keep_Ffail = >=0.80. keep_Fgoal = >=0.5*%.3f = %.3f'%(BASE_FG,0.5*BASE_FG)) +print() +print(f"{'cell':>18s} | {'bootLo':>6s} {'perm':>6s} {'GATE':>5s} | {'Ffail':>6s} {'keep':>4s} | {'Fgoal':>6s} {'keep':>4s} | {'ALL3':>5s}") +n_all3=0; n=0 +for k in sorted(cells,key=lambda k:(cap(k[0]),k[1])): + c=f'JUNC_feat_tinf_{k[0]}_s{k[1]}' + lo=g(c,'R','rsm','boot_lo'); pm=g(c,'R','permuted:rsm','rank_pct') + ff=g(c,'Ffail','rsm','top1'); fg=g(c,'Fgoal','rsm','top1') + G = lo is not None and pm is not None and lo>0.5 and lo>pm + KF= ff is not None and ff>=0.80 + KG= fg is not None and fg>=0.5*BASE_FG + A = G and KF and KG + n+=1; n_all3+= 1 if A else 0 + print(f"{k[0]+'_s'+str(k[1]):>18s} | {f(lo)} {f(pm)} {str(G):>5s} | {f(ff)} {str(KF):>4s} | {f(fg)} {str(KG):>4s} | {str(A):>5s}") +print() +print('cells holding the reverse gate AND both forward arms: %d of %d'%(n_all3,n)) +fg_all=[g(f'JUNC_feat_tinf_{k[0]}_s{k[1]}','Fgoal','rsm','top1') for k in cells] +fg_all=[x for x in fg_all if isinstance(x,float)] +print('Fgoal top-1 over all %d cells with data: max %.3f mean %.3f (baseline %.3f, pose 1.000)'%( + len(fg_all),max(fg_all),sum(fg_all)/len(fg_all),BASE_FG)) diff --git a/rsm_rise/scripts/real/augsucc_qwtraj.py b/rsm_rise/scripts/real/augsucc_qwtraj.py new file mode 100644 index 0000000000000000000000000000000000000000..fb398a68fa45b6fa23baa5b0d1aa07915ba921e8 --- /dev/null +++ b/rsm_rise/scripts/real/augsucc_qwtraj.py @@ -0,0 +1,85 @@ +#!/usr/bin/env python3 +"""AUG_SUCC (gen_q#279) run 27: is the field-health bucket readable from the TRAINING CURVE? + +`q_action_winrate` is written into runs//history.json at every --eval-every tick; it is the +same number the gate table reports as `qwin` (verified: t45/s0 0.9131, t42p5/s0 0.2451). So the +field-health precondition this stream asks RANK_CTRL to apply costs ZERO extra compute -- it is +already on disk. The open question this script answers is whether it is readable EARLY, i.e. +whether a 20k read can stand in for the 100k gate. + +Verdict (see status/real/AUG_SUCC.md, run 27): the LEVEL cannot -- it misclassifies t42p5/s0, the +highest-goal-rank cell this stream ever produced, which sits at 0.899 at 20k and collapses to 0.245. +The SIGN OF THE SLOPE 5k->20k separates all 12 completed cells with a gap (-0.036 | +0.052). + +usage: venv_rsm/bin/python scripts/real/augsucc_qwtraj.py [--out ] +""" +import json, argparse, pathlib + +ROOT = pathlib.Path("/proj/dmfexp/zwhong/rsm_rise") +RUNS = ROOT / "runs/real_cooking_v5/rsm" + +# bucket at 100k from status/real/augsucc/junc_gate_100k.json (Ffail<=0.083 -> D, Ffail>=0.927 -> I) +DONE = { + "JUNC_feat_t35_c0p5_s0": "D", "JUNC_feat_t40_c0p5_s0": "I", "JUNC_feat_t42p5_c0p5_s0": "D", + "JUNC_feat_t45_c0p5_s0": "I", "JUNC_feat_t45_c0p5_s1": "I", "JUNC_feat_t45_c0p5_s2": "I", + "JUNC_feat_t45_c0p5_s3": "I", "JUNC_feat_t45_c0p5_s4": "I", "JUNC_feat_t50_c0p5_s0": "D", + "JUNC_feat_t50_c0p5_s1": "I", "JUNC_feat_t55_c0p5_s0": "D", "JUNC_feat_tinf_c0p5_s0": "D", +} +INFLIGHT = ["JUNC_feat_tinf_c0p1_s0", "JUNC_feat_tinf_c0p1_s1", + "JUNC_feat_tinf_c0p25_s0", "JUNC_feat_tinf_c0p25_s1"] + + +def curve(cell, key="q_action_winrate"): + p = RUNS / cell / "history.json" + if not p.exists(): + return {} + return {r["step"]: r[key] for r in json.load(open(p)) if key in r} + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--out", default=str(ROOT / "status/real/augsucc/qwin_traj.json")) + a = ap.parse_args() + out = {"completed": {}, "inflight": {}} + + rows = [] + for cell, b in DONE.items(): + d = curve(cell) + slope = d[20000] - d[5000] + rows.append((slope, cell, b, d)) + out["completed"][cell] = {"bucket": b, "qw5k": d[5000], "qw20k": d[20000], + "qw100k": d[100000], "slope_5k_20k": slope} + rows.sort() + print(f"{'cell':28s} {'bucket':10s} {'qw5k':>6s} {'qw20k':>6s} {'slope':>7s} {'qw100k':>7s}") + for s, c, b, d in rows: + print(f"{c:28s} {'DESTROYED' if b=='D' else 'INTACT':10s} " + f"{d[5000]:6.3f} {d[20000]:6.3f} {s:+7.3f} {d[100000]:7.3f}") + neg = [r for r in rows if r[0] < 0] + pos = [r for r in rows if r[0] > 0] + sep = all(r[2] == "D" for r in neg) and all(r[2] == "I" for r in pos) + out["separator"] = {"rule": "sign(qw@20k - qw@5k) < 0 -> DESTROYED", + "n_neg": len(neg), "n_pos": len(pos), + "max_neg": max(r[0] for r in neg), "min_pos": min(r[0] for r in pos), + "zero_exception": bool(sep)} + print(f"\nslope<0: n={len(neg)} buckets={sorted({r[2] for r in neg})} max={max(r[0] for r in neg):+.3f}") + print(f"slope>0: n={len(pos)} buckets={sorted({r[2] for r in pos})} min={min(r[0] for r in pos):+.3f}") + print(f"zero-exception separator over {len(rows)} cells: {sep}") + + print("\n=== in-flight ===") + for c in INFLIGHT: + d = curve(c) + if not d: + print(f"{c:28s} (no history yet)"); continue + ks = sorted(d) + s = d[20000] - d[5000] if 20000 in d and 5000 in d else None + out["inflight"][c] = {"steps": ks, "qw": {str(k): d[k] for k in ks}, "slope_5k_20k": s} + print(f"{c:28s} " + " ".join(f"{k//1000}k={d[k]:.3f}" for k in ks) + + (f" slope={s:+.3f} -> predict {'DESTROYED' if s < 0 else 'INTACT'}" if s is not None else "")) + + pathlib.Path(a.out).parent.mkdir(parents=True, exist_ok=True) + json.dump(out, open(a.out, "w"), indent=2) + print(f"\nwrote {a.out}") + + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/real/augsucc_read.py b/rsm_rise/scripts/real/augsucc_read.py new file mode 100644 index 0000000000000000000000000000000000000000..aea3d624dd891b37d3b0c64be3cf664e7aed885f --- /dev/null +++ b/rsm_rise/scripts/real/augsucc_read.py @@ -0,0 +1,29 @@ +#!/usr/bin/env python3 +"""AUG_SUCC run 37: compact reader over status/real/rankctrl cells (reverse and forward arms).""" +import json, sys, glob, os +R='/proj/dmfexp/zwhong/rsm_rise/status/real/rankctrl' +def pick(b, *cands): + for c in cands: + if c in b: return b[c] + return {} +def row(p): + f=os.path.join(p,'logged_action_rank.json') + if not os.path.exists(f): return None + d=json.load(open(f)); b=d['by'] + g =pick(b,'rsm|goal|S2','rsm|correct|S2') + o =pick(b,'rsm|own|S2') + pm=pick(b,'permuted:rsm|goal|S2','permuted:rsm|correct|S2') + po=pick(b,'pose|goal|S2','pose|correct|S2') + bc=pick(b,'bc|goal|S2','bc|correct|S2') + kn=pick(b,'knn|goal|S2','knn|correct|S2') + return dict(cell=os.path.basename(p), n=g.get('n'), rk=g.get('rank_pct'), t1=g.get('top1'), + perm=pm.get('rank_pct'), own_t1=o.get('top1'), ties=g.get('ties_at_max'), + cv=g.get('score_cv'), pose=po.get('rank_pct'), bc=bc.get('rank_pct'), knn=kn.get('rank_pct')) +cells=sorted({p for pat in sys.argv[1:] for p in glob.glob(os.path.join(R,pat))}) +print(f"{'cell':52s} {'n':>3s} {'rk':>6s} {'t1':>6s} {'perm':>6s} {'ownT1':>6s} {'ties':>5s} {'CV':>6s} {'pose':>6s} {'bc':>6s} {'knn':>6s}") +fm=lambda x: ('%6.3f'%x) if isinstance(x,(int,float)) else ' n/a' +for p in cells: + r=row(p) + if not r: print(f"{os.path.basename(p):52s} (no json)"); continue + n=('%3d'%r['n']) if r['n'] is not None else ' n/a' + print(f"{r['cell']:52s} {n} {fm(r['rk'])} {fm(r['t1'])} {fm(r['perm'])} {fm(r['own_t1'])} {fm(r['ties'])} {fm(r['cv'])} {fm(r['pose'])} {fm(r['bc'])} {fm(r['knn'])}") diff --git a/rsm_rise/scripts/real/augsucc_reportcard.py b/rsm_rise/scripts/real/augsucc_reportcard.py new file mode 100644 index 0000000000000000000000000000000000000000..b2b0e3b6606ae7559170fe0ca1b02433f3792fd4 --- /dev/null +++ b/rsm_rise/scripts/real/augsucc_reportcard.py @@ -0,0 +1,48 @@ +#!/usr/bin/env python3 +"""AUG_SUCC run 48: the full four-arm report card the brief asks for, per dose family. +R=reverse gate, Ffail=logged-action arm (failure distractors), Fgoal=on-route-distractor arm.""" +import json, os, re +R='/proj/dmfexp/zwhong/rsm_rise/status/real/rankctrl' +def load(c): + f=os.path.join(R,c,'logged_action_rank.json') + return json.load(open(f)) if os.path.exists(f) else None +def pick(b,*cs): + for c in cs: + if c in b: return b[c] + return {} +def arm(cell,kind,sc): + vals=[] + for sd in (0,1,2): + d=load(f'{cell}__{kind}100k_mc{sd}') or (load(f'{cell}__{kind}val31') if sd==0 else None) + if d is None: continue + vals.append(pick(d['by'],f'{sc}|goal|S2',f'{sc}|correct|S2',f'{sc}|S2')) + return vals +def m(xs): + xs=[x for x in xs if isinstance(x,(int,float))] + return sum(xs)/len(xs) if xs else None +def agg(cell,kind,sc,key): + if key=='boot_lo': + return m([(v.get('boot_rank_pct_mid') or {}).get('lo') for v in arm(cell,kind,sc)]) + return m([v.get(key) for v in arm(cell,kind,sc)]) +pat=re.compile(r'^JUNC_feat_tinf_(c[0-9p]+)_s(\d+)__R(?:100k_mc\d|val31)$') +cells={} +for d in os.listdir(R): + mm=pat.match(d) + if mm: cells.setdefault((mm.group(1),int(mm.group(2))),f'JUNC_feat_tinf_{mm.group(1)}_s{mm.group(2)}') +cap=lambda c: float(c[1:].replace('p','.')) +f=lambda x:('%6.3f'%x) if isinstance(x,(int,float)) else ' n/a' +by={} +for k in sorted(cells,key=lambda k:(cap(k[0]),k[1])): by.setdefault(k[0],[]).append(k[1]) +print('Per-dose means over seeds. REVERSE GATE is the Task-3 gate; the other three arms are the') +print('no-regression checks. rsm vs its own permuted control and vs the zero-parameter pose / BC baselines.') +print() +print(f"{'cap':>7s} {'n':>2s} | {'REVgate':>7s} {'bootLo':>6s} {'perm':>6s} {'pose':>6s} {'bc':>6s} {'ties':>6s} {'CV':>6s} | " + f"{'Ffail_t1':>8s} {'pose':>6s} | {'Fgoal_t1':>8s} {'pose':>6s}") +for cp in sorted(by,key=cap): + sds=by[cp]; C=[f'JUNC_feat_tinf_{cp}_s{s}' for s in sds] + row=lambda kind,sc,key: m([agg(c,kind,sc,key) for c in C]) + print(f"{cp:>7s} {len(sds):2d} | {f(row('R','rsm','rank_pct'))} {f(row('R','rsm','boot_lo'))}" + f" {f(row('R','permuted:rsm','rank_pct'))} {f(row('R','pose','rank_pct'))} {f(row('R','bc','rank_pct'))}" + f" {f(row('R','rsm','ties_at_max'))} {f(row('R','rsm','score_cv'))} | " + f"{f(row('Ffail','rsm','top1'))} {f(row('Ffail','pose','top1'))} | " + f"{f(row('Fgoal','rsm','top1'))} {f(row('Fgoal','pose','top1'))}") diff --git a/rsm_rise/scripts/real/augsucc_run50.py b/rsm_rise/scripts/real/augsucc_run50.py new file mode 100644 index 0000000000000000000000000000000000000000..8336aa24efca54e90fc60b7eaf657c696ae824ab --- /dev/null +++ b/rsm_rise/scripts/real/augsucc_run50.py @@ -0,0 +1,100 @@ +#!/usr/bin/env python3 +"""AUG_SUCC run 50: final scoring of (AI)/(AK) on the completed 3-draw scramble cells, +(AM)/(AN) on the Fgoal 3-draw data, and (AO) on the un-augmented training ladder.""" +import json, os, glob +R='/proj/dmfexp/zwhong/rsm_rise/status/real/rankctrl' +def load(c): + f=os.path.join(R,c,'logged_action_rank.json') + return json.load(open(f)) if os.path.exists(f) else None +def pick(b,*cs): + for c in cs: + if c in b: return b[c] + return {} +def m(xs): + xs=[x for x in xs if isinstance(x,(int,float))] + return sum(xs)/len(xs) if xs else None +def gate(cell): + los,rks,pms=[],[],[] + for sd in (0,1,2): + d=load(f'{cell}__R100k_mc{sd}') + if d is None: continue + g=pick(d['by'],'rsm|goal|S2','rsm|correct|S2'); pm=pick(d['by'],'permuted:rsm|goal|S2','permuted:rsm|correct|S2') + br=g.get('boot_rank_pct_mid') or {} + los.append(br.get('lo')); rks.append(g.get('rank_pct')); pms.append(pm.get('rank_pct')) + return m(los), m(rks), m(pms), len([x for x in rks if x is not None]) +def fwd(cell,kind): + t1=[] + for sd in (0,1,2): + d=load(f'{cell}__{kind}100k_mc{sd}') + if d is None: continue + t1.append(pick(d['by'],'rsm|goal|S2','rsm|correct|S2').get('top1')) + return m(t1), len([x for x in t1 if x is not None]) + +print('=== (AI)/(AK) FINAL: scramble vs deployed, 100k, up to 3 draws ===') +print('cell arm nd bootLo rankpc perm | Ffail nd') +for s in (1,2,3,4): + for arm,pre in (('tinf','JUNC_feat_tinf_c0p5_s'),('scr','JUNC_feat_scr_c0p5_s')): + c=f'{pre}{s}' + lo,rk,pm,nd=gate(c); ff,fn=fwd(c,'Ffail') + surv = 'SURVIVE' if (lo is not None and pm is not None and lo>0.5 and lo>pm) else '' + f=lambda x:('%6.3f'%x) if isinstance(x,(int,float)) else ' n/a' + print(f'{c.replace("JUNC_feat_",""):20s}{arm:5s}{nd:3d}{f(lo)}{f(rk)}{f(pm)} |{f(ff)} {fn} {surv}') + +print() +print('=== (AM)/(AN): Fgoal 3-draw over cap-0.50 cells (bars: 0.339 half / 0.674 baseline) ===') +rows=[] +import re +for d in sorted(os.listdir(R)): + mm=re.match(r'^JUNC_feat_tinf_(c[0-9p]+)_s(\d+)__Fgoal100k_mc0$',d) + if not mm: continue + cell=f'JUNC_feat_tinf_{mm.group(1)}_s{mm.group(2)}' + fg,fn=fwd(cell,'Fgoal'); ff,_=fwd(cell,'Ffail'); lo,rk,pm,nd=gate(cell) + rows.append((mm.group(1),int(mm.group(2)),cell,fg,fn,ff,lo)) +for cap,s,cell,fg,fn,ff,lo in rows: + f=lambda x:('%6.3f'%x) if isinstance(x,(int,float)) else ' n/a' + flag='' + if isinstance(fg,float): + if fg>=0.674: flag='>=BASELINE' + elif fg>=0.339: flag='>=half' + print(f'{cap:8s}s{s} Fgoal{f(fg)} ({fn} draws) Ffail{f(ff)} gateLo{f(lo)} {flag}') +cap05=[r for r in rows if r[0]=='c0p5'] +n_half=sum(1 for r in cap05 if isinstance(r[3],float) and r[3]>=0.339) +n_base=sum(1 for r in cap05 if isinstance(r[3],float) and r[3]>=0.674) +print(f'\n(AM) cap-0.50 cells: {len(cap05)} cells, {n_half} clear 0.339 (falsifier >=4), {n_base} reach 0.674 (falsifier >=1)') +# (AN) spearman on all cells with >=2 Fgoal draws +def spear(a,b): + n=len(a) + if n<3: return None + def rank(v): + o=sorted(range(n),key=lambda i:v[i]); r=[0.0]*n + i=0 + while i1 else None + print(f'{base:8s} {s} 100k={"n/a" if lo100 is None else "%.3f"%lo100} ' + f'max={max(los) if los else None} spread={"n/a" if spread is None else "%.3f"%spread}') diff --git a/rsm_rise/scripts/real/augsucc_run51.py b/rsm_rise/scripts/real/augsucc_run51.py new file mode 100644 index 0000000000000000000000000000000000000000..4701206eeb909a3dd69ce8f6f44d8f5f2ed98ef0 --- /dev/null +++ b/rsm_rise/scripts/real/augsucc_run51.py @@ -0,0 +1,147 @@ +#!/usr/bin/env python3 +"""AUG_SUCC run 51. + +Three things: + (AO) VERDICT -- the 50k rung of the un-augmented ladder landed, and it breaks the spread clause. + (AP) STATUS -- c0p1_s3's Fgoal at 2 of 3 draws, plus the value mc2 must take to falsify. + (AQ) NEW -- registered 02:45Z. The stream's headline is "no cell in 30 buys the gate AND a + forward arm". That sentence is only a TRADE-OFF claim if the joint cell is below what + independence predicts by more than chance. At the observed marginals the joint is a rare + event even under independence, so the shortfall may be nothing at all. Fisher exact on the + 2x2 decides it, and the power calc says how many seeds a rescue would cost. +Pure re-analysis of existing rankctrl jsons. No new compute. +""" +import json, os, re, math +from scipy.stats import fisher_exact, spearmanr + +R = '/proj/dmfexp/zwhong/rsm_rise/status/real/rankctrl' + +def load(c): + f = os.path.join(R, c, 'logged_action_rank.json') + return json.load(open(f)) if os.path.exists(f) else None + +def pick(b, *cs): + for c in cs: + if c in b: return b[c] + return {} + +def mean(xs): + xs = [x for x in xs if isinstance(x, (int, float))] + return sum(xs) / len(xs) if xs else None + +def gate(cell): + los, pms = [], [] + for sd in (0, 1, 2): + d = load(f'{cell}__R100k_mc{sd}') + if d is None: continue + g = pick(d['by'], 'rsm|goal|S2', 'rsm|correct|S2') + pm = pick(d['by'], 'permuted:rsm|goal|S2', 'permuted:rsm|correct|S2') + los.append((g.get('boot_rank_pct_mid') or {}).get('lo')) + pms.append(pm.get('rank_pct')) + return mean(los), mean(pms) + +def fwd(cell, kind): + t1 = [] + for sd in (0, 1, 2): + d = load(f'{cell}__{kind}100k_mc{sd}') + if d is None: continue + t1.append(pick(d['by'], 'rsm|goal|S2', 'rsm|correct|S2').get('top1')) + return mean(t1), len([x for x in t1 if x is not None]) + +f3 = lambda x: ('%6.3f' % x) if isinstance(x, (int, float)) else ' n/a' + +# ---------------------------------------------------------------- (AO) +print('=== (AO) VERDICT: un-augmented gate over the training ladder, 1 draw ===') +print('registered: all 8 cells bootLo < 0.35 AND within-seed spread < 0.20;' + ' falsifier = any cell >= 0.35 OR any spread >= 0.20') +ao_cell_break, ao_spread_break = [], [] +for base in ('R_M', 'R_M_s1'): + pts = [] + for st, lab in (('10000', '10k'), ('30000', '30k'), ('50000', '50k'), ('70000', '70k')): + d = load(f'{base}__R{st}_mc0') + lo = None if d is None else (pick(d['by'], 'rsm|goal|S2', 'rsm|correct|S2').get('boot_rank_pct_mid') or {}).get('lo') + pts.append((lab, lo)) + lo100, _ = gate(f'BASE3_{base}') + pts.append(('100k', lo100)) + los = [lo for _, lo in pts if lo is not None] + spread = max(los) - min(los) + print(' %-8s %s n=%d max=%.3f spread=%.3f%s' % ( + base, ' '.join('%s=%s' % (l, 'pend' if v is None else '%.3f' % v) for l, v in pts), + len(los), max(los), spread, ' <-- SPREAD CLAUSE BROKEN' if spread >= 0.20 else '')) + if max(los) >= 0.35: ao_cell_break.append(base) + if spread >= 0.20: ao_spread_break.append(base) +print(' 0.35 clause: %s spread clause: %s' % ( + 'BROKEN by ' + ','.join(ao_cell_break) if ao_cell_break else 'HOLDS (no cell >= 0.35)', + 'BROKEN by ' + ','.join(ao_spread_break) if ao_spread_break else 'holds')) + +# ---------------------------------------------------------------- (AP) +print() +print('=== (AP) STATUS: c0p1_s3 Fgoal, falsifier = 3-draw mean >= 0.674 ===') +vals = [] +for sd in (0, 1, 2): + d = load(f'JUNC_feat_tinf_c0p1_s3__Fgoal100k_mc{sd}') + vals.append(None if d is None else pick(d['by'], 'rsm|goal|S2', 'rsm|correct|S2').get('top1')) +got = [v for v in vals if v is not None] +print(' draws: ' + ' '.join('mc%d=%s' % (i, 'PEND' if v is None else '%.4f' % v) for i, v in enumerate(vals))) +if len(got) == 3: + print(' 3-draw mean = %.4f -> (AP) %s' % (mean(got), 'FALSIFIED' if mean(got) >= 0.674 else 'HOLDS')) +else: + need = 0.674 * 3 - sum(got) + print(' %d draws, mean %.4f. Remaining draw must be >= %.4f to falsify (observed draws span %.4f-%.4f).' + % (len(got), mean(got), need, min(got), max(got))) + +# ---------------------------------------------------------------- table +print() +print('=== full cell table (gate 3-draw, Fgoal/Ffail as landed) ===') +rows = [] +for d in sorted(os.listdir(R)): + mm = re.match(r'^JUNC_feat_tinf_(c[0-9p]+)_s(\d+)__Fgoal100k_mc0$', d) + if not mm: continue + cell = f'JUNC_feat_tinf_{mm.group(1)}_s{mm.group(2)}' + fg, fn = fwd(cell, 'Fgoal'); ff, _ = fwd(cell, 'Ffail'); lo, pm = gate(cell) + rows.append(dict(cap=mm.group(1), s=int(mm.group(2)), fg=fg, fn=fn, ff=ff, lo=lo, pm=pm)) +use = [r for r in rows if all(isinstance(r[k], float) for k in ('fg', 'lo', 'pm'))] +for r in use: + gp = r['lo'] > 0.5 and r['lo'] > r['pm'] + fh = r['fg'] >= 0.339 + print(' %-7s s%-2d gateLo%s perm%s Fgoal%s(%d) Ffail%s gate=%s field=%s%s' + % (r['cap'], r['s'], f3(r['lo']), f3(r['pm']), f3(r['fg']), r['fn'], f3(r['ff']), + 'PASS' if gp else 'fail', 'half' if fh else 'LOST', ' <== BOTH' if (gp and fh) else '')) + +# ---------------------------------------------------------------- (AQ) +print() +print('=== (AQ) is the "no cell buys both" result a TRADE-OFF or a CHANCE conjunction? ===') +a = b = c = d_ = 0 # gate x field(half bar) +for r in use: + gp = r['lo'] > 0.5 and r['lo'] > r['pm'] + fh = r['fg'] >= 0.339 + if gp and fh: a += 1 + elif gp and not fh: b += 1 + elif not gp and fh: c += 1 + else: d_ += 1 +n = a + b + c + d_ +print(' 2x2 over n=%d cells with gate+Fgoal measured (field bar = Fgoal >= 0.339, half baseline)' % n) +print(' field>=half field LOST') +print(' gate PASS %3d %3d' % (a, b)) +print(' gate fail %3d %3d' % (c, d_)) +pg, pf = (a + b) / n, (a + c) / n +exp = pg * pf * n +odds, p = fisher_exact([[a, b], [c, d_]]) +print(' marginals: P(gate)=%.3f P(field>=half)=%.3f -> independence expects %.2f joint cells, observed %d' + % (pg, pf, exp, a)) +print(' Fisher exact two-sided p = %.4f odds ratio = %s' % (p, ('%.3f' % odds) if math.isfinite(odds) else 'inf')) +sr = spearmanr([r['lo'] for r in use], [r['fg'] for r in use]) +print(' spearman(gateLo, Fgoal) = %+.3f (p = %.4f)' % (sr.statistic, sr.pvalue)) +print(' (AQ) registered: p >= 0.05 (cannot reject independence). FALSIFIER: p < 0.05.') +print(' --> %s' % ('(AQ) FALSIFIED -- the trade-off is real' if p < 0.05 + else '(AQ) HOLDS -- the shortfall is inside chance at this n')) + +# power: how many seeds to see a both-cell, at the observed joint rate and at the independence rate +for lab, pj in (('observed joint rate', a / n), ('independence rate', pg * pf)): + if pj <= 0: + print(' power @ %-20s: joint rate 0 -- 95%% upper bound on it is %.3f, so >= %d seeds to expect one' + % (lab, 3.0 / n, int(math.ceil(n / 3.0)))) + else: + k90 = math.log(0.10) / math.log(1 - pj) + print(' power @ %-20s: p=%.3f -> %.0f seeds for a 90%% chance of at least one both-cell' + % (lab, pj, math.ceil(k90))) diff --git a/rsm_rise/scripts/real/augsucc_run52.py b/rsm_rise/scripts/real/augsucc_run52.py new file mode 100644 index 0000000000000000000000000000000000000000..4511dff38713aac431d1c916bb18d5672f3d2d3e --- /dev/null +++ b/rsm_rise/scripts/real/augsucc_run52.py @@ -0,0 +1,238 @@ +#!/usr/bin/env python3 +"""AUG_SUCC run 52. + + (AO) CLOSE-OUT -- the 70k rung landed, so the un-augmented training ladder is complete at 5 points + for both seeds. Reported once, final, because (AO) is already falsified on its spread clause. + (AR) STATUS -- how much of the Fgoal table is at 3 draws now, and the Fisher p as it stands. + (AS) NEW, registered 03:30Z before running. (AQ)'s 2x2 pools cells from SEVEN doses. Dose drives + BOTH margins -- higher dose raises the reverse gate and lowers the forward field -- so a raw + negative association between them is exactly what a common cause produces, with no per-seed + trade-off anywhere in it. The distinction decides whether (AQ)'s 15-29-seed power calc is + usable: seeds at ONE FIXED dose are unconfounded draws only if the association vanishes once + dose is held constant. + PREDICTION: the dose-residualised (within-dose) spearman(gateLo, Fgoal) is NOT significantly + negative -- two-sided p >= 0.05 -- i.e. the negative association in run 51's -0.271 is a + between-dose effect, not a within-dose trade-off. + FALSIFIER: within-dose spearman p < 0.05 AND negative. + CONFIDENCE: moderate-to-high. For it: the c0p5 row has 9 seeds and the gate PASSes on nearly + all of them, so gateLo is close to constant within the row while Fgoal ranges 0.0-0.5 -- there + is almost no within-row variance in the gate for Fgoal to correlate with. Against it: if the + augmentation trades a fixed budget of representational capacity between the two arms, that + trade would show up within a dose too, and n=26 across 7 doses leaves few df after residualising. + CONSEQUENCE FIXED IN ADVANCE: if (AS) holds, the run-51 trade-off language is downgraded one + further step -- not merely "scarcity, not trade-off" but "a DOSE effect on both arms", and the + 15-29-seed power calc at a fixed dose stands as the rescue cost. If (AS) is falsified, seeds + at a fixed dose are NOT unconfounded draws, the power calc understates the cost, and the + honest report is that the augmentation trades the arms against each other per-seed. +Pure re-analysis of existing rankctrl jsons. No new compute. +""" +import json, os, re, math +from scipy.stats import fisher_exact, spearmanr + +R = '/proj/dmfexp/zwhong/rsm_rise/status/real/rankctrl' +DOSE = {'c0p05': 0.05, 'c0p1': 0.10, 'c0p25': 0.25, 'c0p375': 0.375, + 'c0p5': 0.50, 'c0p625': 0.625, 'c0p75': 0.75} + +def load(c): + f = os.path.join(R, c, 'logged_action_rank.json') + return json.load(open(f)) if os.path.exists(f) else None + +def pick(b, *cs): + for c in cs: + if c in b: return b[c] + return {} + +def mean(xs): + xs = [x for x in xs if isinstance(x, (int, float))] + return sum(xs) / len(xs) if xs else None + +def gate(cell): + los, pms = [], [] + for sd in (0, 1, 2): + d = load(f'{cell}__R100k_mc{sd}') + if d is None: continue + g = pick(d['by'], 'rsm|goal|S2', 'rsm|correct|S2') + pm = pick(d['by'], 'permuted:rsm|goal|S2', 'permuted:rsm|correct|S2') + los.append((g.get('boot_rank_pct_mid') or {}).get('lo')) + pms.append(pm.get('rank_pct')) + return mean(los), mean(pms) + +def fwd(cell, kind): + t1 = [] + for sd in (0, 1, 2): + d = load(f'{cell}__{kind}100k_mc{sd}') + if d is None: continue + t1.append(pick(d['by'], 'rsm|goal|S2', 'rsm|correct|S2').get('top1')) + return mean(t1), len([x for x in t1 if x is not None]) + +f3 = lambda x: ('%6.3f' % x) if isinstance(x, (int, float)) else ' n/a' + +# ---------------------------------------------------------------- (AO) close-out +print('=== (AO) CLOSE-OUT: un-augmented reverse gate over the COMPLETE 5-point training ladder ===') +for base in ('R_M', 'R_M_s1'): + pts = [] + for st, lab in (('10000', '10k'), ('30000', '30k'), ('50000', '50k'), ('70000', '70k')): + d = load(f'{base}__R{st}_mc0') + lo = None if d is None else (pick(d['by'], 'rsm|goal|S2', 'rsm|correct|S2').get('boot_rank_pct_mid') or {}).get('lo') + pts.append((lab, lo)) + lo100, _ = gate(f'BASE3_{base}') + pts.append(('100k', lo100)) + los = [lo for _, lo in pts if lo is not None] + print(' %-8s %s n=%d max=%.3f min=%.3f spread=%.3f' % ( + base, ' '.join('%s=%s' % (l, 'pend' if v is None else '%.3f' % v) for l, v in pts), + len(los), max(los), min(los), max(los) - min(los))) +print(' 0.35 clause (the one the consequence hung on): max over all landed cells = %.3f' % + max(lo for base in ('R_M', 'R_M_s1') + for lo in [(lambda d: None if d is None else (pick(d['by'], 'rsm|goal|S2', 'rsm|correct|S2').get('boot_rank_pct_mid') or {}).get('lo'))(load(f'{base}__R{st}_mc0')) + for st in ('10000', '30000', '50000', '70000')] + [gate(f'BASE3_{base}')[0]] + if lo is not None)) + +# ---------------------------------------------------------------- table +print() +print('=== full cell table (gate 3-draw, Fgoal/Ffail as landed) ===') +rows = [] +for d in sorted(os.listdir(R)): + mm = re.match(r'^JUNC_feat_tinf_(c[0-9p]+)_s(\d+)__Fgoal100k_mc0$', d) + if not mm: continue + cell = f'JUNC_feat_tinf_{mm.group(1)}_s{mm.group(2)}' + fg, fn = fwd(cell, 'Fgoal'); ff, _ = fwd(cell, 'Ffail'); lo, pm = gate(cell) + rows.append(dict(cap=mm.group(1), s=int(mm.group(2)), fg=fg, fn=fn, ff=ff, lo=lo, pm=pm)) +use = [r for r in rows if all(isinstance(r[k], float) for k in ('fg', 'lo', 'pm'))] +for r in use: + gp = r['lo'] > 0.5 and r['lo'] > r['pm'] + print(' %-7s s%-2d gateLo%s perm%s Fgoal%s(%ddraw) Ffail%s gate=%s field=%s%s' + % (r['cap'], r['s'], f3(r['lo']), f3(r['pm']), f3(r['fg']), r['fn'], f3(r['ff']), + 'PASS' if gp else 'fail', 'half' if r['fg'] >= 0.339 else 'LOST', + ' <== BOTH' if (gp and r['fg'] >= 0.339) else '')) + +# ---------------------------------------------------------------- (AR) +print() +print('=== (AR) STATUS: Fgoal table completion and the Fisher p as it stands ===') +at3 = [r for r in use if r['fn'] == 3] +print(' cells at 3 Fgoal draws: %d of %d. still short: %s' % ( + len(at3), len(use), ', '.join('%s_s%d(%d)' % (r['cap'], r['s'], r['fn']) for r in use if r['fn'] < 3) or 'none')) +a = b = c = d_ = 0 +for r in use: + gp = r['lo'] > 0.5 and r['lo'] > r['pm'] + fh = r['fg'] >= 0.339 + if gp and fh: a += 1 + elif gp and not fh: b += 1 + elif not gp and fh: c += 1 + else: d_ += 1 +n = a + b + c + d_ +odds, p = fisher_exact([[a, b], [c, d_]]) +pg, pf = (a + b) / n, (a + c) / n +print(' 2x2 = %d/%d/%d/%d over n=%d expects %.2f joint, observed %d Fisher p = %.4f OR = %s' + % (a, b, c, d_, n, pg * pf * n, a, p, ('%.3f' % odds) if math.isfinite(odds) else 'inf')) +print(' (AR) registered: p stays >= 0.05 on the COMPLETED table. FALSIFIER: p < 0.05.') +print(' --> %s' % ('(AR) CALLABLE: ' + ('FALSIFIED' if p < 0.05 else 'CONFIRMED') if len(at3) == len(use) + else '(AR) NOT YET CALLABLE -- %d cells short of 3 draws' % (len(use) - len(at3)))) + +# ---------------------------------------------------------------- (AS) +print() +print('=== (AS) is the gate-vs-field association BETWEEN doses or WITHIN a dose? ===') +los = [r['lo'] for r in use]; fgs = [r['fg'] for r in use] +sr = spearmanr(los, fgs) +print(' raw (pooled over all doses): spearman = %+.3f p = %.4f n = %d' % (sr.statistic, sr.pvalue, len(use))) +# dose-residualise: within each dose row, replace each value by its rank minus the row mean rank +def within_rank(vals): + order = sorted(range(len(vals)), key=lambda i: vals[i]) + rk = [0.0] * len(vals) + i = 0 + while i < len(vals): + j = i + while j + 1 < len(vals) and vals[order[j + 1]] == vals[order[i]]: j += 1 + avg = (i + j) / 2.0 + 1.0 + for k in range(i, j + 1): rk[order[k]] = avg + i = j + 1 + m = sum(rk) / len(rk) + return [x - m for x in rk] +rx, ry, rowinfo = [], [], [] +for cap in sorted(DOSE, key=lambda c: DOSE[c]): + row = [r for r in use if r['cap'] == cap] + if len(row) < 2: + rowinfo.append('%s n=%d SKIPPED (needs >=2)' % (cap, len(row))) + continue + lx = within_rank([r['lo'] for r in row]); ly = within_rank([r['fg'] for r in row]) + rx += lx; ry += ly + s_row = spearmanr([r['lo'] for r in row], [r['fg'] for r in row]) if len(row) >= 3 else None + rowinfo.append('%s n=%d gateLo %.3f-%.3f (range %.3f) Fgoal %.3f-%.3f%s' % ( + cap, len(row), min(r['lo'] for r in row), max(r['lo'] for r in row), + max(r['lo'] for r in row) - min(r['lo'] for r in row), + min(r['fg'] for r in row), max(r['fg'] for r in row), + ' within-row rho=%+.3f' % s_row.statistic if s_row is not None and not math.isnan(s_row.statistic) else '')) +for s in rowinfo: print(' ' + s) +sw = spearmanr(rx, ry) +# df correction: pooled within-dose correlation loses one df per dose row used +k_rows = len(set(r['cap'] for r in use if sum(1 for q in use if q['cap'] == r['cap']) >= 2)) +df = len(rx) - k_rows - 1 +print(' WITHIN-DOSE (dose-residualised ranks): rho = %+.3f n_pairs = %d rows = %d df = %d' + % (sw.statistic, len(rx), k_rows, df)) +if df > 0 and abs(sw.statistic) < 1.0: + t = sw.statistic * math.sqrt(df / max(1e-12, 1 - sw.statistic ** 2)) + from scipy.stats import t as tdist + p_w = 2 * tdist.sf(abs(t), df) + print(' t(%d) = %+.3f two-sided p = %.4f (df corrected for the %d row means removed)' % (df, t, p_w, k_rows)) +else: + p_w = float('nan'); print(' p not computable') +print(' (AS) FALSIFIER: within-dose p < 0.05 AND rho < 0.') +print(' --> %s' % ('(AS) FALSIFIED -- the trade-off survives holding dose constant' + if (p_w < 0.05 and sw.statistic < 0) + else '(AS) HOLDS -- the negative association is a BETWEEN-DOSE (common-cause) effect')) +# and the between-dose piece, for contrast: dose-row means +print() +print(' contrast, the BETWEEN-dose piece (row means):') +bx, by = [], [] +for cap in sorted(DOSE, key=lambda c: DOSE[c]): + row = [r for r in use if r['cap'] == cap] + if not row: continue + ml, mf = mean([r['lo'] for r in row]), mean([r['fg'] for r in row]) + bx.append(ml); by.append(mf) + print(' dose %-6.3f n=%d mean gateLo %.3f mean Fgoal %.3f' % (DOSE[cap], len(row), ml, mf)) +if len(bx) >= 3: + sb = spearmanr(bx, by) + print(' spearman(mean gateLo, mean Fgoal) over %d dose rows = %+.3f p = %.4f' % (len(bx), sb.statistic, sb.pvalue)) + sd1 = spearmanr([DOSE[c] for c in sorted(DOSE, key=lambda c: DOSE[c]) if any(r['cap'] == c for r in use)], bx) + sd2 = spearmanr([DOSE[c] for c in sorted(DOSE, key=lambda c: DOSE[c]) if any(r['cap'] == c for r in use)], by) + print(' spearman(dose, mean gateLo) = %+.3f (p=%.4f) spearman(dose, mean Fgoal) = %+.3f (p=%.4f)' + % (sd1.statistic, sd1.pvalue, sd2.statistic, sd2.pvalue)) + +# ---------------------------------------------------------------- (AT) registration evidence, 03:40Z +print() +print('=== (AT) registration evidence: is Ffail >= 0.70 NECESSARY for Fgoal >= 0.339? ===') +ffs = sorted(r['ff'] for r in use if isinstance(r['ff'], float)) +mid = [x for x in ffs if 0.20 < x < 0.70] +print(' Ffail over %d cells: %s' % (len(ffs), ' '.join('%.3f' % x for x in ffs))) +print(' in the middle band (0.20,0.70): %d of %d = %.1f%% -> the arm is close to BIMODAL (latch vs collapse)' + % (len(mid), len(ffs), 100.0 * len(mid) / len(ffs))) +viol = [r for r in use if r['fg'] >= 0.339 and r['ff'] < 0.70] +half = [r for r in use if r['fg'] >= 0.339] +print(' cells with Fgoal >= 0.339: %d of which Ffail < 0.70: %d' % (len(half), len(viol))) +for r in half: + print(' %-7s s%-2d Fgoal %.3f Ffail %.3f' % (r['cap'], r['s'], r['fg'], r['ff'])) +lo70 = [r for r in use if r['ff'] < 0.70] +print(' contrapositive: of the %d cells with Ffail < 0.70, %d have Fgoal >= 0.339 (max Fgoal = %.3f)' + % (len(lo70), sum(1 for r in lo70 if r['fg'] >= 0.339), max(r['fg'] for r in lo70))) + +# ------------------------------------------------- decomposition of the joint rate via the Ffail latch +print() +print('=== joint-rate DECOMPOSITION through the Ffail latch (sharpens (AQ) power calc) ===') +lat = [r for r in use if r['ff'] >= 0.70] +gp = lambda r: r['lo'] > 0.5 and r['lo'] > r['pm'] +p_latch = len(lat) / len(use) +p_half_g_latch = sum(1 for r in lat if r['fg'] >= 0.339) / len(lat) +p_gate_g_both = (sum(1 for r in lat if r['fg'] >= 0.339 and gp(r)) / + max(1, sum(1 for r in lat if r['fg'] >= 0.339))) +print(' P(Ffail latch >= 0.70) = %2d/%2d = %.3f' % (len(lat), len(use), p_latch)) +print(' P(Fgoal >= 0.339 | latched) = %2d/%2d = %.3f' % (sum(1 for r in lat if r['fg'] >= 0.339), len(lat), p_half_g_latch)) +print(' P(gate PASS | latched and half-bar) = %2d/%2d = %.3f' % ( + sum(1 for r in lat if r['fg'] >= 0.339 and gp(r)), sum(1 for r in lat if r['fg'] >= 0.339), p_gate_g_both)) +prod = p_latch * p_half_g_latch * p_gate_g_both +print(' product = %.3f vs observed joint %d/%d = %.3f (chain is consistent, no hidden interaction)' + % (prod, sum(1 for r in use if gp(r) and r['fg'] >= 0.339), len(use), + sum(1 for r in use if gp(r) and r['fg'] >= 0.339) / len(use))) +print(' --> the BOTTLENECK is not the gate (%.3f marginal) but the LATCH (%.3f) x half-bar|latch (%.3f).' % ( + sum(1 for r in use if gp(r)) / len(use), p_latch, p_half_g_latch)) +for lab, pp, tgt in (('latch rate', p_latch, 0.15), ('half-bar|latch', p_half_g_latch, 0.20)): + nn = math.ceil(pp * (1 - pp) * (1.96 / tgt) ** 2) + print(' seeds to pin %-16s to +/-%.2f at 95%%: %d' % (lab, tgt, nn)) diff --git a/rsm_rise/scripts/real/augsucc_run53.py b/rsm_rise/scripts/real/augsucc_run53.py new file mode 100644 index 0000000000000000000000000000000000000000..55813d2b2abd68486fa9e5e2b263de3dd239ab36 --- /dev/null +++ b/rsm_rise/scripts/real/augsucc_run53.py @@ -0,0 +1,204 @@ +#!/usr/bin/env python3 +"""AUG_SUCC run 53. Pure re-analysis of artifacts that already exist. No new compute. + + (AR) STATUS -- table completion and the Fisher p as it stands. + (AT) STATUS -- the c0p1 s5-s8 pack is mid-training; reported as pending. + + (AU) NEW, REGISTERED 2026-09-25 04:05Z, BEFORE THE SCRIPT WAS RUN ONCE. + Run 52's structural result is that `Ffail >= 0.70` is a per-seed LATCH that is NECESSARY for the + forward field arm (27/27, clean 0.110 gap) and that it fires on only 41% of seeds -- so the + recommendation was "fix the latch first". That recommendation is only ACTIONABLE if the latch can + be seen WITHOUT paying for the ranking harness, and ideally before a seed has burned its full 100k + steps. Every cell already writes `history.json` with 20 rungs of TRAINING-time metrics, so this is + answerable from disk. + PRIMARY PREDICTION (AU1): the training-time `q_action_gap` at step 100000 separates latched cells + (Ffail >= 0.70) from unlatched ones (Ffail < 0.70) with ROC AUC >= 0.85. + FALSIFIER: AUC < 0.85. + SECONDARY PREDICTION (AU2), the one with the practical payoff: the same separation is ALREADY + present at step 20000 -- i.e. in the first 20% of training -- with AUC >= 0.80. + FALSIFIER: AUC at step 20000 < 0.80. + Both metrics and both steps are fixed HERE, before any of them is computed, so this is one test + each and not a scan. An exploratory scan over the other history keys is printed BELOW the verdict + and is explicitly NOT a test -- it is labelled with its Bonferroni factor and can only generate a + hypothesis for a later run. + CONFIDENCE: AU1 high, AU2 moderate. FOR AU1: `q_action_gap` is the training-time analogue of the + forward arm -- it asks whether the model scores the logged action above alternatives -- so a cell + whose forward discrimination has collapsed at eval should look collapsed here too. AGAINST AU1: + the two are measured on different anchors (random val anchors vs the 96 S2 junction anchors), with + different distractor construction and a different score, and run 52 showed the gate arm's own + within-seed range over training is 4.8x, so training-time numbers at a single rung are noisy. + FOR AU2: the arm is close to bimodal at eval (only 3 of 27 cells in (0.20,0.70)), and a bimodal + outcome usually reflects an early branch rather than a late drift. AGAINST AU2: nothing rules out + the collapse happening late, and 20k is before most of these curves have settled. + CONSEQUENCE FIXED IN ADVANCE. If AU1 holds, the stream reports that the latch is diagnosable from + `history.json` alone and the "fix the latch" recommendation comes with a free detector -- no eval + cost. If AU1 AND AU2 hold, the detector is also EARLY, and the concrete recommendation upgrades + to: screen seeds at 20k and restart the unlatched ones, which cuts the 130-seed cost of settling + run 52's n=5 conditional by roughly the 59% unlatched fraction of the wasted 80k-step tails. If + AU1 fails, the latch is an eval-only phenomenon, the recommendation stays "fix the latch" with no + detector attached, and I say plainly that I could not make it actionable. +""" +import json, os, re, math +from scipy.stats import fisher_exact, mannwhitneyu + +R = '/proj/dmfexp/zwhong/rsm_rise/status/real/rankctrl' +RUNS = '/proj/dmfexp/zwhong/rsm_rise/runs/real_cooking_v5/rsm' +LATCH = 0.70 +HALFBAR = 0.339 + +def load(c): + f = os.path.join(R, c, 'logged_action_rank.json') + return json.load(open(f)) if os.path.exists(f) else None + +def pick(b, *cs): + for c in cs: + if c in b: return b[c] + return {} + +def mean(xs): + xs = [x for x in xs if isinstance(x, (int, float))] + return sum(xs) / len(xs) if xs else None + +def gate(cell): + los, pms = [], [] + for sd in (0, 1, 2): + d = load(f'{cell}__R100k_mc{sd}') + if d is None: continue + g = pick(d['by'], 'rsm|goal|S2', 'rsm|correct|S2') + pm = pick(d['by'], 'permuted:rsm|goal|S2', 'permuted:rsm|correct|S2') + los.append((g.get('boot_rank_pct_mid') or {}).get('lo')) + pms.append(pm.get('rank_pct')) + return mean(los), mean(pms) + +def fwd(cell, kind): + t1 = [] + for sd in (0, 1, 2): + d = load(f'{cell}__{kind}100k_mc{sd}') + if d is None: continue + t1.append(pick(d['by'], 'rsm|goal|S2', 'rsm|correct|S2').get('top1')) + return mean(t1), len([x for x in t1 if x is not None]) + +def auc(pos, neg): + """ROC AUC of `pos` scoring above `neg`, ties at 0.5. Mann-Whitney U / (n*m).""" + if not pos or not neg: return None, None + u = sum((1.0 if a > b else 0.5 if a == b else 0.0) for a in pos for b in neg) + a = u / (len(pos) * len(neg)) + try: + p = mannwhitneyu(pos, neg, alternative='two-sided').pvalue + except ValueError: + p = float('nan') + return a, p + +def hist(cell): + f = os.path.join(RUNS, cell, 'history.json') + return json.load(open(f)) if os.path.exists(f) else None + +def at_step(h, step, key): + for r in h: + if r.get('step') == step: + v = r.get(key) + return v if isinstance(v, (int, float)) else None + return None + +f3 = lambda x: ('%6.3f' % x) if isinstance(x, (int, float)) else ' n/a' + +# ---------------------------------------------------------------- table +rows = [] +for d in sorted(os.listdir(R)): + mm = re.match(r'^JUNC_feat_tinf_(c[0-9p]+)_s(\d+)__Fgoal100k_mc0$', d) + if not mm: continue + cell = f'JUNC_feat_tinf_{mm.group(1)}_s{mm.group(2)}' + fg, fn = fwd(cell, 'Fgoal'); ff, _ = fwd(cell, 'Ffail'); lo, pm = gate(cell) + rows.append(dict(cell=cell, cap=mm.group(1), s=int(mm.group(2)), fg=fg, fn=fn, ff=ff, lo=lo, pm=pm)) +use = [r for r in rows if all(isinstance(r[k], float) for k in ('fg', 'ff', 'lo', 'pm'))] + +print('=== (AR) STATUS ===') +at3 = [r for r in use if r['fn'] == 3] +short = [r for r in use if r['fn'] < 3] +print(' cells at 3 Fgoal draws: %d of %d. still short: %s' % ( + len(at3), len(use), ', '.join('%s_s%d(%d)' % (r['cap'], r['s'], r['fn']) for r in short) or 'none')) +a = b = c = d_ = 0 +for r in use: + gp = r['lo'] > 0.5 and r['lo'] > r['pm'] + fh = r['fg'] >= HALFBAR + if gp and fh: a += 1 + elif gp: b += 1 + elif fh: c += 1 + else: d_ += 1 +n = a + b + c + d_ +odds, p_ar = fisher_exact([[a, b], [c, d_]]) +print(' 2x2 = %d/%d/%d/%d over n=%d expects %.2f joint, observed %d Fisher p = %.4f' + % (a, b, c, d_, n, (a + b) / n * (a + c) / n * n, a, p_ar)) +print(' --> %s' % ('(AR) CALLABLE: ' + ('FALSIFIED' if p_ar < 0.05 else 'CONFIRMED') if not short + else '(AR) NOT YET CALLABLE -- %d cells short of 3 draws' % len(short))) + +# ---------------------------------------------------------------- (AU) +print() +print('=== (AU) is the Ffail LATCH visible in TRAINING-TIME history.json? ===') +lat = [r for r in use if r['ff'] >= LATCH] +unl = [r for r in use if r['ff'] < LATCH] +print(' latched (Ffail>=%.2f): n=%d unlatched: n=%d of %d cells with a Ffail measurement' + % (LATCH, len(lat), len(unl), len(use))) +missing = [r['cell'] for r in use if hist(r['cell']) is None] +if missing: print(' NO history.json for: %s' % ', '.join(missing)) + +for tag, step, bar in (('AU1 PRIMARY', 100000, 0.85), ('AU2 SECONDARY', 20000, 0.80)): + pos = [v for r in lat for v in [at_step(hist(r['cell']) or [], step, 'q_action_gap')] if v is not None] + neg = [v for r in unl for v in [at_step(hist(r['cell']) or [], step, 'q_action_gap')] if v is not None] + A, pv = auc(pos, neg) + if A is None: + print(' %-14s step %6d q_action_gap: NOT COMPUTABLE (n_pos=%d n_neg=%d)' % (tag, step, len(pos), len(neg))) + continue + print(' %-14s step %6d q_action_gap AUC = %.3f (n_pos=%d n_neg=%d, MWU p = %.4g)' + % (tag, step, A, len(pos), len(neg), pv)) + print(' latched mean %+.4f range %+.4f..%+.4f' % (mean(pos), min(pos), max(pos))) + print(' unlatched mean %+.4f range %+.4f..%+.4f' % (mean(neg), min(neg), max(neg))) + print(' bar %.2f --> %s' % (bar, 'HOLDS' if A >= bar else 'FALSIFIED')) + +# ---------------------------------------------------------------- exploratory, NOT a test +print() +print('=== EXPLORATORY SCAN -- NOT A TEST. Hypothesis-generating only. ===') +h0 = hist(use[0]['cell']) if use else None +keys = sorted(k for k, v in (h0[-1].items() if h0 else []) if isinstance(v, (int, float)) and k != 'step') +print(' %d scalar keys x 2 steps = %d comparisons; Bonferroni alpha = %.5f. Nothing here is registered.' + % (len(keys), 2 * len(keys), 0.05 / max(1, 2 * len(keys)))) +for step in (20000, 100000): + out = [] + for k in keys: + pos = [v for r in lat for v in [at_step(hist(r['cell']) or [], step, k)] if v is not None] + neg = [v for r in unl for v in [at_step(hist(r['cell']) or [], step, k)] if v is not None] + if len(pos) < 3 or len(neg) < 3: continue + A, pv = auc(pos, neg) + out.append((abs(A - 0.5), A, pv, k)) + out.sort(reverse=True) + print(' step %6d top 8 by |AUC-0.5|:' % step) + for _, A, pv, k in out[:8]: + print(' %-26s AUC %.3f p %.4g %s' % (k, A, pv, '(survives Bonferroni)' if pv < 0.05 / max(1, 2 * len(keys)) else '')) + +# ------------------------------------------------ descriptive follow-up to the (AU) falsification. +# NOT a test and NOT a new hypothesis: it is the SAME pre-specified metric (q_action_gap) traced over +# every rung, printed only to say WHEN the separation appears, since AU2 says it is not there at 20k. +print() +print('=== DESCRIPTIVE: q_action_gap AUC(latched vs unlatched) over all 20 rungs (same metric as AU1/AU2) ===') +steps = sorted({r['step'] for c in use for r in (hist(c['cell']) or []) if 'step' in r}) +for st in steps: + pos = [v for r in lat for v in [at_step(hist(r['cell']) or [], st, 'q_action_gap')] if v is not None] + neg = [v for r in unl for v in [at_step(hist(r['cell']) or [], st, 'q_action_gap')] if v is not None] + A, pv = auc(pos, neg) + if A is None: continue + print(' step %6d AUC %.3f p %.4g %s' % (st, A, pv, '#' * int(round((A - 0.5) * 40)))) + +# The only number that would have made a screen actionable: at FULL recall of latched seeds (threshold +# set at the lowest latched q_action_gap, so no good seed is ever killed), what fraction of unlatched +# seeds could be stopped early? Same pre-specified metric; descriptive, not a test. +print() +print('=== DESCRIPTIVE: free savings from an early stop at 100%% latched-seed recall ===') +for st in (20000, 30000, 50000, 70000): + pos = [v for r in lat for v in [at_step(hist(r['cell']) or [], st, 'q_action_gap')] if v is not None] + neg = [v for r in unl for v in [at_step(hist(r['cell']) or [], st, 'q_action_gap')] if v is not None] + if not pos or not neg: continue + thr = min(pos) + killed = sum(1 for v in neg if v < thr) + saved = killed * (100000 - st) / 100000.0 + print(' stop at %6d if q_action_gap < %+.4f : kills %2d/%2d unlatched, 0/%d latched -> %.2f seed-equivalents saved per %d seeds (%.0f%%)' + % (st, thr, killed, len(neg), len(pos), saved, len(use), 100.0 * saved / len(use))) diff --git a/rsm_rise/scripts/real/augsucc_run54.py b/rsm_rise/scripts/real/augsucc_run54.py new file mode 100644 index 0000000000000000000000000000000000000000..1dc34ff3bcc721cf104fec26d0130261d4767a58 --- /dev/null +++ b/rsm_rise/scripts/real/augsucc_run54.py @@ -0,0 +1,109 @@ +#!/usr/bin/env python3 +"""AUG_SUCC run 54. Pure re-analysis of artifacts that already exist on disk. No new compute. + + (AR) STATUS -- the 2x2 and its Fisher p, now that `c0p5_s2` (the decider named in runs 52/53) has + landed its mc1 and mc2 draws. This is the SAME test registered earlier; it is not re-specified. + (AT) STATUS -- the c0p1 s5-s8 pack is still mid-training; reported as pending, not tested. + + Nothing new is registered above the table; any new hypothesis is registered in the status file with + its falsifier and its consequence BEFORE it is computed, exactly as in runs 50-53. +""" +import json, os, re +from scipy.stats import fisher_exact + +R = '/proj/dmfexp/zwhong/rsm_rise/status/real/rankctrl' +LATCH, HALFBAR = 0.70, 0.339 + +def load(c): + f = os.path.join(R, c, 'logged_action_rank.json') + return json.load(open(f)) if os.path.exists(f) else None + +def pick(b, *cs): + for c in cs: + if c in b: return b[c] + return {} + +def mean(xs): + xs = [x for x in xs if isinstance(x, (int, float))] + return sum(xs) / len(xs) if xs else None + +def gate(cell): + los, pms = [], [] + for sd in (0, 1, 2): + d = load(f'{cell}__R100k_mc{sd}') + if d is None: continue + g = pick(d['by'], 'rsm|goal|S2', 'rsm|correct|S2') + pm = pick(d['by'], 'permuted:rsm|goal|S2', 'permuted:rsm|correct|S2') + los.append((g.get('boot_rank_pct_mid') or {}).get('lo')) + pms.append(pm.get('rank_pct')) + return mean(los), mean(pms) + +def fwd(cell, kind): + t1 = [] + for sd in (0, 1, 2): + d = load(f'{cell}__{kind}100k_mc{sd}') + if d is None: continue + t1.append(pick(d['by'], 'rsm|goal|S2', 'rsm|correct|S2').get('top1')) + return mean(t1), len([x for x in t1 if x is not None]) + +rows = [] +for d in sorted(os.listdir(R)): + mm = re.match(r'^JUNC_feat_tinf_(c[0-9p]+)_s(\d+)__Fgoal100k_mc0$', d) + if not mm: continue + cell = f'JUNC_feat_tinf_{mm.group(1)}_s{mm.group(2)}' + fg, fn = fwd(cell, 'Fgoal'); ff, ffn = fwd(cell, 'Ffail'); lo, pm = gate(cell) + rows.append(dict(cell=cell, cap=mm.group(1), s=int(mm.group(2)), fg=fg, fn=fn, ff=ff, lo=lo, pm=pm)) +use = [r for r in rows if all(isinstance(r[k], float) for k in ('fg', 'ff', 'lo', 'pm'))] + +print('=== FULL CELL TABLE (n=%d) ===' % len(use)) +print(' %-28s %6s %2s %6s %6s %6s %s' % ('cell', 'Fgoal', 'n', 'Ffail', 'gateLo', 'perm', 'class')) +for r in sorted(use, key=lambda r: (r['cap'], r['s'])): + gp = r['lo'] > 0.5 and r['lo'] > r['pm'] + fh = r['fg'] >= HALFBAR + cls = ('GATE+FIELD' if gp and fh else 'gate only' if gp else 'field only' if fh else '-') + print(' %-28s %6.3f %2d %6.3f %6.3f %6.3f %-10s %s' % ( + r['cell'], r['fg'], r['fn'], r['ff'], r['lo'], r['pm'], cls, + 'LATCH' if r['ff'] >= LATCH else '')) + +print() +print('=== (AR) STATUS ===') +short = [r for r in use if r['fn'] < 3] +print(' cells at 3 Fgoal draws: %d of %d. still short: %s' % ( + len(use) - len(short), len(use), + ', '.join('%s_s%d(%d)' % (r['cap'], r['s'], r['fn']) for r in short) or 'none')) +a = b = c = d_ = 0 +for r in use: + gp = r['lo'] > 0.5 and r['lo'] > r['pm'] + fh = r['fg'] >= HALFBAR + if gp and fh: a += 1 + elif gp: b += 1 + elif fh: c += 1 + else: d_ += 1 +n = a + b + c + d_ +odds, p_ar = fisher_exact([[a, b], [c, d_]]) +print(' 2x2 = %d/%d/%d/%d over n=%d expects %.2f joint, observed %d Fisher p = %.4f' + % (a, b, c, d_, n, (a + b) / n * (a + c) / n * n, a, p_ar)) +print(' --> %s' % (('(AR) CALLABLE: ' + ('FALSIFIED' if p_ar < 0.05 else 'CONFIRMED')) + if not short else '(AR) NOT YET CALLABLE -- %d cells short of 3 draws' % len(short))) + +print() +print('=== run 52 LATCH decomposition, recomputed on the current table ===') +lat = [r for r in use if r['ff'] >= LATCH] +half = [r for r in lat if r['fg'] >= HALFBAR] +both = [r for r in half if r['lo'] > 0.5 and r['lo'] > r['pm']] +viol = [r for r in use if r['fg'] >= HALFBAR and r['ff'] < LATCH] +print(' P(latch) = %d/%d = %.3f' % (len(lat), len(use), len(lat) / len(use))) +print(' P(field half | latch) = %d/%d = %.3f' % (len(half), len(lat), len(half) / max(1, len(lat)))) +print(' P(gate | latch+half) = %d/%d = %.3f (gate marginal %d/%d = %.3f)' + % (len(both), len(half), len(both) / max(1, len(half)), + a + b, n, (a + b) / n)) +print(' product = %.4f observed joint = %d/%d = %.4f' + % (len(lat) / len(use) * len(half) / max(1, len(lat)) * len(both) / max(1, len(half)), + a, n, a / n)) +print(' NECESSITY of the latch for the field arm: violations (Fgoal>=%.3f with Ffail<%.2f) = %d/%d' + % (HALFBAR, LATCH, len(viol), len(use))) +if viol: print(' VIOLATING CELLS: %s' % ', '.join('%s(Fgoal %.3f, Ffail %.3f)' % (v['cell'], v['fg'], v['ff']) for v in viol)) +best_unl = max((r['fg'] for r in use if r['ff'] < LATCH), default=None) +print(' best Fgoal among unlatched = %.3f (gap to bar %.3f)' % (best_unl, HALFBAR - best_unl)) +print(' passing cells (GATE+FIELD): %s' % (', '.join(r['cell'] for r in use if + r['lo'] > 0.5 and r['lo'] > r['pm'] and r['fg'] >= HALFBAR) or 'none')) diff --git a/rsm_rise/scripts/real/augsucc_run54b.py b/rsm_rise/scripts/real/augsucc_run54b.py new file mode 100644 index 0000000000000000000000000000000000000000..a65f6761e6733608efcdedb6cdcc055dfd9badd0 --- /dev/null +++ b/rsm_rise/scripts/real/augsucc_run54b.py @@ -0,0 +1,100 @@ +#!/usr/bin/env python3 +"""AUG_SUCC run 54, part B. DESCRIPTIVE ONLY -- explicitly NOT a test. + +Run 53 ended with "I could not make the 'fix the latch' recommendation actionable" -- no cheap +TRAINING-TIME detector exists. This asks a different question that does not need a detector: is the +latch controlled by the AUGMENTATION DOSE, which is the one knob this stream owns? Everything below is +computed on the table I have already seen, so it is descriptive and hypothesis-generating; the +falsifiable version is registered in the status file against the four c0p1 seeds still training. +""" +import json, os, re +from scipy.stats import spearmanr, fisher_exact + +R = '/proj/dmfexp/zwhong/rsm_rise/status/real/rankctrl' +LATCH, HALFBAR = 0.70, 0.339 + +def load(c): + f = os.path.join(R, c, 'logged_action_rank.json') + return json.load(open(f)) if os.path.exists(f) else None + +def pick(b, *cs): + for c in cs: + if c in b: return b[c] + return {} + +def mean(xs): + xs = [x for x in xs if isinstance(x, (int, float))] + return sum(xs) / len(xs) if xs else None + +def gate(cell): + los, pms = [], [] + for sd in (0, 1, 2): + d = load(f'{cell}__R100k_mc{sd}') + if d is None: continue + g = pick(d['by'], 'rsm|goal|S2', 'rsm|correct|S2') + pm = pick(d['by'], 'permuted:rsm|goal|S2', 'permuted:rsm|correct|S2') + los.append((g.get('boot_rank_pct_mid') or {}).get('lo')) + pms.append(pm.get('rank_pct')) + return mean(los), mean(pms) + +def fwd(cell, kind): + t1 = [] + for sd in (0, 1, 2): + d = load(f'{cell}__{kind}100k_mc{sd}') + if d is None: continue + t1.append(pick(d['by'], 'rsm|goal|S2', 'rsm|correct|S2').get('top1')) + return mean(t1), len([x for x in t1 if x is not None]) + +rows = [] +for d in sorted(os.listdir(R)): + mm = re.match(r'^JUNC_feat_tinf_(c[0-9p]+)_s(\d+)__Fgoal100k_mc0$', d) + if not mm: continue + cell = f'JUNC_feat_tinf_{mm.group(1)}_s{mm.group(2)}' + fg, fn = fwd(cell, 'Fgoal'); ff, _ = fwd(cell, 'Ffail'); lo, pm = gate(cell) + if not all(isinstance(x, float) for x in (fg, ff, lo, pm)): continue + rows.append(dict(cap=mm.group(1), dose=float(mm.group(1)[1:].replace('p', '.')), s=int(mm.group(2)), + fg=fg, ff=ff, lo=lo, pm=pm, + latch=ff >= LATCH, gp=(lo > 0.5 and lo > pm), fh=fg >= HALFBAR)) + +print('=== DESCRIPTIVE: latch rate and gate-PASS rate BY DOSE (n=%d cells) ===' % len(rows)) +print(' %-7s %3s %-12s %-12s %-12s' % ('dose', 'n', 'latch rate', 'gate PASS', 'BOTH arms')) +doses = sorted({r['dose'] for r in rows}) +for d in doses: + g = [r for r in rows if r['dose'] == d] + nl = sum(r['latch'] for r in g); ng = sum(r['gp'] for r in g) + nb = sum(r['gp'] and r['fh'] for r in g) + print(' %-7.3f %3d %d/%d = %.2f %d/%d = %.2f %d/%d = %.2f' % ( + d, len(g), nl, len(g), nl / len(g), ng, len(g), ng / len(g), nb, len(g), nb / len(g))) + +print() +print('=== DESCRIPTIVE: monotone trend over the dose ladder ===') +for nm, key in (('latch (0/1)', 'latch'), ('Ffail (cont.)', 'ff'), + ('gate PASS (0/1)', 'gp'), ('gateLo (cont.)', 'lo'), ('Fgoal (cont.)', 'fg')): + rho, p = spearmanr([r['dose'] for r in rows], [float(r[key]) for r in rows]) + print(' spearman(dose, %-16s) = %+.3f p = %.4f' % (nm, rho, p)) + +print() +print('=== DESCRIPTIVE: the antagonism at the two ends of the ladder ===') +lo_d = [r for r in rows if r['dose'] <= 0.25] +hi_d = [r for r in rows if r['dose'] >= 0.375] +for nm, g in (('dose <= 0.25', lo_d), ('dose >= 0.375', hi_d)): + print(' %-14s n=%2d latch %d/%d = %.2f gate PASS %d/%d = %.2f BOTH %d/%d' % ( + nm, len(g), sum(r['latch'] for r in g), len(g), sum(r['latch'] for r in g) / len(g), + sum(r['gp'] for r in g), len(g), sum(r['gp'] for r in g) / len(g), + sum(r['gp'] and r['fh'] for r in g), len(g))) +a = sum(r['latch'] for r in hi_d); b = len(hi_d) - a +c = sum(r['latch'] for r in lo_d); d_ = len(lo_d) - c +print(' latch x dose-half 2x2 = %d/%d/%d/%d Fisher p = %.4f' % (a, b, c, d_, fisher_exact([[a, b], [c, d_]])[1])) +a = sum(r['gp'] for r in hi_d); b = len(hi_d) - a +c = sum(r['gp'] for r in lo_d); d_ = len(lo_d) - c +print(' gatePASS x dose-half 2x2 = %d/%d/%d/%d Fisher p = %.4f' % (a, b, c, d_, fisher_exact([[a, b], [c, d_]])[1])) + +print() +print('=== the c0p1 arm as it stands, the baseline the incoming s5-s8 will be judged against ===') +g = [r for r in rows if r['dose'] == 0.1] +for r in sorted(g, key=lambda r: r['s']): + print(' c0p1_s%d Fgoal %.3f Ffail %.3f gateLo %.3f perm %.3f latch=%s gatePASS=%s' + % (r['s'], r['fg'], r['ff'], r['lo'], r['pm'], r['latch'], r['gp'])) +print(' c0p1 latch %d/%d, gate PASS %d/%d, marginal latch rate over all doses %d/%d = %.3f' + % (sum(r['latch'] for r in g), len(g), sum(r['gp'] for r in g), len(g), + sum(r['latch'] for r in rows), len(rows), sum(r['latch'] for r in rows) / len(rows))) diff --git a/rsm_rise/scripts/real/augsucc_run54c.py b/rsm_rise/scripts/real/augsucc_run54c.py new file mode 100644 index 0000000000000000000000000000000000000000..b38f77839ba203954388f60cfb3c6657efb530d2 --- /dev/null +++ b/rsm_rise/scripts/real/augsucc_run54c.py @@ -0,0 +1,89 @@ +#!/usr/bin/env python3 +"""AUG_SUCC run 54, part C. How big a dose->latch effect can n=27 actually EXCLUDE? + +Part B found spearman(dose, latch) = +0.025, p = 0.90 -- a null. A null is only worth reporting with +the effect size it rules out, so this computes the Fisher-z CI on that spearman and the power the +design had against a moderate effect. Descriptive; no hypothesis is tested here. +""" +import json, math, os, re, random +from scipy.stats import spearmanr, norm + +R = '/proj/dmfexp/zwhong/rsm_rise/status/real/rankctrl' +LATCH = 0.70 + +def load(c): + f = os.path.join(R, c, 'logged_action_rank.json') + return json.load(open(f)) if os.path.exists(f) else None + +def pick(b, *cs): + for c in cs: + if c in b: return b[c] + return {} + +def mean(xs): + xs = [x for x in xs if isinstance(x, (int, float))] + return sum(xs) / len(xs) if xs else None + +def gate(cell): + los, pms = [], [] + for sd in (0, 1, 2): + d = load(f'{cell}__R100k_mc{sd}') + if d is None: continue + g = pick(d['by'], 'rsm|goal|S2', 'rsm|correct|S2') + pm = pick(d['by'], 'permuted:rsm|goal|S2', 'permuted:rsm|correct|S2') + los.append((g.get('boot_rank_pct_mid') or {}).get('lo')) + pms.append(pm.get('rank_pct')) + return mean(los), mean(pms) + +def fwd(cell, kind): + t1 = [] + for sd in (0, 1, 2): + d = load(f'{cell}__{kind}100k_mc{sd}') + if d is None: continue + t1.append(pick(d['by'], 'rsm|goal|S2', 'rsm|correct|S2').get('top1')) + return mean(t1) + +rows = [] +for d in sorted(os.listdir(R)): + mm = re.match(r'^JUNC_feat_tinf_(c[0-9p]+)_s(\d+)__Fgoal100k_mc0$', d) + if not mm: continue + cell = f'JUNC_feat_tinf_{mm.group(1)}_s{mm.group(2)}' + ff = fwd(cell, 'Ffail'); fg = fwd(cell, 'Fgoal'); lo, pm = gate(cell) + if not all(isinstance(x, float) for x in (fg, ff, lo, pm)): continue + rows.append(dict(dose=float(mm.group(1)[1:].replace('p', '.')), ff=ff, lo=lo, pm=pm, + latch=float(ff >= LATCH), gp=float(lo > 0.5 and lo > pm))) + +n = len(rows) +x = [r['dose'] for r in rows] + +def zci(rho, n, a=0.05): + if abs(rho) >= 1: return rho, rho + z = 0.5 * math.log((1 + rho) / (1 - rho)); se = 1.0 / math.sqrt(n - 3) + k = norm.ppf(1 - a / 2) + return tuple(math.tanh(v) for v in (z - k * se, z + k * se)) + +print('=== effect sizes this design can EXCLUDE (n=%d cells) ===' % n) +for nm, key in (('latch (0/1)', 'latch'), ('Ffail (cont.)', 'ff'), + ('gate PASS (0/1)', 'gp'), ('gateLo (cont.)', 'lo')): + y = [r[key] for r in rows] + rho, p = spearmanr(x, y) + lo_, hi_ = zci(rho, n) + print(' spearman(dose, %-16s) = %+.3f p = %.4f 95%% CI [%+.3f, %+.3f]' % (nm, rho, p, lo_, hi_)) + +# power of n=27 against a moderate true rho, at alpha=0.05 two-sided +print() +print('=== power of n=%d against a TRUE spearman of given size (alpha 0.05, two-sided) ===' % n) +se = 1.0 / math.sqrt(n - 3); k = norm.ppf(0.975) +for rho_t in (0.2, 0.3, 0.4, 0.5, 0.6): + zt = 0.5 * math.log((1 + rho_t) / (1 - rho_t)) + pw = norm.sf(k - zt / se) + norm.cdf(-k - zt / se) + print(' true rho %.1f -> power %.2f' % (rho_t, pw)) + +print() +print('=== the honest reading ===') +y = [r['latch'] for r in rows] +rho, p = spearmanr(x, y); lo_, hi_ = zci(rho, n) +print(' dose->latch: point estimate %+.3f, CI [%+.3f, %+.3f].' % (rho, lo_, hi_)) +print(' The data EXCLUDE |rho| > %.2f but are consistent with anything smaller.' % max(abs(lo_), abs(hi_))) +print(' A dose knob explaining the latch would have to be at least moderate to be useful; that is') +print(' the range this rules out. It does NOT rule out a weak dose dependence.') diff --git a/rsm_rise/scripts/real/augsucc_scrtj_score.py b/rsm_rise/scripts/real/augsucc_scrtj_score.py new file mode 100644 index 0000000000000000000000000000000000000000..a993dee7ae88fd495f26c1aab9060f78eeae71c5 --- /dev/null +++ b/rsm_rise/scripts/real/augsucc_scrtj_score.py @@ -0,0 +1,32 @@ +#!/usr/bin/env python3 +"""AUG_SUCC run 48: matched early ladder, scramble (scr) vs deployed (tinf), cap 0.50, 1 MC draw.""" +import json, os +R='/proj/dmfexp/zwhong/rsm_rise/status/real/rankctrl' +def load(c): + f=os.path.join(R,c,'logged_action_rank.json') + return json.load(open(f)) if os.path.exists(f) else None +def pick(b,*cs): + for c in cs: + if c in b: return b[c] + return {} +def gate(cell,st): + d=load(f'{cell}__R{st}_mc0') + if d is None: return None,None + g=pick(d['by'],'rsm|goal|S2','rsm|correct|S2'); br=g.get('boot_rank_pct_mid') or {} + return br.get('lo'), g.get('rank_pct') +def fld(cell,st): + d=load(f'{cell}__Ffail{st}_mc0') + if d is None: return None + return pick(d['by'],'rsm|correct|S2','rsm|goal|S2').get('top1') +S=[10000,30000,50000,70000] +f=lambda x:('%6.3f'%x) if isinstance(x,(int,float)) else ' n/a' +for label,fn in (('gate bootLo',lambda c,s:gate(c,s)[0]),('gate rank_pct',lambda c,s:gate(c,s)[1]),('Ffail top-1',fld)): + print('=== %s, 1 MC draw ==='%label) + print('seed '+''.join('%10s'%('%dk'%(s//1000)) for s in S)+' (tinf = deployed, scr = scramble)') + for sd in (1,2,3,4): + t=[fn('JUNC_feat_tinf_c0p5_s%d'%sd,s) for s in S] + r=[fn('JUNC_feat_scr_c0p5_s%d'%sd,s) for s in S] + print(' s%d tinf'%sd+''.join(' '+f(x) for x in t)) + print(' scr '+''.join(' '+f(x) for x in r)+' d='+' '.join( + ('%+.3f'%(r[i]-t[i])) if (isinstance(r[i],float) and isinstance(t[i],float)) else ' n/a' for i in range(4))) + print() diff --git a/rsm_rise/scripts/real/augsucc_table.py b/rsm_rise/scripts/real/augsucc_table.py new file mode 100644 index 0000000000000000000000000000000000000000..b8d26004ada09f455f3a5324db55a3188833f24b --- /dev/null +++ b/rsm_rise/scripts/real/augsucc_table.py @@ -0,0 +1,126 @@ +#!/usr/bin/env python3 +"""AUG_SUCC (gen_q#279) -- the Task 3 report table. + +Reads, for every trained AUG__t_s cell: + * the GATE, status/real/rankctrl/__Rval31/logged_action_rank.json -- reverse anchor, n=37 + anchors in 5 failure episodes, K=31. `rsm|goal|S2` is the goal-bound chunk (candidate 0) and + `rsm|own|S2` is the anchor's own next chunk. PASS = the goal chunk's rank percentile clears 0.5 + by more than its episode-bootstrapped SE AND clears the permuted control. + * the two forward arms __Ffail31 (R_M: 0.969) and __Fgoal31 (R_M: 0.677), so a win on the gate + cannot hide a regression there; + * the zero-parameter pose-continuity and the BC log-likelihood baselines ON THE SAME ANCHORS + (1.000 / 1.000 for R_M today) -- the RSM has to beat what a zero-parameter score already does; + * ties@max and score CV beside every rank number; + * the minmse / staymse training gate from each run's own history.json. +The bootstrap is over the 5 anchor EPISODES (the harness's boot_rank_pct_mid), so SE = (hi-lo)/3.92. +Reference row R_M is printed first from the same three cells measured on the un-augmented checkpoint. +""" +import json, os, glob, argparse + +ROOT = "/proj/dmfexp/zwhong/rsm_rise" +RC = f"{ROOT}/status/real/rankctrl" +RUNS = f"{ROOT}/runs/real_cooking_v5/rsm" + + +def load(cell): + p = f"{RC}/{cell}/logged_action_rank.json" + return json.load(open(p)) if os.path.exists(p) and os.path.getsize(p) else None + + +def g(d, key, field, default=float("nan")): + if not d: + return default + return d["by"].get(key, {}).get(field, default) + + +def se(d, key): + """episode-bootstrap SE of the rank percentile = (hi - lo) / 3.92.""" + b = (d or {}).get("by", {}).get(key, {}).get("boot_rank_pct_mid") + return float("nan") if not b else (b["hi"] - b["lo"]) / 3.92 + + +# AUG_SUCC run 28 (2026-09-24 07:5xZ): h[-1] was silently WRONG for any cell whose training is +# EXTENDED past the step its gate arms were scored at. The run-28 200k extension resumes four cells +# in place, so their history.json grows to step 200000 while __{R,Ffail,Fgoal}val31 stay pinned to +# ckpt_s100000.pt -- h[-1] would have printed a 200k qwin/minmse beside a 100k rank and nothing in the +# table would have shown it. Cap the history read at the gate step instead. Default 100000, which +# leaves every row printed before this edit bit-identical (no cell had an entry past 100000). +HIST_STEP = int(os.environ.get("RR_HIST_STEP", "100000")) + + +def hist(cell): + p = f"{RUNS}/{cell}/history.json" + if not os.path.exists(p): + return {} + h = json.load(open(p)) + if not (isinstance(h, list) and h): + return {} + ok = [e for e in h if isinstance(e, dict) and int(e.get("step", 0)) <= HIST_STEP] + return ok[-1] if ok else {} + + +def row(tag, rev_cell, ff_cell, fg_cell, run_cell): + rv, ff, fg = load(rev_cell), load(ff_cell), load(fg_cell) + hh = hist(run_cell) + rp = g(rv, "rsm|goal|S2", "rank_pct_mid") + s = se(rv, "rsm|goal|S2") + pas = "" + if rp == rp and s == s: + pas = "PASS" if (rp - s) > 0.5 and rp > g(rv, "permuted:rsm|goal|S2", "rank_pct_mid", 0) else "fail" + return dict( + cell=tag, pass_=pas, + goal_rank=rp, goal_se=s, + goal_top1=g(rv, "rsm|goal|S2", "top1_tie"), + perm_rank=g(rv, "permuted:rsm|goal|S2", "rank_pct_mid"), + own_top1=g(rv, "rsm|own|S2", "top1_tie"), + pose_rank=g(rv, "pose|goal|S2", "rank_pct_mid"), + bc_rank=g(rv, "bc|goal|S2", "rank_pct_mid"), + # the "1.000" pose / BC numbers the brief quotes are these: on the REVERSE arm both + # zero-parameter scores put the anchor's OWN chunk first 100% of the time, while their + # GOAL-chunk rank is 0.153 / 0.152 -- BELOW the RSM's 0.234. So on the gate's goal axis the + # baselines are not the thing to beat; on the FORWARD arm (pose 1.000 vs rsm 0.969) they are. + pose_own=g(rv, "pose|own|S2", "top1_tie"), bc_own=g(rv, "bc|own|S2", "top1_tie"), + pose_ffail=g(ff, "pose|S2", "top1_tie"), bc_ffail=g(ff, "bc|S2", "top1_tie"), + ties=g(rv, "rsm|goal|S2", "ties_at_max"), cv=g(rv, "rsm|goal|S2", "score_cv"), + ffail=g(ff, "rsm|S2", "top1_tie"), fgoal=g(fg, "rsm|S2", "top1_tie"), + minmse=hh.get("minmse_val", float("nan")), staymse=hh.get("staymse_val", float("nan")), + nnl1=hh.get("nnl1_ratio_vs_stay_val", float("nan")), + ) + + +def fmt(v, n=3): + try: + return " n/a" if v != v else f"{v:.{n}f}" + except Exception: + return str(v) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--out", default=f"{ROOT}/status/real/augsucc/gate_table.json") + a = ap.parse_args() + rows = [row("R_M (baseline)", "T0_BASE_Rval31", "T0_BASE_Ffail31", "T0_BASE_Fgoal31", "R_M")] + for mode in ("contrastive", "invariant"): + for thr in ("0p005", "0p01", "0p02", "0p15"): + for seed in ("0", "1"): + c = f"AUG_{mode}_t{thr}_s{seed}" + rows.append(row(c, f"{c}__Rval31", f"{c}__Ffail31", f"{c}__Fgoal31", c)) + hdr = (f"{'cell':34s} {'gate':5s} {'goalRank':>9s} {'+-SE':>6s} {'g_top1':>7s} {'perm':>6s} " + f"{'ownT1':>6s} {'pose_g':>6s} {'bc_g':>6s} {'poseOwn':>7s} {'ties':>5s} {'CV':>6s} {'Ffail':>6s} {'Fgoal':>6s} " + f"{'minmse':>7s} {'staymse':>7s}") + print(hdr); print("-" * len(hdr)) + for r in rows: + print(f"{r['cell']:34s} {r['pass_']:5s} {fmt(r['goal_rank']):>9s} {fmt(r['goal_se']):>6s} " + f"{fmt(r['goal_top1']):>7s} {fmt(r['perm_rank']):>6s} {fmt(r['own_top1']):>6s} " + f"{fmt(r['pose_rank']):>6s} {fmt(r['bc_rank']):>6s} {fmt(r['pose_own']):>7s} {fmt(r['ties'],2):>5s} " + f"{fmt(r['cv'],2):>6s} {fmt(r['ffail']):>6s} {fmt(r['fgoal']):>6s} " + f"{fmt(r['minmse'],4):>7s} {fmt(r['staymse'],4):>7s}") + os.makedirs(os.path.dirname(a.out), exist_ok=True) + json.dump(rows, open(a.out, "w"), indent=1) + print(f"\n[table] {a.out}") + print("PASS = goal-chunk rank pct clears 0.5 by > 1 episode-bootstrap SE AND clears the permuted " + "control. R_M today: goal rank 0.234, goal top1 0.000, own top1 0.405.") + + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/real/augsucc_v_score.py b/rsm_rise/scripts/real/augsucc_v_score.py new file mode 100644 index 0000000000000000000000000000000000000000..128837e13e0d0bdd01bb4a7a9f59e8e0bb61b47f --- /dev/null +++ b/rsm_rise/scripts/real/augsucc_v_score.py @@ -0,0 +1,72 @@ +#!/usr/bin/env python3 +"""AUG_SUCC run 48: score (V) -- the fresh-seed replication at cap 0.50, s5..s8, and re-read the whole +cap-0.50 family (9 seeds) for the gate x field conjunction rate. Reads only existing JSON.""" +import json, os +R='/proj/dmfexp/zwhong/rsm_rise/status/real/rankctrl' +def load(c): + f=os.path.join(R,c,'logged_action_rank.json') + return json.load(open(f)) if os.path.exists(f) else None +def pick(b,*cs): + for c in cs: + if c in b: return b[c] + return {} +def draws(cell, kind): + out=[] + for sd in (0,1,2): + d=load(f'{cell}__{kind}100k_mc{sd}') or (load(f'{cell}__{kind}val31') if sd==0 else None) + if d is None: continue + g=pick(d['by'],'rsm|goal|S2','rsm|correct|S2') + pm=pick(d['by'],'permuted:rsm|goal|S2','permuted:rsm|correct|S2') + o=pick(d['by'],'rsm|own|S2') + po=pick(d['by'],'pose|goal|S2','pose|correct|S2') + bc=pick(d['by'],'bc|goal|S2','bc|correct|S2') + br=g.get('boot_rank_pct_mid') or {} + out.append(dict(rk=g.get('rank_pct'), t1=g.get('top1'), perm=pm.get('rank_pct'), + own=o.get('top1'), cv=g.get('score_cv'), lo=br.get('lo'), + tie=g.get('ties_at_max') if g.get('ties_at_max') is not None else g.get('top1_tie'), + pose=po.get('rank_pct'), pose_t1=po.get('top1'), + bc=bc.get('rank_pct'), bc_t1=bc.get('top1'))) + return out +def m(xs): + xs=[x for x in xs if isinstance(x,(int,float))] + return sum(xs)/len(xs) if xs else None +f=lambda x:('%6.3f'%x) if isinstance(x,(int,float)) else ' n/a' +print('=== cap 0.50 family, all seeds -- gate (3 MC draws) x field ===') +print(f"{'seed':>4s} {'nd':>2s} {'bootLo':>6s} {'gate':>6s} {'perm':>6s} {'g_t1':>6s} {'own_t1':>6s} {'CV':>6s} {'pose':>6s} {'bc':>6s} | {'Ffail':>6s} {'gate>0.5':>8s} {'fld>=.8':>7s} {'BOTH':>5s}") +rows=[] +for sd in range(9): + c=f'JUNC_feat_tinf_c0p5_s{sd}' + G=draws(c,'R'); F=draws(c,'Ffail') + if not G: continue + lo=m([d['lo'] for d in G]); perm=m([d['perm'] for d in G]); ff=m([d['t1'] for d in F]) + gpass = (lo is not None and lo>0.5 and perm is not None and lo>perm) + fpass = (ff is not None and ff>=0.80) + rows.append((sd,lo,ff,gpass,fpass)) + print(f"{sd:4d} {len(G):2d} {f(lo)} {f(m([d['rk'] for d in G]))} {f(perm)} {f(m([d['t1'] for d in G]))} " + f"{f(m([d['own'] for d in G]))} {f(m([d['cv'] for d in G]))} {f(m([d['pose'] for d in G]))} " + f"{f(m([d['bc'] for d in G]))} | {f(ff)} {str(gpass):>8s} {str(fpass):>7s} {str(gpass and fpass):>5s}") +print() +fresh=[r for r in rows if r[0]>=5] +nboth_fresh=sum(1 for r in fresh if r[3] and r[4]) +print('(V) registered: of tinf_c0p5_s{5..8}, at least 2 are PASS-with-field (bootLo>0.5 AND >perm AND Ffail>=0.80)') +print(' available %d/4, PASS-with-field: %d -> %s'%(len(fresh),nboth_fresh, + 'CONFIRMED' if nboth_fresh>=2 else ('FALSIFIED' if len(fresh)==4 else 'PENDING'))) +print() +nb=sum(1 for r in rows if r[3] and r[4]); ng=sum(1 for r in rows if r[3]); nf=sum(1 for r in rows if r[4]) +print('cap 0.50 over %d seeds: gate-pass %d, field-intact %d, BOTH %d (prior claim was 3 of 5)'%(len(rows),ng,nf,nb)) +# 2x2 and rank correlation of bootLo vs Ffail +import itertools +a=sum(1 for r in rows if r[3] and r[4]); b=sum(1 for r in rows if r[3] and not r[4]) +c_=sum(1 for r in rows if (not r[3]) and r[4]); d_=sum(1 for r in rows if (not r[3]) and not r[4]) +print('2x2 gate+/field+ %d gate+/field- %d gate-/field+ %d gate-/field- %d'%(a,b,c_,d_)) +xs=[r[1] for r in rows if r[1] is not None and r[2] is not None] +ys=[r[2] for r in rows if r[1] is not None and r[2] is not None] +def rank(v): + s=sorted(range(len(v)), key=lambda i:v[i]); rk=[0]*len(v) + for j,i in enumerate(s): rk[i]=j+1 + return rk +rx,ry=rank(xs),rank(ys); n=len(xs) +mx=sum(rx)/n; my=sum(ry)/n +num=sum((rx[i]-mx)*(ry[i]-my) for i in range(n)) +den=(sum((rx[i]-mx)**2 for i in range(n))*sum((ry[i]-my)**2 for i in range(n)))**0.5 +print('spearman(bootLo, Ffail) over %d cap-0.50 seeds = %.3f'%(n, num/den if den else float('nan'))) diff --git a/rsm_rise/scripts/real/bearing_cond_table.py b/rsm_rise/scripts/real/bearing_cond_table.py new file mode 100644 index 0000000000000000000000000000000000000000..cd23ed3ac573cb02d823e35eba77355ace27b92b --- /dev/null +++ b/rsm_rise/scripts/real/bearing_cond_table.py @@ -0,0 +1,52 @@ +"""SUCC_DEBUG run 10: the two conditioning arms of hop_bearing.py side by side. + +TF = one hop from the TRUE frame with its own logged chunk -- exactly a training pair, so this is + the "does it model its training data" number, per hop, bracketed by predict-the-present. +FREE-logged / FREE-hop = the free-running chain conditioned on the logged chunk (oracle) vs on the + hop head at the current latent (what is_ope.q_fold deploys). +Brackets on every column: e/STAY 1.000 = stay-put, 0 = perfect; cos ORACLE 1.000, chance +-1/sqrt(D). +Validity: read with status/real/succdebug/anchor_clamp_census.json -- at beta 0.95 the logged +reference frame is clamped for 0.000 of anchors at every hop through 16, so every column below is a +measurement; at beta 0.99 only h<=4 is (h8 0.260, h12 0.885, h16 0.995 clamped). +""" +import glob, json, os, sys +O = "/proj/dmfexp/zwhong/rsm_rise/status/real/succdebug" +B = float(next((a.split("=")[1] for a in sys.argv[1:] if a.startswith("--beta=")), 0.95)) +H = next((a.split("=")[1] for a in sys.argv[1:] if a.startswith("--hop=")), "16") + +def load(pref): + o = {} + for p in sorted(glob.glob(f"{O}/{pref}*.json")): + t = os.path.basename(p)[len(pref):-len(".json")] + if t.startswith("_"): + continue + j = json.load(open(p)) + r = [x for x in j["rows"] if abs(x["beta"] - B) < 1e-9] + if r: + o[t] = (j, r[0]) + return o + +lg, hp = load("bearing_"), load("bearing_hop_") +lg = {k: v for k, v in lg.items() if not k.startswith("hop_")} +print(f"beta={B} terminal hop H={H} cos chance +-{list(lg.values())[0][0]['cos_chance']:.3f}") +print(f"{'cell':<20}{'W':>5} | {'TF e/STAY h1':>12}{'hH':>6}{'TF cos h1':>10}{'hH':>6} | " + f"{'FREE-logged e/STAY hH':>22}{'cos_step':>9}{'cos_cum':>8} | " + f"{'FREE-hop e/STAY hH':>19}{'cos_step':>9}{'cos_cum':>8} | {'amp1':>6}") +for t in sorted(lg, key=lambda t: (lg[t][0]["flow_width"], t)): + j, r = lg[t]; ph = r["per_hop"] + row = (f"{t:<20}{j['flow_width']:>5} | {ph['1']['e_tf_over_STAYstep']:>12.3f}" + f"{ph[H]['e_tf_over_STAYstep']:>6.3f}{ph['1']['cos_step_tf']:>10.3f}" + f"{ph[H]['cos_step_tf']:>6.3f} | {ph[H]['e_free_over_STAYanchor']:>22.3f}" + f"{ph[H]['cos_step_free']:>9.3f}{ph[H]['cos_cum_free']:>8.3f} | ") + if t in hp: + p2 = hp[t][1]["per_hop"] + row += (f"{p2[H]['e_free_over_STAYanchor']:>19.3f}{p2[H]['cos_step_free']:>9.3f}" + f"{p2[H]['cos_cum_free']:>8.3f} | ") + else: + row += f"{'-':>19}{'-':>9}{'-':>8} | " + row += f"{r['amp']['1.0']['amp_median']:>6.3f}" + print(row) +print(f"{'STAY (bracket)':<20}{'-':>5} | {1.0:>12.3f}{1.0:>6.3f}{0.0:>10.3f}{0.0:>6.3f} | " + f"{1.0:>22.3f}{0.0:>9.3f}{0.0:>8.3f} | {1.0:>19.3f}{0.0:>9.3f}{0.0:>8.3f} | {'-':>6}") +print(f"{'ORACLE (bracket)':<20}{'-':>5} | {0.0:>12.3f}{0.0:>6.3f}{1.0:>10.3f}{1.0:>6.3f} | " + f"{0.0:>22.3f}{1.0:>9.3f}{1.0:>8.3f} | {0.0:>19.3f}{1.0:>9.3f}{1.0:>8.3f} | {'-':>6}") diff --git a/rsm_rise/scripts/real/bearing_table.py b/rsm_rise/scripts/real/bearing_table.py new file mode 100644 index 0000000000000000000000000000000000000000..756e3558afde6aded86f101c692be527c68c3ad3 --- /dev/null +++ b/rsm_rise/scripts/real/bearing_table.py @@ -0,0 +1,69 @@ +"""SUCC_DEBUG run 10: login-safe reader for status/real/succdebug/bearing_*.json. + +One row per cell. Every column carries its own bracket in the header, because a number without its +bracket is not a measurement (status/REGRESSIONS.md): + e_tf/STAYstep one hop from the TRUE previous frame, over "predict the present". <1 beats + stay-put ON the data manifold; >=1 is the gate failure reproduced per hop. + cos_tf cosine of that hop against the logged step. ORACLE 1.0, chance +-1/sqrt(D). + e_free/STAYanc the free-running chain's error over "never move". <1 beats the anchor. + cos_step/cos_cum the free chain's per-step and cumulative bearing. Same brackets as cos_tf. + amp(eps) || hop(z+n) - hop(z) || / ||n|| at n = eps x the data's own step RMS, common + random numbers. <1 contraction (a free chain is stable), >1 expansion. + d/step the residual's L1 over the logged one-hop step: 0 = identity net, 1 = data scale. +""" +import glob, json, os, sys + +O = "/proj/dmfexp/zwhong/rsm_rise/status/real/succdebug" +BETA = float(next((a.split("=")[1] for a in sys.argv[1:] if a.startswith("--beta=")), 0.95)) +H = next((a.split("=")[1] for a in sys.argv[1:] if a.startswith("--hop=")), "16") + +rows = [] +for p in sorted(glob.glob(f"{O}/bearing_*.json")): + tag = os.path.basename(p)[len("bearing_"):-len(".json")] + if tag.startswith("_"): + continue + try: + j = json.load(open(p)) + except Exception as e: + print(f"[skip unreadable] {tag}: {e}") + continue + r = next((r for r in j["rows"] if abs(r["beta"] - BETA) < 1e-9), None) + if r is None: + continue + ph = r["per_hop"] + if "1" not in ph or H not in ph: + continue + amp = r["amp"] + dl = j.get("delta", {}).get(str(BETA), {}) + rows.append({ + "tag": tag, "W": j.get("flow_width") or 0, + "steps": int(tag.split("_s")[-1]) if tag.split("_s")[-1].isdigit() else -1, + "etf": ph["1"]["e_tf_over_STAYstep"], "costf": ph["1"]["cos_step_tf"], + "ef1": ph["1"]["e_free_over_STAYanchor"], "efH": ph[H]["e_free_over_STAYanchor"], + "cs1": ph["1"]["cos_step_free"], "csH": ph[H]["cos_step_free"], + "ccH": ph[H]["cos_cum_free"], + "a05": amp.get("0.5", {}).get("amp_median", float("nan")), + "a10": amp.get("1.0", {}).get("amp_median", float("nan")), + "a20": amp.get("2.0", {}).get("amp_median", float("nan")), + "dstep": dl.get("delta_over_step", float("nan")), + "chance": j["cos_chance"], + }) + +rows.sort(key=lambda r: (r["W"], r["steps"])) +ch = rows[0]["chance"] if rows else 0.025 +print(f"beta={BETA} hop index H={H} cosine chance +-{ch:.3f} " + f"brackets: e/STAY 1.000 = stay-put, 0 = perfect; cos ORACLE 1.000; amp 1.000 = neutral") +print(f"{'cell':<22}{'W':>5}{'steps':>8} | {'e_tf/STAYstep':>14}{'cos_tf':>8} | " + f"{'e_free/STAYanc h1':>18}{'hH':>7} | {'cos_step h1':>12}{'hH':>7}{'cos_cum hH':>11} | " + f"{'amp .5':>7}{'amp 1':>7}{'amp 2':>7} | {'d/step':>7}") +for r in rows: + print(f"{r['tag']:<22}{r['W']:>5}{r['steps']:>8} | {r['etf']:>14.3f}{r['costf']:>8.3f} | " + f"{r['ef1']:>18.3f}{r['efH']:>7.3f} | {r['cs1']:>12.3f}{r['csH']:>7.3f}" + f"{r['ccH']:>11.3f} | {r['a05']:>7.3f}{r['a10']:>7.3f}{r['a20']:>7.3f} | " + f"{r['dstep']:>7.3f}") +print(f"{'STAY (bracket)':<22}{'-':>5}{'-':>8} | {1.000:>14.3f}{0.000:>8.3f} | " + f"{1.000:>18.3f}{1.000:>7.3f} | {0.000:>12.3f}{0.000:>7.3f}{0.000:>11.3f} | " + f"{'-':>7}{'-':>7}{'-':>7} | {0.000:>7.3f}") +print(f"{'ORACLE (bracket)':<22}{'-':>5}{'-':>8} | {0.000:>14.3f}{1.000:>8.3f} | " + f"{0.000:>18.3f}{0.000:>7.3f} | {1.000:>12.3f}{1.000:>7.3f}{1.000:>11.3f} | " + f"{'-':>7}{'-':>7}{'-':>7} | {1.000:>7.3f}") diff --git a/rsm_rise/scripts/real/beta_band.py b/rsm_rise/scripts/real/beta_band.py new file mode 100644 index 0000000000000000000000000000000000000000..970597d886dc7ae4bb47a4ca8a70238d4d7d6c64 --- /dev/null +++ b/rsm_rise/scripts/real/beta_band.py @@ -0,0 +1,82 @@ +#!/usr/bin/env python +"""Derive the beta band for rsm_cooking_v5 from the ACTUAL episode-length distribution +and the per-anchor truncation cap now live in rsm_libero/data.py. + +data.py: anchors are drawn with P(episode) ~ ep_len and uniform within the episode, so +L = frames remaining is what limits beta. The cap is + beta_cap(L) = eps**(1/L), eps = beta_trunc_eps (0.02) +and the sampled beta is uniform on [beta_lo, clip(beta_cap, beta_lo, beta_hi)]. +A nominal beta_hi is therefore only *exercised* by anchors with + L >= ln(eps)/ln(beta_hi) ~= 3.912 / (1 - beta_hi). +""" +import json, sys +from pathlib import Path +import numpy as np +import pyarrow.parquet as pq + +ROOT = Path("/proj/dmfexp/zwhong/rsm_rise/data/real/rsm_cooking_v5") +EPS = 0.02 +FPS_LOCAL = 50.0 # modal inter-frame dt is exactly 20 ms +FPS_EFF = 38.72 # retained frames / wall second, episode-averaged + +info = json.loads((ROOT / "meta/info.json").read_text()) +n_ep = int(info["total_episodes"]); cs = int(info["chunks_size"]); dp = info["data_path"] +lens = np.array([pq.read_metadata(ROOT / dp.format(episode_chunk=i // cs, episode_index=i)).num_rows + for i in range(n_ep)], np.int64) +N = int(lens.sum()) +print(f"[beta] {n_ep} eps, N={N}, len min/p05/p25/med/p75/p95/max = " + + "/".join(f"{v:.0f}" for v in [lens.min(), *np.percentile(lens, [5, 25, 50, 75, 95]), lens.max()])) + +# Exact anchor distribution over L: episode e contributes anchors with L = 1..len_e, +# each with weight 1/sum(len) (since P(e) ~ len_e and uniform-in-episode gives 1/len_e each). +def frac_anchors_with_L_at_least(x): + return float(np.maximum(lens - x + 1, 0).sum() / N) + +print(f"\n[beta] {'beta':>8} {'horizon_fr':>11} {'h_local_s':>10} {'h_eff_s':>9} " + f"{'L_needed':>9} {'%anchors':>9} {'%eps_can':>9}") +rows = [] +for b in [0.90, 0.93, 0.95, 0.96, 0.97, 0.975, 0.98, 0.985, 0.988, 0.99, 0.991, 0.992, + 0.993, 0.994, 0.995, 0.996, 0.997, 0.998]: + H = 1.0 / (1.0 - b) + Lneed = np.log(EPS) / np.log(b) + fa = frac_anchors_with_L_at_least(Lneed) + fe = float((lens >= Lneed).mean()) + rows.append({"beta": b, "horizon_frames": H, "h_local_s": H / FPS_LOCAL, "h_eff_s": H / FPS_EFF, + "L_needed": Lneed, "frac_anchors": fa, "frac_episodes": fe}) + print(f"[beta] {b:8.3f} {H:11.1f} {H/FPS_LOCAL:10.2f} {H/FPS_EFF:9.2f} " + f"{Lneed:9.0f} {fa*100:8.1f}% {fe*100:8.1f}%") + +# What beta does a typical anchor actually get capped to? +rng = np.random.default_rng(0) +e = rng.choice(n_ep, size=400000, p=lens / N) +L = np.maximum((rng.random(400000) * lens[e]).astype(np.int64), 1) +cap = np.power(EPS, 1.0 / L) +print(f"\n[beta] realised beta_cap over anchors: " + + "/".join(f"{v:.4f}" for v in np.percentile(cap, [5, 25, 50, 75, 95])) + " (p05..p95)") +for bhi in (0.98, 0.985, 0.99, 0.992, 0.995): + eff = np.clip(cap, 0.90, bhi) + print(f"[beta] nominal beta_hi={bhi:.3f} -> effective hi median {np.median(eff):.4f}, " + f"mean {eff.mean():.4f}, frac at nominal {float((cap>=bhi).mean())*100:.1f}%") + +# Sim comparison: what did the cap do to the sim cache at its nominal 0.995? +sim = Path("/proj/dmfexp/zwhong/rsm_rise/cache/two_piece_expert_suboptimal/meta.npz") +if sim.exists(): + sl = np.load(sim, allow_pickle=True)["ep_len"] + sN = int(sl.sum()) + print(f"\n[beta] SIM two_piece_expert_suboptimal: {len(sl)} eps, median len {np.median(sl):.0f}, " + f"20 Hz -> {np.median(sl)/20:.1f} s") + for b in (0.99, 0.995): + Ln = np.log(EPS) / np.log(b) + print(f"[beta] sim beta={b}: needs L>={Ln:.0f}; " + f"{float(np.maximum(sl-Ln+1,0).sum()/sN)*100:.1f}% of sim anchors, " + f"{float((sl>=Ln).mean())*100:.1f}% of sim episodes") + se = rng.choice(len(sl), size=200000, p=sl / sN) + sL = np.maximum((rng.random(200000) * sl[se]).astype(np.int64), 1) + scap = np.power(EPS, 1.0 / sL) + print(f"[beta] sim realised beta_cap median {np.median(scap):.4f}; " + f"clipped to [0.90,0.995] median {np.median(np.clip(scap,0.90,0.995)):.4f}") + +out = Path("/proj/dmfexp/zwhong/rsm_rise/status/real_cooking_beta.json") +out.write_text(json.dumps({"lens": lens.tolist(), "N": N, "rows": rows, + "fps_local": FPS_LOCAL, "fps_eff": FPS_EFF, "eps": EPS}, indent=2)) +print(f"\n[beta] wrote {out}") diff --git a/rsm_rise/scripts/real/beta_paired_test.py b/rsm_rise/scripts/real/beta_paired_test.py new file mode 100644 index 0000000000000000000000000000000000000000..0d505b9158f739d8a641ad6095018c7948aa4497 --- /dev/null +++ b/rsm_rise/scripts/real/beta_paired_test.py @@ -0,0 +1,133 @@ +#!/usr/bin/env python +"""PAIRED beta comparison for the action-sensitivity cells (ACT_COND, run 11). + +Run 10 read the beta question off a table of independent-looking column values: +prob top-1 agreement 0.585 (beta 0.99) vs 0.493 (0.97) vs 0.520 (0.95). An +UNPAIRED binomial se on 200 anchors is sqrt(.25/200) = 0.035, so 0.585 vs 0.520 +is ~1.9 se and 0.493 vs 0.520 is <1 se -- i.e. read unpaired, the table cannot +separate 0.97 from 0.95 at all and can barely separate 0.99 from 0.95. + +But the cells are NOT independent samples: every beta cell is drawn with the same +seed and the same --max-anchors, so anchor i is the SAME (episode, t, stage) in +every cell and only beta differs. That makes this a within-anchor comparison, and +the paired test is both the CORRECT one and far more powerful. This script: + + 1. ASSERTS anchor identity across the cells it compares, on (ep, t, stage), and + FAILS LOUDLY if any position disagrees -- pairing misaligned rows would + silently manufacture significance, which is worse than the eyeball it replaces. + 2. Reports, for each statistic and each beta vs the deployed 0.99: the paired + mean difference, a paired bootstrap 95% CI, the Wilcoxon signed-rank p, AND + the unpaired se -- so the gain from pairing is visible rather than asserted. + +Statistics compared: top1_agree_{prob,logit} (decision level), snr_{prob} with the +run-8 1/R bias correction applied per anchor, rep_spearman_{prob,logit}. +Bias correction: E[snr_raw] = snr_true + 1/R, so snr_corr = snr_raw - 1/R. +""" +import json, os, sys, argparse +import numpy as np +from scipy.stats import wilcoxon + +ROOT = "/proj/dmfexp/zwhong/rsm_rise/status/real/ACT_COND/snr" + + +def load(path): + d = json.load(open(path)) + return d + + +def key(r): + return (int(r["ep"]), int(r["t"]), str(r.get("stage"))) + + +def boot_ci(d, n=20000, seed=0): + rng = np.random.default_rng(seed) + idx = rng.integers(0, len(d), size=(n, len(d))) + m = d[idx].mean(1) + return float(np.percentile(m, 2.5)), float(np.percentile(m, 97.5)) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--dir", default=ROOT) + ap.add_argument("--ref", default="snr_beta99.json") + ap.add_argument("--out", default="/proj/dmfexp/zwhong/rsm_rise/status/real/ACT_COND/BETA_PAIRED.json") + a = ap.parse_args() + + cells = sorted(f for f in os.listdir(a.dir) if f.startswith("snr_beta") and f.endswith(".json")) + if a.ref not in cells: + raise SystemExit(f"reference cell {a.ref} not present in {a.dir} ({cells})") + ref = load(os.path.join(a.dir, a.ref)) + R = int(ref["args"].get("repeats", 1)) + if R < 2: + raise SystemExit(f"reference cell has repeats={R}; the noise statistics need R>=2") + refrows = ref["rows"] + refkeys = [key(r) for r in refrows] + + print(f"reference {a.ref}: n={len(refrows)} anchors, repeats={R}, " + f"beta={ref['args'].get('beta')}, seed={ref['args'].get('seed')}") + + stats = [("top1_agree_prob", "top1 agree (prob)"), + ("top1_agree_logit", "top1 agree (logit)"), + ("snr_prob", "SNRcorr (prob, per anchor)"), + ("rep_spearman_prob", "rep spearman (prob)"), + ("rep_spearman_logit", "rep spearman (logit)")] + out = {"ref": a.ref, "ref_beta": ref["args"].get("beta"), "repeats": R, "cmp": []} + + hdr = (f"{'cell':<20} {'beta':>6} {'statistic':<28} {'ref':>8} {'this':>8} " + f"{'dmean':>8} {'bootCI95':>18} {'wilcox_p':>10} {'unpaired_se':>12}") + print("\n" + hdr) + print("-" * len(hdr)) + + for c in cells: + if c == a.ref: + continue + d = load(os.path.join(a.dir, c)) + rows = d["rows"] + Rc = int(d["args"].get("repeats", 1)) + # ---- ASSERTION: the rows must be the SAME anchors, in the same order ---- + if len(rows) != len(refrows): + raise SystemExit(f"FAIL {c}: n_anchors {len(rows)} != reference {len(refrows)} " + f"-- these cells are NOT pairable; do not pair them.") + ks = [key(r) for r in rows] + bad = [(i, refkeys[i], ks[i]) for i in range(len(ks)) if ks[i] != refkeys[i]] + if bad: + raise SystemExit(f"FAIL {c}: {len(bad)} anchor positions differ from the reference, " + f"first={bad[0]} -- pairing these rows would be wrong.") + if Rc != R: + raise SystemExit(f"FAIL {c}: repeats={Rc} != reference {R}; the 1/R bias " + f"correction and the top-1 pair count would not be comparable.") + beta = d["args"].get("beta") + for fld, lab in stats: + if fld not in rows[0] or fld not in refrows[0]: + continue + x = np.array([r[fld] for r in refrows], float) + y = np.array([r[fld] for r in rows], float) + if fld.startswith("snr_"): # per-anchor bias correction + x, y = x - 1.0 / R, y - 1.0 / R + dif = y - x + lo, hi = boot_ci(dif) + try: + p = float(wilcoxon(y, x, zero_method="wilcox").pvalue) + except ValueError: # all differences zero + p = 1.0 + # unpaired se of the difference of means, for contrast with the paired CI + use = float(np.sqrt(x.var(ddof=1) / len(x) + y.var(ddof=1) / len(y))) + print(f"{c:<20} {beta:>6.3f} {lab:<28} {x.mean():>8.3f} {y.mean():>8.3f} " + f"{dif.mean():>8.3f} [{lo:>7.3f},{hi:>7.3f}] {p:>10.2e} {use:>12.3f}") + out["cmp"].append({"cell": c, "beta": beta, "stat": fld, + "ref_mean": float(x.mean()), "mean": float(y.mean()), + "dmean": float(dif.mean()), "boot_lo": lo, "boot_hi": hi, + "wilcoxon_p": p, "unpaired_se": use, "n": len(dif)}) + print("-" * len(hdr)) + + print("\nPAIRED: every cell above was checked anchor-by-anchor against the reference on " + "(ep, t, stage);\na mismatch is a hard exit, not a warning. dmean < 0 means the cell is " + "WORSE than the deployed\nbeta 0.99 on that statistic. Compare bootCI95 (paired) against " + "unpaired_se: where the paired CI\nexcludes 0 but the difference is within ~2 unpaired se, " + "the pairing is what made the call.") + json.dump(out, open(a.out, "w"), indent=1) + print(f"\nwrote {a.out} ({len(out['cmp'])} comparisons)") + + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/real/beta_regime_audit.py b/rsm_rise/scripts/real/beta_regime_audit.py new file mode 100644 index 0000000000000000000000000000000000000000..908fb93b82029fa5d779dc8825ae77ccbdd10fd8 --- /dev/null +++ b/rsm_rise/scripts/real/beta_regime_audit.py @@ -0,0 +1,106 @@ +#!/usr/bin/env python +"""What conditioning beta does the trainer ACTUALLY present, and over what band? + +Run 3 measured the real successor's implied_k(beta) as FLAT AT ZERO over beta 0.80-0.999 while +every sim successor is monotone. Reading the checkpoints' own stored configs then showed the two +were not trained in the same beta regime at all: + + real R_M beta_lo 0.95 beta_hi 0.99 beta_trunc_eps 0.02 (per-anchor cap ON) + sim two_piece/mug M beta_lo 0.90 beta_hi 0.995 (no beta_trunc_eps key -- pre-#262, no cap) + +data.py:442-446 caps each anchor: L = hi - t; beta_hi_eff = clip(eps**(1/L), beta_lo, beta_hi); +beta = beta_lo + U * (beta_hi_eff - beta_lo). So when eps**(1/L) <= beta_lo the band collapses to +a POINT and that anchor is trained at beta = beta_lo exactly. This quantifies how often that +happens, using the dataset's OWN train/val split rather than a re-derived one. + +Three regimes per corpus, so the config and the corpus are separated: + as_trained -- the config stored in that cell's own checkpoint + real_cfg -- 0.95/0.99 + cap 0.02 (what the real cell got) + sim_cfg -- 0.90/0.995 + no cap (what the sim cells got) +""" +from __future__ import annotations +import argparse, json, sys +import numpy as np + +ROOT = "/proj/dmfexp/zwhong/rsm_rise" +sys.path.insert(0, "/proj/dmfexp/zwhong/projs/issue_resolver_richardrl/gen_q_rsm/rsm_libero") + + +def regime(ep_from, ep_to, ep_len, train_eps, beta_lo, beta_hi, eps, n, seed): + """Replicate data.py::sample's anchor draw and beta draw exactly (data.py:427-446).""" + rng = np.random.default_rng(seed) + w = ep_len[train_eps].astype(np.float64); w /= w.sum() + e = rng.choice(train_eps, size=n, p=w) + lo, hi = ep_from[e], ep_to[e] + t = lo + (rng.random(n) * (hi - lo)).astype(np.int64) + L = np.maximum(hi - t, 1).astype(np.float64) + if eps is None: # pre-#262: no cap at all + beta_hi_eff = np.full(n, float(beta_hi)) + else: + beta_hi_eff = np.clip(np.power(eps, 1.0 / L), beta_lo, beta_hi) + beta = beta_lo + rng.random(n) * (beta_hi_eff - beta_lo) + width = beta_hi_eff - beta_lo + # realised horizon: mean of Geom(1-beta) truncated at L + with np.errstate(over="ignore", invalid="ignore"): + b = np.clip(beta, 1e-9, 1 - 1e-12) + bl = np.power(b, L) + ek = b / (1 - b) - L * bl / (1 - bl + 1e-300) + ek = np.nan_to_num(ek, nan=0.0, posinf=0.0) + # the L at which the cap first reaches beta_lo / beta_hi + L_lo = float(np.log(eps) / np.log(beta_lo)) if eps is not None else 0.0 + L_hi = float(np.log(eps) / np.log(beta_hi)) if eps is not None else 0.0 + q = lambda a, p: float(np.percentile(a, p)) + return {"beta_lo": beta_lo, "beta_hi": beta_hi, "beta_trunc_eps": eps, "n_draws": n, + "L_needed_for_any_band": L_lo, "L_needed_for_full_band": L_hi, + "frac_band_collapsed_to_point": float((width <= 1e-12).mean()), + "frac_full_band": float((beta_hi_eff >= beta_hi - 1e-12).mean()), + "mean_band_width": float(width.mean()), "nominal_band_width": float(beta_hi - beta_lo), + "band_width_frac_of_nominal": float(width.mean() / max(beta_hi - beta_lo, 1e-12)), + "beta_mean": float(beta.mean()), "beta_p50": q(beta, 50), "beta_p90": q(beta, 90), + "beta_p99": q(beta, 99), "beta_max": float(beta.max()), + "frac_beta_over_0.97": float((beta > 0.97).mean()), + "frac_beta_over_0.99": float((beta > 0.99).mean()), + "Ek_mean": float(ek.mean()), "Ek_p50": q(ek, 50), "Ek_p90": q(ek, 90), + "Ek_p99": q(ek, 99), + "remaining_L_p10": q(L, 10), "remaining_L_p50": q(L, 50), "remaining_L_p90": q(L, 90)} + + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--cells", default="real_cooking_v5:0.95:0.99:0.02," + "two_piece_expert_suboptimal:0.90:0.995:none," + "mug_expert_suboptimal:0.90:0.995:none," + "square_expert_suboptimal:0.90:0.995:none") + ap.add_argument("--n", type=int, default=2_000_000) + ap.add_argument("--seed", type=int, default=0) + ap.add_argument("--out", required=True) + a = ap.parse_args() + from data import LiberoRSMData + out = {} + for spec in a.cells.split(","): + name, blo, bhi, e = spec.split(":") + blo, bhi = float(blo), float(bhi) + e = None if e == "none" else float(e) + ds = LiberoRSMData(f"{ROOT}/cache/{name}", in_ram=False) + args_ = (ds.ep_from, ds.ep_to, ds.ep_len, ds.train_eps) + cell = {"n_ep": int(ds.n_ep), "n_train_ep": int(len(ds.train_eps)), + "n_frames": int(ds.ep_to[-1]), + "ep_len_p10": float(np.percentile(ds.ep_len, 10)), + "ep_len_p50": float(np.percentile(ds.ep_len, 50)), + "ep_len_p90": float(np.percentile(ds.ep_len, 90))} + for tag, (bl, bh, ee) in {"as_trained": (blo, bhi, e), + "real_cfg": (0.95, 0.99, 0.02), + "sim_cfg": (0.90, 0.995, None)}.items(): + cell[tag] = regime(*args_, bl, bh, ee, a.n, a.seed) + r = cell[tag] + print(f"[{name:32s} {tag:10s}] band {bl}-{bh} eps={ee} " + f"collapsed_to_point {r['frac_band_collapsed_to_point']:.4f} " + f"full_band {r['frac_full_band']:.4f} " + f"mean_width {r['mean_band_width']:.5f} ({r['band_width_frac_of_nominal']:.3f} of " + f"nominal) beta p50 {r['beta_p50']:.4f} p99 {r['beta_p99']:.4f} " + f"E[k] p50 {r['Ek_p50']:.1f} p90 {r['Ek_p90']:.1f}", flush=True) + out[name] = cell + del ds + with open(a.out, "w") as f: + json.dump(out, f, indent=1) + print(f"[wrote] {a.out}", flush=True) diff --git a/rsm_rise/scripts/real/betaswp_table.py b/rsm_rise/scripts/real/betaswp_table.py new file mode 100644 index 0000000000000000000000000000000000000000..1230ebd1e3df59f405d1cfce78dcd470f264a722 --- /dev/null +++ b/rsm_rise/scripts/real/betaswp_table.py @@ -0,0 +1,40 @@ +#!/usr/bin/env python3 +"""Build the implied_k(beta) table across cells from status/real/succdebug/betaswp_*.json. + +Pure JSON reader (no torch, no cache): safe to run on the login node. One row per (cell, beta): + impl_k = median offset, inside the anchor's own episode, of the nearest TRAIN frame to a sample + true_k = median of the logged k the trainer would have drawn at that beta + ratio = impl_k / true_k -- the horizon realisation, the discriminating number of run 2/3 + neg = fraction of samples whose nearest train frame is in the anchor's PAST + nn_* = global nearest-neighbour distance over the whole train corpus, with its own brackets +""" +import json, sys, glob, os + +O = "/proj/dmfexp/zwhong/rsm_rise/status/real/succdebug" +sel = sys.argv[1:] or None + +def load(p): + try: + with open(p) as f: + return json.load(f) + except Exception as e: + return None + +files = sorted(glob.glob(f"{O}/betaswp_*.json")) +print(f"{'cell':<28}{'beta':>7}{'impl_k':>8}{'true_k':>8}{'ratio':>7}{'neg':>6}" + f"{'own_ep':>8}{'nn_mod':>8}{'nn_ora':>8}{'nn_shuf':>8}{'admit':>7}") +for p in files: + name = os.path.basename(p)[len("betaswp_"):-len(".json")] + if sel and not any(s in name for s in sel): + continue + d = load(p) + if d is None: + print(f"{name:<28} (unreadable / still being written)") + continue + for r in d["rows"]: + ik, tk = r["impl_k_model_median_ownep"], r["true_k_median"] + ratio = (ik / tk) if tk else float("nan") + print(f"{name:<28}{r['beta']:>7.3f}{ik:>8.1f}{tk:>8.1f}{ratio:>7.2f}" + f"{r['impl_k_negative_frac_ownep']:>6.2f}{r['own_ep_model']:>8.3f}" + f"{r['nn_model']:>8.4f}{r['nn_oracle']:>8.4f}{r['nn_shuf']:>8.4f}" + f"{r['admit_frac']:>7.3f}") diff --git a/rsm_rise/scripts/real/build_2x2_table.py b/rsm_rise/scripts/real/build_2x2_table.py new file mode 100644 index 0000000000000000000000000000000000000000..09b11261f068df920ee70ff01e33500dbc1a14c7 --- /dev/null +++ b/rsm_rise/scripts/real/build_2x2_table.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +"""Collect the D3 (stitch-feasibility) numbers for the crossed v5 2x2 and its references into one +markdown + LaTeX table. Reads only json written by stitch_feasibility.py; no compute.""" +import json, os, sys +ROOT = "/proj/dmfexp/zwhong/rsm_rise" +S = f"{ROOT}/status/real" +DRAWS = [("12345", f"{S}/STITCH_FEASIBILITY_2x2_seed12345.json"), + ("777", f"{S}/STITCH_FEASIBILITY_2x2_seed777.json"), + ("999", f"{S}/STITCH_FEASIBILITY_2x2_seed999.json")] +ORDER = ["ft_v5", "ft_v5_x10", "ft_v5_x01", "ft_v5_s1", "shipped_R_M", "shipped_R_M_s1", "scratch_v0"] +LABEL = {"ft_v5": "ft_v5 (trunk s0 x rng s0)", "ft_v5_x10": "ft_v5_x10 (trunk s0 x rng s1)", + "ft_v5_x01": "ft_v5_x01 (trunk s1 x rng s0)", "ft_v5_s1": "ft_v5_s1 (trunk s1 x rng s1)", + "shipped_R_M": "R_M shipped (provenance, no ft)", "shipped_R_M_s1": "R_M_s1 shipped", + "scratch_v0": "R_RW_v0 from scratch (dataset rule)"} +rows = {} +for name, path in DRAWS: + if not os.path.exists(path): + print(f"[2x2] MISSING {path}", file=sys.stderr); continue + d = json.load(open(path)) + for h, v in d["heads"].items(): + rows.setdefault(h, {})[name] = v +present = [h for h in ORDER if h in rows] + [h for h in rows if h not in ORDER] +def fmt(v, k): return "--" if v is None else f"{v[k]:.3f}" +md = ["| head | draw | top1-rewarded | per-anchor AUC | frac anchors >0.5 | pooled AUC |", + "|---|---|---|---|---|---|"] +for h in present: + for name, _ in DRAWS: + v = rows[h].get(name) + if v is None: continue + md.append(f"| {LABEL.get(h,h)} | {name} | {fmt(v,'top1_rewarded_frac')} | " + f"{fmt(v,'auc_per_anchor_mean')} | {fmt(v,'auc_per_anchor_frac_above_0.5')} | " + f"{fmt(v,'auc_pooled')} |") +open(f"{S}/D3_2x2_table.md", "w").write("\n".join(md) + "\n") +tex = [r"\begin{tabular}{lrrrrr}\hline", + r"head & draw & top1-rew. & per-anchor AUC & frac$>$0.5 & pooled AUC\\\hline"] +for h in present: + for name, _ in DRAWS: + v = rows[h].get(name) + if v is None: continue + tex.append(f"{LABEL.get(h,h).replace('_',r'\_')} & {name} & {fmt(v,'top1_rewarded_frac')} & " + f"{fmt(v,'auc_per_anchor_mean')} & {fmt(v,'auc_per_anchor_frac_above_0.5')} & " + f"{fmt(v,'auc_pooled')}\\\\") +tex.append(r"\hline\end{tabular}") +open(f"{ROOT}/docs/tex/_d3_2x2.tex", "w").write("\n".join(tex) + "\n") +print("\n".join(md)) diff --git a/rsm_rise/scripts/real/build_actcond_table.py b/rsm_rise/scripts/real/build_actcond_table.py new file mode 100644 index 0000000000000000000000000000000000000000..7dbcd8f5a130d7460b44f7f635cb0315cd029cf9 --- /dev/null +++ b/rsm_rise/scripts/real/build_actcond_table.py @@ -0,0 +1,69 @@ +"""Aggregate the act_sensitivity shards into one table (ACT_COND, gen_q#278). + +The index is a RATIO of variances, so the pooled number is the ratio of the POOLED variances; the +median of the per-anchor ratios is printed beside it because a handful of anchors sit at a near-zero +state variance and dominate any mean of ratios. +""" +import glob, json, sys, collections +import numpy as np + +pat = sys.argv[1] if len(sys.argv) > 1 else \ + "/proj/dmfexp/zwhong/rsm_rise/status/real/ACT_COND/act_sensitivity_chain_v2_s*.json" +out = sys.argv[2] if len(sys.argv) > 2 else \ + "/proj/dmfexp/zwhong/rsm_rise/status/real/ACT_COND/ACT_SENSITIVITY.json" +rows = [] +for f in sorted(glob.glob(pat)): + j = json.load(open(f)) + rows += j["rows"] + args = j["args"] +print(f"{len(rows)} anchors from {len(glob.glob(pat))} shards") + + +def agg(sub, kind): + va = np.array([r[f"var_a_{kind}"] for r in sub]); vs = np.array([r[f"var_s_{kind}"] for r in sub]) + asi = np.array([r[f"asi_{kind}"] for r in sub]) + sp = np.array([r[f"spearman_{kind}"] for r in sub]) + tie = np.array([r[f"tie_frac_{kind}"] for r in sub]); cv = np.array([r[f"cv_{kind}"] for r in sub]) + goal = [r for r in sub if r["route"] == "2->3->4"] + return {"n": len(sub), "n_goal_route": len(goal), + "asi_pooled": float(va.mean() / max(vs.mean(), 1e-30)), + "asi_median": float(np.median(asi)), + "asi_q25": float(np.quantile(asi, .25)), "asi_q75": float(np.quantile(asi, .75)), + "var_a_mean": float(va.mean()), "var_s_mean": float(vs.mean()), + "spearman_mean": float(sp.mean()), "spearman_median": float(np.median(sp)), + "spearman_frac_le_-0.9": float((sp <= -0.9).mean()), + "spearman_by_probe_src": {s: {"n": int(sum(1 for r in sub if r["probe_src"] == s)), + "mean": float(np.mean([r[f"spearman_{kind}"] for r in sub + if r["probe_src"] == s]))} + for s in sorted({r["probe_src"] for r in sub})}, + "ties_at_max_mean": float(tie.mean() * args["n_cand"]), + "ties_at_max_max": float(tie.max() * args["n_cand"]), + "cv_mean": float(np.nanmean(cv)), + "rank_pct_mean": float(np.mean([r[f"rank_pct_{kind}"] for r in sub])), + "rank_pct_goal_route": (float(np.mean([r[f"rank_pct_{kind}"] for r in goal])) if goal else None)} + + +res = {"args": args, "n_anchors": len(rows), + "by_stage": {}, "pooled": {}, + "route_counts": dict(collections.Counter(r["route"] for r in rows)), + "probe_src_counts": dict(collections.Counter(r["probe_src"] for r in rows))} +for s in sorted({r["stage"] for r in rows}): + sub = [r for r in rows if r["stage"] == s] + res["by_stage"][f"S{s}"] = {k: agg(sub, k) for k in ("prob", "logit")} +res["pooled"] = {k: agg(rows, k) for k in ("prob", "logit")} +json.dump(res, open(out, "w"), indent=1) + +hdr = (f"{'stage':>7}{'read':>7}{'n':>5}{'ASI':>8}{'ASI_med':>9}{'[q25':>8}{'q75]':>8}" + f"{'var_a':>11}{'var_s':>11}{'rho':>7}{'rho<=-.9':>9}{'ties/128':>10}{'CV':>10}{'rankpct':>9}") +print(hdr); print("-" * len(hdr)) +for scope in list(res["by_stage"]) + ["POOLED"]: + z = res["by_stage"].get(scope, res["pooled"]) + for kind in ("prob", "logit"): + v = z[kind] + rp = v["rank_pct_goal_route"] + print(f"{scope:>7}{kind:>7}{v['n']:>5}{v['asi_pooled']:>8.3f}{v['asi_median']:>9.3f}" + f"{v['asi_q25']:>8.3f}{v['asi_q75']:>8.3f}{v['var_a_mean']:>11.3e}{v['var_s_mean']:>11.3e}" + f"{v['spearman_mean']:>7.2f}{v['spearman_frac_le_-0.9']:>9.2f}" + f"{v['ties_at_max_mean']:>10.2f}{v['cv_mean']:>10.2e}" + f"{(f'{rp:.3f}' if rp is not None else '-'):>9}") +print(f"\nroutes {res['route_counts']}\nprobe sources {res['probe_src_counts']}\nwrote {out}") diff --git a/rsm_rise/scripts/real/build_audit271_comment_run19.py b/rsm_rise/scripts/real/build_audit271_comment_run19.py new file mode 100644 index 0000000000000000000000000000000000000000..5c99b37fa80e53efe2bb732eeaf290591c4acb07 --- /dev/null +++ b/rsm_rise/scripts/real/build_audit271_comment_run19.py @@ -0,0 +1,64 @@ +#!/usr/bin/env python +"""gen_q #271, run 19 -- the housekeeping comment, every number read from JSON. + +Reads status/real/AUDIT271_RUN17.json (the no-drift audit) and AUDIT271_H3_SELFTEST.json (the negative +control for the widened check H3). Nothing here is typed by hand. +""" +import json, pathlib, re + +ST = pathlib.Path("/proj/dmfexp/zwhong/rsm_rise/status/real") +A = json.loads((ST / "AUDIT271_RUN17.json").read_text()) +S = json.loads((ST / "AUDIT271_H3_SELFTEST.json").read_text()) +C = A["checks"] + +npass = sum(1 for v in C.values() if v["ok"]) +head = A.get("clone_head", "")[:8] or re.search(r"HEAD=(\w+)", C["B_clone_in_sync"]["detail"]).group(1) +npages = int(re.search(r"and (\d+) pages", C["H_name_to_file_map"]["detail"]).group(1)) +nbad = re.search(r"bad=(\[.*\])", C["H_name_to_file_map"]["detail"]).group(1) +pairs = int(re.search(r"(\d+) file->label pairs", C["H_name_to_file_map"]["detail"]).group(1)) +b = A["baselines"] if isinstance(A.get("baselines"), dict) else {} +found = re.search(r"QUICKSTART\.md:\d+[^\"]*", S["detail"]) + +rows = "\n".join(f"| `{k}` | {'PASS' if v['ok'] else '**FAIL**'} | {v['detail'][:150]} |" + for k, v in C.items()) + +print(f"""### Housekeeping, not a measurement: the delivery state re-verified today ({npass}/{len(C)}), and the name→file guard widened to the pages it was missing + +No new measurement, no GPU, and **nothing in the shipped defaults moved**: `rsm_reward: A`, +`rsm_reward_stitching_best: null`, the same eight reward heads on the hub. + +**1. The audit passes {npass}/{len(C)}.** The shared `rsm_real` clone had moved again since the last +run (HEAD now `{head}`), which is why this is re-established from the sources rather than asserted. +The two new commits touch `QUICKSTART.md`'s timing table only — no reward-head claim — and every +check that guards this issue's deliverables still passes: + +| check | | detail | +|---|---|---| +{rows} + +**2. One real gap, in the guard rather than in the artefacts.** Check `H` (added last run, after the +canonical reward names were found attached to the wrong checkpoint files) scanned `rise_stack/*.md` +and the HF model card. It did **not** scan the clone's **root** pages — `QUICKSTART.md`, `README.md` — +even though those are the same class of page: they tell a reader which file to download, they are +edited by another stream, and `QUICKSTART.md` is exactly what the newest commits touched. H now covers +them: {pairs} file→label pairs against **{npages} pages**, `bad={nbad}`. The root pages are clean today; +the point is that they are now checked. + +**3. The widened check is proven able to fail, not just to pass.** A glob that silently matched nothing +would also have reported `bad=[]`. So a negative control (`scripts/real/_audit271_H3_selftest.py`) +points the audit at a throwaway tree — the real `rise_stack` symlinked, the shared clone never written +to — holding a synthetic root page with the run-18 bug's exact shape: a line naming `EXPERT_EPISODE` +next to `successor_rsm_real_A_110000.pt`, which carries `GOAL_SEGMENT`. The check fails on it and names +the page: + +> {found.group(0) if found else S['detail'][:200]} + +and it does **not** flag a truthful line on the same tree that names the label the file actually +carries. Verdict `{"PASS" if S["ok"] else "FAIL"}`, `failures={S["failures"]}`. + +**What is still open, and is not mine to close.** `default_for_planning: GOAL_EPISODE` in +`reward_names.json` still contradicts `baselines.yaml`'s `rsm_reward: A`. Unchanged from last run: +neither is supported by a measurement here (five-draw stitching at hop 4 — `A` 0.4941 ± 0.0139, 2/5 +draws above chance; `GOAL_EPISODE` 0.4864 ± 0.0103, 0/5; both at or below the un-fine-tuned base head's +0.4872, and no head beats the permuted control on the open-loop screen), so it is a choice between two +labels and the owner's call. Only the file map was ever corrected, and it stays correct.""") diff --git a/rsm_rise/scripts/real/build_audit271_comment_run20.py b/rsm_rise/scripts/real/build_audit271_comment_run20.py new file mode 100644 index 0000000000000000000000000000000000000000..046003d384ac5a06df8cc06b331f58ecf68c6503 --- /dev/null +++ b/rsm_rise/scripts/real/build_audit271_comment_run20.py @@ -0,0 +1,75 @@ +#!/usr/bin/env python +"""gen_q #271, run 20 -- the housekeeping comment, every number read from JSON. + +Reads status/real/AUDIT271_RUN17.json (the no-drift audit, now 9 checks) and +status/real/AUDIT271_I_SELFTEST.json (the negative control for the new check I). Nothing typed. +""" +import json, pathlib, re + +ST = pathlib.Path("/proj/dmfexp/zwhong/rsm_rise/status/real") +A = json.loads((ST / "AUDIT271_RUN17.json").read_text()) +S = json.loads((ST / "AUDIT271_I_SELFTEST.json").read_text()) +C = A["checks"] + +npass = sum(1 for v in C.values() if v["ok"]) +head = A.get("clone_head", "")[:8] +I = C["I_hub_bytes_match_source"]["detail"] +nheads = int(re.search(r"(\d+) live reward heads hashed", I).group(1)) +nident = int(re.search(r"(\d+) identical", I).group(1)) +rows_ct = len(A.get("hub_content_rows", [])) +tbytes = sum(r.get("bytes") or 0 for r in A.get("hub_content_rows", [])) +swap = S["detail"] +swap_msg = re.search(r"mismatches=\['([^']*)'\]", swap) +swap_msg = swap_msg.group(1) if swap_msg else swap +import datetime +lastsha = datetime.datetime.fromtimestamp((ST / "hf_sha.json").stat().st_mtime).strftime("%Y-%m-%d %H:%M") + +rows = "\n".join(f"| `{k}` | {'PASS' if v['ok'] else '**FAIL**'} | {v['detail'][:150]} |" + for k, v in C.items()) +content = "\n".join( + f"| `{r['path']}` | `{pathlib.Path(r['src']).parent.name}/{pathlib.Path(r['src']).name}` | " + f"`{r['hub_sha256'][:16]}…` | {'identical' if r['match'] else '**MISMATCH**'} |" + for r in A.get("hub_content_rows", [])) + +print(f"""### Housekeeping, not a measurement: what is on the hub is now checked by its **bytes**, not only by its name — and the new check is proven able to fail + +No new measurement, no GPU, and **nothing in the shipped defaults moved**: `rsm_reward: A`, +`rsm_reward_stitching_best: null`, the same eight reward heads on the hub. + +**1. The audit passes {npass}/{len(C)}.** The shared `rsm_real` clone had moved again (HEAD now +`{head}`); the one new commit rewrites `QUICKSTART.md`'s decision-latency caveat into a 1.1–20.4 s +range and makes no reward-head claim, so nothing this issue delivers is affected. + +| check | | detail | +|---|---|---| +{rows} + +**2. The gap this run closes: every existing check reasons about NAMES.** `D` matches the hub tree +against the table, `H` matches the canonical names against the uploader and the pages — but none of +them reads a byte of what a reader actually downloads. A re-upload from the wrong source, a truncated +transfer or a later overwrite would leave all eight checks green while the file called +`successor_rsm_real_A_110000.pt` held some other reward's head. That is the run-18 bug one level down, +and until now it was only checked when someone ran `scripts/real/hf_verify_sha.py` by hand (last time: +{lastsha}). + +New check **`I_hub_bytes_match_source`**: the hub's LFS `sha256` (HF stores the sha256 of the contents +as the object id) against `hashlib` over the cluster checkpoint that `scripts/real/hf_upload.py` names +as that head's source. **{nident}/{nheads} identical**, {tbytes/1e6:.0f} MB hashed, every audit from now on: + +| hub file | cluster source | sha256 | | +|---|---|---|---| +{content} + +**3. A passing check is not a working check** — so, per the rule this stream adopted last run, the +negative control ships in the same run. `scripts/real/_audit271_I_selftest.py` repoints +`hf_upload.REWARD_HEADS` at a two-entry map: one truthful head, and one head pointed at a **different +reward's checkpoint of the same size** (`R_M_ft_B`). Nothing is uploaded and the hub is never touched. +Four assertions, all met (`status/real/AUDIT271_I_SELFTEST.json`, `ok={str(S['ok']).lower()}`): +check I returns `ok=False`; its message names the swapped file (`{swap_msg}`); the swapped row hashes +to a mismatch; and the truthful head still verifies, so it is the swap that is caught and not the pair. + +**4. Still not mine to resolve, and unchanged:** `reward_names.json`'s `default_for_planning: +GOAL_EPISODE` vs `baselines.yaml`'s `rsm_reward: A`. Neither is supported by a measurement here — +hop-4 five-draw stitching `A` 0.4941 ± 0.0139 (2/5 draws above chance), `GOAL_EPISODE` 0.4864 ± 0.0103 +(0/5), both at or below the un-fine-tuned base head's 0.4872, and no head beats the permuted control on +the open-loop screen. It is a choice between two labels and it stays the owner's.""") diff --git a/rsm_rise/scripts/real/build_aug_knn.py b/rsm_rise/scripts/real/build_aug_knn.py new file mode 100644 index 0000000000000000000000000000000000000000..489cce1bbdaefde5458a76a66a390e1748fd66b0 --- /dev/null +++ b/rsm_rise/scripts/real/build_aug_knn.py @@ -0,0 +1,135 @@ +"""Build the RISE state-space kNN neighbour table the successor's --action-augment flag consumes +(stream AUG_SUCC, gen_q#279). + +RISE's `build_state_augmentation_data` (code/rise_robomimic/robomimic/utils/dataset.py) finds, for each +state i, the `num_neighbors` nearest states j from a DIFFERENT trajectory within `distance_threshold`. +With image observations its metric is a flattened VISUAL FEATURE vector (`_extract_state_for_distance`), +so the faithful analogue here is the successor's own normalised 1546-d DINO+proprio state. + +This script emits the table ONCE, uncapped by any threshold (distances are stored), so a whole threshold +sweep reads the same file and the kNN cost is paid once rather than per training run. + + --metric feat L2 in x = clip((f - mu)/sd, -z_clip, z_clip), the exact state data.py._feat builds + --metric ee L2 in [xyz (m), rot_scale * rot6d], the metric scripts/real/build_knn_pairs_ee.py + ships for the real kNN (so RISE's distance_threshold 0.15 is in these units) + +ONLY TRAIN-SPLIT episodes are used, as anchors AND as neighbours: an augmented pair that reaches into the +validation split would leak the held-out episodes into training through the action channel. + +Output npz: + rows [M] int32 global cache row of each anchor (train frames only) + nbr_row [M, K] int32 global cache row of the k-th nearest DIFFERENT-EPISODE neighbour + nbr_dist [M, K] float32 + metric, K, rot_scale, z_clip, n_train_eps +CPU only. +""" +import argparse, json, time +import numpy as np + +ROOT = "/proj/dmfexp/zwhong/rsm_rise" +ROT_SCALE = 0.05 + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--cache", default=f"{ROOT}/cache/real_cooking_v5") + ap.add_argument("--feat-stats", default="") + ap.add_argument("--metric", default="feat", choices=("feat", "ee")) + ap.add_argument("--k", type=int, default=32) + ap.add_argument("--tile", type=int, default=2048) + ap.add_argument("--val-frac", type=float, default=0.1) + ap.add_argument("--seed", type=int, default=0) + ap.add_argument("--stratify-success", type=int, default=0, + help="must match the training run's --stratify-success so the train split is the SAME") + ap.add_argument("--val-eps-json", default="", + help="must match the training run's --val-eps-json (split=='valid' eps excluded from query+neighbours)") + ap.add_argument("--out", required=True) + a = ap.parse_args() + from pathlib import Path + cache = Path(a.cache) + stats = a.feat_stats or str(cache / "feat_stats.npz") + m = np.load(cache / "meta.npz", allow_pickle=True) + zf = np.load(cache / "z.f16.npy", mmap_mode="r") + pf = np.load(cache / "proprio.f32.npy", mmap_mode="r") + ep_from, ep_to, ep_len = m["ep_from"], m["ep_to"], m["ep_len"] + ep_success = m["ep_success"] + n_ep = len(ep_len); N = int(ep_to[-1]) + + # ---- the SAME episode split data.py builds (data.py: rng = default_rng(seed) then permutation) ---- + rng = np.random.default_rng(a.seed) + n_val = max(1, int(a.val_frac * n_ep)) + if a.stratify_success: + s = np.asarray(ep_success, bool); parts = [] + for grp in (np.nonzero(s)[0], np.nonzero(~s)[0]): + if len(grp) == 0: + continue + pg = grp[rng.permutation(len(grp))] + kk = max(1, int(round(a.val_frac * len(grp)))) if len(grp) > 1 else 0 + parts.append(pg[:kk]) + val_eps = np.sort(np.concatenate(parts)) if parts else np.array([], np.int64) + train_eps = np.sort(np.setdiff1d(np.arange(n_ep), val_eps)) + else: + perm = rng.permutation(n_ep) + val_eps = np.sort(perm[:n_val]); train_eps = np.sort(perm[n_val:]) + if a.val_eps_json: # same override as data.py LiberoRSMData(val_eps_json=...) + sp = json.load(open(a.val_eps_json))["episodes"] + assert len(sp) == n_ep and all(int(sp[str(i)]["length"]) == int(ep_len[i]) for i in range(n_ep)) + val_eps = np.array(sorted(i for i in range(n_ep) if sp[str(i)]["split"] == "valid"), np.int64) + train_eps = np.sort(np.setdiff1d(np.arange(n_ep), val_eps)) + print(f"[knn] split: {len(train_eps)} train / {len(val_eps)} val episodes " + f"(stratify={a.stratify_success}, seed={a.seed})", flush=True) + + rows = np.concatenate([np.arange(int(ep_from[e]), int(ep_to[e])) for e in train_eps]).astype(np.int64) + epid = np.concatenate([np.full(int(ep_to[e]) - int(ep_from[e]), e) for e in train_eps]).astype(np.int32) + M = len(rows) + print(f"[knn] {M} train frames of {N} total", flush=True) + + # ---- the metric ---- + if a.metric == "feat": + st = np.load(stats) + D = zf.shape[1] + pf.shape[1] + mu, sd = st["mu"][:D].astype(np.float32), st["sd"][:D].astype(np.float32) + zclip = float(st["z_clip"]) if "z_clip" in st else 10.0 + X = np.empty((M, D), np.float32) + for i in range(0, M, 20000): + j = min(i + 20000, M); r = rows[i:j] + X[i:j] = np.clip((np.concatenate([np.asarray(zf[r], np.float32), + np.asarray(pf[r], np.float32)], 1) - mu) / sd, -zclip, zclip) + else: + zclip = 0.0 + P = np.asarray(pf[rows], np.float32) + X = np.concatenate([P[:, :3], ROT_SCALE * P[:, 3:9]], 1).astype(np.float32) + D = X.shape[1] + print(f"[knn] metric={a.metric} dim={D} X={X.nbytes/1e9:.2f} GB", flush=True) + + Xsq = (X ** 2).sum(1, dtype=np.float32) + K = a.k + nbr_row = np.zeros((M, K), np.int32); nbr_dist = np.zeros((M, K), np.float32) + t0 = time.time() + for i in range(0, M, a.tile): + j = min(i + a.tile, M) + d2 = Xsq[i:j, None] + Xsq[None, :] - 2.0 * (X[i:j] @ X.T) + np.maximum(d2, 0, out=d2) + # RISE: different trajectory only, and skip self (implied by the episode mask) + d2[epid[i:j][:, None] == epid[None, :]] = np.inf + idx = np.argpartition(d2, K, axis=1)[:, :K] + dd = np.take_along_axis(d2, idx, 1) + o = np.argsort(dd, 1) + idx = np.take_along_axis(idx, o, 1); dd = np.take_along_axis(dd, o, 1) + nbr_row[i:j] = rows[idx]; nbr_dist[i:j] = np.sqrt(dd) + if (i // a.tile) % 10 == 0: + el = time.time() - t0 + print(f"[knn] {j}/{M} {el:.0f}s elapsed, eta {el*(M-j)/max(j,1):.0f}s", flush=True) + np.savez_compressed(a.out, rows=rows.astype(np.int32), nbr_row=nbr_row, nbr_dist=nbr_dist, + metric=a.metric, K=K, rot_scale=ROT_SCALE, z_clip=zclip, + train_eps=train_eps.astype(np.int32), val_eps=val_eps.astype(np.int32), + stratify_success=int(a.stratify_success), seed=a.seed, val_frac=a.val_frac) + q = lambda p: float(np.percentile(nbr_dist[:, 0], p)) + print(f"[knn] wrote {a.out}\n[knn] 1st-neighbour distance percentiles: " + + " ".join(f"p{p}={q(p):.4f}" for p in (1, 5, 25, 50, 75, 95, 99)), flush=True) + print(f"[knn] {K}th-neighbour: " + " ".join( + f"p{p}={float(np.percentile(nbr_dist[:, -1], p)):.4f}" for p in (1, 5, 25, 50, 75, 95, 99)), flush=True) + + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/real/build_cache.sh b/rsm_rise/scripts/real/build_cache.sh new file mode 100644 index 0000000000000000000000000000000000000000..7abd585b7d82c6a51a386f273a3699ea431d5dd7 --- /dev/null +++ b/rsm_rise/scripts/real/build_cache.sh @@ -0,0 +1,12 @@ +#!/usr/bin/env bash +# GPU runner: DINOv2 cache for the real cooking corpus. +# usage: build_cache.sh +set -uo pipefail +ROOT=/proj/dmfexp/zwhong/rsm_rise +NAME="${1:-real_cooking_v5}"; CAMS="${2:-global,wrist}"; CROP="${3:-square}" +echo "[build] host=$(hostname) name=$NAME cams=$CAMS crop=$CROP $(date -u)" +nvidia-smi --query-gpu=name,memory.total --format=csv || true +export TORCH_HOME="${TORCH_HOME:-$HOME/.cache/torch}" +exec "$ROOT/venv_rsm/bin/python" "$ROOT/scripts/real/relabel_dino_lerobot.py" \ + --root "$ROOT/data/real/rsm_cooking_v5" --out "$ROOT/cache/$NAME" \ + --cams "$CAMS" --crop-mode "$CROP" --batch 256 --task-name "$NAME" diff --git a/rsm_rise/scripts/real/build_card271_run11.py b/rsm_rise/scripts/real/build_card271_run11.py new file mode 100644 index 0000000000000000000000000000000000000000..ff0200a607f495a8d10416877331f193a45c9993 --- /dev/null +++ b/rsm_rise/scripts/real/build_card271_run11.py @@ -0,0 +1,325 @@ +#!/usr/bin/env python +"""Insert/refresh the model card's section (1d): the decomposition + the five-draw correction. + +Generated from status/real/STITCH_DECOMP.json and STITCH_DRAWS.json, and idempotent (delimited by its +own HTML comment), for the standing reason in this study: a hand-typed number in the card drifted the +moment the measurement was rerun, and this one is expected to be rerun if a hop head ever exists. +The card is ASCII-only by convention (it renders in the HF widget), so no +- or arrow characters. +""" +from __future__ import annotations +import json +import numpy as _np +from pathlib import Path + +ROOT = Path("/proj/dmfexp/zwhong/rsm_rise") +CARD = ROOT / "status/real/HF_MODEL_CARD.md" +D = json.loads((ROOT / "status/real/STITCH_DECOMP.json").read_text()) +W = json.loads((ROOT / "status/real/STITCH_DRAWS.json").read_text()) +PUB = json.loads((ROOT / "status/real/REWARD_HEAD_DIAG_STITCH.json").read_text()) +HOPF = int(PUB.get("hop_frames", 0)) + +# cell name -> the name the published checkpoint carries on the Hub +HUB = {"B": "B_H100", "B_s1": "B_H100_s1", "B400": "B_H400", "B400_s1": "B_H400_s1"} +nm = lambda k: HUB.get(k, k) + +B4, B1 = D["by_hop"]["4"], D["by_hop"]["1"] +H = B4["heads"] +WB = W["by_hop"]["4"] + + +def m(v, k): + x = v.get(k) + return x.get("mean") if isinstance(x, dict) else x + + +sep, sat, inv = [], [], [] +for n, v in H.items(): + a = m(v, "auc_R_chain_per_anchor") + if max(m(v, "R_chain_goal") or 0.0, m(v, "R_chain_fail") or 0.0) < 0.01: + sat.append(n) + elif a is not None and a > 0.65: + sep.append(n) + elif a is not None and a < 0.35: + inv.append(n) +sep.sort(key=lambda n: -(m(H[n], "auc_R_chain_per_anchor") or 0)) +lst = lambda xs: ", ".join("`%s`" % nm(x) for x in xs) if xs else "none" +bk = sep[0] +lo = min(H, key=lambda n: m(H[n], "auc_R_retrieved_per_anchor") or 1.0) +sig = WB.get("heads_draw_level_significant") or [] +top = max(sig, key=lambda k: WB["heads"][k]["mean_over_draws"]) if sig else None +labs = WB["draw_labels"] +t = WB["heads"][top] if top else None + +FC = json.loads((ROOT / "status/real/FOLD4_COMPARE.json").read_text()) +F4, F2 = FC["by_hop"]["4"], FC["by_hop"].get("2", {}) +PC = FC["per_candidate"] +LVLO = min(v["mean_level_shift"] for v in PC.values()) +LVHI = max(v["mean_level_shift"] for v in PC.values()) +CMIN = min(v["mean_within_anchor_corr"] for v in PC.values()) +CMEAN = sum(v["mean_within_anchor_corr"] for v in PC.values()) / len(PC) + +SK = json.loads((ROOT / "status/real/SK_COMPARE.json").read_text()) +S4, S2 = SK["by_hop"]["4"], SK["by_hop"].get("2", {}) +SB, SS = SK["baseline"], SK["by_hop"]["4"]["summary"] +SKL = {"prob_T25": "`prob` / T = 25 (flagship)", "logit_T25": "`logit`", + "prob_log_T25": "`prob_log`", "prob_T1": "`prob` / T = 1", "prob_T100": "`prob` / T = 100"} +SOTH = [k for k in SS if k != SB] +SDMAX = max((SS[k]["max_abs_delta_vs_baseline"] or 0.0) for k in SOTH) +SDWHO = max(SOTH, key=lambda k: (SS[k]["max_abs_delta_vs_baseline"] or 0.0)) +SBEST = max(SS[k]["max"] for k in SS) +SBESTK = max(SS, key=lambda k: SS[k]["max"]) +SCEIL = S4.get("latent_ceiling") or {} +SCN = SCEIL.get("head") +SCQ = [v for v in ((S4["heads"].get(SCN, {}) or {}).get("Q") or {}).values() if v is not None] +BRACKET = ", ".join(SKL.get(k, k) for k in [SB] + sorted(SOTH)) +CTRL = ("controlled: every cell reproduces the published endpoints exactly" + if SK.get("controlled") else + "**NOT controlled** -- at least one cell's endpoints differ from the published draw") + + +blk = f""" +**(1d) WHERE the signal dies, and why no reward label could have satisfied this diagnostic.** Every head +separates real `S4` frames from real `S6` frames at AUC **1.000** (the first diagnostic above), yet the `Q` +it induces is at chance on chained candidates. `scripts/real/stitch_decompose.py` in rsm_rise -> +`status/real/STITCH_DECOMP.json` reads three quantities per candidate, on the published draw's own anchors +and its own candidates, with `Q` recomputed in the same process so that nothing rests on a cross-run +assumption (the replayed endpoint rows match the published ones at **{B4['endpoint_match_vs_published']:.3f}**): +`R(z_h)` at the chained latent; `R(x[nn(z_h)])` at the real cached frame the endpoint retrieves to -- the +ceiling, because that row's `edge_to` *is* the endpoint label; and `Q` itself. + +*The latent keeps the class; the read-out discards it.* {lst(sep)} read the chained latent at per-anchor +AUC **{m(H[bk], 'auc_R_chain_per_anchor'):.3f}** and above, on a real separation of means +({m(H[bk], 'R_chain_goal'):.3f} on GOAL-ending chains against {m(H[bk], 'R_chain_fail'):.3f} on FAIL-ending +ones for `{nm(bk)}`), **and the `Q` they induce is {m(H[bk], 'auc_Q_per_anchor_here'):.3f}, exactly +chance** (`corr(Q, R(z_h))` = {m(H[bk], 'corr_Q_Rchain'):.3f}). So the signal does not die off-manifold; it +dies in the fold. + +*And the read-out loses it because its horizon does not match the label's.* The read-out every number here +uses is depth 1 at beta = 0.99, so `Q` sees about one hop (~{HOPF} frames), while the endpoint class is +defined **four** hops out (~{4 * HOPF} frames). Of the two ways to widen that window, raising beta is +genuinely unavailable -- the flow was conditioned on beta in [0.95, 0.99], so beta = 0.99 already *is* the +longest horizon it was ever trained at -- but **deepening the fold is available**: a depth >= 2 read-out +needs a hop head, and although no *successor* blob embeds one, `rsm_hop_ckpt` is a **separate** checkpoint +argument and this repo publishes a hop head for exactly this corpus +(`hop_head_rsm_real_gauss_r1.pt`), already used by the fold-4 column of the open-loop screen. *(An earlier +revision of this card called that lever closed and concluded that no reward label could satisfy the +diagnostic; that is withdrawn.)* What stands regardless is the size of the mismatch: **at one hop there are +{B1['n_goal']} GOAL endpoints out of {B1['n_goal'] + B1['n_fail']:,} classified candidates.** Within the +horizon `Q` can see, no candidate drawn at the failure route's `S2` junction reaches a goal-bound segment +at all. So the depth-1 statistic was never a test of the reward labels; whether the schemes separate at +all is what the matched-horizon fold-4 read-out measures -- the closing paragraph below. + +*Two cautions that travel with the table.* {lst(sat)} are saturated **off** at the chained latent +(`R(z_h)` ~ 0 on *both* classes), so their AUCs out there rank numerical dust and must not be read as an +effect in either direction; {lst(inv)} by contrast is genuinely **inverted** +({m(H[inv[0]], 'R_chain_goal'):.3f} GOAL against {m(H[inv[0]], 'R_chain_fail'):.3f} FAIL). The chained +latent does sit **{B4['chain_min_l1_over_real_median']:.1f}x** a real frame's own nearest-neighbour L1 +distance away from the corpus, so the off-manifold story holds for the *majority* of heads even though it +does not explain the phenomenon. And the first diagnostic's ceiling has a crack worth carrying: `R` read at +the *retrieved real frame* is 1.000 for most heads but **{m(H[lo], 'auc_R_retrieved_per_anchor'):.3f}** for +`{nm(lo)}` and 0.75-0.85 for the whole `B` family. That diagnostic labels frames by `reached_state_id`; +these are frames labelled by `edge_to` at the endpoints the chains actually reach, and there the +horizon-window schemes are **not** at ceiling. + +*Correction to (1b).* (1b)'s redraw changed the anchor *stride*, which moves the anchor set as well as the +candidate draw, so its "surviving both: none" is a **confounded** replicate. The clean design -- identical +anchors and weights, only the seed of the draw changing -- is {len(labs)} independent draws +(`status/real/STITCH_DRAWS.json`): above 0.5 in **every** draw +{lst(WB.get('heads_above_half_in_every_draw') or [])}, draw-level significant {lst(sig)}.""" +if t: + blk += f""" The largest is **`{nm(top)}` at {t['mean_over_draws']:.4f}** (sd {t['sd_over_draws']:.4f}, +above 0.5 in {t['n_draws_above_half']}/{len(labs)} draws), and the published single-draw +**{t['per_draw'][labs[0]]:.4f} was the top of its range [{t['min']:.3f}, {t['max']:.3f}]** -- the luckiest +of the five.""" +blk += f""" + +*And widening the window does not rescue it: the matched-horizon read-out was measured.* A depth-4 fold +through this repo's own hop head (`hop_head_rsm_real_gauss_r1.pt`) gives a read-out whose horizon matches +the four-hop depth the endpoint class is defined at. Both runs reproduce the published candidate draw +exactly (endpoint match {F4['endpoint_match_d1']:.3f} and {F4['endpoint_match_fold4']:.3f}), so only the +read-out differs. Over the {F4['n_heads']} heads the within-anchor AUC moves by **rms +{F4['delta_rms']:.4f}**, max {F4['delta_max_abs']:+.4f} (`{F4['delta_max_abs_head']}`) -- below the ++-0.024 this design can resolve and below the ~0.005 that GPU non-determinism alone contributes. The fold +is not idle: the fold-4 `Q` level rises by +{LVLO:.3f} to +{LVHI:.3f} per head, but its within-anchor +correlation with the depth-1 `Q` is {CMIN:.3f}-1.000 (mean {CMEAN:.3f}) over all +{FC['n_anchors_compared']} anchors -- the extra hops add a common-mode offset, not candidate-specific +information, so the ordering survives untouched. **The horizon mismatch is therefore falsified as the +reason `Q` is at chance.** The endpoint class is in the latent and in the head at AUC 0.941 and *both* +read-outs discard it, which left the scoring functional (`prob` / T = 25) as the thing to vary next -- +not the reward labels and not the horizon. Numbers: `status/real/FOLD4_COMPARE.json` in rsm_rise.""" + +blk += """ So "no head clears chance" was too strong; averaged over draws the horizon-window heads clear +chance by about **+0.03**. Read with the paragraphs above, a +0.03 effect at a horizon where the endpoint +label is invisible to the read-out is a **weak leading indicator inside the first hop, not demonstrated +stitching** -- which is why nothing shipped here changes: **A** is still the default head and no head is +validated for selection. +""" + +blk += f""" +*And the scoring functional is not the culprit either.* That was the last degree of freedom left in the +read-out, and it had never been varied -- the decomposition hard-coded `score_kind="prob"` at the scorer. +Swept across its natural bracket ({BRACKET}) on identical anchors, candidates, chains and GOAL/FAIL +labels ({CTRL}), the result is **null**: the best within-anchor AUC anywhere in the sweep is {SBEST:.4f} +(`{nm(SS[SBESTK]["max_head"])}`, {SKL.get(SBESTK, SBESTK)}) against the flagship's own best of +{SS[SB]["max"]:.4f} -- a lift of {SBEST - SS[SB]["max"]:+.4f}, against a design resolution of +-0.024 and a +GPU-non-determinism floor of ~0.005. The largest per-head move any functional makes is {SDMAX:.4f} +(`{SDWHO}`), and that one moves the statistic *down* (its own best is {SS[SDWHO]["max"]:.4f}). The bracket +passes its own validity check: `prob` / T = 100 reproduces `logit` to 3--4 decimals, as the algebra +requires. **The decisive row is `{nm(SCN)}`** -- it reads the endpoint class at the chained latent at AUC +{SCEIL.get("auc_R_chain_per_anchor", float("nan")):.3f} while its `Q` stays {min(SCQ):.4f}--{max(SCQ):.4f} +under *all five* functionals. So three suspects are now excluded on identical candidates: the reward +label, the read-out horizon and the scoring functional. Numbers: `status/real/SK_COMPARE.json` in +rsm_rise. +""" + +# the fourth and last axis: the rollout the fold applies (run 15), from OL_COMPARE.json +OL = json.loads((ROOT / "status/real/OL_COMPARE.json").read_text()) +O4, OC = OL["by_hop"]["4"], OL["control"] +OH = O4["heads"] +OCL = max(OH, key=lambda k: OH[k]["auc_R_chain"]) +OV = OH[OCL] +blk += f""" +*Nor is it how the fold is rolled out -- and that closes the read-out.* The three variations above all +left one uncontrolled difference between `Q` and the GOAL/FAIL label it is scored against, and it is +structural rather than a matter of degree: they are values of two *different trajectories*. The label's +own rollout computes the candidate's action chunk once and re-applies that **same** chunk at every hop; +the fold re-samples the hop head between hops, so at depth four it estimates the value of *apply the +candidate once, then follow the hop head for three hops*. `--q-fold-openloop` repeats the candidate at +every hop, which is exactly the label's generating process (additive, default-off, a no-op at depth one, +and the regression smoke reproduces the pre-patch fold-4 cell bit-exactly). The control is asserted +array-by-array, because the chains, endpoints and labels are computed outside the scorer: {"**" + str(OC["chain_arrays_identical"]) + "/" + str(OC["chain_arrays_checked"]) + " chain arrays bit-identical**" if OL.get("controlled") else "**NOT identical -- the two cells are not the same experiment**"} over +{OC["anchors_compared"]}/150 anchors, endpoint match {O4["endpoint_match_closed"]:.3f} and {O4["endpoint_match_open"]:.3f}, with +{OC["q_arrays_that_moved"]}/{OC["q_arrays_compared"]} `Q` arrays moved. **The result is null:** the best within-anchor AUC goes from +{O4["best_closed_auc"]:.4f} (`{nm(O4["best_closed"])}`) to {O4["best_open_auc"]:.4f} (`{nm(O4["best_open"])}`), a lift of +{O4["lift"]:+.4f}; rms move {O4["delta_rms"]:.4f}, largest single move {O4["delta_max_abs"]:+.4f} (`{nm(O4["delta_max_abs_head"])}`), against +the same +-0.024 design resolution. The prediction was stated in advance and fails: `{nm(OCL)}`, which +reads the endpoint class at the chained latent at AUC {OV["auc_R_chain"]:.3f}, moves {OV["auc_Q_closed"]:.4f} -> {OV["auc_Q_open"]:.4f} +and its correlation with `R(z_h)` *falls* {OV["corr_Q_Rchain_closed"]:.3f} -> {OV["corr_Q_Rchain_open"]:.3f}. **So the read-out is +exonerated on all four axes.** The reason is worth stating precisely, because it is not *nothing can be +done*: `Q` is a discounted **occupancy of the reward set along the chain** while the label is the **class +of the endpoint at hop four**; matching the policy removes the trajectory mismatch, not the +functional-of-the-trajectory mismatch. What is left is what `Q` **is**, not how it is rolled out. Numbers: +`status/real/OL_COMPARE.json` in rsm_rise. +""" + +# ---- run 18: the canonical name <-> FILE map, generated from the two sources of truth ---------- +# rise_stack/configs/reward_names.json attached `successor_rsm_real_A_110000.pt` to the name +# GOAL_EPISODE (it is the GOAL_SEGMENT head) and the error spread to two of that repo's pages. It is +# fixed there (commit 6658581); this paragraph inoculates the hub-side artefact, where someone actually +# clicks download. Both columns are READ, never typed: the names/aliases from reward_names.json in the +# rsm_real clone, the file for each cell from scripts/real/hf_upload.py's REWARD_HEADS. +import importlib.util as _ilu +_spec = _ilu.spec_from_file_location( + "_hfu", "/proj/dmfexp/zwhong/rsm_rise/scripts/real/hf_upload.py") +_hfu = _ilu.module_from_spec(_spec); _spec.loader.exec_module(_hfu) +_file_of_cell = {src.parent.name: dst for _c, src, dst in _hfu.REWARD_HEADS} +_reg = json.loads(Path("/proj/dmfexp/zwhong/projs/rsm_real/rise_stack/configs/reward_names.json") + .read_text()) +_cells = {"GOAL_SEGMENT": "R_M_ft_v1", "GOAL_EPISODE": "R_M_ft_v0", "EXPERT_EPISODE": "R_M_ft_v0lit", + "GOAL_WINDOW_100": "R_M_ft_B", "GOAL_WINDOW_400": "R_M_ft_B400", + "GOAL_SEGMENT_CONTRASTIVE": "R_M_ft_C3"} +# what is actually on the hub, from the last verified tree listing (status/real/hf_tree.json is +# written by the sha/size verification job; the audit JSON is the fallback). +try: + _CARD_LIVE = {r["path"] for r in json.loads( + (Path("/proj/dmfexp/zwhong/rsm_rise/status/real/hf_tree.json")).read_text())["rows"]} +except Exception: + _CARD_LIVE = set(json.loads( + (Path("/proj/dmfexp/zwhong/rsm_rise/status/real/AUDIT271_RUN17.json")).read_text() + )["hub_reward_heads_live"]) +_rows = [] +for _n, _e in _reg["rewards"].items(): + _cell = _cells.get(_n) + if _cell is None: + continue + _f = _file_of_cell.get(_cell) + if _n == "GOAL_EPISODE": + _where = ("inside the base `successor_rsm_real_RM_s0_100k.pt` (`state_dict[\"rew\"]`); the " + "`R_M_ft_v0` fine-tune is trained, not uploaded") + elif _f in _CARD_LIVE: + _where = f"`{_f}`" + else: + _where = "trained, not uploaded" + _rows.append(f"| `{_n}` | `{_e['alias_old_id']}` | {_e['positive_frames']:,} | {_where} |") +_J = json.loads((ROOT / "status/real/AUDIT271_J_DINO.json").read_text()) +assert _J["ok"], f"check J did not pass; refusing to write its numbers onto the hub card: {_J['failures']}" +assert _J["z_max_abs_diff"] == 0.0 and _J["logit_max_abs_diff"] == 0.0, \ + f"J passed within tolerance but not exactly; (1f) claims bit-identical, so reword first: {_J}" +_Jst = _J["source_trees"] +assert _Jst["same_snapshot"], "the two DINOv2 source trees differ; (1f) would be wrong" +assert _J["head_hub_name"] in _CARD_LIVE, \ + f"(1f) would cite {_J['head_hub_name']}, which is not live on the hub" +# (1g): refuse to state the label-provenance claim unless check L passed EXACTLY, on every head the +# card advertises -- the same rule (1f) follows for check J. +_L = json.loads((ROOT / "status/real/AUDIT271_L_LABELPROV.json").read_text()) +assert _L["ok"], f"check L did not pass; refusing to write (1g) onto the hub card: {_L['failures']}" +_Lheads = _L["heads"] +_Ln = _L["n_heads_expected"] +_Lok = sum(1 for _v in _Lheads.values() + if _v.get("recorded_match") and _v.get("functional_match")) +assert _Lok == _Ln, f"(1g) claims all {_Ln} heads; only {_Lok} pass both readings" +assert all(_v["claimed_auc"] == 1.0 for _v in _Lheads.values()), \ + "(1g) states AUC 1.0000 for every head; one head is not at 1.0, so reword first" +_Llive = {_f for _f in _CARD_LIVE + if _f.startswith("successor_rsm_real_") and _f.endswith(".pt")} +assert set(_Lheads) >= _Llive, \ + f"(1g) would claim heads L never read: {sorted(_Llive - set(_Lheads))}" +_Lnp = len(next(iter(_Lheads.values()))["perm_null_auc"]["draws"]) +_Lnull_lo = min(_v["perm_null_auc"]["max"] for _v in _Lheads.values()) +_Lnull_hi = max(_v["perm_null_auc"]["max"] for _v in _Lheads.values()) +assert _Lnull_hi < 0.55, f"(1g) calls the permuted null chance-level; it is {_Lnull_hi}" +_n_frames = int(_np.load(ROOT / "cache/real_cooking_v5/reward_A_tosucc.f32.npy").shape[0]) +blk = blk[:blk.rindex("")] + f""" +**(1e) Which canonical name is in which file.** `rise_stack` names these labels in words +(`REWARD_NAMES.md`); this repo names the files after the old ids, so the map is worth stating once. The +rows are read from `rise_stack/configs/reward_names.json` and from `hf_upload.py`'s upload table, not +typed. The one to be careful with: **`successor_rsm_real_A_110000.pt` is the `GOAL_SEGMENT` head** +(scheme `A`, `r_t = 1[to(t) = S4]`, cell `R_M_ft_v1`) -- **not** `GOAL_EPISODE`, whose label is the +provenance one the base successor already carries. + +| canonical name | old id in these file names | positive frames | where it lives here | +|---|---|---|---| +{chr(10).join(_rows)} + +**(1f) These numbers reproduce with the DINOv2 YOU will build.** Every R(z) number in this card was +measured on the training cluster, where the DINOv2 backbone is built from a local archive of +`facebookresearch/dinov2`. Your clone has no such archive and fetches that source from GitHub, so the +features feeding the head are computed by a different copy of the model code -- while the checkpoint +itself is bit-identical either way. A reward head is only as reproducible as its features, so this is +checked rather than assumed. On {_J['n_frames']} frames of the shipped replay fixture, featurised +through both sources: the two source trees are the same snapshot ({_Jst['n_py_local']} of +{_Jst['n_py_local']} .py files sha256-identical), z is bit-identical (max abs diff 0), and +`{_J['head_hub_name']}` returns bit-identical logits (max abs diff 0, identical ranking of all +{_J['n_frames']} frames). Checked {_J['utc']}, and re-checked on every audit of gen_q #271 (check `J`, +`scripts/real/audit271_J_dino_source.py`), with the GitHub source re-fetched each time so the check +tracks `main` instead of a frozen snapshot of it. + +**(1g) Each file is verified to carry the LABEL its name claims.** (1e) is a map; this is the check +that the map is true of the WEIGHTS. A file could be named, hashed, and reproduce its features +perfectly while having been fine-tuned on the wrong label, and nothing above would notice. So every +delivered head is read twice, independently: the training label is rebuilt from the checkpoint's own +stored config through the trainer's own data pipeline, and the head is scored over all {_n_frames:,} +corpus frames to see which label R(z) actually fits best. For all **{_Lok}/{_Ln}** heads the rebuilt +label is the one this card advertises, and the advertised label is the strict argmax of AUC -- at +**1.0000** for every head, against a permuted null measured per head that lands at chance (max over +{_Lnp} draws per head: {_Lnull_lo:.4f}-{_Lnull_hi:.4f}). Note what this is: an IN-SAMPLE identity +test, the fingerprint that says which reward a file optimises. It is not a generalisation number and +must not be quoted as one. Checked on every audit of gen_q #271 (check `L`, +`scripts/real/audit271_L_label_provenance.py`; negative control +`scripts/real/_audit271_L_selftest.py`). + +""" + "" + +s = CARD.read_text() +BEG = "" +if s.count(BEG) == 2: + i = s.index(BEG) + j = s.index(BEG, i + len(BEG)) + len(BEG) + s = s[:i] + blk + s[j:] +else: + ANCHOR = "**(2) The RISE-recipe open-loop screen" + assert ANCHOR in s, "card section (2) anchor moved; refusing to guess where to insert" + k = s.index(ANCHOR) + s = s[:k] + blk + "\n\n" + s[k:] +CARD.write_text(s) +print(f"wrote {CARD} ({len(s)} B); separating={sep} saturated={sat} inverted={inv}") diff --git a/rsm_rise/scripts/real/build_checkpoints_reward_rows.py b/rsm_rise/scripts/real/build_checkpoints_reward_rows.py new file mode 100644 index 0000000000000000000000000000000000000000..1d71446bd36588deefefc89597db7703031109ce --- /dev/null +++ b/rsm_rise/scripts/real/build_checkpoints_reward_rows.py @@ -0,0 +1,636 @@ +#!/usr/bin/env python +"""Emit the gen_q #271 reward-head block for rise_stack/CHECKPOINTS.md, from the diagnostics JSONs. + +Writes status/real/CHECKPOINTS_reward_block.md, which is spliced into the clone's CHECKPOINTS.md +between the markers / . Regenerating is idempotent, so this can be +re-run every time a head or a diagnostic lands.""" +from __future__ import annotations +import json +from pathlib import Path + +ROOT = Path("/proj/dmfexp/zwhong/rsm_rise") +ST = ROOT / "status/real" +OUT = ST / "CHECKPOINTS_reward_block.md" + +# scheme -> (display name, formula in the text stage words, REWARD_SCHEMES key, diag key, HF name) +HEADS = [ + ("A", "**A (default)**", "`r_t = 1[to(t) = S4]` — the frame's annotated segment leads into " + "*pan on grate, tomato in the bowl*", "A_to_eq_S4", "A", "successor_rsm_real_A_110000.pt"), + ("A_s1", "A, seed 1", "same label, seed 1", "A_to_eq_S4", "A_s1", "successor_rsm_real_A_s1_110000.pt"), + ("v0", "v0 provenance (shipped)", "`r_t = 1[f_i = S4]` — every frame of an episode that ends " + "with the tomato in the bowl and the pan on the grate", "v0_shipped_final_eq_S4", "v0", + "(inside `successor_rsm_real_RM_s0_100k.pt`)"), + ("v0lit", "v0 as written in #271", "`r_t = 1[f_i in {S3,S4}]` — every frame of an episode that ends " + "with the tomato in the bowl, pan on grate *or* pan still held", "v0lit_final_in_S3_S4", + "v0lit", "successor_rsm_real_v0lit_110000.pt"), + ("v0lit_s1", "v0 as written in #271, seed 1", "same label, seed 1", "v0lit_final_in_S3_S4", + "v0lit_s1", "successor_rsm_real_v0lit_s1_110000.pt"), + ("B", "B, H=100", "`r_t = 1[0 <= a_i - t <= 100]` — the last 100 frames (one hop at β=0.99) " + "before the goal is reached", "B_window_H100", "B", "successor_rsm_real_B_H100_110000.pt"), + ("B_s1", "B, H=100, seed 1", "same label, seed 1", "B_window_H100", "B_s1", + "successor_rsm_real_B_H100_s1_110000.pt"), + ("B400", "B, H=400", "`r_t = 1[0 <= a_i - t <= 400]` — four hops' worth", "B_window_H400", "B400", + "successor_rsm_real_B_H400_110000.pt"), + ("B400_s1", "B, H=400, seed 1", "same label, seed 1", "B_window_H400", "B400_s1", + "successor_rsm_real_B_H400_s1_110000.pt"), + ("C3", "C, w_neg=3", "A's label with a weighted loss: frames whose segment leads into a failure " + "terminal (*pan left on the stove*, *tomato dropped*) count 3×", "C_label_to_eq_S4", "C3", + "successor_rsm_real_C_w3_110000.pt"), + ("C3_s1", "C, w_neg=3, seed 1", "same label and weights, seed 1", "C_label_to_eq_S4", "C3_s1", + "successor_rsm_real_C_w3_s1_110000.pt"), + ("C10", "C, w_neg=10", "as above with 10×", "C_label_to_eq_S4", "C10", + "successor_rsm_real_C_w10_110000.pt"), + ("C10_s1", "C, w_neg=10, seed 1", "as above with 10×, seed 1", "C_label_to_eq_S4", "C10_s1", + "successor_rsm_real_C_w10_s1_110000.pt"), +] +HF = "https://huggingface.co/rli14/rsm_cooking_v5_checkpoints" + + +def f(x, n=3): + return "—" if x is None else ("%.*f" % (n, x)) + + +def main(): + sch = {s["name"]: s for s in json.loads((ST / "REWARD_SCHEMES.json").read_text())["schemes"]} + diag = json.loads((ST / "REWARD_HEAD_DIAG.json").read_text())["heads"] \ + if (ST / "REWARD_HEAD_DIAG.json").exists() else {} + snf = ST / "REWARD_HEAD_DIAG_STITCH.json" + stitch = json.loads(snf.read_text()) if snf.exists() else None + sgf = ST / "STITCH_SIGNIFICANCE.json" + sig = json.loads(sgf.read_text()) if sgf.exists() else None + # hop 4 is the only depth at which the question is answerable: at hop 1 no endpoint reaches a GOAL + # frame at all, and at hop 2 only 4.9 % do, so both are reported as nan/no-signal for every head. + sigh = ((sig or {}).get("by_hop", {}).get("4") or {}).get("heads", {}) + sig_n = ((sig or {}).get("by_hop", {}).get("4") or {}).get("n_anchors", 0) + stf = ST / "hf_upload_stamps.json" + stamps = json.loads(stf.read_text()) if stf.exists() else {} + scf = ST / "REWARD_SCREEN.json" + screen = json.loads(scf.read_text()) if scf.exists() else None + rpf = ST / "SCREEN_REPRODUCIBILITY.json" # the two-run replicate: the screen's real noise floor + repro = json.loads(rpf.read_text()) if rpf.exists() else None + srf = ST / "STITCH_REPRODUCIBILITY.json" # the SAME check for the stitching number (run 8) + srep = json.loads(srf.read_text()) if srf.exists() else None + mcf = ST / "STITCH_MECHANISM.json" # WHY it does not replicate, measured (run 9) + mech = json.loads(mcf.read_text()) if mcf.exists() else None + dwf = ST / "STITCH_DRAWS.json" # the designed replication: 5 independent candidate draws + draws = json.loads(dwf.read_text()) if dwf.exists() else None + dcf = ST / "STITCH_DECOMP.json" # WHERE the signal dies: R(z_h) vs R(retrieved) vs Q (run 10) + decomp = json.loads(dcf.read_text()) if dcf.exists() else None + f4f = ST / "FOLD4_COMPARE.json" # the matched-horizon read-out, measured (run 11) + fold4 = json.loads(f4f.read_text()) if f4f.exists() else None + skf = ST / "SK_COMPARE.json" # the scoring-functional sweep, measured (run 13) + skc = json.loads(skf.read_text()) if skf.exists() else None + olf = ST / "OL_COMPARE.json" # the rollout policy the fold applies, measured (run 15) + olc = json.loads(olf.read_text()) if olf.exists() else None + # the screen block to quote: the pooled one once both proposer seeds are in, else the single seed + sblk = None + if screen: + sblk = screen.get("combined") or (list(screen["seeds"].values())[0] if screen.get("seeds") else None) + sheads = (sblk or {}).get("heads", {}) + + # Why a trained head is not on the hub, stated PER HEAD from the five-draw replication rather than + # as one blanket sentence. STITCH_DRAWS.json is the design that accounts for the candidate-draw + # noise floor (the published single draw cannot: run 8-10), so it is the right instrument for + # "does this head have a replicated advantage over the base head at all". Falls back to the old + # wording only if the JSON is missing. + _dh4 = ((draws or {}).get("by_hop", {}).get("4") or {}).get("heads", {}) + _dbase = (_dh4.get("base") or {}).get("mean_over_draws") + + def _why_not(dkey): + d = _dh4.get(dkey) + if d is None or _dbase is None: + return "no measured advantage over the base head" + return ("five-draw stitching AUC %.4f, above chance in %d/5 draws (p=%.3f) against the base " + "head's %.4f — no replicated advantage" % ( + d["mean_over_draws"], d["n_draws_above_half"], + d["p_draw_level_vs_half"], _dbase)) + + L = ["", + "## The reward head, scheme by scheme (gen_q #271)", + "", + "`R(z)` rides inside the successor `.pt` (see above), so **a reward scheme is a checkpoint file**.", + "Each head below is a 10,000-step fine-tune of `successor_rsm_real_RM_s0_100k.pt` (seed 1: `_s1`)", + "in which *only* the per-frame label array changes — architecture, cache, optimiser, β band, chunk,", + "split and step budget are identical. Notation, on the operator's state graph: `t` is a frame,", + "`to(t)` is the state the annotated segment containing `t` leads into, `k(t)` is the operator's", + "arrival marker, `a_i` is the frame at which episode `i` reaches the goal, `f_i` is its final state,", + "and `S4` = *pan on the grate, tomato in the bowl*. Full statement, with the weighted loss written", + "out: `docs/real_reward_study.pdf` in rsm_rise, and", + f"[gen_q #271]({'https://github.com/williamd4112/gen_q/issues/271'}).", + "", + "| head | label (in stage words) | +1 frames | AUC S4 vs S6 (segment) | junction AUC R3 vs R4 | " + "stitching AUC (within-anchor, 4 hops) | open-loop screen (Δ vs permuted) | file |", + "|---|---|---|---|---|---|---|---|"] + for key, name, form, skey, dkey, hf in HEADS: + s = sch.get(skey, {}) + d = diag.get(dkey) + trained = d is not None and d.get("step", 0) >= 110000 + pos = "{:,}".format(s.get("pos_frames", 0)) if s else "—" + a1 = f(d["auc_S4_vs_S6_segment"]) if trained else "_pending_" + a2 = f(d["auc_junction_R3_vs_R4"]) if trained else "_pending_" + sc = sheads.get(dkey) + if sc is None: + a3 = "_pending_" + else: + a3 = "%.3f (%+.3f [%+.3f, %+.3f])%s" % ( + sc["oracle_rank_pct_mean"], sc["delta_vs_permuted"], sc["ci95"][0], sc["ci95"][1], + " **✓**" if sc["beats_control"] else "") + sg = sigh.get(dkey) + if sg is None: + a4 = "_pending_" + else: + a4 = "%.3f [%.3f, %.3f] p=%s%s" % ( + sg["auc_per_anchor_mean"], sg["auc_per_anchor_ci95"][0], sg["auc_per_anchor_ci95"][1], + ("%.4f" % sg["p_boot_vs_half"]) if sg["p_boot_vs_half"] >= 1e-4 else "<1e-4", + " **✓**" if sg["p_boot_vs_half"] < 0.05 else "") + # only link a file that is ACTUALLY on the hub -- an unuploaded head must not get a dead URL + up = bool((stamps.get(hf) or {}).get("ok")) + if not hf.endswith(".pt"): + fn = hf + elif up: + fn = f"[`{hf}`]({HF}/resolve/main/{hf})" + elif not trained: + fn = f"`{hf}` _(not uploaded: head still training)_" + else: + fn = f"`{hf}` _(trained, not uploaded: {_why_not(dkey)})_" + L.append(f"| {name} | {form} | {pos} | {a1} | {a2} | {a4} | {a3} | {fn} |") + L += ["", + "**What the two diagnostic columns mean.** *AUC S4 vs S6* is the head's separation of frames whose", + "segment leads into the goal from frames whose segment leads into *pan left on the stove, tomato in", + "the bowl* — the two states differ only in where the pan ends, so a head that scores them apart has", + "encoded the pan. *Junction AUC R3 vs R4* is the same head's score on the ±50 frames around the S2", + "junction, split by the route the episode then took. **Lower is better here**: at that junction both", + "continuations are still physically open, so a head that already separates them is reading *which", + "recording a frame came from*, not the state. That is the confound the provenance head has and the", + "reason #271 exists — and it is measured, not suspected: v0 scores 1.000 (and reads `p ≈ 1` on route-3", + "junction frames *before anything has happened*), while the default head A scores" + f" {f(diag.get('A',{}).get('auc_junction_R3_vs_R4')) if 'A' in diag else '—'}" + f" / {f(diag.get('A_s1',{}).get('auc_junction_R3_vs_R4')) if 'A_s1' in diag else '—'} over the two seeds," + " with every junction probability at numerical zero.", + ""] + if sblk is not None: + seeds = screen.get("seeds", {}) + nseed = len(screen.get("combined", {}).get("seeds", [])) or 1 + ref = (list(seeds.values())[0] if seeds else {}).get("reference", {}) + win = sorted((k for k, v in sheads.items() if v["beats_control"]), + key=lambda k: -sheads[k]["oracle_rank_pct_mean"]) + win = [w for w in win if w not in ("oracle", "idql", "permuted:idql", "permuted:rsm")] + # the idql critic is the RISE recipe's own scorer and is NOT one of these reward heads; how it + # does per seed is the evidence for whether a seed indicts the heads or indicts the screen + idq = {k: (v.get("heads", {}).get("idql") or {}).get("oracle_rank_pct_mean") for k, v in seeds.items()} + per = {k: (v.get("heads", {}).get("permuted:rsm") or {}).get("oracle_rank_pct_mean") for k, v in seeds.items()} + # the seed-0 headline is READ from the JSON: hard-coding it is how run 5's numbers went stale + # in this file after the screen was rerun on the hardened checkpoint resolvers. + s0h = (seeds.get("s0") or {}).get("heads", {}) + s0w = sorted((k for k, v in s0h.items() if v.get("beats_control") + and k not in ("oracle", "idql", "permuted:idql", "permuted:rsm")), + key=lambda k: -s0h[k]["oracle_rank_pct_mean"]) + _nulls = [h[k]["oracle_rank_pct_mean"] for h in (seeds.get("s0", {}).get("heads", {}), + seeds.get("s1", {}).get("heads", {})) + for k in ("permuted:rsm", "permuted:idql") if k in h] + _nulls += [v["reference"]["greedy"] for v in seeds.values() if "greedy" in v.get("reference", {})] + _nlo, _nhi = (min(_nulls), max(_nulls)) if _nulls else (float("nan"), float("nan")) + s0_best = (", ".join("`%s` %.3f, %+.3f [%+.3f, %+.3f]" % ( + w, s0h[w]["oracle_rank_pct_mean"], s0h[w]["delta_vs_permuted"], *s0h[w]["ci95"]) + for w in s0w[:1]) or "no head cleared it") + L += ["**What the screen column means.** The RISE recipe: draw N = 128 action chunks from the " + f"`S0Aidql` proposer at each of {sblk['n_decisions']:,} held-out decisions " + f"({'both proposer seeds pooled' if nseed > 1 else 'proposer seed 0 only'}), take the head's " + "argmax, and record `oracle_rank_pct` — the fraction of the 128 candidates the pick beats on " + "first-step error. **Every head scores the identical candidate set**, so the Δ against the " + "control is paired decision by decision; the CI is a 95 % bootstrap over decisions. The control " + "is `permuted:rsm`, the base head's own scores shuffled within each decision — that makes the " + "argmax a uniform index over the 128, so this column's control **is** random-of-128, it is the " + "right null for every head, and `greedy` " + + (f"({ref['greedy']:.3f}) " if "greedy" in ref else "") + + "is an independent second draw of it. A per-head permutation was not run.", "", + "**The heads that clear it: " + (", ".join(f"`{w}`" for w in win) if win else "none") + ".**"] + if nseed > 1 and len(idq) > 1: + L += ["", + "**And that column should not be used to rank reward schemes, because it does not " + "replicate across proposer seeds.** On proposer seed 0 the B family cleared the control " + f"({s0_best}); on proposer seed 1 *every learned scorer* " + "falls far below it — including **`idql`, the RISE recipe's own critic, which is not one " + "of these reward heads at all** (" + + " vs ".join(f"{k}: idql {idq[k]:.3f}, control {per[k]:.3f}" for k in sorted(idq) if idq[k]) + + f"). All three nulls — both permutation columns and `greedy` — stay inside " + f"[{_nlo:.3f}, {_nhi:.3f}] across both seeds, exactly where a null belongs, so seed 1 " + "is not a statement about the reward labels: the seed-1 proposer's " + "candidate cloud is tighter (0.217 cm vs 0.256 cm spread) and its oracle-best candidate is " + "already on the expert action (0.111 cm vs 0.193 cm), so any learned preference for a " + "*distinctive* candidate moves you off it. Pooled, no head and no critic beats the " + "control. **Use the stitching column, not this one, to compare schemes.**"] + if repro is not None and repro.get("seeds"): + rr = repro["seeds"] + nf = repro.get("noise_floor_paired_delta_rms") + L += ["", + "**How large an effect this screen can resolve at all.** The screen was run end to end " + + ("%d times; the replicate quoted here is the pair " % len(repro.get("available_tags") or []) + if len(repro.get("available_tags") or []) > 2 else "twice ") + + "(tags %s), on the same decisions and %s, but with an independently re-drawn candidate " + "set. That is a replicate of the whole measurement rather than of the bootstrap. " + "Between the two runs the quoted paired Δ moves by " + % (" and ".join("`%s`" % t for t in repro["tags"]), + ("— for every head except the %d whose weights changed — the same weights" + % len(repro["excluded_weights_changed"])) if repro.get("excluded_weights_changed") + else "the same weights for every head (only the candidate draw differs)") + + ", ".join( + "rms %.3f (max %.3f) on %s" % (v["paired_delta"]["rms"], v["paired_delta"]["max_abs"], k) + for k, v in sorted(rr.items())) + + (", and pairing against the control barely helps — " + if max(v["paired_delta"]["rms"] for v in rr.values()) + > 0.6 * max(v["raw"]["rms"] for v in rr.values()) + else ", while pairing against the control does reduce it — ") + + "the raw level moves by " + + ", ".join("rms %.3f on %s" % (v["raw"]["rms"], k) for k, v in sorted(rr.items())) + + f". So the screen's noise floor (rms {nf:.3f}) is of the same order as the largest head " + "effect it ever reported, which is a second, independent reason not to rank schemes with " + "it. The bootstrap-over-decisions CIs quoted above are therefore optimistic: they hold " + "the candidate draw fixed."] + L += [""] + # which cells actually clear chance is READ off the JSON: "the B family clears" was true of three + # of the four B cells and false of B_s1, and a hand-written headline cannot notice that. + _clr = sorted((k for k, v in sigh.items() if v["auc_per_anchor_ci95"][0] > 0.5), + key=lambda k: -sigh[k]["auc_per_anchor_mean"]) if sigh else [] + _nclr = sorted((k for k in sigh if k not in _clr and k != "base"), + key=lambda k: -sigh[k]["auc_per_anchor_mean"]) if sigh else [] + # "in this candidate draw" is not hedging: the redraw below shows none of these survives one, and + # the sentence was read as a property of the head when it is a property of the draw (run 8). + _clr_txt = ("**" + ", ".join(f"`{k}`" for k in _clr) + "** " + + ("clear chance" if len(_clr) > 1 else "clears chance") + + " *in this candidate draw*") if _clr else "**No head clears chance**" + _clr_d = ", ".join("`%s` Δ%+.3f p=%.4f" % (k, sigh[k]["delta_vs_ref"], sigh[k]["p_boot_delta"]) + for k in _clr) or "n/a" + _nul_txt = ("Every other head — " + ", ".join(f"`{k}`" for k in _nclr) + + " — and the un-fine-tuned base itself are inside their CI of 0.5.") if _nclr else "" + # The "why B and not A/C" story predicts that a FLAT, episode-level label is at chance. Whether any + # flat label is in the clearing set is checked, not assumed: v0lit (positive on every frame of every + # episode that ends in S3 or S4) landed in it, which is the story's own counter-example (run 8). + _flat = [k for k in _clr if k in ("v0", "v0lit", "v0lit_s1", "A", "A_s1", + "C3", "C3_s1", "C10", "C10_s1", "v2", "v2_s1")] + _prox_txt = ( + "The story offered for this was structural — A, C and v0 are flat indicators of *this segment " + "ends in the goal*, so `R(z)` is constant across the positive set and a candidate landing " + "**closer** to the goal scores exactly the same as one landing at the far end, while B's arrival " + "window is the only label whose value varies with proximity. That story predicts a flat label at " + "chance, and " + + ("**it fails its own test here**: " + ", ".join(f"`{k}`" for k in _flat) + + (" is a" if len(_flat) == 1 else " are") + " flat, episode-level label" + + ("" if len(_flat) == 1 else "s") + " with no proximity structure at all, and clear" + + ("s" if len(_flat) == 1 else "") + " chance in this draw alongside B." + if _flat else "no flat label clears chance in this draw, which is consistent with it.") + ) + if sig is not None and sigh: + # The per-run configuration lives in REWARD_HEAD_DIAG_STITCH.json, which is written by the GPU + # job and can legitimately be absent or mid-rewrite while STITCH_SIGNIFICANCE.json (read from the + # parts) is already current. Render "?" rather than crashing the whole block on a None (run 8). + blk4 = (stitch or {}).get("by_hop", {}).get("4", {}) + gf = (blk4.get("endpoint_class_frac") or {}).get("goal") + rp = (stitch or {}).get("retrieval_pool", {}).get("n") + nc = (stitch or {}).get("n_cand") + # Hop 2 is not undefined -- it has its own table, and quoting it is the honest version of the + # old "nan or no-signal for everyone" clause (run 9). Derived, never asserted. + _h2 = ((sig or {}).get("by_hop", {}).get("2") or {}) + _h2h = _h2.get("heads") or {} + if _h2h: + _h2top = max(_h2h, key=lambda k: _h2h[k]["auc_per_anchor_mean"]) + _h2sig = [k for k, v in _h2h.items() if v["p_boot_vs_half"] < 0.05] + _hop2_txt = (f"Two hops is answerable too ({_h2['n_anchors']} anchors, 0.049 GOAL endpoints) " + f"and reads flat: the top head is `{_h2top}` at " + f"{_h2h[_h2top]['auc_per_anchor_mean']:.3f} " + f"(p={_h2h[_h2top]['p_boot_vs_half']:.2f}), and " + + (", ".join(f"`{k}`" for k in _h2sig) + " clear chance." + if _h2sig else "**no head clears chance**.")) + else: + _hop2_txt = "" + _rp = f"{rp:,}" if rp else "the" + _gf = f"{gf:.3f}" if gf is not None else "a majority" + L += ["**What the stitching column means — this is the number #271 exists to produce.** At each of " + f"{(stitch or {}).get('n_anchors', '?')} S2-junction frames of the **failure** route " + f"(`0 → 2 → 6`), the `S0Aidql` proposer draws {nc} action chunks; each chunk is chained " + "four hops (400 frames) through the **same base successor flow** for every head, so only the " + "reward differs and never the dynamics. The endpoint latent is retrieved against " + f"{_rp} cached frames and the nearest one's `edge_to` labels it **GOAL** (`= S4`) or " + "**FAIL** (`∈ {S5, S6}`). The column is then " + "`P[ Q(a GOAL-ending candidate) > Q(a FAIL-ending one) ]` **computed inside one anchor and " + f"averaged over the {sig_n} anchors that produced both classes**, with a 95 % bootstrap CI " + "over anchors. It must be read within-anchor: anchors sit at very different absolute `Q` " + "levels, so a pooled AUC (0.63–0.74 for heads that are at chance inside a decision) mixes " + "*ranks candidates correctly in this decision* with *scores some junctions higher than " + "others*, and only the former is stitching. Four hops is the depth the column reports — one " + "hop reaches a GOAL frame in **0.000** of candidates so the statistic is undefined there, " + f"and at four hops {_gf} of endpoints are GOAL. " + _hop2_txt, "", + f"**{_clr_txt}, and {'they do' if len(_clr) > 1 else 'it does'} so paired against the " + f"un-fine-tuned base head too** ({_clr_d}). {_nul_txt} The control that shows the statistic " + f"has sign: a head trained on *the final segment of every episode, failures included* reads " + f"{sigh['v3']['auc_per_anchor_mean']:.3f}, **significantly below** chance. " + + _prox_txt + " Take the size seriously: AUC 0.53–0.54 " + "means the stitch is preferred in ~54 % of GOAL-vs-FAIL pairs and at 61 % of junctions. That " + "is a small effect even taken at face value, and not a head you could plan with.", ""] + # Whether any of that survives a redraw is MEASURED, never asserted. The first version of this + # paragraph called the B family "a demonstrable stitching signal -- the first in this study" on + # the strength of one candidate draw; the redraw below retracts it (run 8). + sr4 = (srep or {}).get("by_hop", {}).get("4") + if sr4: + surv = sr4.get("heads_sig_both") or [] + siga, sigb = sr4.get("heads_sig_a") or [], sr4.get("heads_sig_b") or [] + hh = sr4.get("heads", {}) + worst = max(hh, key=lambda k: abs(hh[k]["d_auc"])) if hh else None + L += ["**And the significance does not survive a redraw at a different anchor stride.** " + "`stitch_number.py` seeds each anchor's draw with `seed*1000003 + anchor_index`, so a " + "rerun over the same anchors is guaranteed to return identical numbers — that is a " + "determinism check, not a replication. Running instead at a finer `--anchor-stride` " + "visits the same anchor *frames* with completely different candidates; restricted back " + f"to the published anchors ({sr4.get('n_anchors_b')} usable against " + f"{sr4.get('n_anchors_a')}) it is close to a replicate — but only close, because " + "the stride moved the anchor set as well as the draw. Over the " + f"{sr4.get('n_heads')} shared heads the within-anchor AUC moves by **rms " + f"{sr4['level_rms']:.4f}** (max {sr4['level_max_abs']:+.4f}" + + (f", `{worst}`" if worst else "") + f"), against a largest reported effect of " + f"**{sr4['largest_effect_reported']:+.4f}**; pairing against the base head " + + ("removes most of it" if sr4.get("pairing_helps") else + f"barely helps (rms {sr4['paired_rms']:.4f})") + + ". Significantly above 0.5 in the published draw: " + + (", ".join(f"`{k}`" for k in siga) if siga else "none") + + "; in this redraw: " + (", ".join(f"`{k}`" for k in sigb) if sigb else "**none**") + + "; surviving both: " + (", ".join(f"`{k}`" for k in surv) if surv else "**none**") + + ". **But read that line with the confound it carries:** the redraw was obtained by " + "changing the anchor *stride*, which changes the candidate draw AND the anchor set, so " + "it is not a clean replicate. The clean design — identical anchors and weights, only " + "the seed of the draw changing — is the five-draw paragraph below, and where the two " + "disagree that one is the statement to believe. What both agree on is that the " + "published single-draw figure is not a scheme ranking: each statistic has a noise " + "floor the size of its own largest effect, so **neither can rank these reward " + "schemes.** What replicates in every draw is the sign check: `v3`, the one label that " + "is not a function of episode success, is below chance throughout.", ""] + elif stitch is None: + L += ["**Stitching number:** _in flight_ (`scripts/real/stitch_number.py` in rsm_rise).", ""] + # run 9: the three explanations for the non-replication, all MEASURED rather than asserted. This + # paragraph is generated for the same reason as the one above it: the previous "why" sentence in + # circulation ("the heads all re-score the base flow's ordering") turned out to be false. + if mech: + _mh = "4" if "4" in mech.get("by_hop", {}) else None + _mb = (mech.get("by_hop") or {}).get(_mh) or {} + _ag = mech.get("head_agreement_with_ref") or {} + _ed = _mb.get("endpoint_diversity") or {} + _pn = _mb.get("permutation_null") or {} + _str = (_mb.get("stratified") or {}).get("strata") or {} + if _ag and _pn: + _lo = min(_ag, key=lambda k: _ag[k]["spearman_vs_ref_mean"]) + _hi = max(_ag, key=lambda k: _ag[k]["spearman_vs_ref_mean"]) + _lsp = (mech.get("least_similar_head_pairs") or [{}])[0] + _sn = [k for k in _str if isinstance(_str[k], dict) and "heads" in _str[k]] + _strtxt = "" + if len(_sn) == 2: + _c, _d = _sn + _top = max(_str[_c]["heads"], key=lambda k: _str[_c]["heads"][k]["auc"]) + _strtxt = (f" Splitting the {_mb['n_anchors']} anchors at the median number of *distinct* " + f"GOAL endpoints leaves `{_top}` at " + f"{_str[_c]['heads'][_top]['auc']:.3f} (p={_str[_c]['heads'][_top]['p_vs_half']:.3f}) " + f"on the {_str[_c]['n_anchors']} collapsed anchors and " + f"{_str[_d]['heads'][_top]['auc']:.3f} (p={_str[_d]['heads'][_top]['p_vs_half']:.3f}) " + f"on the {_str[_d]['n_anchors']} diverse ones — collapse sharpens the effect, it " + f"does not create it.") + L += ["**Why it does not replicate — three explanations, measured** " + "(`status/real/STITCH_MECHANISM.json`). *(a) It is not that every head re-scores one " + "shared ordering.* Candidates are chained through the same base flow for every head, but " + f"the within-anchor Spearman of a head's Q against the base's ranges from " + f"{_ag[_lo]['spearman_vs_ref_mean']:.3f} (`{_lo}`) to {_ag[_hi]['spearman_vs_ref_mean']:.3f} " + f"(`{_hi}`), and the least similar pair of heads (`{_lsp.get('a')}` vs `{_lsp.get('b')}`) " + f"sits at {_lsp.get('mean_spearman', float('nan')):.3f}; `{_lo}` orders " + f"{100 * _ag[_lo]['pair_disorder_vs_ref_mean']:.0f} % of candidate pairs differently from " + "the base. Sixteen materially different rankings of the same candidates all land near " + "chance, which is a stronger statement than any one head failing. " + "*(b) Endpoint collapse (#270) is real but does not explain it.* At four hops an anchor's " + f"128 candidates end on a median of {_ed.get('n_distinct_all_per_anchor', {}).get('median', 0):.0f} " + f"distinct cache rows, the GOAL class on a median of " + f"{_ed.get('n_distinct_goal_per_anchor', {}).get('median', 0):.0f}, and the modal endpoint " + f"takes {100 * _ed.get('modal_endpoint_share_within_anchor_mean', 0):.0f} % of them." + + _strtxt + + " *(c) Power.* Shuffling the GOAL/FAIL labels **inside** each anchor, class sizes " + f"preserved, puts the statistic at {_pn['mean']:.4f} ± {_pn['sd']:.4f} " + f"(95 % [{_pn['q025']:.3f}, {_pn['q975']:.3f}]), so ±{_pn['two_sided_95_halfwidth']:.3f} is " + "the smallest effect this design can resolve against a largest reported effect of " + f"{(srep or {}).get('by_hop', {}).get('4', {}).get('largest_effect_reported', 0.055):+.3f}.", ""] + if draws: + _dh = "4" if "4" in draws.get("by_hop", {}) else None + _db = (draws.get("by_hop") or {}).get(_dh) or {} + if _db: + _al = _db.get("heads_above_half_in_every_draw") or [] + _ds = _db.get("heads_draw_level_significant") or [] + L += [f"**And with the draw as the unit of replication** ({len(_db['draw_labels'])} independent " + "candidate draws at the same anchors, `status/real/STITCH_DRAWS.json`): the between-draw " + f"SD of a head's AUC is {_db['noise_floor']['between_draw_sd_mean_over_heads']:.4f} on " + f"average and {_db['noise_floor']['between_draw_sd_max_over_heads']:.4f} at worst. Above " + "0.5 in **every** draw: " + + (", ".join(f"`{k}`" for k in _al) if _al else "**none**") + + "; draw-level significant: " + + (", ".join(f"`{k}`" for k in _ds) if _ds else "**none**") + ".", ""] + # run 11: the decomposition. Generated, like everything above it, because the hand-written + # explanation it replaces ("the heads all re-score the base ordering") was false and had to be + # retracted. The classification into separating / saturated / inverted is on the MEANS first: a + # head whose R(z_h) is ~0 on both classes has an AUC decided by numerical dust and must not be + # reported as an inverted effect. + if decomp: + _k4 = "4" if "4" in decomp.get("by_hop", {}) else None + _b4 = (decomp.get("by_hop") or {}).get(_k4) or {} + _b1 = (decomp.get("by_hop") or {}).get("1") or {} + _hd = _b4.get("heads") or {} + if _hd: + def _m(v, k): + x = v.get(k) + return x.get("mean") if isinstance(x, dict) else x + _sep, _sat, _inv = [], [], [] + for _n, _v in _hd.items(): + _a = _m(_v, "auc_R_chain_per_anchor") + _gm, _fm = _m(_v, "R_chain_goal") or 0.0, _m(_v, "R_chain_fail") or 0.0 + if max(_gm, _fm) < 0.01: + _sat.append(_n) + elif _a is not None and _a > 0.65: + _sep.append(_n) + elif _a is not None and _a < 0.35: + _inv.append(_n) + _sep.sort(key=lambda n: -(_m(_hd[n], "auc_R_chain_per_anchor") or 0)) + _bk = _sep[0] if _sep else None + _fmt = lambda xs: ", ".join(f"`{x}`" for x in xs) if xs else "none" + _retr_lo = min(_hd, key=lambda n: _m(_hd[n], "auc_R_retrieved_per_anchor") or 1.0) + L += ["**Where the signal actually dies — the decomposition** " + "(`status/real/STITCH_DECOMP.json`, `scripts/real/stitch_decompose.py`). Every head " + "separates real S4 from real S6 frames at AUC 1.000 (diagnostic 1) while the Q it " + "induces is at chance on chained candidates, so the question is *where* in " + "`R(z) → Q` the class is lost. On the published stitching number's own anchors and " + "its own candidate draw, with Q recomputed in the same process (so no cross-run " + "assumption is needed; the replayed endpoint rows match the published parts at " + f"{_b4.get('endpoint_match_vs_published', float('nan')):.3f}), three quantities are " + "read per candidate: `R(z_h)` at the chained latent, `R(x[nn(z_h)])` at the cached " + "frame it retrieves to — the ceiling, since `edge_to` of that row *is* the endpoint " + "label — and Q itself. " + + (f"**The latent keeps the class and the fold discards it:** {_fmt(_sep)} read the " + f"chained latent at per-anchor AUC " + f"{_m(_hd[_bk], 'auc_R_chain_per_anchor'):.3f} and above, on a real separation of " + f"means ({_m(_hd[_bk], 'R_chain_goal'):.3f} on GOAL-ending chains against " + f"{_m(_hd[_bk], 'R_chain_fail'):.3f} on FAIL-ending ones for `{_bk}`), and their " + f"Q is {_m(_hd[_bk], 'auc_Q_per_anchor_here'):.3f} — chance " + f"(`corr(Q, R(z_h))` = {_m(_hd[_bk], 'corr_Q_Rchain'):.3f}). " if _bk else "") + + "**The reason is a horizon mismatch between the read-out and the label.** The " + "flagship read-out is depth 1 at β=0.99, so Q sees roughly one hop (~100 frames), " + "while the endpoint class is defined four hops (~400 frames) out. Of the two ways to " + "widen that window, raising β is genuinely unavailable (the flow was conditioned on " + "β ∈ [0.95, 0.99], so β=0.99 already is the longest horizon it was trained at), but " + "**deepening the fold is available**: `--rsm-depth ≥ 2` needs a hop head, and although " + "no *successor* blob embeds one, the hop head is a separate checkpoint (`rsm_hop_ckpt`) " + "and this corpus has one — `runs/real_cooking_v5/hop/gauss/policy_r1.pt`, published as " + "`hop_head_rsm_real_gauss_r1.pt` and already used by the fold-4 column of the open-loop " + "screen. *(An earlier revision of this paragraph called that lever closed and concluded " + "no reward label could satisfy the diagnostic; that conclusion is withdrawn and the " + "matched-horizon fold is being measured.)* What stands either way is the size of the " + "mismatch, and the clincher is the hop-1 " + f"row: at one hop there are **{_b1.get('n_goal', 0)} GOAL endpoints out of " + f"{_b1.get('n_goal', 0) + _b1.get('n_fail', 0):,} classified candidates**, so within " + "the horizon Q can see, no candidate drawn at the failure route's S2 junction reaches " + "a goal-bound segment at all. **So the depth-1 statistic was never a test of the " + "reward labels** — it asks Q to discriminate a class that lives outside the window Q " + "can see. The paragraph after this one measures what happens when that window is " + "widened to match. " + + (f"Two cautions that come with it. {_fmt(_sat)} are saturated OFF at the chained " + f"latent (R(z_h) ≈ 0 on *both* classes), so their AUCs are ranking numerical dust " + f"and must not be read as effects" if _sat else "") + + (f", while {_fmt(_inv)} is genuinely inverted " + f"({_m(_hd[_inv[0]], 'R_chain_goal'):.3f} GOAL vs " + f"{_m(_hd[_inv[0]], 'R_chain_fail'):.3f} FAIL)" if _inv else "") + + f"; the chained latent sits {_b4.get('chain_min_l1_over_real_median', 0):.1f}× a " + "real frame's own nearest-neighbour distance from the corpus. And diagnostic 1's " + "ceiling has a crack: `R` at the *retrieved real frame* is 1.000 for most heads but " + f"{_m(_hd[_retr_lo], 'auc_R_retrieved_per_anchor'):.3f} for `{_retr_lo}` and " + "0.75–0.85 for the whole B/B400 family — diagnostic 1 labels frames by " + "`reached_state_id`, these are labelled by `edge_to` at the endpoints chains actually " + "reach, and there the horizon-window schemes are not at ceiling.", ""] + # run 11: and the matched-horizon read-out, which is the test of the paragraph above it. + if fold4: + _f4 = (fold4.get("by_hop") or {}).get("4") or {} + _f2 = (fold4.get("by_hop") or {}).get("2") or {} + _pc = fold4.get("per_candidate") or {} + if _f4 and _pc: + _lv = [v["mean_level_shift"] for v in _pc.values()] + _cr = [v["mean_within_anchor_corr"] for v in _pc.values()] + _bh = _f4["best_fold4"] + L += ["**And widening the window does not rescue it — the matched-horizon read-out was " + "measured** (`status/real/FOLD4_COMPARE.json`, from `STITCH_DECOMP_FOLD4.json`). " + "`--rsm-mode fold --rsm-depth 4` through `runs/real_cooking_v5/hop/gauss/policy_r1.pt` " + "gives a read-out whose horizon matches the four-hop depth the endpoint class is " + "defined at. Both runs reproduce the published candidate draw exactly (endpoint match " + f"{_f4['endpoint_match_d1']:.3f} and {_f4['endpoint_match_fold4']:.3f}), so the " + "candidates, chains, retrieval pool and GOAL/FAIL labels are identical and the " + f"read-out is the only difference. Over the {_f4['n_heads']} heads the within-anchor " + f"AUC moves by **rms {_f4['delta_rms']:.4f}**, max {_f4['delta_max_abs']:+.4f} " + f"(`{_f4['delta_max_abs_head']}`); at two hops rms {_f2.get('delta_rms', 0):.4f}. That " + "is below the ±0.024 this design can resolve and below the ~0.005 that GPU " + f"non-determinism alone contributes. The top head is still `{_bh}` at " + f"{_f4['best_fold4_auc']:.4f}. **The fold is not idle** — per candidate the fold-4 Q " + f"level rises by +{min(_lv):.3f} to +{max(_lv):.3f} — **but its within-anchor " + f"correlation with the depth-1 Q is {min(_cr):.3f}–1.000 (mean " + f"{sum(_cr) / len(_cr):.3f})** over all {fold4['n_anchors_compared']} anchors: the " + "extra hops add a common-mode offset, not candidate-specific information, so the " + "ordering survives untouched. **So the horizon mismatch, though real, is falsified as " + "the reason Q is at chance.** The endpoint class is in the latent and in the head at " + "AUC 0.941 and *both* read-outs discard it, which left the scoring functional " + "itself — `prob`/T=25 compresses R over particles into a value whose differences " + "*between* candidates sit in the fourth significant figure — as the thing to vary " + "next. Neither the reward labels nor the horizon is the binding constraint.", ""] + # run 13: the third and last degree of freedom in the read-out, swept. + if skc: + _s4 = (skc.get("by_hop") or {}).get("4") or {} + _s2 = (skc.get("by_hop") or {}).get("2") or {} + _sm = _s4.get("summary") or {} + _sb = skc.get("baseline") + if _sm and _sb in _sm: + _KL = {"prob_T25": "`prob`/T=25", "logit_T25": "`logit`", "prob_log_T25": "`prob_log`", + "prob_T1": "`prob`/T=1", "prob_T100": "`prob`/T=100"} + _o = [k for k in _sm if k != _sb] + _dmax = max((_sm[k]["max_abs_delta_vs_baseline"] or 0.0) for k in _o) + _dwho = max(_o, key=lambda k: (_sm[k]["max_abs_delta_vs_baseline"] or 0.0)) + _best = max(_sm[k]["max"] for k in _sm) + _bestk = max(_sm, key=lambda k: _sm[k]["max"]) + _ceil = _s4.get("latent_ceiling") or {} + _cn = _ceil.get("head") + _cq = [v for v in ((_s4.get("heads", {}).get(_cn, {}) or {}).get("Q") or {}).values() + if v is not None] + _d2 = (max((_s2.get("summary", {}).get(k, {}).get("max_abs_delta_vs_baseline") or 0.0) + for k in _s2.get("summary", {}) if k != _sb) + if _s2.get("summary") else None) + L += ["**Nor is the scoring functional** (`status/real/SK_COMPARE.json`). That was the last " + "degree of freedom left in the read-out, and it had never been varied — the " + "decomposition hard-coded `score_kind=\"prob\"` at the scorer. It is now a flag " + "(`--q-score-kind`), folded into the parts signature so two functionals cannot share a " + f"cache, and the bracket {', '.join(_KL.get(k, k) for k in [_sb] + sorted(_o))} was run " + "on identical anchors, candidates, chains and GOAL/FAIL labels (" + + ("controlled: every cell reproduces the published endpoints exactly" + if skc.get("controlled") else + "**NOT controlled** — at least one cell's endpoints differ from the published draw") + + f"). `logit` is the T→∞ linear limit of `prob` and `prob_log` is gen_q#266's " + "log-complement read-out; the bracket passes its own validity check in that " + "`prob`/T=100 reproduces `logit` to 3–4 decimals, as the algebra requires. **The " + f"result is null.** The best within-anchor AUC anywhere in the sweep is {_best:.4f} " + f"(`{_sm[_bestk]['max_head']}`, {_KL.get(_bestk, _bestk)}) against the flagship's own " + f"best of {_sm[_sb]['max']:.4f} — a lift of {_best - _sm[_sb]['max']:+.4f}, against a " + "design resolution of ±0.024 and a GPU-non-determinism floor of ~0.005. The largest " + f"per-head move any functional makes is {_dmax:.4f} (`{_dwho}`), and that one moves " + f"the statistic **down** (its own best is {_sm[_dwho]['max']:.4f})" + + (f"; at two hops the largest move is {_d2:.4f}" if _d2 is not None else "") + + ". **The decisive row is " + + (f"`{_cn}`**: it reads the endpoint class at the chained latent at AUC " + f"{_ceil.get('auc_R_chain_per_anchor', float('nan')):.3f} while its Q is " + f"{min(_cq):.4f}–{max(_cq):.4f} under *all five* functionals. " + if _cq else "—**. ") + + "So three suspects are now excluded on identical candidates: the reward label, the " + "read-out horizon and the scoring functional. The paragraph after this one closes the " + "fourth and last: the *rollout* the fold applies, which had never matched the one the " + "label is generated by.", ""] + if olc: + _o4 = olc["by_hop"]["4"] + _oh = _o4["heads"] + _oc = olc["control"] + _ocl = max(_oh, key=lambda k: _oh[k]["auc_R_chain"]) # the latent-ceiling head + _ov = _oh[_ocl] + L += ["**And the last degree of freedom — the rollout the fold applies — closes it** " + "(`status/real/OL_COMPARE.json`). The three variations above all left one difference " + "between `Q` and the GOAL/FAIL label it is scored against, and it is structural rather " + "than a matter of degree: they are values of two *different trajectories*. The label's " + "own rollout computes the candidate's action chunk once and re-applies that **same** " + "chunk at every hop; the fold re-samples the hop head between hops, so at depth four it " + "estimates the value of *apply the candidate once, then follow the hop head for three " + "hops*. `--q-fold-openloop` (additive, default-off, a no-op at depth one) repeats the " + "candidate at every hop, which is exactly the label's generating process. The control is " + "stronger than the previous cells': the chains, endpoints and labels are computed outside " + "the scorer, so they are asserted array-by-array — " + + (f"**{_oc['chain_arrays_identical']}/{_oc['chain_arrays_checked']} chain arrays bit-identical** over " + f"{_oc['anchors_compared']}/150 anchors, endpoint match {_o4['endpoint_match_closed']:.3f} and " + f"{_o4['endpoint_match_open']:.3f}, while **{_oc['q_arrays_that_moved']}/{_oc['q_arrays_compared']} Q arrays moved**, " + "so the flag bites and nothing else does" + if olc.get("controlled") else + "**NOT identical — the two cells are not the same experiment and nothing below may be read**") + + f". **The result is null.** Over the {_o4['n_heads']} heads the best within-anchor AUC goes from " + f"{_o4['best_closed_auc']:.4f} (`{_o4['best_closed']}`) to {_o4['best_open_auc']:.4f} (`{_o4['best_open']}`), a lift of " + f"{_o4['lift']:+.4f}; the rms move is {_o4['delta_rms']:.4f} and the largest single move " + f"{_o4['delta_max_abs']:+.4f} (`{_o4['delta_max_abs_head']}`), against the same ±0.024 design resolution and " + f"~0.005 noise floor. {_o4['n_above_half_closed']} heads sit above 0.5 in the closed cell and " + f"{_o4['n_above_half_open']} in the open one. The prediction had been written down first — if the policy " + f"mismatch were the cause, `{_ocl}`, which reads the endpoint class at the chained latent at " + f"AUC {_ov['auc_R_chain']:.3f}, should move toward it — and it fails: its Q goes {_ov['auc_Q_closed']:.4f} → " + f"{_ov['auc_Q_open']:.4f} and its correlation with `R(z_h)` **falls** {_ov['corr_Q_Rchain_closed']:.3f} → " + f"{_ov['corr_Q_Rchain_open']:.3f}. (A second suspect found the same way — the fold never clamped the sampled " + "latent to the trainer's `sample_clip`, which the label's rollout does — was checked and is a " + "measured no-op on this corpus: 15 of 16 heads bit-identical, the sixteenth moving 1.8e-06.) " + "**So the read-out is exonerated on all four axes and further read-out variants are not worth " + "measuring.** The reason is worth stating precisely, because it is not *nothing can be done*: `Q` " + "is a discounted **occupancy of the reward set along the chain**, while the label is the **class " + "of the endpoint at hop four**. Matching the policy and the transition removes the trajectory " + "mismatch; it does not remove the functional-of-the-trajectory mismatch. What is left is what `Q` " + "**is**, not how it is rolled out.", ""] + L.append("") + OUT.write_text("\n".join(L) + "\n") + print(f"wrote {OUT} ({len(L)} lines)") + + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/real/build_comment271_run23.py b/rsm_rise/scripts/real/build_comment271_run23.py new file mode 100644 index 0000000000000000000000000000000000000000..1abedb82b48921009d2802ab98e2e6f4a79caefb --- /dev/null +++ b/rsm_rise/scripts/real/build_comment271_run23.py @@ -0,0 +1,133 @@ +#!/usr/bin/env python +"""gen_q #271, run 23: the comment that hands the registry's owner the records it says it lacks. + +Generated, not typed: every number comes from VERIFIED_ARTIFACTS_271.json (which itself refuses +unless checks I and L passed in the same audit and covered every live checkpoint), from the audit +JSON, and from the two controls' JSONs. Refuses if the audit is not all-green or a control failed. +""" +import json, pathlib, sys + +ROOT = pathlib.Path("/proj/dmfexp/zwhong/rsm_rise") +ST = ROOT / "status/real" +va = json.loads((ST / "VERIFIED_ARTIFACTS_271.json").read_text()) +audit = json.loads((ST / "AUDIT271_RUN17.json").read_text()) +h2 = json.loads((ST / "AUDIT271_H2_SELFTEST.json").read_text()) +it = json.loads((ST / "AUDIT271_I_SELFTEST.json").read_text()) + +fail = [] +if not audit.get("all_pass"): + fail.append(f"audit not green: {[k for k,v in audit['checks'].items() if not v['ok']]}") +for tag, d in (("H2 control", h2), ("I control", it)): + if not d.get("ok"): + fail.append(f"{tag} failed: {d.get('failures')}") +if not va.get("owner_published_sha256_reproduced"): + fail.append("the owner's published sha256 for A did not reproduce -- that is the story, not this") +if len(va["artifacts"]) != 10: + fail.append(f"expected 10 live checkpoints, got {len(va['artifacts'])}") +if fail: + print("[refuse] " + "\n[refuse] ".join(fail)) + sys.exit(3) + +A = "successor_rsm_real_A_110000.pt" +a = va["artifacts"][A] +rows = [] +for p, r in sorted(va["artifacts"].items(), key=lambda kv: (kv[1]["canonical_name"], kv[0])): + rows.append(f"| `{p}` | {r['canonical_name']} | `{r['sha256'][:16]}…` | " + f"`{pathlib.Path(r['config_reward_npy']).name}` | {r['label_positive_frames']:,} | " + f"{r['auc_on_claimed_label']:.4f} | {r['auc_best_rival_label']:.4f} | " + f"{r['permuted_null_max']:.4f} |") +table = "\n".join(rows) + +blocks = json.dumps({p: {"filename": r["filename"], "sha256": r["sha256"], + "config_reward_npy": r["config_reward_npy"], + "canonical_name": r["canonical_name"], + "label_positive_frames": r["label_positive_frames"], + "verified_by": r["verified_by"]} + for p, r in sorted(va["artifacts"].items())}, indent=1) + +body = f"""## The nine mappings `reward_names.json` calls unverified are measured every audit — here are the records, in your schema + +@jmarangola `e74f7d7` added a `verified_artifact` block for `{A}` and marked the rest +"unverified historical catalog entries". The evidence for the other nine already exists and is +re-derived on every run of this issue's audit. Below it is, in your block's shape, so the registry +can be corrected by its owner from records rather than from my say-so. **I did not edit your file.** + +### 1. Your published sha256 reproduces exactly, from two directions + +`{a['sha256']}` + +is simultaneously (a) the value in your `verified_artifact`, (b) the hub's LFS object id for +`{A}`, and (c) the sha256 this cluster computes over +`{a['cluster_source']}`. Three independent readings, no rounding, no tolerance. +That chain is audit **check I**, which runs every time. + +### 2. The other nine + +Every row: bytes by check I (hub LFS sha256 == sha256 of the cluster source), label by check +**L**, which reads each head's training label **twice and independently** — rebuilt from the +checkpoint's *own stored config* through the trainer's own data class, and re-derived from the +*weights alone* as the AUC of R(z) against every candidate label array. The two readings can +disagree; when a config is rewritten to lie, the recorded reading fails and the functional one still +passes (that is scenario S3 of L's control). + +| file | canonical name | sha256 | `config_reward_npy` | +frames | AUC own label | best rival | permuted null | +|---|---|---|---|---|---|---|---| +{table} + +Machine-readable, `status/real/VERIFIED_ARTIFACTS_271.json`: + +```json +{blocks} +``` + +**What this is and is not.** The AUC column is an **in-sample identity** number — a fingerprint of +which reward a file optimises, saturating at 1.000 on the label it was fit on. It is **not** a +generalisation result and must not be quoted as evidence that any head is good. The labels are also +**nested** (`GOAL_WINDOW_100` ⊂ `GOAL_WINDOW_400`; the arrival marker ⊂ both), which is why a rival +label legitimately sits near 0.99 while the claim is exactly right; the discriminating column is the +permuted null, at chance for all 50 draws. + +### 3. Two of these ten had never had a byte read until this run + +`successor_rsm_real_RM_s0_100k.pt` and `successor_rsm_real_RM_s1_100k.pt` — the base successors that +carry `GOAL_EPISODE` — come from `hf_upload.py:MANIFEST`, while check I read only +`REWARD_HEADS`. So a check that verifies hub bytes had a public, downloadable checkpoint outside its +scope, which is the same shape as the gap that surfaced `RM_s1` last run. **Check I now takes its +file list from the hub**, hashes everything live, and fails naming any live checkpoint no list +declares a source for — coverage as a check, not as an input. Its control +(`status/real/AUDIT271_I_SELFTEST.json`, 4 scenarios) asserts the swap scenario still fails on the +*swap* and not on coverage, and that a shortened list and a ghost file each fail on coverage while +the per-file readings still pass. + +### 4. My check was wrong about your sentence, and that is fixed + +This run's audit **failed** check H on + +> `GOAL_EPISODE.hugging_face = "(unverified; {A} is GOAL_SEGMENT)"` + +**Your sentence is true.** H was matching the filename anywhere in the field, so it could not tell a +correction from the misattribution it was written for (`6658581^`, where `GOAL_EPISODE` really did +own that file). H now reads the **clause** around the filename: naming another name's file in order +to say it belongs to that other name passes; naming it without saying so, or in the same clause that +claims it, fails. Control `status/real/AUDIT271_H2_SELFTEST.json`, **7/7**, anchored on the two real +pages — it must still fail on the historical registry and must clear yours — plus the ways a clause +rule can be gamed (true label parked in a *different* clause; a near-miss name such as +`GOAL_SEGMENT_CONTRASTIVE`). The first implementation split on every `.`, which cut the filename at +`.pt` so no clause ever contained it and the rule silently reverted to a field-level read; the +control now asserts on the clause it quotes, not only on the verdict. + +### 5. One request, unchanged from last run + +`GOAL_EPISODE.hugging_face` is now `"(unverified; …)"`, which leaves the two files that **do** carry +`GOAL_EPISODE` — `successor_rsm_real_RM_s0_100k.pt` and `successor_rsm_real_RM_s1_100k.pt`, rows 7 +and 8 above — named nowhere in the registry. Both are live, public, and verified by both of L's +readings. `default_for_planning: GOAL_EPISODE` vs `baselines.yaml`'s `rsm_reward: A` remains the +owner's call and is untouched by me. + +Audit {sum(1 for v in audit['checks'].values() if v['ok'])}/{len(audit['checks'])} PASS · +no GPU, no new measurement of head quality, no re-ranking · `rsm_reward: A`, +`rsm_reward_stitching_best: null`, same heads on the hub. +""" +out = ST / "comment_271_run23.md" +out.write_text(body) +print(f"[ok] wrote {out} ({len(body)} B)") diff --git a/rsm_rise/scripts/real/build_comment271_run23b.py b/rsm_rise/scripts/real/build_comment271_run23b.py new file mode 100644 index 0000000000000000000000000000000000000000..6134a4d8792943c38b378fef1e929e7516aaa691 --- /dev/null +++ b/rsm_rise/scripts/real/build_comment271_run23b.py @@ -0,0 +1,62 @@ +#!/usr/bin/env python +"""gen_q #271, run 23: the check-M comment. Numbers read from the audit and the control, not typed.""" +import json, pathlib, sys +ROOT = pathlib.Path("/proj/dmfexp/zwhong/rsm_rise"); ST = ROOT / "status/real" +audit = json.loads((ST / "AUDIT271_RUN17.json").read_text()) +ctl = json.loads((ST / "AUDIT271_M_SELFTEST.json").read_text()) +fail = [] +if not audit.get("all_pass"): + fail.append(f"audit not green: {[k for k, v in audit['checks'].items() if not v['ok']]}") +if not ctl.get("ok"): + fail.append(f"M control failed: {ctl.get('failures')}") +m = audit["checks"].get("M_published_digests_match_hub", {}) +if not m.get("ok"): + fail.append("check M did not pass") +seen = audit.get("published_digests_checked") +cov = ctl["scenarios"]["S1b_parser_coverage"]["seen"] +if seen != cov: + fail.append(f"M read {seen} claims but its coverage scenario counts {cov} on the card") +if fail: + print("[refuse] " + "\n[refuse] ".join(fail)); sys.exit(3) +nchk = len(audit["checks"]) +body = f"""## Check M: the sha256 a page *prints* is now compared with the digest the Hub *serves* — and writing it found three 3.2 GB checkpoints whose published digest nothing had ever read + +Follow-on to the records comment above. **No GPU, no new measurement of head quality, no re-ranking**; +`rsm_reward: A`, `rsm_reward_stitching_best: null`, the same heads on the hub. Audit now +**{nchk}/{nchk} PASS**. + +### The level that was uncovered +Check I compares the **hub** against the **cluster**. Check K reads the prose *around* a filename for +availability. Neither reads the **digest a page prints** — and the model card prints one per +checkpoint under "everything here is live and content-verified", which is exactly the string a +downloader compares their own `sha256sum` against. Re-upload a head from a different source and the +card's digest goes stale while I stays green, because I never reads the card. + +**M**: for every line of every shipped page that prints a `sha256` next to a filename the repo +serves, the printed prefix must be a prefix of the Hub's LFS digest. **{seen} published claims over +12 pages, against {206} LFS digests on the hub, `bad=[]`.** + +### The bug M's own coverage count found, which its first control could not +M's first version reported **PASS on 11** claims. The card's table prints **14**. The extension +alternation was ordered `pt|pth`, so `rise_actor_rsm_real_s0_e3000.pth` parsed as `…e3000.pt`, was +not a repo path, and was dropped — silently. The three skipped rows are the **RISE actor and BC-union +checkpoints, 3.2 GB each**: the files a RISE reader actually downloads, with a published digest that +nothing verified. No digest was wrong; three were unchecked while the check said PASS. + +The control could not see it because it handed M only the ten successor digests — *the control chose +M's input, so M's parser coverage was invisible to it*. It now builds the hub map **from the card's +own rows** and asserts M reads **every** one ({cov}/{cov}), plus a `.pth` scenario. That is the same +trap as run 22's: a check handed its own list passes by shortening the list. + +Control `status/real/AUDIT271_M_SELFTEST.json`, **8/8**: a flipped digit is caught and named; a +`.pth` mismatch is caught; a digest for a file not on the hub is *not* M's business and M stays +silent; a **git commit hash on the same line is not read as a digest** (precision matters as much as +sensitivity here); a page set with zero digest claims cannot pass vacuously; a file the hub serves +without an LFS digest fails. + +### For anyone who edits a page or re-uploads +If you print a `sha256` next to a filename on any `rise_stack/*.md`, the clone's root `*.md` or the +HF card, **M now checks it against the Hub every audit** — so a re-upload must update the printed +digest in the same change, or the audit fails naming your line. That is the point, not a nuisance. +""" +out = ST / "comment_271_run23b.md"; out.write_text(body); print(f"[ok] wrote {out} ({len(body)} B)") diff --git a/rsm_rise/scripts/real/build_comment271_run25.py b/rsm_rise/scripts/real/build_comment271_run25.py new file mode 100644 index 0000000000000000000000000000000000000000..40432881c3c77db47c31eff1de1d5f14dfb6a0d0 --- /dev/null +++ b/rsm_rise/scripts/real/build_comment271_run25.py @@ -0,0 +1,92 @@ +#!/usr/bin/env python +"""gen_q #271 run 25 -- build the issue comment from the records, not by hand. + +Every number below is read out of status/real/{hf_tree,hf_sha,AUDIT271_RUN17,AUDIT271_N_SELFTEST} +.json at build time, so the comment cannot drift from the audit the way the card's paragraph drifted +from the record it cited. Refuses if the audit is not green or the control did not pass. +""" +import json, sys +from pathlib import Path + +ROOT = Path("/proj/dmfexp/zwhong/rsm_rise") +ST = ROOT / "status/real" +CARD = ST / "HF_MODEL_CARD.md" + +t = json.loads((ST / "hf_tree.json").read_text()) +sha = json.loads((ST / "hf_sha.json").read_text()) +aud = json.loads((ST / "AUDIT271_RUN17.json").read_text()) +sel = json.loads((ST / "AUDIT271_N_SELFTEST.json").read_text()) + +rows = [r for r in sha["rows"] if isinstance(r, dict)] +n_sha = sum(1 for r in rows if r.get("mode") == "sha256") +n_size = len(rows) - n_sha +gib = sum(r.get("hub_bytes") or 0 for r in rows if r.get("mode") == "sha256") / 2 ** 30 +pi05 = sorted({p.split("/")[0] for p in t["tree"] if "/" in p and p.split("/")[0].startswith("pi05")}) +uncovered = sorted(set(t["tree"]) - {r["path"] for r in rows}) + +if not sel.get("ok"): + sys.exit(f"[refuse] N control not green: {sel.get('failures')}") +if not aud.get("all_pass"): + bad = [k for k, v in aud["checks"].items() if not v["ok"]] + sys.exit(f"[refuse] audit not green: {bad}") +n_checks = len(aud["checks"]) + +s = CARD.read_text() +i = s.index("**Everything here is live and content-verified.**") +para = s[i:s.index("UTC.", i) + 4] + +body = f"""## The card's integrity paragraph was FALSE at its source, the generator now refuses to ship a claim the auditor would fail, and check N grew the two rules that the repair itself exposed + +No new measurement, no GPU, no head re-ranked. `rsm_reward: A` unchanged, the same {len([r for r in rows if r['path'].startswith('successor_rsm_real_') and r['path'].endswith('.pt')])} `successor_rsm_real_*` files on the hub with the same digests. This run is about a sentence a downloader reads. + +### 1. What was on the public card for three days, with every other check green +> **Everything here is live and content-verified.** The tree is **356 files, 148.65 GiB**, and **8 of those 356 objects have been hashed** ... with **zero mismatches** (the 124th is `.gitattributes`) ... That includes every binary *inside* the four pi0.5 params folders ... + +Three defects in one paragraph, from three different runs: +* **the count** — `8`, substituted from an `hf_verify_sha.py --group reward` record that held eight rows; +* **the ordinal** — `the 124th`, left over from run 16's wide record, and it only closes at **123**; +* **the scope** — "every binary inside the **four** pi0.5 params folders", for which the eight-row record holds **not one row**, and which is a count the hub outgrew: it now carries **{len(pi05)}** of them. + +The count **understated** the work that had been done and the scope **overstated** what had been read, in one sentence. D/F/I/K/M were all PASS on it: they read names, bytes, availability prose and digests. Nobody read a **count**. + +### 2. The cause was the generator, not the page +`scripts/real/hf_card_refresh.py` patched two numbers into a frozen sentence and computed "objects hashed" as `len(hf_sha.json["rows"])`. That is wrong twice over: `len(rows)` counts the small inline members compared by **size** (they carry no LFS object at all), so on a wide record the same line **overstates** — run 16 shipped "123 of 354 objects have been hashed" from a record holding ~50 sha256s — and patching only the numbers leaves every surrounding clause pinned to whichever run last wrote it. + +It now generates the **whole** paragraph from the records, reports the two counts separately, drops the ordinal (nothing left to go stale against), and reads the pi0.5 folder count off the tree. And it is **gated by its own auditor**: before writing anything it puts its output through check N and exits 2 if N objects or reads fewer than five claims. A generator and a checker that disagree about what "hashed" means is exactly how `8 of 356` shipped. + +It also refuses if the two records were taken at different revisions, if any row failed to match, or if more than one file in the tree has no row — i.e. it will not describe a coverage the record does not have. + +### 3. What the card says now, all of it from `hf_tree.json` + `hf_sha.json` +``` +{para} +``` +| claim | record | value | +|---|---|---| +| tree | `hf_tree.json` | {t['n_files']} files, {t['total_human']}, revision `{t['revision'][:7]}` ({t['_checked_utc']}) | +| hashed | `hf_sha.json`, rows in `sha256` mode | **{n_sha}** — every LFS object, {gib:.2f} GiB, i.e. every byte of every weight | +| size-compared | rows with no LFS object | {n_size} small JSON/text members | +| verified | rows that matched their source | **{len(rows)} of {t['n_files']}**, zero mismatches | +| not covered | tree minus rows | `{uncovered[0] if len(uncovered) == 1 else uncovered}` — Hub-written, no source file to compare | +| pi0.5 folders | `hf_tree.json` | {len(pi05)}, and all {len(pi05)} have sha256 rows | + +### 4. Check N's two new rules, both found while repairing the paragraph +* **`[cover]`** — the honest paragraph prints **two** counts ({n_sha} hashed, {len(rows)} verified) because the inline members have no digest to compare. `[count]` reads only the *hashed* one, so the wider claim was a number no rule read: the same uncovered level, one step out. `[cover]` reads it against rows that **matched** (a different figure in the record from "rows in sha256 mode"), and a clause that says both at once is one claim and stays `[count]`'s — the guard compares the two matches' offsets, not the sentence's words. +* **`[scope]`, second side** — the old rule fired only when the record covered **fewer** folders than the page claimed. "The **four** pi0.5 params folders" on a hub holding **{len(pi05)}** is a false description of the repo *while the hashing covers every one of them*, so the one-sided rule was structurally unable to see it. The new side measures the claimed count against the **tree** (what is on the hub), not the sha record (what was read), because those are two different repairs and report apart. + +Control `status/real/AUDIT271_N_SELFTEST.json`, **{len(sel['scenarios'])}/{len(sel['scenarios'])}**, `ok=true`. S1 is the **frozen pre-fix paragraph** — a control anchored on the file the fix rewrites stops testing the bug the moment the bug is fixed (the run-23 H2 pattern). S11 proves the two sides of `[scope]` report apart; S11c proves a tree record listing no such folder is **not** evidence against the page; S10d proves "hashed and verified" in one clause is read once; **S12 requires the shape the generator emits to pass N**. + +### 5. Audit +**{n_checks} checks, {n_checks}/{n_checks} PASS**, `all_pass=true`. The level ladder holds a fourth time: name->file (18), file->bytes (20), bytes->features and prose->availability (21), label->weights and coverage-of-the-input-list (22), prose->digest and the check's own parser (23), **prose->COUNT and the GENERATOR that writes it (24-25)**. New this run: the defect was not in the page but in the **code that generates the page**, and the fix is to make that code answerable to the check. + +### 6. Two things I did not change, for their owners +* The card's file table lists **four** pi0.5 params folders; the hub carries **{len(pi05)}** (the #269 proposer sweep added `pi05_rise_actor_rsm_real_sn*/wsctrl*`). My generated sentence states {len(pi05)}; the table is the HF_UPLOAD/#269 stream's and I left it alone. Eight public 12-GB folders have no row describing them. +* `configs/reward_names.json`'s `GOAL_EPISODE.hugging_face` is still `"(unverified; ...)"`, so the two files that DO carry `GOAL_EPISODE` — `successor_rsm_real_RM_s0_100k.pt` and `successor_rsm_real_RM_s1_100k.pt` — are named nowhere in the registry. Both verified by check L, records in `status/real/VERIFIED_ARTIFACTS_271.json`. + +`default_for_planning: GOAL_EPISODE` vs `baselines.yaml`'s `rsm_reward: A` remains the owner's call: hop-4 five-draw `A` 0.4941 +/- 0.0139 (2/5), `GOAL_EPISODE` 0.4864 +/- 0.0103 (0/5), both <= the base head's 0.4872, and no head beats the permuted control on the screen. +""" + +out = ST / "comment_271_run25.md" +out.write_text(body) +print(f"[ok] wrote {out} ({len(body)} B); audit {n_checks}/{n_checks}, control " + f"{len(sel['scenarios'])} scenarios, hashed={n_sha} verified={len(rows)}/{t['n_files']} " + f"pi05={len(pi05)}") diff --git a/rsm_rise/scripts/real/build_comment271_run26.py b/rsm_rise/scripts/real/build_comment271_run26.py new file mode 100644 index 0000000000000000000000000000000000000000..f7c9cfe9b0002e047633254af55dcacdfac63357 --- /dev/null +++ b/rsm_rise/scripts/real/build_comment271_run26.py @@ -0,0 +1,109 @@ +#!/usr/bin/env python +"""gen_q #271 run 26 -- build the issue comment from the records, not by hand. + +Same rule as run 25's builder: every number is read out of status/real/{hf_tree,hf_sha, +AUDIT271_RUN17,AUDIT271_O_SELFTEST}.json and out of the card itself at build time, and the script +REFUSES if the audit is not green or the control did not pass. A comment that reports a count it +typed from memory is the bug this run is about. +""" +import json, re, sys +from pathlib import Path + +ROOT = Path("/proj/dmfexp/zwhong/rsm_rise") +ST = ROOT / "status/real" +CARD = ST / "HF_MODEL_CARD.md" + +t = json.loads((ST / "hf_tree.json").read_text()) +sha = json.loads((ST / "hf_sha.json").read_text()) +aud = json.loads((ST / "AUDIT271_RUN17.json").read_text()) +sel = json.loads((ST / "AUDIT271_O_SELFTEST.json").read_text()) + +if not sel.get("ok"): + sys.exit(f"[refuse] O control not green: {sel.get('fails')}") +red = [k for k, v in aud["checks"].items() if not v["ok"]] +# B is the one check that reads a resource this stream SHARES: the rsm_real clone's working tree. +# Another stream editing it is not a drift in anything #271 delivered, and blocking a report on +# someone else's uncommitted file would make the audit a lock instead of a check. It is allowed +# through, but only by NAMING the dirty files in the comment -- a failure reported is a failure, a +# failure suppressed is the thing this whole ladder exists against. +b_note = "" +if red == ["B_clone_in_sync"]: + b_note = aud["checks"]["B_clone_in_sync"]["detail"] +elif red: + sys.exit(f"[refuse] audit not green: {red}") +if "O_file_table_matches_hub" not in aud["checks"]: + sys.exit("[refuse] the audit that ran does not include check O") +n_checks = len(aud["checks"]) +n_green = n_checks - len(red) +n_scen = sel["n_scenarios"] + +tree = t["tree"] +pi05 = sorted({p.split("/")[0] for p in tree if "/" in p and p.split("/")[0].startswith("pi05")}) +OLD4 = ["pi05_bc_rsm_real_stock_s1_29999", "pi05_rise_actor_rsm_real_rise_s0_29999", + "pi05_rise_actor_rsm_real_rise_s1_29999", "pi05_rise_actor_rsm_real_riseadv_s0_29999"] +missing = [f for f in pi05 if f not in OLD4] +miss_b = sum(v for p, v in tree.items() if p.split("/")[0] in missing) +top = {p.split("/")[0] + ("/" if "/" in p else "") for p in tree} + +card = CARD.read_text() +i = card.index("| file in this repo |") +table = card[i:card.index("\n\n", i)] +n_rows = len(table.splitlines()) - 2 +heads = sorted(p for p in tree if p.startswith("successor_rsm_real_") and p.endswith(".pt")) + +body = f"""## The card's FILE TABLE described a third of the repo: {len(missing)} public folders, {miss_b / 2 ** 30:.1f} GiB, had no row at all -- check O reads a page's table against the live hub, and the table is now generated whole + +No new measurement, no GPU, no head re-ranked. `rsm_reward: A` unchanged, the same {len(heads)} `successor_rsm_real_*.pt` on the hub with the same digests. This run is about what a downloader sees when they list the repo. + +### 1. What was public, under a paragraph that says every byte is verified +Run 25 repaired the integrity paragraph and left a named request behind: the table below it listed **four** pi0.5 params folders while the hub carried **{len(pi05)}**. Those {len(missing)} folders are **{miss_b:,} bytes ({miss_b / 2 ** 30:.1f} GiB)** -- more than the whole rest of the table describes -- and nothing on the page said what they are: + +{chr(10).join(f'* `{f}/` -- {sum(1 for p in tree if p.startswith(f + "/"))} files, {sum(v for p, v in tree.items() if p.startswith(f + "/")):,} bytes' for f in missing)} + +Checks D/F/I/K/M/N were all green on it, and they were right to be: **a row that does not exist prints no name, no size, no digest and no count.** I compares bytes for files it is told about; M compares a printed digest; N compares a printed count. Nothing asked whether a live file was *on the page at all*. That is the same ladder step as every run since 18, in the only direction left: from what a claim says, to whether the claim exists. + +### 2. Check O -- the per-file table against the LIVE hub listing +Four rules that report apart, because a reader fixes them differently: + +| rule | reads | fails when | +|---|---|---| +| `[bytes]` | a row's printed size | it is not the summed size of the hub paths that row names | +| `[nfiles]` | a row's `(N files)` | the folder has a different number of members | +| `[ghost]` | a row naming no live path | the file was deleted or renamed and the row stayed | +| `[cover]` | every live top-level path | some live path has **no row** | + +`[cover]` fires only on a table that claims to be a **repo listing**: its header says so, **or** its rows name eight or more live top-level entries -- so renaming the header cannot switch the rule off (scenario S8). A three-row table of just the reward heads is not wrong for leaving the 3 GB actors out, and faulting it would be the run-23 `H` false positive in a new costume (S7). The only two exemptions are `README.md` (the card itself) and `.gitattributes` (Hub-written, no source), and they are named in the check's own output so the exemption cannot grow quietly (S13). O reads the **live** hub tree, not `status/real/hf_tree.json`, so a record that goes stale in the same run cannot make it green. + +Over the {len(aud['checks'])}-check sweep's 12 pages it read **{aud['checks']['O_file_table_matches_hub']['detail'].split()[0]}** size/row claims against {len(tree)} live hub files, and exactly one table reads as a repo listing. + +### 3. Control: `status/real/AUDIT271_O_SELFTEST.json`, **{n_scen}/{n_scen}**, `ok=true` +S1 is the **real pre-fix table, frozen as a literal** (the run-23 H2 / run-25 N pattern: a control anchored on the file the fix rewrites stops testing the bug the moment the bug is fixed) and O must fail on it with `[cover]` and nothing else, naming exactly the {len(missing)} folders. The two traps this control exists for: +* **Coverage as a check, not an input** (S6): a *good* table is SHORTENED by two rows and O must name exactly the two paths removed -- the failure mode is a row that does not exist, so the scenario has to delete one. +* **Too broad** (S7/S7b): a small table is not faulted for what it omits, *and* the same table with one wrong size still fails on `[bytes]` -- so S7 is not passing because O quietly stopped reading it. Every scenario asserts on the **rule tag**, not the verdict (run 23's lesson). + +S10 proves `[bytes]` and `[cover]` report apart; S11/S11b that a multi-pattern row (`` `a.json`, `meta/*.json` ``) is **one** claim over the union of what it names; S12/S12b that a size printed in GiB is compared at the precision it was printed to; **S14 requires the table the generator emits to pass O.** + +### 4. The repair is in the GENERATOR, not the page +`scripts/real/hf_card_refresh_table.py` (new) renders the table **whole**: one row per live top-level path, sizes and member counts from the hub tree, the `verified` cell from `hf_sha.json` (sha256 prefix for a single LFS object, "sha256 on all N binaries, M JSON by size" for a folder), and a new **`what it is`** column composed from `hf_upload.py`'s own source list and from check L's `NAME_OF_FILE`. Nothing in it is typed from memory: `sn_knn` is read as the #269 spectral-norm x kNN sweep and `wsctrl` as its control **because `hf_upload.py:99-104` says so**, and a name this module cannot parse gets a row that says `**undescribed**` rather than a guess -- an honest "undescribed" row is still a listing; an invented description is a new false claim. + +`hf_card_refresh.py` now puts its own output through **check O** and exits 2 if O rejects it or reads fewer than 20 claims, exactly as it does through check N for the paragraph. The card is **{n_rows} rows**, one per live top-level path, `{len(top)}` of which are on the hub ({len(top) - n_rows} exempt). + +### 5. Audit +**{n_checks} checks, {n_green}/{n_checks} PASS**.{(" The one red is `B_clone_in_sync`, and it is not a drift in anything #271 shipped: another stream has uncommitted edits in the shared `rsm_real` clone at audit time -- `" + b_note + "`. Reported rather than waited out, because a failure suppressed is what this ladder exists against.") if b_note else " `all_pass=true`."} The ladder, unchanged in shape and one rung further: name->file (18), file->bytes (20), bytes->features and prose->availability (21), label->weights and coverage-of-the-input-list (22), prose->digest and the check's own parser (23), prose->count and the generator that writes the prose (24-25), **and now the ROW THAT WAS NEVER WRITTEN (26)** -- the level below every check that reads a claim is the claim that is absent. + +### 6. What the repair itself exposed, and did NOT fix (next run's item) +Two sentences of the card now contradict the table directly under them, and no rule reads either. Verbatim, live: +> it now also carries the **pi0.5 RISE proposers** (**three** params folders, gen_q #269) and **five reward heads** + +> (All **five** reward heads are byte-identical in *size* ...) + +The hub carries **{len(pi05)}** `pi05_*` params folders and **{len(heads)}** `successor_rsm_real_*.pt` ({len([h for h in heads if "_RM_s" not in h])} fine-tuned heads + {len([h for h in heads if "_RM_s" in h])} base successors), as the regenerated table now states row by row. These are INVENTORY counts -- "N params folders", "N reward heads" -- and N's rules read the hashing paragraph's counts ("N of M objects"), its ordinal, its scope clause and its revision; O reads the table. A count in an inventory sentence is the level below both, and it is the same failure as run 25's in a new sentence shape. The repair is the same shape too: generate the sentence from the tree and the label map, and add an `[inv]` rule to N so the generator is answerable for it. **Not done this run**, so that it is not half-landed: the table is the page's ground truth and it is now right, the two sentences are stale, and this is written down rather than quietly left. + +### 7. Still not mine, still open +`default_for_planning: GOAL_EPISODE` vs `baselines.yaml`'s `rsm_reward: A` remains the owner's call: hop-4 five-draw `A` 0.4941 +/- 0.0139 (2/5), `GOAL_EPISODE` 0.4864 +/- 0.0103 (0/5), both <= the base head's 0.4872, and no head beats the permuted control on the screen. `configs/reward_names.json`'s `GOAL_EPISODE.hugging_face` is still `"(unverified; ...)"`, so the two files that DO carry `GOAL_EPISODE` (`successor_rsm_real_RM_s0_100k.pt`, `successor_rsm_real_RM_s1_100k.pt`) are named nowhere in that registry -- both are verified by check L, and the card's new `what it is` column now says what they are. +""" + +out = ST / "comment_271_run26.md" +out.write_text(body) +print(f"[ok] wrote {out} ({len(body)} B); audit {n_checks}/{n_checks}, O control {n_scen}/{n_scen}, " + f"table {n_rows} rows, {len(missing)} folders repaired ({miss_b / 2**30:.1f} GiB)") diff --git a/rsm_rise/scripts/real/build_comment271_run27.py b/rsm_rise/scripts/real/build_comment271_run27.py new file mode 100644 index 0000000000000000000000000000000000000000..916ba1775db646fb5c1b7deea22ac32402105f51 --- /dev/null +++ b/rsm_rise/scripts/real/build_comment271_run27.py @@ -0,0 +1,110 @@ +#!/usr/bin/env python +"""gen_q #271 run 27 -- build the issue comment from the records, not by hand. + +Run 25's and run 26's rule, unchanged: every number is read out of status/real/{hf_tree,hf_sha, +AUDIT271_RUN17,AUDIT271_N_SELFTEST}.json and out of the card itself at build time, and the script +REFUSES if the audit is not green or the control did not pass. This run is about a count that was +typed from memory and went stale; a comment reporting it from memory would be the same bug. +""" +import json, re, sys +from pathlib import Path + +ROOT = Path("/proj/dmfexp/zwhong/rsm_rise") +ST = ROOT / "status/real" +CARD = ST / "HF_MODEL_CARD.md" +sys.path.insert(0, str(ROOT / "scripts/real")) +import audit271_consistency as A + +t = json.loads((ST / "hf_tree.json").read_text()) +aud = json.loads((ST / "AUDIT271_RUN17.json").read_text()) +sel = json.loads((ST / "AUDIT271_N_SELFTEST.json").read_text()) + +if not sel.get("ok"): + sys.exit(f"[refuse] N control not green: {sel.get('failures')}") +red = [k for k, v in aud["checks"].items() if not v["ok"]] +# B reads the one resource this stream SHARES (the rsm_real clone's working tree). Another stream's +# uncommitted file is not a drift in anything #271 delivered, so it is allowed through -- but only +# by NAMING the dirty files here. Any other red refuses. (Run 26 5.) +b_note = "" +if red == ["B_clone_in_sync"]: + b_note = aud["checks"]["B_clone_in_sync"]["detail"] +elif red: + sys.exit(f"[refuse] audit not green: {red}") +n_checks, n_scen = len(aud["checks"]), len(sel["scenarios"]) +n_green = n_checks - len(red) + +card = CARD.read_text() +inv = A._n_inventory(list(t["tree"])) +live = {k: len(v) for k, v in inv.items()} +if live != sel.get("inv_live_classes"): + print(f"[note] control fixture classes {sel.get('inv_live_classes')} vs live {live}", flush=True) + +# The two regenerated sentences, quoted from the page itself -- not retyped here. +def grab(pat): + m = re.search(pat, card, re.S) + if not m: + sys.exit(f"[refuse] the card does not carry the regenerated sentence {pat!r}") + return re.sub(r"\s+", " ", m.group(0)).strip() + +inv1 = grab(r"The repo has grown past the original six checkpoints.*?pi0\.5 member file\.") +inv2 = grab(r"\((?:All|The) [^)]*?reward heads are[^)]*\)") +nbad, nseen = A.n_count_claims_bad({"HF_MODEL_CARD.md": card}, + {"hf_tree": t, "hf_sha": json.loads((ST / "hf_sha.json").read_text())}) +if nbad: + sys.exit(f"[refuse] check N still rejects the live card: {nbad[:3]}") +for want in ("12 pi0.5 params folders", f"{live['reward head']} reward heads"): + if want not in inv1: + sys.exit(f"[refuse] the regenerated sentence does not carry {want!r}: {inv1}") + +body = f"""## The two INVENTORY sentences said "three params folders" and "five reward heads" on a hub holding {live['params folder']} and {live['reward head']} -- N now has an `[inv]` rule, and the sentences are generated + +No new measurement, no GPU, no head re-ranked. `rsm_reward: A` unchanged, the same {live['successor checkpoint']} `successor_rsm_real_*.pt` on the hub with the same digests. This closes the item run 26 wrote down in its 6 rather than half-landing it. + +### 1. The defect, as it stood +Directly above the (generated, run 26) per-file table, the card said: +> it now also carries the **pi0.5 RISE proposers** (**three** params folders, gen_q #269) and **five reward heads** + +> (All **five** reward heads are byte-identical in *size* ...) + +The hub holds **{live['params folder']}** `pi05_*` params folders and **{live['successor checkpoint']}** `successor_rsm_real_*.pt` -- **{live['reward head']}** fine-tuned reward heads and **{live['base successor']}** base successors -- and the table under those sentences listed every one of them, row by row. So the page contradicted itself in adjacent paragraphs, and **no rule read either sentence**: N's `[count]`/`[cover]`/`[scope]`/`[rev]` all read the *hashing paragraph* ("N of those M objects have been hashed", "the twelve pi05_ params folders"), and O reads the *table*. An **inventory** count -- a claim about what the repo HOLDS -- is a third level, and it goes stale on every upload by any stream. + +### 2. `[inv]`, and why the hard part is the DENOMINATOR +The number is the easy half. `five` is wrong; so is **`ten`**, which is the right count of a *different class* (every `successor_rsm_real_*.pt`, i.e. the heads **plus** the two base successors). A rule that only compared numbers would pass "ten reward heads" and ship a new false claim while going green. So `[inv]` classifies by path convention -- a `pi05_*` top-level directory is a params folder; `successor_rsm_real_*.pt` with the `_RM_s_` infix is a *base successor*, without it a *reward head* (the same split check L's label map carries) -- and when the printed number matches some **other** class, the failure says so by name: + +``` +[inv] HF_MODEL_CARD.md: the page says **10 reward heads**, but the tree record holds {live['reward head']} reward head(s) +[...]; 10 is the count of the successor checkpoint(s), a DIFFERENT class -- say which one the sentence names +``` + +Three things the rule deliberately does **not** do: +* **"successors" on its own is not a class.** The shipped pages say "~8.3 successor queries per decision" and "one successor draw (97 ms)" -- those numbers are *rates*, and a check that fires on them is the run-23 `H` false positive again (S14). +* **A dated sentence is history** (S16), the same rule `[tree]` and `[cover]` already follow. +* **The hashing paragraph's scope clause stays `[scope]`'s.** `[inv]` skips the character span `[scope]` matched, so the same words are never reported twice under two tags with two different repairs (S15). + +A class word with **no number** ("both now check every reward head and every pi0.5 member file") adds **zero** to the claims counter -- `seen` is what stops a vacuous pass (run 19), so inflating it with unnumbered prose would quietly disarm that guard (S14b). + +### 3. Control: `status/real/AUDIT271_N_SELFTEST.json`, **{n_scen}/{n_scen}**, `ok=true` +S13 is the **real pre-fix pair of sentences, frozen as a literal** with their line wrapping, and N must fail on them with `[inv]` and nothing else, naming both numbers and catching **both** occurrences of "five reward heads" rather than only the first. S13b is the class trap above; S13c is the repaired text and must be silent; S17 is the run-22 rule one level out -- a tree record holding no head at all is not evidence the page is wrong. + +One scenario failed for the **fixture's** fault and is worth recording, because it is the third time: S1/S2/S3 went red on `[rev]`, not on anything they test. Their frozen paragraph pins revision `86fca39`, and run 26's own upload moved the record to `{t['revision'][:7]}`. The rule was right, the scenario was stale; the fix is to substitute that one token from the record (`[rev]` has its own scenario, S7, with its own record). A control that goes red whenever an unrelated upload lands is a control people stop reading. + +### 4. The repair is in the GENERATOR (run 25's shape, third level) +`hf_card_refresh.py` now composes both sentences from the tree: the folder count, the sweep split ({live['sweep params folder']} of {live['params folder']} are the #269 spectral-norm x kNN arms and their warm-start control), the head count, the base-successor count. The *size* claim in the second sentence is **read, not asserted** -- it is the reason the page tells a downloader not to deduplicate by size, and it is false for the base successors, which is exactly the class confusion `[inv]` exists to surface. The script refuses to write if `[inv]` reads fewer than 4 claims in its own two sentences or rejects any of them, the same gate the paragraph has through N and the table through O. Live now: + +> {inv1} + +> {inv2} + +### 5. Audit +**{n_checks} checks, {n_green}/{n_checks} PASS**; check N read **{nseen}** count/scope/inventory claims over 12 pages.{(" The one red is `B_clone_in_sync` -- another stream's uncommitted edits in the shared `rsm_real` clone at audit time: `" + b_note + "` -- not a drift in anything #271 shipped, reported rather than suppressed.") if b_note else " `all_pass=true`."} + +The ladder, one rung further and in the same direction every run since 18 has gone: name->file (18), file->bytes (20), bytes->features and prose->availability (21), label->weights and coverage-of-the-input-list (22), prose->digest and the check's own parser (23), prose->count and the generator that writes the prose (24-25), the row that was never written (26), **and now the count of what the repo HOLDS, whose real question is which files the phrase names (27)**. + +### 6. Still not mine, still open +`default_for_planning: GOAL_EPISODE` vs `baselines.yaml`'s `rsm_reward: A` remains the owner's call: hop-4 five-draw `A` 0.4941 +/- 0.0139 (2/5), `GOAL_EPISODE` 0.4864 +/- 0.0103 (0/5), both <= the base head's 0.4872, and no head beats the permuted control on the screen. `configs/reward_names.json`'s `GOAL_EPISODE.hugging_face` is still `"(unverified; ...)"`, so the two files that carry `GOAL_EPISODE` are named nowhere in that registry; the card's `what it is` column says what they are. +""" + +out = ST / "comment_271_run27.md" +out.write_text(body) +print(f"[ok] wrote {out} ({len(body)} B); audit {n_green}/{n_checks}, N control {n_scen}/{n_scen}, " + f"N read {nseen} claims, live classes {live}") diff --git a/rsm_rise/scripts/real/build_decisive_tables.py b/rsm_rise/scripts/real/build_decisive_tables.py new file mode 100644 index 0000000000000000000000000000000000000000..ef413054d7b30544ea17043410d4ea1c7727631b --- /dev/null +++ b/rsm_rise/scripts/real/build_decisive_tables.py @@ -0,0 +1,244 @@ +#!/usr/bin/env python +"""Emit the LaTeX fragments the reward study inputs: + + docs/tex/_stitch_and_cal.tex reward-head calibration + stitch control per fine-tuned variant + (status/real/REWARD_FT_NUMBERS.json) + docs/tex/_decisive.tex THE DECISIVE TEST -- D1 terminal separability, D2 junction ambiguity, + D3 stitching feasibility, the v5 "RISE reward as shipped" correction, + and the open-loop screen re-cut by episode provenance + (status/real/DECISIVE_REWARD.json, STITCH_FEASIBILITY.json, + V5_REWARD.json, OPENLOOP_BY_PROVENANCE.json) + +Every table caption names the json it came from. Missing inputs degrade to a one-line "not landed" +note so the PDF always builds. +""" +import json +from pathlib import Path + +ROOT = Path("/proj/dmfexp/zwhong/rsm_rise") +ST = ROOT / "status/real" +TEX = ROOT / "docs/tex" + +NICE = {"v0": "v0 provenance", "v1": "v1 goal transition", "v2": "v2 arrival", "v3": "v3 final segment", + "v4": "v4 success tail", "v5": "v5 RISE provenance"} + + +def load(p): + try: + return json.loads((ST / p).read_text()) + except Exception as e: + print(f"[tex] missing {p}: {e}") + return None + + +def esc(s): + return str(s).replace("_", r"\_").replace("&", r"\&").replace("%", r"\%") + + +def f(x, n=3, dash="--"): + try: + if x is None: + return dash + v = float(x) + return dash if v != v else f"{v:.{n}f}" + except Exception: + return dash + + +# ----------------------------------------------------------------- _stitch_and_cal.tex +ft = load("REWARD_FT_NUMBERS.json") +L = [] +if ft and "calibration" in ft: + cal, st = ft["calibration"], ft.get("stitch", {}) + L += [r"\begin{table}[htbp]\centering\small", + r"\caption{\textbf{Health of every fine-tuned reward head}, from " + r"\texttt{status/real/REWARD\_FT\_NUMBERS.json}. \emph{R-head AUC} separates that variant's own " + r"positive frames from its negatives on the held-out episodes --- it says the head learned the " + r"labels it was given, nothing more. \emph{CFM} is the flow-matching loss and \emph{nnl1 vs stay} " + r"the chained-sample distance divided by the hold-still control ($>1$ = worse than standing " + r"still). The stitch columns are the cross-trajectory control of " + r"\texttt{scripts/real/stitch\_multihop.py} (\texttt{status/real/stitch\_multihop\_R\_M\_ft\_*.json}): " + r"\emph{ratio} is the route-2 $\to$ route-3 splice distance over the within-route reference and " + r"\emph{control} the same quantity for the route-1 splice, which must be worse.}" + r"\label{tab:rheadcal}", + r"\begin{tabular}{lrrrrrrr}\toprule", + r"variant & step & R-head AUC & CFM & nnl1 vs stay & stitch ratio & control & $R$ logit \\\midrule"] + for k in sorted(cal): + c = cal[k]; s = st.get(k, {}) + L.append(f"{esc(k)} & {c.get('step','--')} & {f(c.get('rhead_auc_val'),4)} & {f(c.get('cfm_val'))} & " + f"{f(c.get('nnl1_ratio_vs_stay_val'))} & {f(s.get('ratio_median'))} & " + f"{f(s.get('route1_control_median'))} & {f(s.get('rhead_logit_mean'),1)} \\\\") + L += [r"\bottomrule\end{tabular}\end{table}"] + L += [r"", r"\noindent\textbf{Read the AUC column with care.} An AUC of 1.000 means the head reproduces " + r"\emph{its own} labels perfectly; for v0 those labels are ``this episode succeeded'', which is " + r"decidable from provenance alone. v2's AUC is \texttt{NaN} because its 50 positive frames all fall " + r"in the training split (2 in validation, both in one episode). What the head can actually " + r"\emph{discriminate} is the subject of the next section.", r""] +else: + L = [r"\noindent\emph{(Health table not yet landed: status/real/REWARD\_FT\_NUMBERS.json missing.)}"] +(TEX / "_stitch_and_cal.tex").write_text("\n".join(L) + "\n") +print("[tex] wrote _stitch_and_cal.tex") + +# ----------------------------------------------------------------- _decisive.tex +D = load("DECISIVE_REWARD.json") +S3 = load("STITCH_FEASIBILITY.json") +V5 = load("V5_REWARD.json") +PR = load("OPENLOOP_BY_PROVENANCE.json") +L = [r"\clearpage", r"\section{The decisive test: can stitching be shown under this reward?}" + r"\label{sec:decisive}", + r"""The corpus has exactly the structure a stitching demonstration needs. State 2 (\emph{pan on stove, +tomato at its initial position}) is visited by three different routes: route 2 (\texttt{0->2->3}), route 3 +(\texttt{2->3->4}, the \emph{only} rewarded route) and route 4 (\texttt{0->2->6}, a failure). So from one +junction state the data contains both a rewarded continuation and a failure continuation, and the two +terminals differ only in where the pan ends up (Fig.~\ref{fig:success} vs Fig.~\ref{fig:stage6}). What was +never established is whether the \emph{trained reward head} can tell those apart --- and if it cannot, every +green/red marking in a stitching figure is decoration. Three diagnostics answer that, all on cached features +with no new training.""", r""] + +if D: + L += [r"\subsection{D1 --- can the head separate the two terminals?}", + r"""$R(z)$ evaluated on every frame whose \texttt{annot.edge\_to} is 4 (rewarded: pan on grate, +tomato in bowl) versus 6 (failure: pan on the stove, tomato in bowl), and on the last 30 frames of each such +episode. 0.5 is chance. \texttt{scripts/real/decisive\_reward.py} $\to$ +\texttt{status/real/DECISIVE\_REWARD.json}.""", + r"\begin{table}[htbp]\centering\small", + r"\caption{\textbf{D1/D2 --- what each reward head can actually discriminate.} AUC of $R(z)$; " + r"0.5 is chance. \emph{4 vs 6} is the decisive column: those two states differ only in where the " + r"pan ends. \emph{4 vs 3} asks whether the head can tell the finished state from the mid-task " + r"cooking state. \emph{junction} is D2: frames in the first 30 after leaving state 2, rewarded " + r"continuation (route 3) versus failure continuation (route 4) --- physically the same situation, " + r"so a provenance head should sit near chance or, worse, be confidently wrong." + r"}\label{tab:decisive}", + r"\begin{tabular}{lrrrrr}\toprule", + r"head & 4 vs 6 (all) & 4 vs 6 (tail 30) & 4 vs 3 (tail) & 4 vs 5 (tail) & junction r3 vs r4 \\\midrule"] + for k, h in D["heads"].items(): + a = h["auc"] + L.append(f"{esc(k)} & {f(a['D1_term4_vs_term6_allframes'],4)} & {f(a['D1_term4_vs_term6_tail'],4)} & " + f"{f(a['D1_term4_vs_term3_tail'],4)} & {f(a['D1_term4_vs_term5_tail'],4)} & " + f"{f(a['D2_junction_leave_r3_vs_r4'],4)} \\\\") + L += [r"\bottomrule\end{tabular}\end{table}", r""] +else: + L += [r"\noindent\emph{(D1/D2 not yet landed: status/real/DECISIVE\_REWARD.json missing; LSF rr\_decisive.)}", r""] + +if S3: + L += [r"\subsection{D3 --- the demonstration number}", + r"""Standing at a junction state \emph{as it is actually visited on the failure route} (the last 40 +frames before route-4 episodes leave state 2), 128 candidate action chunks are scored: 64 drawn from the +rewarded continuation (route 3, segment $2\to3$) and 64 from the failure continuation (route 4, segment +$2\to6$). Logged chunks are used rather than proposer samples precisely so that the label ``this candidate +continues toward the goal'' is ground truth. The read-out is the flagship one --- \texttt{d1}, $\beta=0.99$, +16 particles, probability, $T=25$, argmax over 128 --- identical to +\texttt{status/real/openloop\_*/scorer\_openloop.json}. Chance is 0.5 for both columns. +\texttt{scripts/real/stitch\_feasibility.py} $\to$ \texttt{status/real/STITCH\_FEASIBILITY.json}.""", + r"\begin{table}[htbp]\centering\small", + r"\caption{\textbf{D3 --- does $Q$ separate the rewarded continuation from the failure " + r"continuation at the shared junction state?} \emph{AUC} pooled over all anchors and averaged " + r"per anchor; \emph{top-1} is how often the argmax of 128 is a rewarded-continuation chunk " + r"(chance $0.5$); \emph{spread} is the mean max$-$min of the 128 scores, i.e.\ how much dynamic " + r"range the ranking has at all.}\label{tab:d3}", + r"\begin{tabular}{lrrrrr}\toprule", + r"head & AUC (pooled) & AUC (per anchor) & frac anchors $>0.5$ & top-1 rewarded & score spread \\\midrule"] + for k, h in S3["heads"].items(): + L.append(f"{esc(k)} & {f(h['auc_pooled'],4)} & {f(h['auc_per_anchor_mean'],4)} & " + f"{f(h['auc_per_anchor_frac_above_0.5'],3)} & {f(h['top1_rewarded_frac'],3)} & " + f"{h['score_spread_mean']:.2e} \\\\") + L += [r"\bottomrule\end{tabular}\end{table}", r""] +else: + L += [r"\noindent\emph{(D3 not yet landed: status/real/STITCH\_FEASIBILITY.json missing; LSF rr\_d3stitch.)}", r""] + +if V5: + L += [r"\subsection{A correction: the reward RISE trains on is not the reward the dataset defines}", + r"""The robomimic conversion labels an episode \emph{expert} when its final state is in $\{3,4\}$ +(\texttt{scripts/real/convert\_cooking\_hdf5.py:100}) and writes $+1$ on every frame of those episodes +(\texttt{:150}), also storing that flag as the hdf5 attribute \texttt{success} (\texttt{:158}). The dataset +card is narrower: \textbf{``Reward state IDs: [4]''}, with +\texttt{reward = float(goal\_reached == 1 and reached\_state\_id in reward\_states)}, and its state table +marks state 3 as \emph{``[Cooking state] Pan on stove, Tomato in the pan --- Terminal in task: False --- +Rewarded arrival: False''}. State 3 is therefore not a second success terminal; it is the mid-task state +with the tomato still in the pan, where routes 1 and 2 simply stop.""", + r"\begin{center}\small\begin{tabular}{rrrcc}\toprule", + r"terminal & episodes & frames & RISE calls it expert & dataset rewards it \\\midrule"] + for t, v in sorted(V5["by_terminal_state"].items()): + L.append(f"{t} & {v['n_eps']} & {v['frames']} & {'yes' if v['rise_expert'] else 'no'} & " + f"{'yes' if v['dataset_rewarded'] else 'no'} \\\\") + L += [r"\bottomrule\end{tabular}\end{center}", + r"\noindent So RISE's critic is trained with $+1$ on every frame of " + + str(V5["n_episodes_positive"]) + r" of 248 episodes (" + str(V5["pos_frames"]) + + r" frames, " + f"{100*V5['frac_frames']:.1f}" + r"\% of the corpus), and " + + str(V5["episodes_rise_says_expert_but_dataset_does_not_reward"]) + + r" of those episodes never put the tomato in the bowl. The successor's own \texttt{v0} uses the " + r"dataset rule instead (" + str(V5["n_episodes_positive_dataset_rule"]) + + r" episodes). No successor cell had ever been trained on RISE's labels, so they were added as " + r"\texttt{v5} (\texttt{scripts/real/make\_v5\_reward.py} $\to$ " + r"\texttt{cache/real\_cooking\_v5/reward\_v5\_riseprov.f32.npy}, counts in " + r"\texttt{status/real/V5\_REWARD.json}).", r""] + +if PR: + key = next((k for k in PR if PR[k].get("n_decisions", 0) > 100), None) + if key: + v = PR[key] + L += [r"\subsection{The open-loop screen re-cut by episode provenance}", + r"A natural defence of the open-loop numbers is that only " + + str(v["n_rewarded_episodes"]) + r" of the " + str(len(v["episodes"])) + + r" held-out episodes reach the goal, so on the rest ``agreeing with the logged chunk'' is " + r"agreeing with a failure. That defence is testable and it fails: every learned scorer " + r"ranks \emph{below} chance on the rewarded episodes too. " + r"\texttt{scripts/real/openloop\_by\_provenance.py} $\to$ " + r"\texttt{status/real/OPENLOOP\_BY\_PROVENANCE.json}, cell \texttt{" + + esc(v.get("tag", key)) + r"}, " + str(v["n_decisions"]) + + r" paired decisions, nothing re-scored.", + r"\begin{table}[htbp]\centering\small", + r"\caption{\textbf{Oracle rank percentile split by whether the episode reaches the goal.} " + r"$1.0$ = the oracle's own pick, $0.0$ = the worst of 128; a plain sample (\texttt{greedy}) " + r"and the permutation controls sit at $0.5$ by construction. Lower than $0.5$ means the " + r"scorer systematically prefers candidates the oracle ranks badly." + r"}\label{tab:provsplit}", + r"\begin{tabular}{lrrrr}\toprule", + r"scorer & all & rewarded eps & failure eps & route 3 only \\\midrule"] + for k, r in v["scorers"].items(): + L.append(f"{esc(k.replace('score_',''))} & {f(r['all']['rank_pct'],4)} & " + f"{f(r['rewarded_eps']['rank_pct'],4)} & {f(r['failure_eps']['rank_pct'],4)} & " + f"{f(r.get('route3',{}).get('rank_pct'),4)} \\\\") + L += [r"\bottomrule\end{tabular}\end{table}", r""] + + +# ----------------------------------------------------------------- the verdict +L += [r"\subsection{Verdict, and the smallest fix}", + r"""\textbf{No head passes.} D1 looks perfect for v0/v1 --- AUC $1.000$ separating state 4 from state 6 +--- but D2 shows what that AUC is made of: the \emph{same} head separates the \emph{junction} frames of +route 3 from those of route 4 with AUC $1.000$ as well, and route 3's junction frames are its \emph{first} +frames, before the pan has been touched. The shipped head reads $R(z)=+24.4$ there and $-24.8$ on route 4, +the same $\pm25$ it reads at the terminals (Table~\ref{tab:decisive}, logit means in +\texttt{status/real/DECISIVE\_REWARD.json}). Sharper still: routes 2 and 3 both contain the physical edge +$2\to3$, labelled $0$ in one recording and $+1$ in the other, and the head separates those two copies of the +same transition with AUC $1.000$. The head has learned \emph{which recording a frame belongs to}. +And D3, which is the demonstration itself, comes out below chance for every head: the top-ranked of 128 +candidates is a rewarded-continuation chunk $3$--$28\%$ of the time (chance $50\%$), and for the shipped +head the chain from the \emph{top} candidate retrieves a state-6 failure frame ($0\%$ of particles in the +goal region) while the chain from the \emph{bottom} candidate retrieves a state-4 goal frame ($100\%$).""", + r"", + r"""\textbf{Why this is structural, not a training failure.} Only route 3 is rewarded, and route 3 is +also the only route that \emph{starts} at state 2 (\texttt{cache/real\_cooking\_v5/SEGMENTS.json}: route 3 is +\texttt{2->3->4}, two segments, no \texttt{0->2} prefix). So within this corpus ``this state is on the way to +the goal'' and ``this frame was recorded in a route-3 session'' are the same predicate, and a per-frame label +that is constant over the recording cannot distinguish them. No amount of relabelling inside the existing +episodes fixes that; v1, v2 and v3 are three different ways of slicing the same 50 recordings.""", + r"", + r"""\textbf{The smallest fix}, in increasing cost: +\begin{enumerate}\itemsep1pt +\item \textbf{Record route 5.} The dataset card already declares route 5 $=$ \texttt{1->3->4} with a target + of 50 episodes and none collected. Route 5 and route 1 (\texttt{0->1->3}) share state 1, and route 5 + reaches the goal --- a second junction with a success and a non-success continuation, recorded in the + \emph{same} session style. Two junctions instead of one also breaks the ``route 3 is special'' cue. +\item \textbf{Record a failure continuation out of state 3 in a route-3 session} (pour, then leave the pan on + the stove $=$ state 6). That puts both terminals inside the \emph{same} recording family, which is the + only thing that makes the reward a function of the scene rather than of the session. +\item \textbf{Replace the provenance label with a state-based one:} the dataset's own rule + \texttt{reward = float(goal\_reached == 1 and reached\_state\_id in [4])} is exactly v2 and is already + state-based --- but it fires on 50 frames in 181{,}530, and the v2 heads measured here are the worst of + the set (D1 AUC $0.11$--$0.33$). A detector-style label (``pan on grate'' from the scene, applied to + every frame of every recording) is the version of v2 that would have enough positives to train on. +\end{enumerate}""", r""] + +(TEX / "_decisive.tex").write_text("\n".join(L) + "\n") +print("[tex] wrote _decisive.tex") diff --git a/rsm_rise/scripts/real/build_decomp271_comment.py b/rsm_rise/scripts/real/build_decomp271_comment.py new file mode 100644 index 0000000000000000000000000000000000000000..23b50fde47c61cd789b2d0ca1a8c5659d078def4 --- /dev/null +++ b/rsm_rise/scripts/real/build_decomp271_comment.py @@ -0,0 +1,184 @@ +#!/usr/bin/env python +"""Generate the #271 comment (and the CHECKPOINTS paragraph) for the decomposition, FROM the JSON. + +Every number in the prose is read out of STITCH_DECOMP.json, for the standing reason that the +retraction and the run-9 paragraphs are generated too: a hand-typed number drifts the moment the +measurement is rerun, and this one WILL be rerun (the deeper-fold test is the obvious follow-up). +""" +from __future__ import annotations +import json, sys +from pathlib import Path + +ROOT = Path("/proj/dmfexp/zwhong/rsm_rise") +D = json.loads((ROOT / "status/real/STITCH_DECOMP.json").read_text()) + + +def g(v, k): + x = v.get(k) + return x.get("mean") if isinstance(x, dict) else x + + +def f(x, n=3): + return f"{x:.{n}f}" if isinstance(x, (int, float)) else "-" + + +def table(h): + r = D["by_hop"][h] + rows = sorted(r["heads"].items(), key=lambda kv: -(g(kv[1], "auc_R_chain_per_anchor") or 0)) + out = ["| head | AUC R(z_h) | AUC R(retrieved) | AUC Q (here) | AUC Q (published) " + "| mean R(z_h) GOAL | mean R(z_h) FAIL | corr(Q, R(z_h)) |", + "|---|---|---|---|---|---|---|---|"] + for n, v in rows: + out.append("| `%s` | %s | %s | %s | %s | %s | %s | %s |" % ( + n, f(g(v, "auc_R_chain_per_anchor")), f(g(v, "auc_R_retrieved_per_anchor")), + f(g(v, "auc_Q_per_anchor_here")), f(g(v, "auc_Q_per_anchor_published")), + f(g(v, "R_chain_goal")), f(g(v, "R_chain_fail")), f(g(v, "corr_Q_Rchain")))) + return "\n".join(out) + + +def classify(h, sat=0.01, edge=0.15): + """Four regimes, kept apart on purpose. + + SATURATED is not the same as WEAK and neither is the same as a small AUC: a head whose R(z_h) is + ~0 on both classes has an AUC decided by numerical dust, and lumping it in with a head that has a + real but modest separation would invent an effect. The split is on the MEANS first (is there any + signal to rank?) and only then on the AUC. + """ + r = D["by_hop"][h]["heads"] + sep, inv, satu, weak = [], [], [], [] + for n, v in r.items(): + a = g(v, "auc_R_chain_per_anchor") + gm, fm = g(v, "R_chain_goal"), g(v, "R_chain_fail") + if max(gm, fm) < sat: + satu.append(n) + elif a is not None and a > 0.5 + edge: + sep.append(n) + elif a is not None and a < 0.5 - edge: + inv.append(n) + else: + weak.append(n) + key = lambda n: -(g(r[n], "auc_R_chain_per_anchor") or 0) + return (sorted(sep, key=key), sorted(inv, key=key), + sorted(satu, key=key), sorted(weak, key=key)) + + +h4, h2, h1 = D["by_hop"]["4"], D["by_hop"]["2"], D["by_hop"]["1"] +sep4, inv4, satu4, weak4 = classify("4") +PUB = json.loads((ROOT / "status/real/REWARD_HEAD_DIAG_STITCH.json").read_text()) +HOPF = int(PUB.get("hop_frames", 0)) +H = h4["heads"] +best = sep4[0] if sep4 else None +lst = lambda xs: ", ".join("`%s`" % x for x in xs) if xs else "(none)" + +md = f"""### Open question 3, answered: the signal is at the chained latent — **the read-out is what loses it** + +Run 9 closed two of the three explanations for why the stitching number does not replicate and named +the experiment that would decide the third. This is that experiment. + +**The paradox.** Every reward head separates real S4 frames from real S6 frames at AUC 1.000 +(diagnostic 1), yet the Q it induces is at chance on chained candidates (diagnostic 3, retracted as a +scheme ranking in run 8). Two rival explanations that differ in *where* the signal dies: + +* **(i) off-manifold** — the multi-hop latent has left the region where R means anything. Then R read + *at* the chained latent is itself at chance, and **no reward scheme can fix the diagnostic**. +* **(ii) the fold** — the latent still carries the class, and the discounted `d1 / β=0.99 / prob / + T=25` read-out that turns R into Q throws it away. + +**Method** (`scripts/real/stitch_decompose.py`, new). On the published stitching number's own anchors +and its own candidate draw, per head and per hop: + +$$R_{{\\text{{chain}}}} = R(z_h), \\qquad + R_{{\\text{{retr}}}} = R\\!\\left(x_{{\\,\\mathrm{{nn}}(z_h)}}\\right), \\qquad + Q = \\text{{the flagship fold of }} R,$$ + +where $z_h$ is the candidate's latent after $h$ successor hops and $\\mathrm{{nn}}(z_h)$ is its min-L1 +retrieval in the cached corpus. The endpoint **class is defined by** $\\texttt{{edge\\_to}}$ of that +retrieved row, so $R_{{\\text{{retr}}}}$ is the ceiling: diagnostic 1 restricted to exactly the frames +this experiment lands on. Q is **recomputed in this process** from the same candidates, so nothing +here rests on a cross-run assumption. + +**Fidelity, checked rather than assumed.** The recomputed endpoint rows match the published parts at +**{h4['endpoint_match_vs_published']:.3f}** (hop 4) and **{h2['endpoint_match_vs_published']:.3f}** +(hop 2) — the draw is reproduced exactly — and the recomputed Q agrees with the published Q to within +±0.006 per-anchor AUC. *That residual is itself worth writing down*: the published per-anchor Q spread +is `q_spread_cv ≈ 0.0017`, i.e. the 128 candidates differ in the fourth significant figure, so plain +GPU non-determinism moves the stitching number by ~0.005 — **about a fifth of the ±0.024 resolution +run 9 measured, from the hardware alone.** + +### Hop 4 ({h4['n_anchors_usable']} usable anchors, {h4['n_goal']} GOAL / {h4['n_fail']} FAIL candidates) + +{table("4")} + +### Hop 2 ({h2['n_anchors_usable']} usable anchors, {h2['n_goal']} GOAL / {h2['n_fail']} FAIL candidates) + +{table("2")} + +### What this says + +**1. Explanation (i) is wrong for the heads that have anything to lose.** +{lst(sep4)} read the chained latent at AUC **{f(g(H[best], 'auc_R_chain_per_anchor'))}** and +**{f(g(H[sep4[1]], 'auc_R_chain_per_anchor')) if len(sep4) > 1 else '-'}** per anchor, on a real +separation of means ({f(g(H[best], 'R_chain_goal'))} on GOAL-ending chains vs +{f(g(H[best], 'R_chain_fail'))} on FAIL-ending ones for `{best}`) — and **their Q is +{f(g(H[best], 'auc_Q_per_anchor_here'))} and +{f(g(H[sep4[1]], 'auc_Q_per_anchor_here')) if len(sep4) > 1 else '-'}, i.e. exactly chance.** +`corr(Q, R(z_h))` is only {f(g(H[best], 'corr_Q_Rchain'))} for `{best}`. The information about where +the chain lands is present in the latent and present in the head; the read-out does not carry it. So +the signal does not die off-manifold — it dies in the fold. Point 2 says why, and the "why" is not +fixable by choosing a better reward. + +**2. The mechanism is a HORIZON MISMATCH, and it is STRUCTURAL — not a flag I can turn.** The +flagship fold is `--rsm-depth 1` at `β = 0.99`, so Q sees one hop, ≈{HOPF} frames. The endpoint class +is defined **four** hops out, ≈{4*HOPF} frames. Q is being asked to predict a {4*HOPF}-frame-away +outcome through a {HOPF}-frame window. And the two obvious ways to widen that window are both closed +on these checkpoints (`rr_cpu_foldprobe` 1874320): + +* `--rsm-depth ≥ 2` raises *"read-out at depth N needs a hop head (`rsm_hop_ckpt`)"* in + `rsm_scorer.q`, and **none of the sixteen checkpoints carries a hop head**. +* raising β is extrapolation: the flow was conditioned on `beta_lo = 0.95 … beta_hi = 0.99`, so + **β = 0.99 already IS the longest horizon this flow was ever trained at.** + +**And the clincher, which was sitting in the hop-1 row the whole time: at hop 1 there are +{h1['n_goal']} GOAL endpoints out of {h1['n_goal'] + h1['n_fail']} classified candidates — zero.** +Within the horizon Q can actually see, **no candidate drawn at the S2 junction of a failure episode +reaches a goal-bound segment at all**, so there is nothing for Q to rank. That is why hop 1 has always +read `nan` for every head, and it is not a quirk of that row: it is the whole result. The stitching +number asks Q to discriminate a class that lives entirely outside its horizon. + +**So the honest verdict on the diagnostic is stronger than "it does not replicate": as designed, it +cannot be satisfied by any reward label, because the read-out available on this corpus is blind to +the horizon at which the label is defined.** Fixing it needs a *model* change — train a hop head, or +retrain the flow to a higher β — not a reward change. That reframes run 8's retraction: the schemes +were never the binding constraint. + +**3. Most heads are saturated OFF out there, which is a different failure and must not be read as an +effect.** {lst(satu4)} return R(z_h) ≈ 0 on **both** classes (means +{f(g(H[satu4[0]], 'R_chain_goal'), 4)} / {f(g(H[satu4[0]], 'R_chain_fail'), 4)} for `{satu4[0]}`), so +their AUC — including the eye-catching {f(g(H[satu4[-1]], 'auc_R_chain_per_anchor'))} of +`{satu4[-1]}` — is ranking numerical dust and means nothing in either direction. A further +{lst(weak4)} have a real but modest separation and sit inside ±0.15 of chance. The chained latent sits +**{h4['chain_min_l1_over_real_median']:.1f}×** (hop 4) and **{h2['chain_min_l1_over_real_median']:.1f}×** +(hop 2) a real frame's own nearest-neighbour min-L1 distance away from the corpus, so this is the +off-manifold story after all — just for the *majority* of heads rather than for the phenomenon. + +**4. {lst(inv4)} is genuinely INVERTED, not dead** — R(z_h) = {f(g(H[inv4[0]], 'R_chain_goal'))} on +GOAL-ending chains against {f(g(H[inv4[0]], 'R_chain_fail'))} on FAIL-ending ones, a large separation +with the wrong sign. (`v3` is the final-segment label.) + +**5. A crack in the diagnostic-1 ceiling.** `R_retr` is 1.000 for most heads, but the whole **B/B400 +family reads {f(g(H['B400'], 'auc_R_retrieved_per_anchor'))}–{f(g(H['B_s1'], 'auc_R_retrieved_per_anchor'))} +and `v2` reads {f(g(H['v2'], 'auc_R_retrieved_per_anchor'))}** — on *real* cached frames. The AUC 1.000 +of diagnostic 1 is measured on frames labelled by `reached_state_id`; these are frames labelled by +`edge_to` at the endpoints the chains actually reach, and on those the horizon-window schemes are +**not** at ceiling. Any claim resting on "the heads separate S4 from S6 perfectly" should carry this. + +### Standing position, unchanged +`rsm_reward: A` remains the shipped default by the owner's choice; `rsm_reward_stitching_best` remains +`null`; **no head is validated as a stitcher.** This comment moves the explanation, not the ranking: +the run-8 retraction stands, and so does run 9's ±0.024 resolution. Numbers: +`status/real/STITCH_DECOMP.json`. +""" +out = ROOT / "status/real/comment_271_run10.md" +out.write_text(md) +print(f"wrote {out} ({len(md)} B)") +print(f"regimes hop4: separating={sep4} inverted={inv4} saturated={satu4} weak={weak4}") diff --git a/rsm_rise/scripts/real/build_dilution_table.py b/rsm_rise/scripts/real/build_dilution_table.py new file mode 100644 index 0000000000000000000000000000000000000000..35bfdb36b974ac76cf9faccba7e9a9a0f4a37952 --- /dev/null +++ b/rsm_rise/scripts/real/build_dilution_table.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""ACT_COND carry-forward (gen_q#278): assemble the CHAIN-LENGTH DILUTION CURVE. + +Reads status/real/ACT_COND/dilution/dilute_*.json (one cell per chain length) and prints ASI, ties, +Spearman and the realized hops_mean, so the claim "the deployed chain read-out is ~4.5x less +action-sensitive than d1" gets an actual curve instead of two endpoints. + +TWO FAMILIES, NEVER POOLED: + cap* truncates the walk at a fixed cap with beta/gamma unchanged -- the SAME value, estimated + short (biased). This isolates chain LENGTH. + beta* moves beta toward gamma, shortening the walk through p=(g-b)/(g(1-b)) -- a DIFFERENT value + function. This is the knob a planner would actually turn. +Within one family every cell runs the identical 200 stratified train anchors at the SAME seed, so the +cells are paired. Cells at a different anchor seed form their own family (see fam()) and are a +REPLICATION, not a paired comparison. +""" +import glob, json, os, sys +import numpy as np + +ROOT = "/proj/dmfexp/zwhong/rsm_rise" +D = f"{ROOT}/status/real/ACT_COND/dilution" + +def ck_tag(ckpt): + """Which checkpoint a cell was measured on. Cells from DIFFERENT checkpoints must never share a + family: the dilution factor is computed against the longest walk IN THE FAMILY, so pooling R_M with + a fine-tune would divide one model's ASI by another model's.""" + return os.path.basename(os.path.dirname(str(ckpt))) + +def fam(tag, ckpt, seed): + """Family key = checkpoint + ANCHOR SEED + knob. The seed is in the key because the dilution factor + is computed against the longest walk IN THE FAMILY: pooling two anchor draws would divide one draw's + ASI by another draw's and quietly turn a replication into a single curve. Run 5 added a seed-1 + replication of the R_M beta ladder, so `R_M/s0/beta` and `R_M/s1/beta` print as SEPARATE curves and + are compared by eye, as replications, never paired cell-for-cell.""" + return f"{ck_tag(ckpt)}/s{int(seed)}/" + ("cap" if tag.startswith("cap") else "beta") + +def analytic(beta, gamma, cap_req): + """p_cont and E[walk length] from (beta, gamma), the same formula the scorer uses. The cells run + before the chain-stats fix carry no measured hops; the coin's law is exact, so the analytic value + is the honest x-axis for them. A requested cap truncates it: E[N] = (1-p**L)/(1-p) levels.""" + p = (gamma - beta) / (gamma * (1.0 - beta)) if beta < 1.0 else 0.0 + p = min(max(p, 0.0), 1.0) + L = int(cap_req) if cap_req else None + if p >= 1.0: + return p, float(L) if L else float("inf") + e = (1.0 - p) ** -1 if L is None else (1.0 - p ** L) / (1.0 - p) + return p, e + +rows = [] +for p in sorted(glob.glob(f"{D}/dilute_*.json")): + tag = os.path.basename(p)[len("dilute_"):-len(".json")] + j = json.load(open(p)) + a, ch = j["args"], j.get("chain", {}) + for kind in ("prob", "logit"): + z = j["pooled"].get(kind) + if not z: + continue + pa, ea = analytic(a["beta"], a["gamma"], a.get("chain_cap", 0)) + rows.append(dict(tag=tag, family=fam(tag, a["ckpt"], a.get("seed", 0)), ckpt=ck_tag(a["ckpt"]), + seed=a.get("seed", 0), read=kind, + beta=a["beta"], cap_req=a.get("chain_cap", 0), + cap=ch.get("cap", a.get("chain_cap") or None), + p_cont=ch.get("p_cont") if ch.get("p_cont") is not None else pa, + hops=ch["hops_mean"] if ch.get("hops_mean") else ea, + hops_src="measured" if ch.get("hops_mean") else "analytic", + capped=ch.get("capped_frac_mean"), + n=z["n"], asi=z["asi_pooled"], asi_med=z["asi_median"], + rho=z["spearman_mean"], ties=z["tie_frac_mean"] * a["n_cand"], + cv=z["cv_mean"], rank=z.get("rank_pct_mean"), + # S2 is the BOTTLENECK stage and the weakest one in the Task-2 table + # (ASI 0.54 logit vs ~1.0 at S1/S3). The pooled ASI can rise on the back of + # the easy stages, so the question "does a longer walk fix the bottleneck?" + # needs S2 carried separately -- never averaged into the pooled column. + asi_s2=(j.get("by_stage", {}).get("S2", {}).get(kind) or {}).get("asi_pooled"), + n_s2=(j.get("by_stage", {}).get("S2", {}).get(kind) or {}).get("n"))) +if not rows: + sys.exit(f"no cells under {D}") + +# sort each family by realized walk length so the curve reads left-to-right short -> long +rows.sort(key=lambda r: (r["family"], r["hops"] if r["hops"] is not None else 0, r["read"])) +hdr = (f"{'cell':>14}{'read':>7}{'beta':>8}{'cap':>7}{'p':>7}{'hops':>7}{'src':>6}{'capd':>7}" + f"{'n':>5}{'ASI':>8}{'ASI_med':>9}{'ASI_S2':>8}{'rho':>7}{'ties':>7}{'CV':>10}{'rankpct':>9}") +out = {"cells": rows} +for f in sorted({r["family"] for r in rows}): + sub = [r for r in rows if r["family"] == f] + if not sub: + continue + print(f"\n=== family {f} " + + ("(truncated walk, beta/gamma fixed: SAME value, short estimator)" if f.endswith("cap") + else "(beta moves vs gamma: a DIFFERENT value at each cell; lower beta = longer walk)")) + print(hdr) + for r in sub: + g = lambda v, s="{:.3f}": "-" if v is None else s.format(v) + print(f"{r['tag']:>14}{r['read']:>7}{r['beta']:>8.4g}{str(r['cap']):>7}" + f"{g(r['p_cont']):>7}{g(r['hops'],'{:.2f}'):>7}{r['hops_src'][:4]:>6}{g(r['capped'],'{:.3f}'):>7}" + f"{r['n']:>5}{r['asi']:>8.3f}{r['asi_med']:>9.3f}{g(r['asi_s2']):>8}{r['rho']:>7.2f}" + f"{r['ties']:>7.2f}{r['cv']:>10.2e}{g(r['rank']):>9}") + # dilution factor relative to the LONGEST walk in the family (the deployed end of the curve) + for kind in ("prob", "logit"): + s = [r for r in sub if r["read"] == kind and r["hops"] is not None] + if len(s) < 2: + continue + base = max(s, key=lambda r: r["hops"]) + print(f" [{kind}] ASI relative to the longest walk ({base['tag']}, hops {base['hops']:.2f}, " + f"ASI {base['asi']:.3f}): " + + ", ".join(f"{r['tag']} {r['asi']/base['asi']:.2f}x" for r in s)) + out[f"dilution_{f.replace('/','_')}_{kind}"] = {r["tag"]: r["asi"] / base["asi"] for r in s} + s2 = [r for r in s if r.get("asi_s2")] + if len(s2) >= 2 and base.get("asi_s2"): + print(f" [{kind}] S2 ONLY (bottleneck, n={base['n_s2']}/cell), relative to " + f"{base['tag']} (ASI_S2 {base['asi_s2']:.3f}): " + + ", ".join(f"{r['tag']} {r['asi_s2']:.3f} ({r['asi_s2']/base['asi_s2']:.2f}x)" for r in s2)) + out[f"dilution_S2_{f.replace('/','_')}_{kind}"] = {r["tag"]: r["asi_s2"] for r in s2} + +json.dump(out, open(f"{ROOT}/status/real/ACT_COND/DILUTION.json", "w"), indent=1) +print(f"\nwrote {ROOT}/status/real/ACT_COND/DILUTION.json ({len(rows)} rows)") diff --git a/rsm_rise/scripts/real/build_draws271_comment.py b/rsm_rise/scripts/real/build_draws271_comment.py new file mode 100644 index 0000000000000000000000000000000000000000..71f0d2ee840f92c2c19b39b14d194f9b7eb3b450 --- /dev/null +++ b/rsm_rise/scripts/real/build_draws271_comment.py @@ -0,0 +1,84 @@ +#!/usr/bin/env python +"""The #271 comment for the DESIGNED REPLICATION (five independent candidate draws), from the JSON.""" +from __future__ import annotations +import json +from pathlib import Path + +ROOT = Path("/proj/dmfexp/zwhong/rsm_rise") +D = json.loads((ROOT / "status/real/STITCH_DRAWS.json").read_text()) +PUB = json.loads((ROOT / "status/real/REWARD_HEAD_DIAG_STITCH.json").read_text()) + + +def rows(h): + r = D["by_hop"][str(h)]["heads"] + return sorted(r.items(), key=lambda kv: -kv[1]["mean_over_draws"]) + + +def table(h): + out = ["| head | mean over 5 draws | between-draw SD | the 5 draws | above .5 in | p (draw-level) | published (draw 0) |", + "|---|---|---|---|---|---|---|"] + for n, v in rows(h): + pub = PUB["by_hop"][str(h)]["heads"][n]["auc_per_anchor"]["mean"] + out.append("| `%s` | **%.4f** | %.4f | %s | %d/5 | %.3f | %.4f |" % ( + n, v["mean_over_draws"], v["sd_over_draws"], + " ".join("%.3f" % v["per_draw"][k] for k in D["draws"]), + v["n_draws_above_half"], v["p_draw_level_vs_half"], pub)) + return "\n".join(out) + + +h4, h2 = D["by_hop"]["4"], D["by_hop"]["2"] +top4 = rows(4)[0] +lst = lambda xs: ", ".join("`%s`" % x for x in xs) if xs else "(none)" + +md = f"""### The designed replication: five independent candidate draws + +Run 9 promised this and it has now landed (`scripts/real/stitch_draws.py` → +`status/real/STITCH_DRAWS.json`). `--seed k` changes **only** the per-anchor candidate draw, so seeds +0–4 are five replicates on the same anchors, the same weights and the same endpoint machinery. **The +draw is the unit of replication** — the unit the published bootstrap-over-anchors CI cannot see, +because it resamples anchors *inside one draw*. + +### Hop 4 ({min(h4['n_anchors_per_draw'].values())}-{max(h4['n_anchors_per_draw'].values())} usable anchors per draw) + +{table(4)} + +### Hop 2 ({min(h2['n_anchors_per_draw'].values())}-{max(h2['n_anchors_per_draw'].values())} usable anchors per draw) + +{table(2)} + +*(The draw-level p is TWO-SIDED, so the `p = 0.000` rows at the bottom of each table — `base`, `v0`, +`v3`, `A_s1` — are heads reliably BELOW chance, not above it. Read the "above .5 in" column with it.)* + +### What it says — a partial reinstatement, at half the size + +**The effect is real but the published number was the luckiest draw.** {lst(h4['heads_above_half_in_every_draw'])} +are above 0.5 in **all five** draws at hop 4, and `{top4[0]}` averages **{top4[1]['mean_over_draws']:.4f}** +(SD {top4[1]['sd_over_draws']:.4f} between draws, p = {top4[1]['p_draw_level_vs_half']:.3f} at the draw level). But the +published single-draw value for `{top4[0]}` was **{PUB['by_hop']['4']['heads'][top4[0]]['auc_per_anchor']['mean']:.4f}**, +the top of its five-draw range {top4[1]['min']:.3f}–{top4[1]['max']:.3f}. So run 8's +retraction was right that the published figure could not be read as a scheme ranking, and run 9 was +right that the candidate draw is the dominant variance component — **but "no head clears chance" was +too strong.** Averaged over draws, the horizon-window family (`B400`, `B400_s1`) and `v0lit` clear it, +by ≈{top4[1]['mean_over_draws'] - 0.5:.3f} rather than the ≈{PUB['by_hop']['4']['heads'][top4[0]]['auc_per_anchor']['mean'] - 0.5:.3f} first published. +Between-draw SD is {h4['noise_floor']['between_draw_sd_mean_over_heads']:.4f} at hop 4 and {h2['noise_floor']['between_draw_sd_mean_over_heads']:.4f} at hop 2. + +**Read it together with the decomposition in the comment above, which constrains what it can mean.** +Q at `depth 1, β = 0.99` sees ≈{int(PUB.get('hop_frames', 0))} frames, and at that horizon there are +**zero** GOAL endpoints — so a head cannot be ranking candidates by "does this chain reach the goal". +An effect of ≈0.027 that survives five draws is therefore best read as a **weak leading indicator** +inside the first hop that happens to correlate with a {4*int(PUB.get('hop_frames', 0))}-frame-away +outcome, not as demonstrated stitching. It is consistent with `B400`'s label being the horizon-window +one (H ≈ 400 frames), which is the only scheme whose positives are defined by *time-to-goal* at all. + +### Standing position +Still unchanged: `rsm_reward: A` remains the shipped default by the owner's choice, +`rsm_reward_stitching_best` remains **`null`**, and **no head is validated as a stitcher** — an +effect of 0.027 with a per-draw SD of {h4['noise_floor']['between_draw_sd_mean_over_heads']:.4f}, at a horizon where the label is +invisible to the read-out, is not a claim I will ship. What has changed is the wording: the correct +statement is *"averaged over draws the horizon-window heads clear chance by ≈0.03, and the published +0.54 was the best of five"*, not *"nothing clears"*. The PDF, `CHECKPOINTS.md` and PR #1 are being +regenerated from `STITCH_DRAWS.json` so the prose cannot drift from the table. +""" +out = ROOT / "status/real/comment_271_run10b.md" +out.write_text(md) +print(f"wrote {out} ({len(md)} B)") diff --git a/rsm_rise/scripts/real/build_fold4_compare.py b/rsm_rise/scripts/real/build_fold4_compare.py new file mode 100644 index 0000000000000000000000000000000000000000..9bff03e736b3dc863f2fad41855487dfc183c608 --- /dev/null +++ b/rsm_rise/scripts/real/build_fold4_compare.py @@ -0,0 +1,81 @@ +#!/usr/bin/env python +"""Compare the depth-1 and the matched-horizon fold-4 read-outs on IDENTICAL candidates. + +status/real/STITCH_DECOMP.json -- Q from --q-mode d1 (one hop, ~100 frames) +status/real/STITCH_DECOMP_FOLD4.json -- Q from --q-mode fold --q-depth 4 through this corpus's hop head + (four hops, ~400 frames = the depth the endpoint label is at) + +Both runs replay the same candidate draw and reach the same endpoints (endpoint_match_vs_published +1.000 in each), so the ONLY thing that differs between them is the read-out. Writes +status/real/FOLD4_COMPARE.json; every downstream artefact is generated from that file. +""" +from __future__ import annotations +import json +from pathlib import Path +import numpy as np + +ROOT = Path("/proj/dmfexp/zwhong/rsm_rise") +D = json.loads((ROOT / "status/real/STITCH_DECOMP.json").read_text()) +F = json.loads((ROOT / "status/real/STITCH_DECOMP_FOLD4.json").read_text()) + +out = {"d1": "status/real/STITCH_DECOMP.json", "fold4": "status/real/STITCH_DECOMP_FOLD4.json", + "read_out_d1": {"mode": "d1", "depth": 1, "beta": 0.99}, + "read_out_fold4": {"mode": "fold", "depth": 4, "beta": 0.99, + "hop_ckpt": "runs/real_cooking_v5/hop/gauss/policy_r1.pt"}, + "by_hop": {}} + +# the level/ordering split is the whole point: if the deeper fold moved the RANKING the AUC would +# move, so a large level change with an unchanged AUC is evidence the extra hops are common-mode. +parts_d = ROOT / "status/real/STITCH_DECOMP.json_parts" +parts_f = ROOT / "status/real/STITCH_DECOMP_FOLD4.json_parts" +lvl, cor = {}, {} +for a in sorted(parts_d.glob("*.npz")): + b = parts_f / a.name + if not b.exists(): + continue + A, B = np.load(a), np.load(b) + for k in A.files: + if not k.startswith("q_"): + continue + x, y = np.asarray(A[k], float), np.asarray(B[k], float) + if x.shape != y.shape or x.std() == 0 or y.std() == 0: + continue + h = k[2:] + lvl.setdefault(h, []).append(float(y.mean() - x.mean())) + cor.setdefault(h, []).append(float(np.corrcoef(x, y)[0, 1])) +out["per_candidate"] = {h: {"mean_level_shift": float(np.mean(lvl[h])), + "mean_within_anchor_corr": float(np.mean(cor[h])), + "n_anchors": len(lvl[h])} for h in sorted(lvl)} +out["n_anchors_compared"] = max((v["n_anchors"] for v in out["per_candidate"].values()), default=0) + +for hop in sorted(set(D["by_hop"]) & set(F["by_hop"]), key=int): + dh, fh = D["by_hop"][hop], F["by_hop"][hop] + if not dh.get("n_anchors_usable"): + out["by_hop"][hop] = {"n_anchors_usable": 0, "note": "no GOAL endpoints at this depth"} + continue + heads = {} + for k in sorted(set(dh["heads"]) & set(fh["heads"])): + q1 = dh["heads"][k]["auc_Q_per_anchor_here"]["mean"] + q4 = fh["heads"][k]["auc_Q_per_anchor_here"]["mean"] + heads[k] = {"auc_Q_d1": q1, "auc_Q_fold4": q4, "delta": q4 - q1, + "auc_Q_published_d1": dh["heads"][k]["auc_Q_per_anchor_published"], + "auc_R_chain": dh["heads"][k]["auc_R_chain_per_anchor"]["mean"]} + ds = [v["delta"] for v in heads.values()] + out["by_hop"][hop] = { + "n_anchors_usable": dh["n_anchors_usable"], "n_goal": dh["n_goal"], "n_fail": dh["n_fail"], + "endpoint_match_d1": dh["endpoint_match_vs_published"], + "endpoint_match_fold4": fh["endpoint_match_vs_published"], + "heads": heads, + "delta_rms": float(np.sqrt(np.mean(np.square(ds)))), + "delta_max_abs": float(max(ds, key=abs)), + "delta_max_abs_head": max(heads, key=lambda k: abs(heads[k]["delta"])), + "n_heads": len(heads), + "best_fold4": max(heads, key=lambda k: heads[k]["auc_Q_fold4"]), + "best_fold4_auc": max(v["auc_Q_fold4"] for v in heads.values()), + } +P = ROOT / "status/real/FOLD4_COMPARE.json" +P.write_text(json.dumps(out, indent=1)) +b4 = out["by_hop"].get("4", {}) +print(f"wrote {P}: hop4 delta rms {b4.get('delta_rms', float('nan')):.4f} " + f"max {b4.get('delta_max_abs', float('nan')):+.4f} ({b4.get('delta_max_abs_head')}); " + f"best fold4 {b4.get('best_fold4')} {b4.get('best_fold4_auc', float('nan')):.4f}") diff --git a/rsm_rise/scripts/real/build_junction_pairs.py b/rsm_rise/scripts/real/build_junction_pairs.py new file mode 100644 index 0000000000000000000000000000000000000000..dd0f3f4957768cc19650fa7522eb3f20ae6e63bb --- /dev/null +++ b/rsm_rise/scripts/real/build_junction_pairs.py @@ -0,0 +1,373 @@ +"""TASK 4 (stream AUG_SUCC, gen_q#279): build the COUNTERFACTUAL pair set from the JUNCTION itself +instead of from RISE's state-space kNN, and measure it before training on it. + +WHY THIS EXISTS. Task 1's verdict: RISE's kNN augmentation is starved on this corpus -- 0.67 +counterfactual pairs per junction anchor from the failure route at RISE's shipped radius, 8.3 % of +anchors covered, and 0.00 / 0 % in the 1546-d metric the successor actually trains in. But the corpus +hands us the counterfactual by construction: at meta-state S2 three routes are coincident by definition +of the meta state -- + + 2->3->4 (50 eps, reaches the goal) + 0->2->3 (48 eps, cooks, never pours) + 0->2->6 (50 eps, fails) + +so every S2 frame of one route is a state at which another route's S2 action is a genuine counterfactual, +and the route label gives that action its OUTCOME. That is thousands of contrastive pairs rather than +0.67 per anchor. + +WHAT IT EMITS. Exactly the npz schema `data.py --augment-table` already consumes (rows / nbr_row / +nbr_dist / train_eps), so NO trainer change is needed: `--augment-mode contrastive` already gives the +counterfactual action the PARTNER's own truncated-geometric future, which is precisely Task 4's +"train the occupancy toward the failure route's future rather than the anchor's own". The pairing is +the only thing that changes -- one change per measurement. + + rows [M] global cache row of each S2 anchor (TRAIN-split episodes only) + nbr_row [M, K] the K nearest DIFFERENT-ROUTE S2 partners, ascending in `--metric` + nbr_dist [M, K] the distance; UNFILLED SLOTS ARE +inf so any threshold drops them + +WHAT IT MEASURES (the report the brief demands before any training): + * the S2 segment's extent per route, in frames and seconds, since the meta state is long and the + "same physical configuration" claim has to be checked, not assumed; + * the cross-route state-distance distribution at S2 in BOTH metrics (feat1546, the one the model + trains in; ee10 in metres, RISE's shipped units), against the WITHIN-route distance as the scale; + * pairs per anchor and anchor coverage on a threshold ladder whose top end is +inf, i.e. pure + meta-state pairing with no proximity gate at all; + * LABEL PURITY of the admitted pairs: EE-pose distance (physical coincidence), |phase difference| + inside the S2 segment, and the frame/second offset; + * the ACTION distance between the anchor's own chunk and the partner's -- a pair whose action equals + the anchor's own carries no counterfactual signal at all, and the reference scale is the 1.9955 + median goal-vs-failure chunk gap the ranking test must resolve. +CPU only; MUJOCO_GL=disable. +""" +import argparse, collections, json, os, sys, time +import numpy as np + +ROOT = "/proj/dmfexp/zwhong/rsm_rise" +ROT_SCALE = 0.05 +FPS_LOCAL = 50.0 # modal inter-frame dt is exactly 20 ms +FPS_EFF = 38.72 # retained frames / wall second (status/real_cooking_chars.json) +# the ladder's top end is +inf on purpose: that is pure meta-state pairing, no proximity gate +LADDER_FEAT = [20.0, 30.0, 35.0, 40.0, 45.0, 50.0, 60.0, float("inf")] +LADDER_EE = [0.02, 0.05, 0.10, 0.15, 0.30, 0.50, float("inf")] + + +def pct(a, qs=(1, 5, 25, 50, 75, 95, 99)): + a = np.asarray(a, np.float64) + a = a[np.isfinite(a)] + return {f"p{q}": (float(np.percentile(a, q)) if len(a) else float("nan")) for q in qs} + + +def fmt(d): + return " ".join(f"{k}={v:.4f}" for k, v in d.items()) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--hdf5", default=f"{ROOT}/data/raw/cooking_v5_expert_suboptimal.hdf5") + ap.add_argument("--cache", default=f"{ROOT}/cache/real_cooking_v5") + ap.add_argument("--feat-stats", default="") + ap.add_argument("--meta-state", type=int, default=2) + ap.add_argument("--routes", default="2->3->4,0->2->6,0->2->3", + help="routes that participate; pairs are formed between DIFFERENT routes in this list") + ap.add_argument("--metric", default="feat", choices=("feat", "ee"), + help="the metric the nbr_dist column is expressed in (i.e. the one --action-augment " + "thresholds); the other is still reported") + ap.add_argument("--k", type=int, default=32) + ap.add_argument("--tile", type=int, default=1024) + ap.add_argument("--horizon", type=int, default=8) + ap.add_argument("--val-frac", type=float, default=0.1) + ap.add_argument("--seed", type=int, default=0) + ap.add_argument("--stratify-success", type=int, default=0) + ap.add_argument("--pair-sample", type=int, default=20000, + help="pairs subsampled per ladder rung for the action/purity statistics") + # AUG_SUCC run 38: HOLD THE GATE EPISODES OUT OF THE PAIR TABLE. The reverse-arm gate anchors in + # episodes 204/223/224/230/231 (harness split `data/derived/cooking_v5_split.json`, key "valid"), + # and that file is a DIFFERENT partition from the one data.py draws from --seed: at every seed + # 0-8 all five gate episodes land in the successor's TRAIN split, and at seed 1 they contribute + # 958 of the table's 47339 anchor rows (2.0%), all on the failure route -- i.e. the augmentation + # trains counterfactual pairs anchored in the exact episodes the gate scores. This flag removes + # a set of episodes from the S2 frame table entirely, so they are neither anchor nor neighbour, + # WITHOUT touching `train_eps` (data.py's split guard still sees the matching split). + ap.add_argument("--exclude-eps", default="", + help="comma-separated episode ids to drop from the S2 frame table (anchors AND " + "neighbours), or 'split:valid' to drop every episode the harness split file " + "marks valid") + ap.add_argument("--exclude-split", default=f"{ROOT}/data/derived/cooking_v5_split.json", + help="split file read by --exclude-eps split:") + ap.add_argument("--out-table", required=True) + ap.add_argument("--out-report", required=True) + a = ap.parse_args() + import h5py + from pathlib import Path + os.makedirs(os.path.dirname(a.out_report) or ".", exist_ok=True) + os.makedirs(os.path.dirname(a.out_table) or ".", exist_ok=True) + routes = [r for r in a.routes.split(",") if r] + rng = np.random.default_rng(a.seed) + + cache = Path(a.cache) + stats = a.feat_stats or str(cache / "feat_stats.npz") + m = np.load(cache / "meta.npz", allow_pickle=True) + zf = np.load(cache / "z.f16.npy", mmap_mode="r") + pf = np.load(cache / "proprio.f32.npy", mmap_mode="r") + ep_from, ep_to, ep_len = m["ep_from"], m["ep_to"], m["ep_len"] + ep_success = m["ep_success"] + n_ep = len(ep_len) + + # ---- the SAME episode split data.py builds, for THIS seed (a table built on another split would + # leak held-out episodes into training through the action channel; data.py's guard enforces it) + srng = np.random.default_rng(a.seed) + n_val = max(1, int(a.val_frac * n_ep)) + if a.stratify_success: + s = np.asarray(ep_success, bool); parts = [] + for grp in (np.nonzero(s)[0], np.nonzero(~s)[0]): + if len(grp) == 0: + continue + pg = grp[srng.permutation(len(grp))] + kk = max(1, int(round(a.val_frac * len(grp)))) if len(grp) > 1 else 0 + parts.append(pg[:kk]) + val_eps = np.sort(np.concatenate(parts)) if parts else np.array([], np.int64) + train_eps = np.sort(np.setdiff1d(np.arange(n_ep), val_eps)) + else: + perm = srng.permutation(n_ep) + val_eps = np.sort(perm[:n_val]); train_eps = np.sort(perm[n_val:]) + is_train = np.zeros(n_ep, bool); is_train[train_eps] = True + print(f"[junc] split: {len(train_eps)} train / {len(val_eps)} val episodes " + f"(stratify={a.stratify_success}, seed={a.seed})", flush=True) + + # ---- episodes held out of the PAIR TABLE (not out of training) ------------------------------- + excl = set() + if a.exclude_eps: + if a.exclude_eps.startswith("split:"): + want = a.exclude_eps.split(":", 1)[1] + _sp = json.load(open(a.exclude_split))["episodes"] + excl = set(int(k) for k, v in _sp.items() if v.get("split") == want) + print(f"[junc] EXCLUDE from pair table: {len(excl)} episodes marked '{want}' in " + f"{a.exclude_split}", flush=True) + else: + excl = set(int(x) for x in a.exclude_eps.split(",") if x.strip()) + print(f"[junc] EXCLUDE from pair table: {sorted(excl)}", flush=True) + n_in_train = len([e for e in excl if is_train[e]]) + print(f"[junc] of those, {n_in_train} are in THIS seed's train split and are the ones " + f"the exclusion actually removes", flush=True) + + # ---- routes, meta-state annotation, actions ------------------------------------------------- + with h5py.File(a.hdf5, "r") as f: + d = f["data"] + keys = list(d) + path = {int(k.split("_")[1]): str(d[k].attrs.get("path", "")) for k in keys} + stage, acts = {}, {} + for k in keys: + e = int(k.split("_")[1]); g = d[k] + stage[e] = g["annot"]["edge_from"][()].astype(np.int16) + acts[e] = (g["actions_raw"] if "actions_raw" in g else g["actions"])[()].astype(np.float32) + print("[junc] routes: " + " ".join(f"{r}={n}" for r, n in + sorted(collections.Counter(path.values()).items())), flush=True) + + # ---- the S2 frame table: row, episode, route, t, phase inside the S2 segment ----------------- + rows_l, ep_l, rt_l, t_l, ph_l, seglen_l = [], [], [], [], [], [] + seg_frames = collections.defaultdict(list) + for e in sorted(path): + rt = path[e] + if rt not in routes or not is_train[e] or e in excl: + continue + L = min(int(ep_len[e]), len(stage[e]), len(acts[e])) + st = stage[e][:L].astype(np.int64) + idx = np.nonzero(st == a.meta_state)[0] + if len(idx) == 0: + continue + lo, hi = int(idx[0]), int(idx[-1]) # the S2 segment of this episode + span = max(hi - lo, 1) + seg_frames[rt].append(hi - lo + 1) + rows_l.append(int(ep_from[e]) + idx) + ep_l.append(np.full(len(idx), e)) + rt_l.append(np.full(len(idx), routes.index(rt))) + t_l.append(idx) + ph_l.append((idx - lo) / span) + seglen_l.append(np.full(len(idx), hi - lo + 1)) + rows = np.concatenate(rows_l).astype(np.int64) + epid = np.concatenate(ep_l).astype(np.int32) + rtid = np.concatenate(rt_l).astype(np.int32) + tidx = np.concatenate(t_l).astype(np.int32) + phase = np.concatenate(ph_l).astype(np.float32) + seglen = np.concatenate(seglen_l).astype(np.int32) + M = len(rows) + print(f"[junc] {M} TRAIN S{a.meta_state} frames over {len(np.unique(epid))} episodes", flush=True) + + report = {"meta_state": a.meta_state, "routes": routes, "metric": a.metric, "k": a.k, + "seed": a.seed, "val_frac": a.val_frac, "stratify_success": a.stratify_success, + "n_train_eps": int(len(train_eps)), "n_s2_train_frames": int(M), + "exclude_eps": sorted(int(x) for x in excl), + "fps_local": FPS_LOCAL, "fps_eff": FPS_EFF, + "ladder_feat": [x if np.isfinite(x) else "inf" for x in LADDER_FEAT], + "ladder_ee": [x if np.isfinite(x) else "inf" for x in LADDER_EE]} + + # ---- 0. how long IS the meta state, per route? the purity question starts here -------------- + report["segment"] = {} + print(f"\n[junc] S{a.meta_state} segment extent per route " + f"(train episodes; seconds at {FPS_EFF} fps effective / {FPS_LOCAL} fps local)") + for rt in routes: + L = np.asarray(seg_frames[rt], np.float64) + n_rt = int((rtid == routes.index(rt)).sum()) + rec = {"n_eps": int(len(L)), "n_frames": n_rt, "frames": pct(L), + "sec_eff": {k: v / FPS_EFF for k, v in pct(L).items()}, + "sec_local": {k: v / FPS_LOCAL for k, v in pct(L).items()}} + report["segment"][rt] = rec + print(f" {rt:10s} {len(L):3d} eps, {n_rt:6d} S2 frames, span frames {fmt(rec['frames'])}") + print(f" {'':10s} span sec(eff) {fmt(rec['sec_eff'])}") + sys.stdout.flush() + + # ---- the two metrics ------------------------------------------------------------------------- + st = np.load(stats) + D = zf.shape[1] + pf.shape[1] + mu, sd = st["mu"][:D].astype(np.float32), st["sd"][:D].astype(np.float32) + zclip = float(st["z_clip"]) if "z_clip" in st else 10.0 + X = np.empty((M, D), np.float32) + for i in range(0, M, 20000): + j = min(i + 20000, M); r = rows[i:j] + X[i:j] = np.clip((np.concatenate([np.asarray(zf[r], np.float32), + np.asarray(pf[r], np.float32)], 1) - mu) / sd, -zclip, zclip) + P = np.asarray(pf[rows], np.float32) + Emet = np.concatenate([P[:, :3], ROT_SCALE * P[:, 3:9]], 1).astype(np.float32) + print(f"[junc] feat1546 dim={D} ({X.nbytes/1e9:.2f} GB), ee10 dim={Emet.shape[1]}", flush=True) + Xsq = (X ** 2).sum(1, dtype=np.float64) + Esq = (Emet ** 2).sum(1, dtype=np.float64) + PRIM, PRIMsq = (X, Xsq) if a.metric == "feat" else (Emet, Esq) + + # ---- 1. K nearest DIFFERENT-ROUTE S2 partner of every S2 anchor ------------------------------ + K = a.k + nbr_row = np.zeros((M, K), np.int32) + nbr_dist = np.full((M, K), np.inf, np.float32) + nbr_pos = np.full((M, K), -1, np.int64) # index into the S2 table, for the purity stats + # the within-route distance is the scale the cross-route number has to be read against + within_nn = np.full(M, np.inf, np.float64) + cross_nn_by_pair = collections.defaultdict(list) + t0 = time.time() + for i in range(0, M, a.tile): + j = min(i + a.tile, M) + # float32 sgemm, exactly as scripts/real/build_aug_knn.py does: the Gram trick in float64 + # would rebuild a 0.5 GB transpose on every tile for no measurable accuracy at these norms + d2 = (PRIMsq[i:j, None] + PRIMsq[None, :] - 2.0 * (PRIM[i:j] @ PRIM.T).astype(np.float64)) + np.maximum(d2, 0, out=d2) + same_rt = rtid[i:j][:, None] == rtid[None, :] + same_ep = epid[i:j][:, None] == epid[None, :] + dw = np.where(same_rt & ~same_ep, d2, np.inf) # within route, different episode + within_nn[i:j] = np.sqrt(dw.min(1)) + dc = np.where(same_rt, np.inf, d2) # cross route (implies a different episode) + kk = min(K, dc.shape[1] - 1) + idx = np.argpartition(dc, kk, axis=1)[:, :K] + dd = np.take_along_axis(dc, idx, 1) + o = np.argsort(dd, 1) + idx = np.take_along_axis(idx, o, 1); dd = np.take_along_axis(dd, o, 1) + nbr_pos[i:j] = idx + nbr_row[i:j] = rows[idx] + nbr_dist[i:j] = np.sqrt(dd).astype(np.float32) + for aa in range(i, j): + best = np.sqrt(dd[aa - i, 0]) + if np.isfinite(best): + cross_nn_by_pair[(routes[rtid[aa]], routes[rtid[nbr_pos[aa, 0]]])].append(best) + if (i // a.tile) % 10 == 0: + el = time.time() - t0 + print(f"[junc] knn {j}/{M} {el:.0f}s, eta {el*(M-j)/max(j,1):.0f}s", flush=True) + nbr_dist[~np.isfinite(nbr_dist)] = np.inf + + # the SECOND metric on the same admitted pairs (so a feat-gated pair can be read in metres) + flat_a = np.repeat(np.arange(M), K) + flat_b = nbr_pos.reshape(-1) + ok = flat_b >= 0 + alt = np.full(M * K, np.inf, np.float32) + ALT = Emet if a.metric == "feat" else X + for s in range(0, len(flat_a), 2_000_000): + e_ = min(s + 2_000_000, len(flat_a)) + sel = ok[s:e_] + if not sel.any(): + continue + u = ALT[flat_a[s:e_][sel]].astype(np.float64); v = ALT[flat_b[s:e_][sel]].astype(np.float64) + alt[s:e_][sel] = np.sqrt(((u - v) ** 2).sum(1)) + alt = alt.reshape(M, K) + + print(f"\n[junc] nearest CROSS-route S{a.meta_state} partner ({a.metric}), per anchor: " + f"{fmt(pct(nbr_dist[:, 0]))}") + print(f"[junc] nearest WITHIN-route S{a.meta_state} partner ({a.metric}), per anchor: " + f"{fmt(pct(within_nn))}") + report["nn_cross"] = pct(nbr_dist[:, 0]) + report["nn_within"] = pct(within_nn) + report["nn_kth_cross"] = pct(nbr_dist[:, -1]) + report["nn_cross_by_pair"] = {f"{u}|{v}": {"n": len(w), **pct(w)} + for (u, v), w in sorted(cross_nn_by_pair.items())} + for kk, vv in report["nn_cross_by_pair"].items(): + print(f" nearest partner {kk:26s} n={vv['n']:6d} p5={vv['p5']:.3f} p50={vv['p50']:.3f} " + f"p95={vv['p95']:.3f}") + sys.stdout.flush() + + # ---- 2. actions, for the counterfactual-gap statistic ---------------------------------------- + H = a.horizon + + def chunk_of(pos): + e = int(epid[pos]); t = int(tidx[pos]); A = acts[e] + c = A[t:t + H] + if len(c) < H: + c = np.concatenate([c, np.repeat(c[-1:], H - len(c), 0)], 0) + return c.reshape(-1) + + # ---- 3. the ladder: pairs per anchor, coverage, purity, action gap --------------------------- + ladder = LADDER_FEAT if a.metric == "feat" else LADDER_EE + report["ladder"] = [] + print(f"\n[junc] threshold ladder in {a.metric} (inf = pure meta-state pairing, no proximity gate)") + hdr = (f"{'thr':>8s} {'pairs':>10s} {'pairs/anc':>9s} {'cov':>6s} {'ee_p50':>7s} {'ee_p95':>7s} " + f"{'|dphase|p50':>11s} {'dt_s_p50':>8s} {'phys<2cm':>8s} {'act_p50':>8s} {'act>gap':>7s}") + print(hdr) + GAP = 1.9955 # the median goal-vs-failure chunk distance the ranking test must resolve (Task 1) + for thr in ladder: + keep = nbr_dist <= thr + ai, aj = np.nonzero(keep) + n_pairs = len(ai) + cov = len(np.unique(ai)) / max(M, 1) + rec = {"thr": thr if np.isfinite(thr) else "inf", "n_pairs": int(n_pairs), + "pairs_per_anchor": n_pairs / max(M, 1), "anchor_coverage": cov} + if n_pairs: + pick = rng.choice(n_pairs, size=min(a.pair_sample, n_pairs), replace=False) + pa, pb = ai[pick], nbr_pos[ai[pick], aj[pick]] + ee = alt[ai[pick], aj[pick]] if a.metric == "feat" else nbr_dist[ai[pick], aj[pick]] + ft = nbr_dist[ai[pick], aj[pick]] if a.metric == "feat" else alt[ai[pick], aj[pick]] + dph = np.abs(phase[pa] - phase[pb]) + dfr = np.abs(tidx[pa].astype(np.float64) - tidx[pb].astype(np.float64)) + ad = np.array([np.linalg.norm(chunk_of(int(u)) - chunk_of(int(v))) for u, v in zip(pa, pb)]) + rec.update({"n_sampled": int(len(pick)), + "ee_m": pct(ee), "feat": pct(ft), "abs_dphase": pct(dph), + "dframe": pct(dfr), "dsec_eff": {k: v / FPS_EFF for k, v in pct(dfr).items()}, + "phys_coincident_frac_2cm": float((ee < 0.02).mean()), + "phys_coincident_frac_5cm": float((ee < 0.05).mean()), + "action_dist": pct(ad), + "action_beyond_gap_frac": float((ad > GAP).mean()), + "action_gap_ref": GAP, + # BUGFIX: the Counter keys are ALREADY route ids, so the first version + # indexed rtid[] with a route id and mislabelled every bucket (the seed-0 + # feat report's pair_route_mix is wrong for that reason; nn_cross_by_pair, + # which is built correctly, is the reading to use there). + "pair_route_mix": {f"{routes[u]}|{routes[v]}": int(c) for (u, v), c + in collections.Counter( + [(int(rtid[u]), int(rtid[v])) for u, v in + zip(pa[:5000], pb[:5000])]).items()}}) + print(f"{str(rec['thr']):>8s} {n_pairs:10d} {rec['pairs_per_anchor']:9.2f} {cov:6.3f} " + f"{rec['ee_m']['p50']:7.4f} {rec['ee_m']['p95']:7.4f} {rec['abs_dphase']['p50']:11.3f} " + f"{rec['dsec_eff']['p50']:8.2f} {rec['phys_coincident_frac_2cm']:8.3f} " + f"{rec['action_dist']['p50']:8.3f} {rec['action_beyond_gap_frac']:7.3f}") + else: + print(f"{str(rec['thr']):>8s} {n_pairs:10d} {'0.00':>9s} {cov:6.3f} STARVED") + report["ladder"].append(rec) + sys.stdout.flush() + + # ---- 4. the table -------------------------------------------------------------------------- + np.savez_compressed(a.out_table, rows=rows.astype(np.int32), nbr_row=nbr_row, + nbr_dist=nbr_dist, metric=f"junction_{a.metric}", K=K, rot_scale=ROT_SCALE, + z_clip=zclip, train_eps=train_eps.astype(np.int32), + val_eps=val_eps.astype(np.int32), stratify_success=int(a.stratify_success), + seed=a.seed, val_frac=a.val_frac, meta_state=a.meta_state, + routes=np.array(routes), anchor_route=rtid.astype(np.int32), + anchor_ep=epid.astype(np.int32)) + json.dump(report, open(a.out_report, "w"), indent=2, default=str) + print(f"\n[junc] wrote {a.out_table}\n[junc] wrote {a.out_report}", flush=True) + + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/real/build_junction_scramble.py b/rsm_rise/scripts/real/build_junction_scramble.py new file mode 100644 index 0000000000000000000000000000000000000000..7b62eb022acb7e54aae3f52d74f57e854f77e264 --- /dev/null +++ b/rsm_rise/scripts/real/build_junction_scramble.py @@ -0,0 +1,206 @@ +"""AUG_SUCC run 46 (gen_q#279): the SCRAMBLED-PARTNER control for the junction pair table. + +WHY THIS EXISTS -- the number that forced it. Runs 44/45 measured two things that together threaten the +stream's headline: + * (T)/(U): holding all 25 harness-valid gate episodes out of the pair table does NOT lower the reverse + gate. Matched at 3 MC draws, mean bootstrap lower bound is std 0.594 / hg 0.655 / ho 0.599 -- the + held-out arms are equal or BETTER. So the gate is insensitive to WHICH episodes supply the pairs. + * (AD): the gate is monotone increasing in training at every dose, and cap 0.10 -- whose field is dead + at every checkpoint -- has a BETTER gate than cap 0.50 at every checkpoint. +A score that does not care which episodes it was taught from, and that is better at the dose where the +occupancy field is destroyed, may not be reading the counterfactual semantics at all. The un-augmented +baseline's gate is 0.234, so the augmentation is doing SOMETHING; the open question is whether the +something is the JUNCTION COINCIDENCE (an S2 frame of another route, physically coincident, whose future +is that route's outcome) or merely the PRESENCE of cross-route action-swapped rows. + +THE CONTROL. One change, and only one: the partner's IDENTITY. For every anchor we keep + * the anchor set (`rows`) exactly, + * the pair COUNT exactly (same [M, K] shape, and the first --aug-k columns are what data.py slices), + * the cross-route property (partner route != anchor route), + * the per-anchor ROUTE COMPOSITION of the partner slots, column-block by column-block, so the reward + labels the contrastive mode reads off the partner's route are drawn from the identical mixture, + * different-episode and skip-self, +and we destroy ONLY the feature-space coincidence: the partner is drawn UNIFORMLY from that route's S2 +train pool instead of being its nearest frame. Everything data.py consumes (rows / nbr_row / nbr_dist) +keeps its schema, so no trainer change is needed and no deployed file is touched. + +Deployed arms run `--action-augment 1e9`, i.e. no threshold at all, so `nbr_dist` gates nothing and the +admitted pair count is identical by construction rather than by luck. We still COMPUTE the true +feat1546 distance of every scrambled pair, because the size of the coincidence we destroyed is the +measurement that makes the control interpretable: if the scrambled distances sit on top of the originals +the control is void, and if the scrambled arm then reproduces the gate we have learned that the gate is +bought by the mere presence of the rows. + +PREDICTION REGISTERED BEFORE THE RUN -- see status/real/AUG_SUCC.md (AI). +CPU only; MUJOCO_GL=disable. +""" +import argparse, json, os, sys +import numpy as np +from pathlib import Path + +ROOT = "/proj/dmfexp/zwhong/rsm_rise" + + +def pct(a, qs=(1, 5, 25, 50, 75, 95, 99)): + a = np.asarray(a, np.float64) + a = a[np.isfinite(a)] + return {f"p{q}": (float(np.percentile(a, q)) if len(a) else float("nan")) for q in qs} + + +def fmt(d): + return " ".join(f"{k}={v:.3f}" for k, v in d.items()) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--src", required=True, help="the DEPLOYED junction table to scramble") + ap.add_argument("--out-table", required=True) + ap.add_argument("--out-report", required=True) + ap.add_argument("--cache", default=f"{ROOT}/cache/real_cooking_v5") + ap.add_argument("--aug-k", type=int, default=15, + help="data.py's --augment-neighbors: the columns the trainer actually slices. " + "Route composition is matched separately inside [0,aug_k) and [aug_k,K) so " + "the slice the trainer sees has the identical label mixture.") + ap.add_argument("--seed", type=int, default=0) + a = ap.parse_args() + os.makedirs(os.path.dirname(a.out_table) or ".", exist_ok=True) + os.makedirs(os.path.dirname(a.out_report) or ".", exist_ok=True) + rng = np.random.default_rng(a.seed) + + z = np.load(a.src, allow_pickle=True) + rows = z["rows"].astype(np.int64) + nbr_row = z["nbr_row"].astype(np.int64) + nbr_dist = z["nbr_dist"].astype(np.float32) + a_rt = z["anchor_route"].astype(np.int64) + a_ep = z["anchor_ep"].astype(np.int64) + M, K = nbr_row.shape + assert a.aug_k <= K, f"aug_k {a.aug_k} > K {K}" + print(f"[scr] src={a.src} M={M} anchors K={K} aug_k={a.aug_k}", flush=True) + + # ---- frame -> (route, episode) from the anchor columns themselves. Every partner is an S2 train + # frame, hence also an anchor, so the map is total; we VERIFY rather than assume it. + fr_rt = {int(r): int(t) for r, t in zip(rows, a_rt)} + fr_ep = {int(r): int(e) for r, e in zip(rows, a_ep)} + uniq_nb = np.unique(nbr_row[np.isfinite(nbr_dist)]) + miss = [int(x) for x in uniq_nb if int(x) not in fr_rt] + print(f"[scr] partner-frame route coverage: {len(uniq_nb) - len(miss)}/{len(uniq_nb)} " + f"({'TOTAL' if not miss else 'INCOMPLETE -- ' + str(len(miss)) + ' uncovered'})", flush=True) + if miss: + sys.exit("partner frames absent from the anchor table; cannot match route composition honestly") + + n_routes = int(a_rt.max()) + 1 + # per-route pool of S2 train frames, and the episode of each, for the different-episode constraint + pool = [rows[a_rt == r] for r in range(n_routes)] + pool_ep = [a_ep[a_rt == r] for r in range(n_routes)] + for r in range(n_routes): + print(f"[scr] route {r}: {len(pool[r])} S2 frames over {len(np.unique(pool_ep[r]))} episodes", + flush=True) + + # ---- the scramble. Per anchor, per column block, match the ORIGINAL route composition exactly. + nb_rt = np.vectorize(fr_rt.get)(nbr_row) + nb_rt[~np.isfinite(nbr_dist)] = -1 + new_nbr = np.zeros((M, K), np.int64) + new_fin = np.zeros((M, K), bool) + blocks = [(0, a.aug_k), (a.aug_k, K)] + n_resample = 0 + for i in range(M): + for lo, hi in blocks: + if hi <= lo: + continue + want = nb_rt[i, lo:hi] + for j, r in enumerate(want): + col = lo + j + if r < 0: # an unfilled slot stays unfilled: +inf, dropped by any thr + continue + # uniform over that route's S2 pool, excluding the anchor's own episode (different- + # trajectory) -- the anchor's own episode is on its own route anyway when r != a_rt[i], + # but the guard is kept so the invariant holds for any src table. + for _ in range(20): + p = rng.integers(len(pool[r])) + if pool_ep[r][p] != a_ep[i]: + break + n_resample += 1 + new_nbr[i, col] = pool[r][p] + new_fin[i, col] = True + if (i + 1) % 10000 == 0: + print(f"[scr] scrambled {i+1}/{M} anchors", flush=True) + print(f"[scr] same-episode rejections resampled: {n_resample}", flush=True) + + # ---- invariants the control claims, checked not asserted + orig_fin = np.isfinite(nbr_dist) + new_rt = np.full((M, K), -1, np.int64) + fsel = np.nonzero(new_fin) + new_rt[fsel] = np.array([fr_rt[int(x)] for x in new_nbr[fsel]], np.int64) + inv = { + "filled_slots_orig": int(orig_fin.sum()), + "filled_slots_scr": int(new_fin.sum()), + "route_composition_identical": bool((new_rt == nb_rt).all()), + "cross_route_frac_scr": float((new_rt[new_fin] != a_rt[:, None].repeat(K, 1)[new_fin]).mean()), + "same_episode_pairs_scr": int(sum( + 1 for i, c in zip(*fsel) if fr_ep[int(new_nbr[i, c])] == int(a_ep[i]))), + "self_pairs_scr": int(sum( + 1 for i, c in zip(*fsel) if int(new_nbr[i, c]) == int(rows[i]))), + "identical_partner_frac": float(np.mean(new_nbr[orig_fin & new_fin] == nbr_row[orig_fin & new_fin])), + } + print("[scr] invariants: " + json.dumps(inv), flush=True) + + # ---- the true feat1546 distance of every scrambled pair: the size of what we destroyed + cache = Path(a.cache) + st = np.load(cache / "feat_stats.npz") + zf = np.load(cache / "z.f16.npy", mmap_mode="r") + pf = np.load(cache / "proprio.f32.npy", mmap_mode="r") + D = zf.shape[1] + pf.shape[1] + mu, sd = st["mu"][:D].astype(np.float32), st["sd"][:D].astype(np.float32) + zclip = float(st["z_clip"]) if "z_clip" in st else 10.0 + need = np.unique(np.concatenate([rows, new_nbr[new_fin]])) + pos = {int(r): i for i, r in enumerate(need)} + X = np.empty((len(need), D), np.float32) + for i in range(0, len(need), 20000): + j = min(i + 20000, len(need)); r = need[i:j] + X[i:j] = np.clip((np.concatenate([np.asarray(zf[r], np.float32), + np.asarray(pf[r], np.float32)], 1) - mu) / sd, -zclip, zclip) + print(f"[scr] feat1546 dim={D}, {len(need)} distinct frames ({X.nbytes/1e9:.2f} GB)", flush=True) + ai = np.array([pos[int(r)] for r in rows], np.int64) + new_dist = np.full((M, K), np.inf, np.float32) + for c in range(K): + sel = np.nonzero(new_fin[:, c])[0] + if not len(sel): + continue + bj = np.array([pos[int(x)] for x in new_nbr[sel, c]], np.int64) + d = np.linalg.norm(X[ai[sel]] - X[bj], axis=1) + new_dist[sel, c] = d + ok = orig_fin & new_fin + print(f"\n[scr] feat1546 partner distance -- the coincidence we destroyed") + print(f" ORIGINAL (nearest cross-route) {fmt(pct(nbr_dist[ok]))}") + print(f" SCRAMBLED (uniform, same route) {fmt(pct(new_dist[ok]))}") + print(f" aug_k={a.aug_k} slice only:") + ok_k = ok[:, :a.aug_k] + print(f" ORIGINAL {fmt(pct(nbr_dist[:, :a.aug_k][ok_k]))}") + print(f" SCRAMBLED {fmt(pct(new_dist[:, :a.aug_k][ok_k]))}") + med_o = float(np.median(nbr_dist[:, :a.aug_k][ok_k])) + med_s = float(np.median(new_dist[:, :a.aug_k][ok_k])) + print(f"\n[scr] VERDICT on the control's validity: median partner distance in the trained slice " + f"{med_o:.3f} -> {med_s:.3f} (x{med_s/max(med_o,1e-9):.2f}). " + f"{'VALID -- coincidence destroyed' if med_s > 1.15 * med_o else 'VOID -- the scramble did not move the distance'}", + flush=True) + + out = {k: z[k] for k in z.files} + out["nbr_row"] = new_nbr.astype(np.int32) + out["nbr_dist"] = new_dist.astype(np.float32) + out["scramble_src"] = np.array(a.src) + out["scramble_seed"] = np.array(a.seed) + out["scramble_aug_k"] = np.array(a.aug_k) + np.savez_compressed(a.out_table, **out) + rep = {"src": a.src, "out_table": a.out_table, "seed": a.seed, "aug_k": a.aug_k, + "M": int(M), "K": int(K), "invariants": inv, + "feat_dist_all": {"orig": pct(nbr_dist[ok]), "scrambled": pct(new_dist[ok])}, + "feat_dist_augk": {"orig": pct(nbr_dist[:, :a.aug_k][ok_k]), + "scrambled": pct(new_dist[:, :a.aug_k][ok_k])}, + "median_augk_orig": med_o, "median_augk_scrambled": med_s, + "control_valid": bool(med_s > 1.15 * med_o)} + json.dump(rep, open(a.out_report, "w"), indent=1) + print(f"[scr] wrote {a.out_table} and {a.out_report}", flush=True) + + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/real/build_knn_pairs.py b/rsm_rise/scripts/real/build_knn_pairs.py new file mode 100644 index 0000000000000000000000000000000000000000..f8e1b33c180206724684c277883def9bced5d6cc --- /dev/null +++ b/rsm_rise/scripts/real/build_knn_pairs.py @@ -0,0 +1,97 @@ +#!/usr/bin/env python +"""RISE kNN "advanced augmentation" neighbour table for the cooking data, computed exactly like +robomimic/utils/dataset.py::build_state_augmentation_data_advanced (the sim flagship), but OFFLINE so the openpi +pi0.5 RISE-recipe cell can consume it (#263). + +State-for-distance = DinoV2Core(dinov2_vits14, concatenate=False -> GeM-pooled patch tokens, 384/cam) on the +84x84 hdf5 images of BOTH cameras, concatenated (768) and L2-normalised (so euclidean == cosine ranking). +play = frames of r==0 episodes with index_in_demo >= 50 (augment_init_cutoff_thresh) +expert= frames of r==1 episodes with index_in_demo >= 20 (augment_init_cutoff_thresh_expert) +For every play frame: its 16 nearest expert frames (p2e) and 16 nearest play frames (p2p). The sim then keeps +neighbours with dist <= distance_threshold, p2e additionally requires equal (binary) gripper, p2p a different demo. +We store ALL 16 neighbours + distances (+ gripper, demo) so the threshold is chosen at load time; the log prints +the distance percentiles for the 0.05-0.15 calibration. Only TRAIN-split episodes (mask/train) on both sides. +Output npz: play_gidx, p2e_gidx [Np,16], p2e_dist, p2p_gidx, p2p_dist, gripper (per global frame), demo (per global +frame), n_frames, hdf5, plus summary counts per threshold. +""" +import argparse, json, time +import numpy as np, h5py, torch + +ROOT = "/proj/dmfexp/zwhong/rsm_rise" + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--hdf5", default=f"{ROOT}/data/raw/cooking_v5_expert_suboptimal.hdf5") + ap.add_argument("--out", default=f"{ROOT}/data/derived/cooking_v5_knn_pairs.npz") + ap.add_argument("--k", type=int, default=15) + ap.add_argument("--cutoff-play", type=int, default=50) + ap.add_argument("--cutoff-expert", type=int, default=20) + ap.add_argument("--batch", type=int, default=512) + args = ap.parse_args() + t0 = time.time() + dev = torch.device("cuda") + import sys + sys.path.insert(0, f"{ROOT}/code/rise_robomimic") + from robomimic.models.obs_core import DinoV2Core + enc = DinoV2Core(input_shape=(3, 84, 84), backbone_name="dinov2_vits14", concatenate=False).to(dev).eval() + + with h5py.File(args.hdf5, "r") as f: + train = {x.decode() for x in f["mask"]["train"][()]} + demos = sorted(f["data"].keys(), key=lambda k: int(k.split("_")[1])) + # LeRobot global index = cumulative length over episodes in episode_index order (all 248, incl. held-out) + lengths = {d: int(f["data"][d].attrs["num_samples"]) for d in demos} + starts, s = {}, 0 + for d in demos: + starts[d] = s; s += lengths[d] + N = s + feats = np.zeros((N, 768), np.float32); gripper = np.zeros(N, np.float32); demo_id = np.zeros(N, np.int64) + reward = np.zeros(N, np.float32); idx_in_demo = np.zeros(N, np.int64); in_train = np.zeros(N, bool) + for n, d in enumerate(demos): + g = f["data"][d]; T = lengths[d]; a, b = starts[d], starts[d] + T + imgs = [g["obs"]["agentview_image"][()], g["obs"]["robot0_eye_in_hand_image"][()]] # sim key order + out = [] + with torch.no_grad(): + for i in range(0, T, args.batch): + per_cam = [] + for im in imgs: + x = torch.from_numpy(im[i:i + args.batch]).to(dev).float().div_(255.0).permute(0, 3, 1, 2) # process_frame + per_cam.append(enc(x).float().cpu().numpy()) + out.append(np.concatenate(per_cam, -1)) + fe = np.concatenate(out); fe /= np.linalg.norm(fe, axis=1, keepdims=True) + feats[a:b] = fe; gripper[a:b] = g["obs"]["robot0_gripper_qpos"][()][:, 0]; demo_id[a:b] = int(d.split("_")[1]) + reward[a:b] = g["rewards"][()]; idx_in_demo[a:b] = np.arange(T); in_train[a:b] = d in train + if n % 25 == 0: + print(f"[knn] {n+1}/{len(demos)} {d} T={T} {time.time()-t0:.0f}s", flush=True) + play = np.where(in_train & (reward == 0) & (idx_in_demo >= args.cutoff_play))[0] + expert = np.where(in_train & (reward > 0) & (idx_in_demo >= args.cutoff_expert))[0] + print(f"[knn] frames {N}; play states {len(play)} expert states {len(expert)} (train split only)", flush=True) + from sklearn.neighbors import NearestNeighbors + k1 = args.k + 1 + e_nn = NearestNeighbors(n_neighbors=min(k1, len(expert))).fit(feats[expert]) + p_nn = NearestNeighbors(n_neighbors=min(k1, len(play))).fit(feats[play]) + d_e, i_e = e_nn.kneighbors(feats[play]); d_p, i_p = p_nn.kneighbors(feats[play]) + p2e_g, p2p_g = expert[i_e], play[i_p] + print(f"[knn] kneighbors done {time.time()-t0:.0f}s", flush=True) + print("[knn] p2e nearest-expert distance percentiles (1st neighbour): " + + " ".join(f"p{q}={np.percentile(d_e[:,0],q):.3f}" for q in (5, 25, 50, 75, 95))) + print("[knn] p2e 15th-neighbour distance percentiles: " + " ".join(f"p{q}={np.percentile(d_e[:,-1],q):.3f}" for q in (5, 25, 50, 75, 95))) + print("[knn] p2p 2nd-neighbour (1st is self) percentiles: " + " ".join(f"p{q}={np.percentile(d_p[:,1],q):.3f}" for q in (5, 25, 50, 75, 95))) + summary = {} + for thr in (0.03, 0.05, 0.08, 0.10, 0.12, 0.15, 0.20): + ok_e = (d_e <= thr) & (gripper[p2e_g] == gripper[play][:, None]) + ok_p = (d_p <= thr) & (p2p_g != play[:, None]) & (demo_id[p2p_g] != demo_id[play][:, None]) + summary[str(thr)] = {"p2e_pairs": int(ok_e.sum()), "p2e_play_states_covered": int(ok_e.any(1).sum()), + "p2p_pairs": int(ok_p.sum()), "p2p_play_states_covered": int(ok_p.any(1).sum())} + print(f"[knn] thr {thr}: p2e pairs {ok_e.sum()} (covering {ok_e.any(1).sum()}/{len(play)} play states), " + f"p2p pairs {ok_p.sum()} (covering {ok_p.any(1).sum()})", flush=True) + np.savez_compressed(args.out, play_gidx=play, expert_gidx=expert, p2e_gidx=p2e_g, p2e_dist=d_e.astype(np.float32), + p2p_gidx=p2p_g, p2p_dist=d_p.astype(np.float32), gripper=gripper, demo=demo_id, reward=reward, + idx_in_demo=idx_in_demo, in_train=in_train, n_frames=N, hdf5=args.hdf5, + summary=json.dumps(summary), cutoff_play=args.cutoff_play, cutoff_expert=args.cutoff_expert) + np.save(args.out.replace(".npz", "_feats768.f16.npy"), feats.astype(np.float16)) + print(f"[knn] wrote {args.out} {time.time()-t0:.0f}s", flush=True) + + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/real/build_knn_pairs_ee.py b/rsm_rise/scripts/real/build_knn_pairs_ee.py new file mode 100644 index 0000000000000000000000000000000000000000..16be90fa3cf6b452dee4f045c3d02f6b08fe63fe --- /dev/null +++ b/rsm_rise/scripts/real/build_knn_pairs_ee.py @@ -0,0 +1,64 @@ +#!/usr/bin/env python +"""EE-space variant of the RISE kNN neighbour table (#263): same play/expert/cutoff/gripper/demo logic as +build_knn_pairs.py, but the state-for-distance is the 10-d proprio, NOT DINOv2 features: + feat = [xyz (m), rot_scale * rot6d] (gripper handled by the equality test, as in the sim) +so the threshold is in METRES of end-effector displacement (rot6d unit change == rot_scale metres). Parquet only. +Output npz has the same keys as the DINO table (so KNNAugmentedDataset can load either) + rot_scale. +""" +import argparse, glob, json, time +import numpy as np, pyarrow.parquet as pq + +ROOT = "/proj/dmfexp/zwhong/rsm_rise" + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--out", default=f"{ROOT}/data/derived/cooking_v5_knn_pairs_ee.npz") + ap.add_argument("--k", type=int, default=15) + ap.add_argument("--rot-scale", type=float, default=0.05) + ap.add_argument("--grip-thresh", type=float, default=0.052) + ap.add_argument("--cutoff-play", type=int, default=50) + ap.add_argument("--cutoff-expert", type=int, default=20) + # COOKV6: dataset root + split json (defaults = the v5 table every existing config uses) + ap.add_argument("--root", default=f"{ROOT}/data/real/rsm_cooking_v5") + ap.add_argument("--split", default=f"{ROOT}/data/derived/cooking_v5_split.json") + args = ap.parse_args() + t0 = time.time() + split = json.load(open(args.split))["episodes"] + S, demo, reward, iid, intr = [], [], [], [], [] + for f in sorted(glob.glob(f"{args.root}/data/chunk-*/episode_*.parquet")): + t = pq.read_table(f, columns=["episode_index", "observation.state"]).to_pandas() + ep = int(t["episode_index"].iloc[0]); T = len(t); info = split[str(ep)] + S.append(np.stack(t["observation.state"].values).astype(np.float32)); demo.append(np.full(T, ep)) + reward.append(np.full(T, 1.0 if info["provenance"] == "expert" else 0.0, np.float32)) + iid.append(np.arange(T)); intr.append(np.full(T, info["split"] == "train")) + S = np.concatenate(S); demo = np.concatenate(demo); reward = np.concatenate(reward); iid = np.concatenate(iid); intr = np.concatenate(intr) + N = len(S); gripper = (S[:, 9] < args.grip_thresh).astype(np.float32) + feats = np.concatenate([S[:, :3], args.rot_scale * S[:, 3:9]], 1) + play = np.where(intr & (reward == 0) & (iid >= args.cutoff_play))[0] + expert = np.where(intr & (reward > 0) & (iid >= args.cutoff_expert))[0] + print(f"[knn-ee] frames {N}; play {len(play)} expert {len(expert)}; rot_scale {args.rot_scale}", flush=True) + from sklearn.neighbors import NearestNeighbors + k1 = args.k + 1 + d_e, i_e = NearestNeighbors(n_neighbors=k1).fit(feats[expert]).kneighbors(feats[play]) + d_p, i_p = NearestNeighbors(n_neighbors=k1).fit(feats[play]).kneighbors(feats[play]) + p2e_g, p2p_g = expert[i_e], play[i_p] + print("[knn-ee] p2e 1st-neighbour dist (m) percentiles: " + " ".join(f"p{q}={np.percentile(d_e[:,0],q):.4f}" for q in (5, 25, 50, 75, 95))) + print("[knn-ee] p2e 15th-neighbour: " + " ".join(f"p{q}={np.percentile(d_e[:,-1],q):.4f}" for q in (5, 25, 50, 75, 95))) + print("[knn-ee] p2p 2nd-neighbour: " + " ".join(f"p{q}={np.percentile(d_p[:,1],q):.4f}" for q in (5, 25, 50, 75, 95))) + summary = {} + for thr in (0.005, 0.01, 0.02, 0.03, 0.05, 0.08): + ok_e = (d_e <= thr) & (gripper[p2e_g] == gripper[play][:, None]) + ok_p = (d_p <= thr) & (p2p_g != play[:, None]) & (demo[p2p_g] != demo[play][:, None]) + summary[str(thr)] = {"p2e_pairs": int(ok_e.sum()), "p2e_play_states_covered": int(ok_e.any(1).sum()), + "p2p_pairs": int(ok_p.sum()), "p2p_play_states_covered": int(ok_p.any(1).sum())} + print(f"[knn-ee] thr {thr} m: p2e pairs {ok_e.sum()} (covering {ok_e.any(1).sum()}/{len(play)}), p2p pairs {ok_p.sum()} (covering {ok_p.any(1).sum()})", flush=True) + np.savez_compressed(args.out, play_gidx=play, expert_gidx=expert, p2e_gidx=p2e_g, p2e_dist=d_e.astype(np.float32), + p2p_gidx=p2p_g, p2p_dist=d_p.astype(np.float32), gripper=gripper, demo=demo, reward=reward, + idx_in_demo=iid, in_train=intr, n_frames=N, rot_scale=args.rot_scale, summary=json.dumps(summary), + cutoff_play=args.cutoff_play, cutoff_expert=args.cutoff_expert, space="ee") + print(f"[knn-ee] wrote {args.out} {time.time()-t0:.0f}s") + + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/real/build_names271_tex.py b/rsm_rise/scripts/real/build_names271_tex.py new file mode 100644 index 0000000000000000000000000000000000000000..7af704361c61a4e79f0a50c0c824ecb3505a8b14 --- /dev/null +++ b/rsm_rise/scripts/real/build_names271_tex.py @@ -0,0 +1,56 @@ +#!/usr/bin/env python +"""gen_q #271, run 18: emit docs/tex/_names271.tex -- the canonical name <-> formula <-> FILE map. + +Every column is READ: the names, aliases and positive-frame counts from the rsm_real clone's +rise_stack/configs/reward_names.json, the file for each training cell from scripts/real/hf_upload.py's +REWARD_HEADS, the counts cross-checked against status/real/REWARD_SCHEMES.json. Nothing is typed, so the +table cannot drift away from what is on the hub (audit271_consistency.py check H enforces the same map). +""" +from __future__ import annotations +import importlib.util, json +from pathlib import Path + +ROOT = Path("/proj/dmfexp/zwhong/rsm_rise") +CLONE = Path("/proj/dmfexp/zwhong/projs/rsm_real") +REG = json.loads((CLONE / "rise_stack/configs/reward_names.json").read_text()) +SCH = {s["name"]: s for s in json.loads((ROOT / "status/real/REWARD_SCHEMES.json").read_text())["schemes"]} +spec = importlib.util.spec_from_file_location("_hfu", ROOT / "scripts/real/hf_upload.py") +hfu = importlib.util.module_from_spec(spec); spec.loader.exec_module(hfu) +FILE_OF_CELL = {src.parent.name: dst for _c, src, dst in hfu.REWARD_HEADS} +LIVE = {r["path"] for r in json.loads((ROOT / "status/real/hf_tree.json").read_text())["rows"]} + +esc = lambda s: s.replace("_", r"\_") +# name -> (formula in the paper's notation, training cell, the scheme key in REWARD_SCHEMES.json) +ROWS = [ + ("GOAL_EPISODE", r"$r_t = \mathbf{1}[f_i = S_4]$", "R_M_ft_v0", "v0_shipped_final_eq_S4"), + ("GOAL_SEGMENT", r"$r_t = \mathbf{1}[\mathrm{to}(t) = S_4]$", "R_M_ft_v1", "A_to_eq_S4"), + ("EXPERT_EPISODE", r"$r_t = \mathbf{1}[f_i \in \{S_3,S_4\}]$", "R_M_ft_v0lit", "v0lit_final_in_S3_S4"), + ("GOAL_WINDOW_100", r"$r_t = \mathbf{1}[0 \le a_i - t \le 100]$", "R_M_ft_B", "B_window_H100"), + ("GOAL_WINDOW_400", r"$r_t = \mathbf{1}[0 \le a_i - t \le 400]$", "R_M_ft_B400", "B_window_H400"), +] +L = [r"\begin{table}[t]\centering\small", + r"\caption{The canonical names of \texttt{rise\_stack/REWARD\_NAMES.md} against this document's " + r"formulas and the file on the hub that carries each label. Generated from " + r"\texttt{rise\_stack/configs/reward\_names.json} and \texttt{scripts/real/hf\_upload.py}; the " + r"positive-frame counts are cross-checked against \texttt{status/real/REWARD\_SCHEMES.json}. The " + r"pair to be careful with is the first two rows: \texttt{successor\_rsm\_real\_A\_110000.pt} carries " + r"\textsc{goal\_segment}, not \textsc{goal\_episode}.}\label{tab:names271}", + r"\begin{tabular}{llrl}\toprule", + r"canonical name & label & positive frames & where it lives \\\midrule"] +for name, formula, cell, key in ROWS: + n_reg = REG["rewards"][name]["positive_frames"] + n_sch = SCH[key]["pos_frames"] + assert n_reg == n_sch, f"{name}: registry {n_reg} != REWARD_SCHEMES {n_sch}" + f = FILE_OF_CELL.get(cell) + if name == "GOAL_EPISODE": + where = (r"in the base \texttt{successor\_rsm\_real\_RM\_s0\_100k.pt}; " + r"the \texttt{" + esc(cell) + r"} fine-tune is not uploaded") + elif f in LIVE: + where = r"\texttt{" + esc(f) + "}" + else: + where = r"\texttt{" + esc(cell) + r"}, trained, not uploaded" + L.append(f"\\textsc{{{esc(name.lower())}}} & {formula} & {n_sch:,} & {where} \\\\") +L += [r"\bottomrule\end{tabular}\end{table}"] +out = ROOT / "docs/tex/_names271.tex" +out.write_text("\n".join(L) + "\n") +print(f"[names271] wrote {out} ({len(L)} lines), {len(ROWS)} names, counts cross-checked") diff --git a/rsm_rise/scripts/real/build_ol271_comment.py b/rsm_rise/scripts/real/build_ol271_comment.py new file mode 100644 index 0000000000000000000000000000000000000000..56ba12e7ef56d02aa54713f67cb151441cff39ae --- /dev/null +++ b/rsm_rise/scripts/real/build_ol271_comment.py @@ -0,0 +1,112 @@ +#!/usr/bin/env python +"""run 15: the #271 comment for the OPEN-LOOP fold, generated from status/real/OL_COMPARE.json. + +Every number below is read out of the JSON the measurement wrote, so the prose cannot drift from +the table and the table cannot drift from the cell. Writes status/real/comment_271_run15.md. +""" +from __future__ import annotations +import json +from pathlib import Path + +ROOT = Path("/proj/dmfexp/zwhong/rsm_rise") +D = json.loads((ROOT / "status/real/OL_COMPARE.json").read_text()) +h4, c = D["by_hop"]["4"], D["control"] +H = h4["heads"] +ceil_head = max(H, key=lambda k: H[k]["auc_R_chain"]) + +L = [] +a = L.append +a("### The policy the fold rolls out, matched to the label's own: measured, and it changes **nothing**") +a("") +a("The last comment said the latent each head is evaluated at -- not the score -- was the next thing to") +a("control. Reading the two rollouts side by side turned up something sharper than a latent mismatch, and") +a("it is structural, not a matter of degree: **`Q` and the `GOAL`/`FAIL` label it is scored against are") +a("values of two different trajectories.**") +a("") +a("* The **label's** rollout (`scripts/real/stitch_decompose.py`, hop loop) computes the action chunk `a`") +a(" once from the candidate and **never reassigns it** -- the chain re-applies the *same* `a` at every") +a(" hop, and the label is the class of `nn(z_H)` of that open-loop repeat.") +a("* The **fold's** rollout (`rsm_scorer.py:_q_fold_logit`) re-samples the hop head between hops,") +a(" `a_{k+1} ~ pi_hop(.|z_{k+1})`. At depth four it therefore estimates the value of *apply the candidate") +a(" once, then follow the hop head for three hops*.") +a("") +a("So the read-out was never trying to predict its own label. `--q-fold-openloop` (additive, default-off,") +a("a no-op at depth one) repeats the candidate at every hop, which is exactly the label's generating") +a("process. **The prediction was written down before the job landed:** if the policy mismatch was the") +a(f"cause, `{ceil_head}`'s `Q` should move toward the **{H[ceil_head]['auc_R_chain']:.3f}** its `R(z_h)` already reaches and") +a(f"`corr(Q, R(z_h))` should rise well above **{H[ceil_head]['corr_Q_Rchain_closed']:.2f}**. It did neither.") +a("") +a("#### The control comes first") +a(f"The chains, the endpoints and the labels are computed **outside** the scorer, so they must be identical") +a(f"between the two cells and this asserts it array-by-array: **{c['chain_arrays_identical']}/{c['chain_arrays_checked']} chain arrays") +a(f"bit-identical** over {c['anchors_compared']}/150 anchors, `endpoint_match_vs_published` **{h4['endpoint_match_closed']:.3f}** (closed) and") +a(f"**{h4['endpoint_match_open']:.3f}** (open). And the flag does bite: **{c['q_arrays_that_moved']}/{c['q_arrays_compared']} `Q` arrays moved.** Same") +a("candidates, same chains, same labels; the only thing that differs is which action the fold applies at") +a("hops 2..4.") +a("") +a(f"#### Hop 4 ({h4['n_anchors_usable']} usable anchors, {h4['n_goal']} GOAL / {h4['n_fail']} FAIL candidates)") +a("") +a("| head | AUC `Q` closed | AUC `Q` open | Δ | Δ/SEM | ρ(`Q`,`R(z_h)`) closed → open | AUC `R(z_h)` |") +a("|---|---|---|---|---|---|---|") +for k, v in sorted(H.items(), key=lambda kv: -kv[1]["auc_Q_closed"]): + z = v["delta"] / v["Q_sem_open"] if v["Q_sem_open"] else float("nan") + a(f"| `{k}` | {v['auc_Q_closed']:.4f} | {v['auc_Q_open']:.4f} | {v['delta']:+.4f} | {z:+.2f} | " + f"{v['corr_Q_Rchain_closed']:.3f} → {v['corr_Q_Rchain_open']:.3f} | {v['auc_R_chain']:.3f} |") +a("") +a(f"**The best head moves from {h4['best_closed_auc']:.4f} (`{h4['best_closed']}`) to {h4['best_open_auc']:.4f} (`{h4['best_open']}`) -- a lift of") +a(f"{h4['lift']:+.4f}.** Over the {h4['n_heads']} heads the rms move is **{h4['delta_rms']:.4f}** and the largest single move is") +a(f"**{h4['delta_max_abs']:+.4f}** (`{h4['delta_max_abs_head']}`, {H[h4['delta_max_abs_head']]['delta']/H[h4['delta_max_abs_head']]['Q_sem_open']:+.1f} SEM -- about what 16 heads on one draw produce by chance).") +a(f"{h4['n_above_half_closed']} heads sit above 0.5 in the closed cell and **{h4['n_above_half_open']}** in the open one. For scale, the design's own") +a("resolution is **±0.024** (the within-anchor label permutation) and plain GPU non-determinism moves this") +a("statistic by **~0.005**.") +a("") +a(f"And the head the prediction named: `{ceil_head}` goes {H[ceil_head]['auc_Q_closed']:.4f} → {H[ceil_head]['auc_Q_open']:.4f}, and its") +a(f"`corr(Q, R(z_h))` **falls** {H[ceil_head]['corr_Q_Rchain_closed']:.4f} → {H[ceil_head]['corr_Q_Rchain_open']:.4f}. The latent ceiling is unchanged at") +a(f"**{h4['latent_ceiling']:.3f}**, so the gap the read-out leaves on the table goes from {h4["gap_to_ceiling_closed"]:.4f} to {h4["gap_to_ceiling_open"]:.4f}. Hop 2") +a(f"behaves the same way: lift {D['by_hop']['2']['lift']:+.4f}, rms {D['by_hop']['2']['delta_rms']:.4f}.") +a("") +a("#### One more mismatch, checked and empty") +a("Reading the two rollouts side by side also turned up that `stitch_decompose.py` clamps the sampled") +a("latent to the trainer's `sample_clip` (10.0 on this corpus) after every hop while `_q_fold_logit` never") +a("clamped at all. That is a second, independent way the fold could drift. It is **a measured no-op**: with") +a("the clamp on, **15 of 16 heads are bit-identical** at depth 4 and the sixteenth moves by **1.8e-06**,") +a("against a noise floor of ~0.005. The clamp at ±10 essentially never binds on this corpus, so it needed") +a("no GPU cell.") +a("") +a("#### What this settles -- and what it does not") +a("Four degrees of freedom have now been varied on **identical candidates**, and none of them moves the") +a("stitching number out of the noise:") +a("") +a("1. the **reward label** -- 16 heads, five candidate draws;") +a("2. the read-out's **horizon** -- depth 1 (~100 frames) vs fold-4 (~400): rms 0.0028;") +a("3. the scoring **functional** -- prob / log-prob / logit, T ∈ {1, 25, 100}: best lift +0.0052;") +a("4. the rollout **policy** -- this comment: lift %+.4f, rms %.4f." % (h4["lift"], h4["delta_rms"])) +a("") +a("**The read-out is exonerated.** The honest conclusion, stated in advance as the null branch of the") +a("prediction, is that this diagnostic's `GOAL`/`FAIL` label is not predictable from the candidate by `Q`,") +a("and further read-out variants are not worth measuring.") +a("") +a("The reason is worth stating precisely, because it is *not* \"nothing more can be done\": `Q` is a") +a("discounted **occupancy of the reward set along the chain**, while the label is the **class of the") +a("endpoint at hop 4**. Matching the policy and the transition removes the *trajectory* mismatch; it does") +a("not remove the *functional-of-the-trajectory* mismatch. What is left is what `Q` **is**, not how it is") +a("rolled out.") +a("") +a(f"Two standing caveats carry over unchanged. This is **one** candidate draw -- the draw is the dominant") +a("variance component -- so **no per-head ranking may be read off the table above**; the scheme comparison") +a("stands on the five-draw replication. And the ~0.94 latent figure is a **ceiling, not a demonstration**:") +a("the label is defined as the class of `nn(z_h)`, so `R(z_h)` predicting it is close to a smoothness check") +a("on `R` near `z_h` (`auc_R_retrieved_per_anchor` is exactly 1.000). Nothing shipped changes: the default") +a("reward stays **A**, and `rsm_reward_stitching_best` stays **null**.") +a("") +a("Artefacts: `status/real/STITCH_DECOMP_FOLD4_OL.json` (+ its 150-anchor parts dir),") +a("`status/real/OL_COMPARE.json`, `scripts/real/build_ol_compare.py`. Cells: `rr_pack4_ol271n` 1878752 and") +a("`rr_pack4_ol271n2` 1879137 (4 GPUs each, 8 shards, 150/150 anchors), `rr_cpu_olagg15` 1879178.") +a("Regression smokes for the flag: `rr_cpu_fosmoke2` 1878549 (flag off reproduces the archived fold-4 part") +a("bit-exactly; flag on at depth 1 is bit-exact; flag on at depth 4 moves) and `rr_cpu_fcsmoke` 1878573") +a("(the sample clip). Full table and formulas in `docs/real_reward_study.pdf`, §\"The policy the fold") +a("rolls out\".") + +out = ROOT / "status/real/comment_271_run15.md" +out.write_text("\n".join(L) + "\n") +print("wrote", out, len(L), "lines") diff --git a/rsm_rise/scripts/real/build_ol_compare.py b/rsm_rise/scripts/real/build_ol_compare.py new file mode 100644 index 0000000000000000000000000000000000000000..836cb73ec260dc5b4ca442743e2c780816349218 --- /dev/null +++ b/rsm_rise/scripts/real/build_ol_compare.py @@ -0,0 +1,149 @@ +#!/usr/bin/env python +"""run 14: CLOSED-LOOP vs OPEN-LOOP fold-4, on identical candidates and identical chains. + +status/real/STITCH_DECOMP_FOLD4.json -- Q from `--q-mode fold --q-depth 4`, hop head RE-SAMPLED + between hops (the historic read-out) +status/real/STITCH_DECOMP_FOLD4_OL.json -- the same, `--q-fold-openloop`: the candidate action chunk + is REPEATED at every hop + +WHY. The GOAL/FAIL label these Q values are scored against is the class of nn(z_H) of a rollout that +re-applies the SAME action chunk H times -- `act` is never reassigned inside stitch_decompose.py's hop +loop. The closed-loop fold therefore estimates the value of a DIFFERENT trajectory than the one the +label records. Runs 7-13 excluded, on identical candidates, the reward label, the read-out horizon +and the scoring functional; this is the remaining mismatch between Q and its own label. + +The chains, the endpoints and the labels are computed by stitch_decompose.py itself and do NOT go +through the scorer, so they must be BIT-IDENTICAL between the two cells. `controlled` asserts that: +if it is false the two cells are not the same experiment and nothing below may be read. + +Writes status/real/OL_COMPARE.json; every downstream artefact is generated from that file. +""" +from __future__ import annotations + +import json +from pathlib import Path + +import numpy as np + +ROOT = Path("/proj/dmfexp/zwhong/rsm_rise") +CL_P = ROOT / "status/real/STITCH_DECOMP_FOLD4.json" +OL_P = ROOT / "status/real/STITCH_DECOMP_FOLD4_OL.json" +CL = json.loads(CL_P.read_text()) +OL = json.loads(OL_P.read_text()) + +out = { + "closed": str(CL_P.relative_to(ROOT)), "open": str(OL_P.relative_to(ROOT)), + "read_out": {"mode": "fold", "depth": 4, "beta": 0.99, + "hop_ckpt": "runs/real_cooking_v5/hop/gauss/policy_r1.pt"}, + "fold_closed": CL.get("fold"), "fold_open": OL.get("fold"), + "by_hop": {}, +} + +# ---- the control: the chains must be identical, only Q may differ ------------------------------ +pc = ROOT / "status/real/STITCH_DECOMP_FOLD4.json_parts" +po = ROOT / "status/real/STITCH_DECOMP_FOLD4_OL.json_parts" +chain_ident, chain_checked, q_moved, q_pairs = 0, 0, 0, 0 +lvl, cor = {}, {} +for a in sorted(pc.glob("*.npz")): + b = po / a.name + if not b.exists(): + continue + A, B = np.load(a), np.load(b) + # e_h / dmin_h / rc_* / rr_* come from stitch_decompose's own hop loop, not the scorer + for k in A.files: + if k.startswith(("e_", "dmin_", "rc_", "rr_")): + chain_checked += 1 + chain_ident += int(k in B.files and np.array_equal(A[k], B[k])) + for k in A.files: + if not k.startswith("q_") or k not in B.files: + continue + x, y = np.asarray(A[k], float), np.asarray(B[k], float) + if x.shape != y.shape: + continue + q_pairs += 1 + q_moved += int(not np.array_equal(A[k], B[k])) + if x.std() == 0 or y.std() == 0: + continue + h = k[2:] + lvl.setdefault(h, []).append(float(y.mean() - x.mean())) + cor.setdefault(h, []).append(float(np.corrcoef(x, y)[0, 1])) + +out["control"] = { + "chain_arrays_checked": chain_checked, "chain_arrays_identical": chain_ident, + "chains_identical": chain_checked > 0 and chain_ident == chain_checked, + "q_arrays_compared": q_pairs, "q_arrays_that_moved": q_moved, + "anchors_compared": len(list(pc.glob("*.npz"))), +} +out["per_candidate"] = {h: {"mean_level_shift": float(np.mean(lvl[h])), + "mean_within_anchor_corr": float(np.mean(cor[h])), + "n_anchors": len(lvl[h])} for h in sorted(lvl)} + +for hop in sorted(set(CL["by_hop"]) & set(OL["by_hop"]), key=int): + ch, oh = CL["by_hop"][hop], OL["by_hop"][hop] + if not ch.get("n_anchors_usable"): + out["by_hop"][hop] = {"n_anchors_usable": 0, "note": "no GOAL endpoints at this depth"} + continue + heads = {} + for k in sorted(set(ch["heads"]) & set(oh["heads"])): + c, o = ch["heads"][k], oh["heads"][k] + qc = c["auc_Q_per_anchor_here"]["mean"] + qo = o["auc_Q_per_anchor_here"]["mean"] + n = o["auc_Q_per_anchor_here"]["n"] or 1 + heads[k] = { + "auc_Q_closed": qc, "auc_Q_open": qo, "delta": qo - qc, + "Q_sem_open": o["auc_Q_per_anchor_here"]["std"] / np.sqrt(n), + "corr_Q_Rchain_closed": c.get("corr_Q_Rchain"), + "corr_Q_Rchain_open": o.get("corr_Q_Rchain"), + # the ceiling: what R read directly at the chained latent already achieves. Identical in + # both cells by construction (R does not go through the scorer), and asserted as such. + "auc_R_chain": c["auc_R_chain_per_anchor"]["mean"], + "auc_R_chain_open_cell": o["auc_R_chain_per_anchor"]["mean"], + } + ds = [v["delta"] for v in heads.values()] + best_o = max(heads, key=lambda k: heads[k]["auc_Q_open"]) + best_c = max(heads, key=lambda k: heads[k]["auc_Q_closed"]) + ceiling = max(v["auc_R_chain"] for v in heads.values()) + out["by_hop"][hop] = { + "n_anchors_usable": ch["n_anchors_usable"], "n_goal": ch["n_goal"], "n_fail": ch["n_fail"], + "endpoint_match_closed": ch["endpoint_match_vs_published"], + "endpoint_match_open": oh["endpoint_match_vs_published"], + "heads": heads, "n_heads": len(heads), + "delta_rms": float(np.sqrt(np.mean(np.square(ds)))), + "delta_max_abs": float(max(ds, key=abs)), + "delta_max_abs_head": max(heads, key=lambda k: abs(heads[k]["delta"])), + "best_closed": best_c, "best_closed_auc": heads[best_c]["auc_Q_closed"], + "best_open": best_o, "best_open_auc": heads[best_o]["auc_Q_open"], + # the one number the run is for: does matching the policy recover any of the gap between the + # read-out and what R already reads at the chained latent? + "latent_ceiling": ceiling, + "lift": heads[best_o]["auc_Q_open"] - heads[best_c]["auc_Q_closed"], + "gap_to_ceiling_closed": ceiling - heads[best_c]["auc_Q_closed"], + "gap_to_ceiling_open": ceiling - heads[best_o]["auc_Q_open"], + "n_above_half_closed": sum(v["auc_Q_closed"] > 0.5 for v in heads.values()), + "n_above_half_open": sum(v["auc_Q_open"] > 0.5 for v in heads.values()), + } + +# `controlled` gates everything: same chains, same endpoints, and Q actually recomputed. +b4 = out["by_hop"].get("4", {}) +out["controlled"] = bool( + out["control"]["chains_identical"] + and b4.get("endpoint_match_closed") == 1.0 and b4.get("endpoint_match_open") == 1.0 + and out["control"]["q_arrays_that_moved"] > 0) + +# The design's own resolution, carried forward from runs 8-13 so no reader has to remember it: +# +-0.024 for this design, ~0.005 of GPU non-determinism, per-head SEM ~0.013. +out["resolution"] = {"design": 0.024, "gpu_noise": 0.005, + "note": "a delta below ~0.01 is nothing; this is ONE draw, so no per-head " + "ranking may be read off this table (replicate across STITCH_DRAWS.json's " + "five draws first)"} + +P = ROOT / "status/real/OL_COMPARE.json" +P.write_text(json.dumps(out, indent=1)) +print(f"wrote {P}: controlled={out['controlled']} " + f"(chains {out['control']['chain_arrays_identical']}/{out['control']['chain_arrays_checked']} " + f"identical, {out['control']['q_arrays_that_moved']}/{out['control']['q_arrays_compared']} Q moved)") +if b4: + print(f" hop4: best closed {b4['best_closed']} {b4['best_closed_auc']:.4f} -> " + f"best open {b4['best_open']} {b4['best_open_auc']:.4f} lift {b4['lift']:+.4f} " + f"(ceiling {b4['latent_ceiling']:.4f}, delta rms {b4['delta_rms']:.4f}, " + f"max {b4['delta_max_abs']:+.4f} on {b4['delta_max_abs_head']})") diff --git a/rsm_rise/scripts/real/build_openpi_env.sh b/rsm_rise/scripts/real/build_openpi_env.sh new file mode 100644 index 0000000000000000000000000000000000000000..e11962d8dc5bc8ad5f87db97b7035bd9e44a40de --- /dev/null +++ b/rsm_rise/scripts/real/build_openpi_env.sh @@ -0,0 +1,25 @@ +#!/usr/bin/env bash +# Build the openpi (pi0.5) environment + fetch pi05_base. CPU LSF job -- nothing on the login node. +# openpi pins python>=3.11, jax[cuda12]==0.5.3, lerobot@0cf8648; uv already has a 3.11 interpreter. +# download.py routes openpi-assets through gsutil (no gcsfs), and this cluster has no gsutil -> install it. +set -uo pipefail +ROOT=/proj/dmfexp/zwhong/rsm_rise +UV=/u/zwhong/.local/bin/uv +export OPENPI_DATA_HOME=$ROOT/.openpi_assets # shared storage, visible to GPU nodes +export UV_CACHE_DIR=$ROOT/.uv_cache +mkdir -p "$OPENPI_DATA_HOME" "$UV_CACHE_DIR" +echo "[openpi-env] host=$(hostname) start=$(date -u)" +cd $ROOT/third_party +[ -d openpi ] || git clone --depth 1 https://github.com/Physical-Intelligence/openpi.git +cd openpi && git rev-parse --short HEAD | xargs -I{} echo "[openpi-env] openpi @ {}" +GIT_LFS_SKIP_SMUDGE=1 $UV sync 2>&1 | tail -5 +$UV pip install gsutil 2>&1 | tail -2 +echo "[openpi-env] python: $($UV run python -c 'import sys,jax;print(sys.version.split()[0], "jax", jax.__version__)')" +echo "[openpi-env] downloading pi05_base ..." +$UV run python - <<'PY' +from openpi.shared import download +p = download.maybe_download("gs://openpi-assets/checkpoints/pi05_base/params") +print("[openpi-env] pi05_base params at", p, flush=True) +PY +du -sh "$OPENPI_DATA_HOME" 2>/dev/null | xargs -I{} echo "[openpi-env] assets size: {}" +echo "[openpi-env] done=$(date -u)" diff --git a/rsm_rise/scripts/real/build_pi05_screen_table.py b/rsm_rise/scripts/real/build_pi05_screen_table.py new file mode 100644 index 0000000000000000000000000000000000000000..6c76a380aa18cfac5ac0240cc2d9328ee877f315 --- /dev/null +++ b/rsm_rise/scripts/real/build_pi05_screen_table.py @@ -0,0 +1,140 @@ +#!/usr/bin/env python3 +"""rsm_rise #269 -- rebuild the pi0.5 PLANNING SCREEN table from the scorer_openloop.json files. + +The screen, not greedy fit, decides the default proposer, and the sweep adds a row per cell, so the table is +built mechanically instead of by hand: every number here is read straight out of a json under status/real/. + + usage: build_pi05_screen_table.py [--eps 25] [--out status/real/pi05_screen_table_25.md] + +Columns (first-action xyz error, cm, over the held-out episodes): + spread candidate_spread_xyz_cm -- did the RISE regularisers WIDEN the proposal distribution? + greedy candidate 0, a plain sample -- the OLD, wrong criterion + oracle the best of the 128 candidates -- the quality of the SET planning gets to choose from + head greedy - oracle -- the prize a scorer can win + idql / rsm and their permuted controls on the IDENTICAL candidates -- does any scorer harvest it? + rank oracle_rank_pct_mean of the picked candidate (1.0 = picked the oracle, 0.5 = random) +A proposer PASSES the screen if it widens the set (spread up AND oracle error down vs stock) or if any scorer +beats its permuted control. +""" +import argparse, json, pathlib, sys + +ROOT = pathlib.Path("/proj/dmfexp/zwhong/rsm_rise") +STATUS = ROOT / "status" / "real" + +# label : tag stem under status/real/openloop_/ . Order = the order they are reported in. +ROWS = [ + ("pi0.5 **stock** s1", "pi05stock_s1"), + ("pi0.5 **rise** s0 (sn 0.1, knn 0.01)", "pi05rise_s0"), + ("pi0.5 **rise** s1 (sn 0.1, knn 0.01)", "pi05rise_s1"), + ("pi0.5 **riseadv** s0", "pi05riseadv_s0"), + # the warm-start sweep (#269 step 2'); ws9999 = the 10k warm start's final checkpoint + ("pi0.5 **wsctrl** (warm-start control)", "pi05wsctrl_ws9999"), + ("pi0.5 sn 0.03 / knn 0.01", "pi05sn0p03_knn0p01_ws9999"), + ("pi0.5 sn 0.3 / knn 0.01", "pi05sn0p3_knn0p01_ws9999"), + ("pi0.5 sn 0.1 / knn 0.03", "pi05sn0p1_knn0p03_ws9999"), + ("pi0.5 sn 0.3 / knn 0.03", "pi05sn0p3_knn0p03_ws9999"), + ("pi0.5 sn 1.0 / knn 0.03", "pi05sn1_knn0p03_ws9999"), + ("pi0.5 sn 0.1 / knn 0.05", "pi05sn0p1_knn0p05_ws9999"), + ("pi0.5 sn 1.0 / knn 0.05", "pi05sn1_knn0p05_ws9999"), + ("pi0.5 **risebn** (warm start, knn 0.01 + VIB bottleneck)", "pi05risebn_ws9999"), + # the small RISE-stack actor: the IQL-critic source and the control, NOT a real-robot proposer + ("*small-stack S0Aidql s0* (reference, not a proposer)", "S0Aidql_s0_e2000_d1_d1_T25"), + ("*small-stack S0Aidql s1* (reference, not a proposer)", "S0Aidql_s1_e2500_d1_d1_T25"), +] +HDR = ("| proposer | spread | greedy | **oracle** | head | idql | perm:idql | rsm | perm:rsm " + "| rank idql (perm) | rank rsm (perm) | n ep / dec |") +SEP = "|---" * 11 + "|" + + +# rsm_real#14 / ft50scr: the chunk-50 FINE-TUNE rows. ROWS above is a literal list because the 13 chunk-10 +# rows are a fixed, published set; the ft50 rows are 8 cells x 4 keep steps and arrive over ~28 h, so they are +# DISCOVERED from the tags the screen writes (pi05_) rather than hand-listed. Purely additive and +# OPT-IN via --ft50: with the flag unset this script's output is byte-identical to before, so nothing that +# already quotes status/real/pi05_screen_table_25.md changes. +# +# These rows are comparable to the 13 above: measured at --horizon 8, the same anchors (range(0, T-8, 25)) and +# the same 8 logged reference frames. --horizon is a pure post-hoc truncation of the policy's own chunk and +# the RSM critic's own chunk is 8, so every read-out sees the identical object in both generations -- +# MEASURED, see status/real/pi05_ft50_screen_horizon.json (verdict COMPARABLE). +FT50_CELLS = [ + ("stock_s0_ft50", "pi0.5 **stock** s0 ft50"), + ("stock_s1_ft50", "pi0.5 **stock** s1 ft50"), + ("rise_s0_ft50", "pi0.5 **rise** s0 ft50"), + ("rise_s1_ft50", "pi0.5 **rise** s1 ft50"), + ("riseadv_s0_ft50", "pi0.5 **riseadv** s0 ft50"), + ("sn1_knn0p03_ft50", "pi0.5 sn 1.0 / knn 0.03 ft50"), + ("sn0p1_knn0p03_ft50", "pi0.5 sn 0.1 / knn 0.03 ft50"), + ("stock_s0_h50", "pi0.5 stock s0 *h50 (from base, init ablation)*"), +] +FT50_STEPS = (50000, 100000, 150000, 199999) + + +def ft50_rows(suffix): + """(label, tag stem) for every chunk-50 cell whose screen json exists, ordered by step then by cell.""" + out = [] + for st in FT50_STEPS: + for exp, label in FT50_CELLS: + stem = f"pi05{exp}_{st}" + if (STATUS / f"openloop_{stem}{suffix}" / "scorer_openloop.json").exists() \ + or (STATUS / f"openloop_{stem}" / "scorer_openloop.json").exists(): + out.append((f"{label} @ {st}", stem)) + return out + + +def load(stem, suffix): + for d in (STATUS / f"openloop_{stem}{suffix}", STATUS / f"openloop_{stem}"): + f = d / "scorer_openloop.json" + if f.exists(): + return json.loads(f.read_text()), f + return None, None + + +def fmt(x, nd=3): + return "--" if x is None else f"{x:.{nd}f}" + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--eps", type=int, default=25, help="25 = the full held-out set (no _eN suffix)") + ap.add_argument("--out", default=None) + ap.add_argument("--ft50", action="store_true", + help="append the chunk-50 FINE-TUNE rows (rsm_real#14) that have been screened so far. " + "OFF by default so the 13-row table is byte-identical to before.") + a = ap.parse_args() + suffix = "" if a.eps >= 25 else f"_e{a.eps}" + rows = list(ROWS) + (ft50_rows(suffix) if a.ft50 else []) + + lines, sources, missing = [HDR, SEP], [], [] + for label, stem in rows: + d, f = load(stem, suffix) + if d is None: + missing.append(stem) + continue + s = d["scorers"] + g = s["greedy"]["first_mean_cm"] + o = s["oracle"]["first_mean_cm"] + + def m(k): + return s[k]["first_mean_cm"] if k in s else None + + def r(k): + return s[k]["oracle_rank_pct_mean"] if k in s else None + lines.append( + f"| {label} | {fmt(d['candidate_spread_xyz_cm'])} | {fmt(g)} | {fmt(o)} | {fmt(g - o)} " + f"| {fmt(m('idql'))} | {fmt(m('permuted:idql'))} | {fmt(m('rsm'))} | {fmt(m('permuted:rsm'))} " + f"| {fmt(r('idql'), 3)} ({fmt(r('permuted:idql'), 3)}) | {fmt(r('rsm'), 3)} ({fmt(r('permuted:rsm'), 3)}) " + f"| {d['n_episodes']} / {d['n_decisions']} |") + sources.append(f"- `{label}` -> `{f.relative_to(ROOT)}`") + + out = "\n".join(lines) + "\n\n**Sources** (every number is read from these files):\n" + "\n".join(sources) + "\n" + if missing: + out += "\nNot screened yet: " + ", ".join(f"`{m}`" for m in missing) + "\n" + if a.out: + pathlib.Path(a.out).write_text(out) + print(f"wrote {a.out} ({len(lines) - 2} rows, {len(missing)} missing)") + print(out) + return 0 if lines[2:] else 1 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/rsm_rise/scripts/real/build_pr1_271_run11.py b/rsm_rise/scripts/real/build_pr1_271_run11.py new file mode 100644 index 0000000000000000000000000000000000000000..77dd08f65b709acb900c3c3e5f3e3b2c39da37ff --- /dev/null +++ b/rsm_rise/scripts/real/build_pr1_271_run11.py @@ -0,0 +1,315 @@ +#!/usr/bin/env python +"""Insert/refresh the #271 PR-body sections (5) decomposition and (6) five-draw replication. + +Generated from the JSONs for the standing reason: hand-typed numbers in the PR body have already +drifted once in this study. Idempotent -- the sections are delimited by their own HTML comments, so +re-running replaces them instead of stacking copies. Operates on a LIVE body fetched at call time +(never on a saved copy: that is how the run-4 section was lost). + +usage: build_pr1_271_run11.py +""" +from __future__ import annotations +import json, sys +from pathlib import Path + +ROOT = Path("/proj/dmfexp/zwhong/rsm_rise") +D = json.loads((ROOT / "status/real/STITCH_DECOMP.json").read_text()) +W = json.loads((ROOT / "status/real/STITCH_DRAWS.json").read_text()) +PUB = json.loads((ROOT / "status/real/REWARD_HEAD_DIAG_STITCH.json").read_text()) +HOPF = int(PUB.get("hop_frames", 0)) + +B4, B2, B1 = D["by_hop"]["4"], D["by_hop"]["2"], D["by_hop"]["1"] +H = B4["heads"] +WB = W["by_hop"]["4"] + + +def m(v, k): + x = v.get(k) + return x.get("mean") if isinstance(x, dict) else x + + +sep, sat, inv = [], [], [] +for n, v in H.items(): + a = m(v, "auc_R_chain_per_anchor") + if max(m(v, "R_chain_goal") or 0.0, m(v, "R_chain_fail") or 0.0) < 0.01: + sat.append(n) + elif a is not None and a > 0.65: + sep.append(n) + elif a is not None and a < 0.35: + inv.append(n) +sep.sort(key=lambda n: -(m(H[n], "auc_R_chain_per_anchor") or 0)) +lst = lambda xs: ", ".join(f"`{x}`" for x in xs) if xs else "none" +bk = sep[0] if sep else None +lo_retr = min(H, key=lambda n: m(H[n], "auc_R_retrieved_per_anchor") or 1.0) +sig = WB.get("heads_draw_level_significant") or [] +top = max(sig, key=lambda k: WB["heads"][k]["mean_over_draws"]) if sig else None +labs = WB["draw_labels"] + +FC = json.loads((ROOT / "status/real/FOLD4_COMPARE.json").read_text()) +F4, F2 = FC["by_hop"]["4"], FC["by_hop"].get("2", {}) +PC = FC["per_candidate"] +LVLO = min(v["mean_level_shift"] for v in PC.values()) +LVHI = max(v["mean_level_shift"] for v in PC.values()) +CMIN = min(v["mean_within_anchor_corr"] for v in PC.values()) +CMEAN = sum(v["mean_within_anchor_corr"] for v in PC.values()) / len(PC) + + +sec5 = f""" +**(5) Where the signal dies — and why no reward label could have satisfied the stitching diagnostic.** +Every head separates real `S4` from real `S6` frames at AUC **1.000**, yet the `Q` it induces is at chance +on chained candidates. `scripts/real/stitch_decompose.py` → `status/real/STITCH_DECOMP.json` reads three +quantities per candidate on the published draw's *own* anchors and candidates, with `Q` recomputed in the +same process so nothing rests on a cross-run assumption (the replayed endpoint rows match the published +parts at **{B4['endpoint_match_vs_published']:.3f}**): `R(z_h)` at the chained latent, `R(x[nn(z_h)])` at +the real cached frame the endpoint retrieves to — the ceiling, because that row's `edge_to` *is* the +endpoint label — and `Q`. + +*The latent keeps the class; the fold discards it.* {lst(sep)} read the chained latent at per-anchor AUC +**{m(H[bk], 'auc_R_chain_per_anchor'):.3f}** and above, on a real separation of means +({m(H[bk], 'R_chain_goal'):.3f} on GOAL-ending chains against {m(H[bk], 'R_chain_fail'):.3f} on +FAIL-ending ones for `{bk}`), **and their `Q` is {m(H[bk], 'auc_Q_per_anchor_here'):.3f} — exactly +chance** (`corr(Q, R(z_h))` = {m(H[bk], 'corr_Q_Rchain'):.3f}). So the signal does not die off-manifold. + +*The reason is a horizon mismatch between the read-out and the label.* The flagship read-out is depth 1 at +β = 0.99, so `Q` sees about one hop (≈{HOPF} frames); the endpoint class is defined **four** hops out +(≈{4 * HOPF} frames). Of the two ways to widen that window, raising β is genuinely unavailable — the flow was +conditioned on β ∈ [0.95, 0.99], so β = 0.99 already *is* the longest horizon it was trained at — but +**deepening the fold is available**: `--rsm-depth ≥ 2` needs a hop head, and although no *successor* blob +embeds one, `rsm_hop_ckpt` is a **separate** checkpoint argument and this corpus has a hop head — +`runs/real_cooking_v5/hop/gauss/policy_r1.pt`, published as `hop_head_rsm_real_gauss_r1.pt`, already used +by the fold-4 column of the open-loop screen. *(An earlier revision of this section called that lever +closed and concluded that no reward label could ever satisfy the diagnostic. That is withdrawn: I checked +the successor blobs for an embedded hop head and stopped there instead of checking the argument.)* What +stands regardless is the size of the mismatch: **at one hop there are {B1['n_goal']} GOAL endpoints out of +{B1['n_goal'] + B1['n_fail']:,} classified candidates.** Within the horizon `Q` can see, no candidate drawn at the failure +route's `S2` junction reaches a goal-bound segment at all. **So the depth-1 statistic was never a test of +the reward labels** — it asks `Q` to discriminate a class that lives outside the window `Q` can see. +Whether the schemes separate at all is what the matched-horizon fold-4 read-out measures — section (7). + +*Two cautions that travel with it.* {lst(sat)} are saturated **off** at the chained latent (`R(z_h)` ≈ 0 on +*both* classes), so their AUCs rank numerical dust and must not be read as effects in either direction; +{lst(inv)} by contrast is genuinely **inverted** ({m(H[inv[0]], 'R_chain_goal'):.3f} GOAL vs +{m(H[inv[0]], 'R_chain_fail'):.3f} FAIL). And diagnostic 1's ceiling has a crack: `R` at the *retrieved +real frame* is 1.000 for most heads but **{m(H[lo_retr], 'auc_R_retrieved_per_anchor'):.3f}** for +`{lo_retr}` and 0.75–0.85 for the whole `B` family — diagnostic 1 labels frames by `reached_state_id`, +these are labelled by `edge_to` at the endpoints the chains actually reach, and there the horizon-window +schemes are **not** at ceiling. +""" + +sec6 = f""" +**(6) Correction to (3): "surviving both: none" was a confounded replicate, and averaged over draws the +window heads do clear chance.** The redraw in (3) was obtained by changing the anchor *stride*, which +changes the anchor set as well as the candidate draw. The clean design — identical anchors and weights, +only the seed of the draw changing — is {len(labs)} independent draws +(`status/real/STITCH_DRAWS.json`). There, above 0.5 in **every** draw: +{lst(WB.get('heads_above_half_in_every_draw') or [])}; draw-level significant: {lst(sig)}.""" +if top: + t = WB["heads"][top] + sec6 += f""" The largest is **`{top}` at {t['mean_over_draws']:.4f}** (SD {t['sd_over_draws']:.4f}, +above 0.5 in {t['n_draws_above_half']}/{len(labs)} draws), and **the published single-draw +{t['per_draw'][labs[0]]:.4f} was the *top* of its five-draw range [{t['min']:.3f}, {t['max']:.3f}]** — the +luckiest of the five. Between-draw SD over all heads is +{WB['noise_floor']['between_draw_sd_mean_over_heads']:.4f}.""" +sec6 += f""" So the earlier phrasing *"no head clears chance"* was too strong; the correct statement is +that averaged over draws the horizon-window heads clear chance by about **+0.03**. Read together with (5), +a +0.03 effect at a horizon where the endpoint label is invisible to the read-out is a **weak leading +indicator inside the first hop, not demonstrated stitching** — which is why nothing shipped changes: +`rsm_reward:` stays **A** and `rsm_reward_stitching_best` stays `null`. +""" + + +frows = sorted(F4["heads"].items(), key=lambda kv: -kv[1]["auc_Q_fold4"]) +ftbl = ["| head | AUC Q, depth 1 | AUC Q, fold-4 | delta | AUC R(z_h) |", "|---|---|---|---|---|"] +for k, v in frows: + ftbl.append(f"| `{k}` | {v['auc_Q_d1']:.4f} | {v['auc_Q_fold4']:.4f} | {v['delta']:+.4f} | {v['auc_R_chain']:.3f} |") +sec7 = f""" +**(7) The matched-horizon read-out, measured — and it changes nothing.** (5) says the depth-1 read-out's +window is four times too short for the label. That is a claim about the read-out, so it was tested: +`--rsm-mode fold --rsm-depth 4` through this corpus's hop head +(`runs/real_cooking_v5/hop/gauss/policy_r1.pt`) gives a read-out whose horizon **matches** the four-hop +depth at which the endpoint class is defined. Both runs reproduce the published candidate draw exactly +(endpoint match **{F4['endpoint_match_d1']:.3f}** and **{F4['endpoint_match_fold4']:.3f}**), so the +candidates, chains, retrieval pool and GOAL/FAIL labels are byte-identical and the read-out is the only +difference. + +{chr(10).join(ftbl)} + +Over the {F4['n_heads']} heads the within-anchor AUC moves by **rms {F4['delta_rms']:.4f}**, max +{F4['delta_max_abs']:+.4f} (`{F4['delta_max_abs_head']}`); at two hops rms {F2.get('delta_rms', 0):.4f}. +For scale, the design's own resolution is ±0.024 and GPU non-determinism alone moves this statistic by +~0.005 — **the matched-horizon fold moves it by less than the hardware noise.** + +*And the fold is not idle — it just does not discriminate.* Per candidate the fold-4 `Q` level rises by +**+{LVLO:.3f} to +{LVHI:.3f}** depending on the head, but its within-anchor correlation with the depth-1 +`Q` is **{CMIN:.3f}–1.000 (mean {CMEAN:.3f})** across all {FC['n_anchors_compared']} anchors. The three +extra hops add a *common-mode offset*, not candidate-specific information, so the ordering — the entire +statistic — survives untouched. + +**What this settles.** The horizon mismatch is real but is **falsified as the reason `Q` is at chance**. +The endpoint class is in the latent and in the head at AUC 0.941 and *both* read-outs discard it. So it is +no longer a reward question and no longer a horizon question; what is left to vary is the **scoring +functional** — `prob`/`T=25` compresses `R` over particles into a value whose differences *between* +candidates sit in the fourth significant figure. **That has now been tested too — see (8).** Nothing +shipped changes. +""" + + +SK = json.loads((ROOT / "status/real/SK_COMPARE.json").read_text()) +S4, S2 = SK["by_hop"]["4"], SK["by_hop"].get("2", {}) +SB = SK["baseline"] +SS = S4["summary"] +_KL = {"prob_T25": "`prob`, T=25 (flagship)", "logit_T25": "`logit`", + "prob_log_T25": "`prob_log`", "prob_T1": "`prob`, T=1", "prob_T100": "`prob`, T=100"} +slabs = [SB] + sorted(k for k in SS if k != SB) +sdmax = max((SS[k]["max_abs_delta_vs_baseline"] or 0.0) for k in SS if k != SB) +sdwho = max((k for k in SS if k != SB), key=lambda k: (SS[k]["max_abs_delta_vs_baseline"] or 0.0)) +sbest = max(SS[k]["max"] for k in SS) +sbestk = max(SS, key=lambda k: SS[k]["max"]) +sceil = S4.get("latent_ceiling") or {} +slift = sbest - SS[SB]["max"] +snanch = (list(S4["n_anchors_usable"].values()) or [0])[0] +# the head that reads the class best at the chained latent, and what Q does for it under every cell +cn = sceil.get("head") +crow = S4["heads"].get(cn, {}) if cn else {} +cq = [v for v in (crow.get("Q") or {}).values() if v is not None] +# how well Q tracks the quantity that actually carries the class, for that head, at the flagship +ccorr = B4["heads"][cn]["corr_Q_Rchain"] if cn in B4["heads"] else float("nan") + +stbl = ["| head | " + " | ".join(_KL.get(k, f"`{k}`") for k in slabs) + " | AUC R(z_h) |", + "|---" * (len(slabs) + 2) + "|"] +for k, v in sorted(S4["heads"].items(), + key=lambda kv: -(kv[1]["Q"].get(SB) if kv[1]["Q"].get(SB) is not None else -1)): + cells = [(f"{v['Q'][l]:.4f}" if v["Q"].get(l) is not None else "—") for l in slabs] + rc = f"{v['auc_R_chain_per_anchor']:.3f}" if v.get("auc_R_chain_per_anchor") is not None else "—" + stbl.append(f"| `{k}` | " + " | ".join(cells) + f" | {rc} |") + +sec8 = f""" +**(8) The scoring functional, swept — and it is not the culprit either.** (7) left exactly one degree of +freedom between `R(z_h)` and the ranking: the functional that compresses `R` over the n=16 particles into +one scalar. It had never been varied — the decomposition hard-coded `score_kind="prob"` at the scorer — +so it is now a flag (`--q-score-kind`), folded into the parts signature so two functionals cannot share a +cache. The bracket below is run on identical anchors, candidates, chains and GOAL/FAIL labels +(**controlled: {"every cell reproduces the published endpoints exactly" if SK.get("controlled") else "NOT controlled — see `SK_COMPARE.json`"}**), {snanch} anchors, within-anchor AUC at four hops. + +{chr(10).join(stbl)} + +`logit` is the T→∞ linear limit of `prob` (mean raw logit, no sigmoid to tie at 1.000); `prob_log` is +gen_q#266's log-complement read-out; `prob`/T=1 is the saturated end and `prob`/T=100 the flat end. The +bracket passes its own validity check: **`prob`/T=100 reproduces `logit` to 3–4 decimals**, as the algebra +requires (σ(ℓ/T) ≈ ½ + ℓ/4T is a monotone map of the mean logit), so the cells are neither identical nor +mislabelled. + +**The result is null.** The best within-anchor AUC anywhere in the sweep is **{sbest:.4f}** +(`{SS[sbestk]["max_head"]}`, {_KL.get(sbestk, sbestk)}) against the flagship's own best of +{SS[SB]["max"]:.4f} — a lift of **{slift:+.4f}**, against a design resolution of ±0.024 and a +GPU-non-determinism floor of ~0.005. The largest per-head move any functional makes is {sdmax:.4f} +(`{sdwho}`), and that one moves the statistic **down** (its own best is {SS[sdwho]["max"]:.4f}). At two +hops the largest move is {max((S2.get("summary", {}).get(k, {}).get("max_abs_delta_vs_baseline") or 0.0) for k in S2.get("summary", {}) if k != SB) if S2.get("summary") else float("nan"):.4f}. + +**The decisive row is `{cn}`.** It reads the endpoint class at the chained latent at AUC +**{sceil.get("auc_R_chain_per_anchor", float("nan")):.3f}**, and its `Q` is +{min(cq):.4f}–{max(cq):.4f} under **all five** functionals. The information is in the latent and in the +head; no functional in this bracket recovers it. Nor is the fix a better compressor further out: across +candidates the correlation between `Q` and `R(z_h)` for that head is only +{ccorr:.3f} at the flagship — `Q` is +simply not a function of the quantity that carries the class. + +**What is left.** Three suspects have now been excluded on identical candidates: the reward label (6), the +read-out horizon (7), and the scoring functional (8). Section (9) closes the fourth and last — the +*rollout* the fold applies, which had never matched the one the label is generated by. Nothing shipped +changes: `rsm_reward:` stays **A** and `rsm_reward_stitching_best` stays `null`. +""" + + +# ---- (9) the rollout the fold applies, matched to the label's own (run 15) ---------------------- +OL = json.loads((ROOT / "status/real/OL_COMPARE.json").read_text()) +O4 = OL["by_hop"]["4"] +OH, OC = O4["heads"], OL["control"] +ocl = max(OH, key=lambda k: OH[k]["auc_R_chain"]) +ov = OH[ocl] +otbl = ["| head | AUC `Q` closed | AUC `Q` open | Δ | Δ/SEM | ρ(`Q`,`R(z_h)`) closed → open | AUC `R(z_h)` |", + "|---|---|---|---|---|---|---|"] +for k, v in sorted(OH.items(), key=lambda kv: -kv[1]["auc_Q_closed"]): + z = v["delta"] / v["Q_sem_open"] if v["Q_sem_open"] else float("nan") + otbl.append(f"| `{k}` | {v['auc_Q_closed']:.4f} | {v['auc_Q_open']:.4f} | {v['delta']:+.4f} | {z:+.2f} | " + f"{v['corr_Q_Rchain_closed']:.3f} → {v['corr_Q_Rchain_open']:.3f} | {v['auc_R_chain']:.3f} |") + +sec9 = f""" +**(9) The rollout the fold applies — the last degree of freedom, and the read-out is exonerated.** (5)–(8) +all left one uncontrolled difference between `Q` and the GOAL/FAIL label it is scored against, and it is +structural rather than a matter of degree: **they are values of two different trajectories.** The label's +own rollout computes the candidate's action chunk once and re-applies that *same* chunk at every hop +(`stitch_decompose.py` never reassigns `act` inside its hop loop); the fold re-samples the hop head +between hops, so at depth four it estimates the value of *apply the candidate once, then follow the hop +head for three hops*. `--q-fold-openloop` repeats the candidate at every hop, matching the label's +generating process; it is additive, default-off and provably a no-op at depth one, so every archived cell +is unchanged (the regression smoke reproduces the pre-patch fold-4 part bit-exactly). + +The control here is stronger than in (7)/(8): the chains, endpoints and labels are computed **outside** +the scorer, so they are asserted array-by-array — **{OC['chain_arrays_identical']}/{OC['chain_arrays_checked']} chain arrays bit-identical** over +{OC['anchors_compared']}/150 anchors, endpoint match {O4['endpoint_match_closed']:.3f} (closed) and {O4['endpoint_match_open']:.3f} (open), while +**{OC['q_arrays_that_moved']}/{OC['q_arrays_compared']} `Q` arrays moved**. {O4['n_anchors_usable']} usable anchors, {O4['n_goal']} GOAL / {O4['n_fail']} FAIL candidates. + +{chr(10).join(otbl)} + +**The result is null.** The best within-anchor AUC goes from {O4['best_closed_auc']:.4f} (`{O4['best_closed']}`) to +{O4['best_open_auc']:.4f} (`{O4['best_open']}`) — a lift of **{O4['lift']:+.4f}**. The rms move over the {O4['n_heads']} heads is +{O4['delta_rms']:.4f} and the largest single move {O4['delta_max_abs']:+.4f} (`{O4['delta_max_abs_head']}`), against the same ±0.024 +design resolution and ~0.005 noise floor; {O4['n_above_half_closed']} heads sit above 0.5 in the closed cell and {O4['n_above_half_open']} in the +open one. At two hops the lift is {OL['by_hop']['2']['lift']:+.4f}. + +**The prediction was written down before the job landed, so this is a test and not a story:** if the +policy mismatch were the cause, `{ocl}` — which reads the endpoint class at the chained latent at AUC +**{ov['auc_R_chain']:.3f}** — should move toward it, and `corr(Q, R(z_h))` should rise well above {ov['corr_Q_Rchain_closed']:.2f}. It does +neither: `{ocl}`'s `Q` goes {ov['auc_Q_closed']:.4f} → {ov['auc_Q_open']:.4f} and its correlation **falls** +{ov['corr_Q_Rchain_closed']:.3f} → {ov['corr_Q_Rchain_open']:.3f}. (A second mismatch found the same way — the fold never clamped the +sampled latent to the trainer's `sample_clip`, which the label's rollout does — was checked and is a +measured no-op on this corpus: 15 of 16 heads bit-identical at depth four, the sixteenth moving 1.8e-06.) + +**So the read-out is exonerated on all four axes and further read-out variants are not worth measuring.** +The reason is worth stating precisely, because it is *not* "nothing can be done": `Q` is a discounted +**occupancy of the reward set along the chain**, while the label is the **class of the endpoint at hop +four**. Matching the policy and the transition removes the *trajectory* mismatch; it does not remove the +*functional-of-the-trajectory* mismatch. What is left is what `Q` **is**, not how it is rolled out. Two +standing caveats: this is **one** candidate draw, so no per-head ranking may be read off the table above +(the scheme comparison stands on the five-draw replication in (6)); and the ~0.94 latent figure is a +**ceiling, not a demonstration** — the label is defined as the class of `nn(z_h)`, so `R(z_h)` predicting +it is close to a smoothness check on `R` near `z_h`. Nothing shipped changes: `rsm_reward:` stays **A** +and `rsm_reward_stitching_best` stays `null`. +""" + +body = Path(sys.argv[1]).read_text() +assert "" in body and "" in body, "PR body lost its #271 markers" + + +def upsert(s, block, beg, end, anchor): + if beg in s: + i, j = s.index(beg), s.index(end) + len(end) + return s[:i] + block + s[j:] + k = s.index(anchor) + return s[:k] + block + "\n\n" + s[k:] + + +ANCHOR = "**(2) The open-loop screen cannot rank the schemes" +assert ANCHOR in body, "section (2) anchor moved; refusing to guess where to insert" +body = upsert(body, sec5, "", "", ANCHOR) +body = upsert(body, sec6, "", "", ANCHOR) +body = upsert(body, sec7, "", "", ANCHOR) +# a brand-new section goes AFTER the previous section's end marker, not at the (2) anchor -- +# otherwise (8) would be spliced in front of (2) while (5)-(7) stay put, scrambling the order. +S7END = "" +if "" not in body: + assert S7END in body, "section (7) end marker missing; refusing to guess where (8) goes" + k = body.index(S7END) + len(S7END) + body = body[:k] + "\n\n" + sec8 + body[k:] +else: + body = upsert(body, sec8, "", "", ANCHOR) +S8END = "" +if "" not in body: + assert S8END in body, "section (8) end marker missing; refusing to guess where (9) goes" + k = body.index(S8END) + len(S8END) + body = body[:k] + "\n\n" + sec9 + body[k:] +else: + body = upsert(body, sec9, "", "", ANCHOR) +Path(sys.argv[2]).write_text(body) +print(f"wrote {sys.argv[2]} ({len(body)} B); separating={sep} saturated={sat} inverted={inv}") diff --git a/rsm_rise/scripts/real/build_pr1_271_run16.py b/rsm_rise/scripts/real/build_pr1_271_run16.py new file mode 100644 index 0000000000000000000000000000000000000000..35439764f3a5557d6f2eaf15e9a7a4f2a7f68997 --- /dev/null +++ b/rsm_rise/scripts/real/build_pr1_271_run16.py @@ -0,0 +1,86 @@ +#!/usr/bin/env python +"""Splice #271 section (10) -- the shipped file set reconciled with its gate -- into a LIVE PR-1 body. + +usage: build_pr1_271_run16.py +Numbers come from status/real/STITCH_DRAWS.json, REWARD_SCREEN.json and hf_upload_stamps.json, never +from the prose. Refuses if the markers are missing or out of order (the run-4 section was lost that way). +""" +from __future__ import annotations +import json, sys +from pathlib import Path + +ROOT = Path("/proj/dmfexp/zwhong/rsm_rise") +D = json.loads((ROOT / "status/real/STITCH_DRAWS.json").read_text()) +ST = json.loads((ROOT / "status/real/hf_upload_stamps.json").read_text()) +SCR = json.loads((ROOT / "status/real/REWARD_SCREEN.json").read_text()) +src, out = Path(sys.argv[1]), Path(sys.argv[2]) +b = src.read_text() + +h4 = D["by_hop"]["4"]["heads"] +nf = D["by_hop"]["4"]["noise_floor"]["between_draw_sd_mean_over_heads"] +g = lambda k: h4[k] +sh = SCR["combined"]["heads"] +best_d = max(v["delta_vs_permuted"] for k, v in sh.items() + if k not in ("oracle", "idql", "permuted:idql", "permuted:rsm")) +liveN = lambda f: "**live**" if (ST.get(f) or {}).get("ok") else "not uploaded" + +rows = [("B400", "successor_rsm_real_B_H400_110000.pt"), + ("B400_s1", "successor_rsm_real_B_H400_s1_110000.pt"), + ("v0lit", "successor_rsm_real_v0lit_110000.pt"), + ("B", "successor_rsm_real_B_H100_110000.pt"), + ("v0lit_s1", "successor_rsm_real_v0lit_s1_110000.pt"), + ("B_s1", "successor_rsm_real_B_H100_s1_110000.pt"), + ("A", "successor_rsm_real_A_110000.pt"), + ("base", "(inside successor_rsm_real_RM_s0_100k.pt)")] +tbl = ["| head | five-draw AUC, hop 4 | above .5 in | p (draw-level) | on the hub |", "|---|---|---|---|---|"] +for k, f in rows: + v = g(k) + tbl.append("| `%s` | %.4f ± %.4f | %d/5 | %.3f | %s |" % ( + k, v["mean_over_draws"], v["sd_over_draws"], v["n_draws_above_half"], + v["p_draw_level_vs_half"], liveN(f) if f.endswith(".pt") else "n/a (rides in the base)")) + +sec = f""" +**(10) Housekeeping: the shipped file set now matches the gate that was actually applied.** No new +measurement — this reconciles the *bucket* with the *table*, and fixes a sentence in the uploader that +named the wrong gate. `scripts/real/hf_upload.py` said a head ships "once it beats the permuted control on +the open-loop screen". **No head does**: pooled over both proposer seeds every Δ against `permuted:rsm` is +negative (best {best_d:+.3f}), and that column does not replicate across proposer seeds — which is why the +table already tells the reader to use the stitching column instead. The gate actually applied was the +**stitching** statistic, and at run 4 it was applied to the *single published candidate draw*. The +five-draw design (same anchors, same weights, only the draw seed varying) landed later and reordered it, +but the file set was never revisited. The result: `B_H100_s1` — {g('B_s1')['mean_over_draws']:.4f}, +{g('B_s1')['n_draws_above_half']}/5 draws, p={g('B_s1')['p_draw_level_vs_half']:.3f}, flatly null — was on +the hub, while `v0lit` — {g('v0lit')['mean_over_draws']:.4f}, 5/5 draws, p<1e-3, and the only head above +chance in all five draws at **both** hops — was not, under a generated row note claiming it had "no +measured advantage over the base head" ({g('base')['mean_over_draws']:.4f}). That note was wrong for that +head. + +{chr(10).join(tbl)} + +Between-draw SD {nf:.4f}. `successor_rsm_real_v0lit_110000.pt` and `_v0lit_s1_110000.pt` are now uploaded +and content-verified (sha256 against the cluster source; hub tree 356 files, no mismatches), the +"not uploaded" note in `CHECKPOINTS.md` is generated **per head** from `STITCH_DRAWS.json` instead of one +blanket sentence, and `baselines.yaml` gains paragraph (b3): the clean five-draw replication corrects +(b2)'s "NONE survives an independent draw", which came from a stride redraw that moved the anchor set as +well as the candidate draw. + +**What does not change.** `rsm_reward: A` is still the default **by the owner's choice**, +`rsm_reward_stitching_best` is still `null`, and none of this ranks the schemes. Averaged over draws the +lead is ~0.03 in within-anchor AUC, measured at a horizon where the endpoint class is invisible to the +read-out (at one hop, **0 of 13,199** classified candidates reach a goal-bound segment at all), and (6)–(9) +have since exonerated the read-out on all four of its degrees of freedom without the number moving. A weak +leading indicator inside the first hop is not demonstrated stitching, and nothing shipped moves on it. + +""" + +anchor = "" +assert b.count(anchor) == 1, "s9end marker not found exactly once" +assert "" not in b, "section 10 already present" +b2 = b.replace(anchor, anchor + "\n\n" + sec.rstrip("\n")) +# order check: every section marker must still be strictly increasing, and inside the 271 block +idx = [b2.index(m) for m in ("", "", "", + "", "", "", + "", "")] +assert idx == sorted(idx), idx +out.write_text(b2) +print(f"[pr1] {len(b)} B -> {len(b2)} B, section (10) spliced after s9end") diff --git a/rsm_rise/scripts/real/build_pr1_271_run18.py b/rsm_rise/scripts/real/build_pr1_271_run18.py new file mode 100644 index 0000000000000000000000000000000000000000..cd9ff6cd52e5bb74b93945dd2b99625584ea0bd3 --- /dev/null +++ b/rsm_rise/scripts/real/build_pr1_271_run18.py @@ -0,0 +1,91 @@ +#!/usr/bin/env python +"""Splice #271 section (11) -- the canonical reward names were on the wrong files -- into a LIVE PR-1 body. + +usage: build_pr1_271_run18.py +The file <-> name map is READ from scripts/real/hf_upload.py's REWARD_HEADS and from the clone's +rise_stack/configs/reward_names.json, never typed; the five-draw numbers come from STITCH_DRAWS.json. +Refuses if the markers are missing or out of order (the run-4 section was lost that way). +""" +from __future__ import annotations +import importlib.util, json, subprocess, sys +from pathlib import Path + +ROOT = Path("/proj/dmfexp/zwhong/rsm_rise") +CLONE = Path("/proj/dmfexp/zwhong/projs/rsm_real") +D = json.loads((ROOT / "status/real/STITCH_DRAWS.json").read_text()) +REG = json.loads((CLONE / "rise_stack/configs/reward_names.json").read_text()) +spec = importlib.util.spec_from_file_location("_hfu", ROOT / "scripts/real/hf_upload.py") +hfu = importlib.util.module_from_spec(spec); spec.loader.exec_module(hfu) +FILE_OF_CELL = {src.parent.name: dst for _c, src, dst in hfu.REWARD_HEADS} +src, out = Path(sys.argv[1]), Path(sys.argv[2]) +b = src.read_text() + +h4 = D["by_hop"]["4"]["heads"] +sha = subprocess.run(["git", "-C", str(CLONE), "log", "-1", "--format=%h", "--", + "rise_stack/configs/reward_names.json"], capture_output=True, text=True).stdout.strip() + +CELLS = [("GOAL_EPISODE", "R_M_ft_v0", "v0"), ("GOAL_SEGMENT", "R_M_ft_v1", "A"), + ("EXPERT_EPISODE", "R_M_ft_v0lit", "v0lit"), ("GOAL_WINDOW_100", "R_M_ft_B", "B"), + ("GOAL_WINDOW_400", "R_M_ft_B400", "B400")] +rows = ["| canonical name | old id | cell | the file that carries it |", "|---|---|---|---|"] +for name, cell, old in CELLS: + f = FILE_OF_CELL.get(cell) + where = ("inside the base `successor_rsm_real_RM_s0_100k.pt` (`state_dict[\"rew\"]`); the " + "`R_M_ft_v0` fine-tune is trained, not uploaded") if name == "GOAL_EPISODE" else f"`{f}`" + rows.append(f"| `{name}` | `{old}` | `{cell}` | {where} |") +assert REG["rewards"]["GOAL_SEGMENT"]["alias_old_id"] == "A_to_eq_S4" + +A, V0 = h4["A"], h4["v0"] +sec = f""" +**(11) A name-registry bug, caught by the audit: the canonical reward names were attached to the wrong +checkpoint files.** No new measurement and no default moved. `rise_stack/configs/reward_names.json` — the +canonical-name registry added on this branch — listed `successor_rsm_real_A_110000.pt` as the Hugging Face +copy of **`GOAL_EPISODE`** and `GOAL_SEGMENT` as *"(to upload)"*. It is the other way round, and the +mis-attribution had already spread into `WHAT_TO_LOAD.md`'s one-line answer and `FINDINGS.md`'s +what-to-load table. Acting on any of the three downloads a head trained on a **different reward** than the +one you asked for — the one failure mode a name registry exists to prevent. + +Checked rather than asserted: `status/real/REWARD_SCHEMES.json` carries `"A_equals_v1_goaltrans": true` +(scheme A's label array is bit-identical to v1's, asserted when the labels are built), and +`scripts/real/hf_upload.py` uploads `R_M_ft_v1/ckpt_s110000.pt` as `successor_rsm_real_A_110000.pt`. +`baselines.yaml`, `CHECKPOINTS.md`, `REWARDS.md` and `README.md` already said A = `r_t = 1[to(t) = S4]` = +`GOAL_SEGMENT`, so the fix makes the three outliers agree with them. Corrected map: + +{chr(10).join(rows)} + +`EXPERT_EPISODE`'s *"(not uploaded)"* was also stale — both `successor_rsm_real_v0lit{{,_s1}}_110000.pt` +went up in (10). And `FINDINGS.md`'s *avoid* row justified itself with *"its positives include every +episode that reached the cooking state without ever pouring"*; they do not. The base head's positives are +the 50 goal-reaching episodes only (`reaches_goal_equals_ep_success: true` in +`status/real/GOAL_REWARD.json`); the label that includes the 98 non-pouring episodes is `EXPERT_EPISODE` +(132,350 positive frames), a different head. That row's recommendation is untouched — only its reason. + +**What was deliberately left alone.** `default_for_planning: GOAL_EPISODE` still disagrees with +`baselines.yaml`'s `rsm_reward: A` (reported in (9)). That is a **choice** between two labels, and neither +is supported by a measurement here: five-draw stitching at hop 4 reads `A` +{A['mean_over_draws']:.4f} ± {A['sd_over_draws']:.4f} ({A['n_draws_above_half']}/5 draws above chance) and +`GOAL_EPISODE` {V0['mean_over_draws']:.4f} ± {V0['sd_over_draws']:.4f} ({V0['n_draws_above_half']}/5), +both at or below the un-fine-tuned base head's {h4['base']['mean_over_draws']:.4f}, and no head beats the +permuted control on the open-loop screen at all. Resolving it is the owner's call, so only the file map +was corrected. + +**Guarded against recurrence.** `scripts/real/audit271_consistency.py` gains **check H**: every name → file +claim is compared against `hf_upload.py` and the live hub, and any line in `rise_stack/*.md` or in the +Hugging Face model card that names one reward label beside a file carrying a different one is a FAIL. It +reproduces both errors on the pre-commit text and passes on the corrected text; the audit is 8/8. Check B +was also fixed to ignore untracked `__pycache__` in the shared clone — a build artefact, not drift. The +model card gains a generated **(1e)** paragraph with the same map, so the hub-side artefact states it too. +Commit `{sha}`. + +""" + +anchor = "" +assert b.count(anchor) == 1, "s10end marker not found exactly once" +assert "" not in b, "section 11 already present" +b2 = b.replace(anchor, anchor + "\n\n" + sec.rstrip("\n")) +idx = [b2.index(m) for m in ("", "", "", + "", "", "", + "", "", "")] +assert idx == sorted(idx), idx +out.write_text(b2) +print(f"[pr1] {len(b)} B -> {len(b2)} B, section (11) spliced after s10end") diff --git a/rsm_rise/scripts/real/build_pr1_271_run21.py b/rsm_rise/scripts/real/build_pr1_271_run21.py new file mode 100644 index 0000000000000000000000000000000000000000..de0b6c37623cd85f8430fe4312c832e93850ee73 --- /dev/null +++ b/rsm_rise/scripts/real/build_pr1_271_run21.py @@ -0,0 +1,95 @@ +#!/usr/bin/env python +"""Splice #271 section (12) -- the delivered head verified against a READER's DINOv2, and a shipped +page that told readers to wait -- into a LIVE PR-1 body. + +usage: build_pr1_271_run21.py +Every number is read from status/real/AUDIT271_J_DINO.json (check J) and from the audit's own result, +never typed, and the script REFUSES if J did not pass exactly or if the audit is not green -- a PR +body must not carry a reproducibility claim that the check behind it does not currently support. +Refuses if the markers are missing or out of order (the run-4 section was lost that way). +""" +from __future__ import annotations +import json, subprocess, sys +from pathlib import Path + +ROOT = Path("/proj/dmfexp/zwhong/rsm_rise") +CLONE = Path("/proj/dmfexp/zwhong/projs/rsm_real") +J = json.loads((ROOT / "status/real/AUDIT271_J_DINO.json").read_text()) +AUD = json.loads((ROOT / "status/real/AUDIT271_RUN17.json").read_text()) +SEL = json.loads((ROOT / "status/real/AUDIT271_J_SELFTEST.json").read_text()) +KSEL = json.loads((ROOT / "status/real/AUDIT271_K_SELFTEST.json").read_text()) + +assert J["ok"], f"check J did not pass; refusing to write its numbers into the PR body: {J['failures']}" +assert J["z_max_abs_diff"] == 0.0 and J["logit_max_abs_diff"] == 0.0, \ + f"J passed within tolerance but not exactly; the text below claims bit-identical: {J}" +assert SEL["ok"] and KSEL["ok"], "a negative control failed; the checks are not shown to work" +assert AUD["all_pass"], f"the audit is not green: {[k for k, v in AUD['checks'].items() if not v['ok']]}" +assert KSEL["historical_page"]["ok"] is False, \ + "check K passed on the real pre-fix page, so the claim that it catches the bug is false" +ST_ = J["source_trees"] +n_checks = len(AUD["checks"]) + +src, out = Path(sys.argv[1]), Path(sys.argv[2]) +b = src.read_text() +sha = subprocess.run(["git", "-C", str(CLONE), "log", "-1", "--format=%h", "--", + "rise_stack/REWARDS.md"], capture_output=True, text=True).stdout.strip() + +sec = f""" +**(12) The delivered head is verified against a *reader's* DINOv2 for the first time, and a shipped page +was telling readers to wait for a checkpoint that will never come.** Neither is a measurement of head +quality: `rsm_reward: A` and `rsm_reward_stitching_best: null` are unchanged, and no head was re-ranked. + +**The gap.** `dino_crop_mode`/`dino_hub_dir` in `configs/baselines.yaml` point at an absolute path on the +training cluster, so a reader never has it, and `db2e0cbe` makes the clean clone fetch +`facebookresearch/dinov2` from GitHub instead. A reward head is only as reproducible as its features: the +checkpoint is bit-identical either way, so had the two DINOv2 *sources* differed in the model code, every +R(z) number in this PR would silently not apply to the person the hub copy exists for -- and the existing +checks would all have stayed green, because they verify the head's table row, its name → file map and its +**bytes**, none of which move. + +**Measured** on the {J['n_frames']} frames of `rise_stack/fixtures` (the shipped replay fixture, full-resolution +mp4s, decoded by the clone's own `ReplayEnv`), featurised twice through the clone's own +`DinoStateFeaturiser` -- once from the cluster archive every #271 number was measured with, once from a +fresh GitHub fetch: + +| | local archive | fresh GitHub fetch | +|---|---|---| +| DINOv2 source tree | {ST_['n_py_local']} `.py` | {ST_['n_py_github']} `.py`, all sha256-identical | +| `z` (1546-d) | -- | **bit-identical**, max abs diff {J['z_max_abs_diff']:.0f} | +| `{J['head_hub_name']}` logits | [{J['logit_range_local'][0]:.2f}, {J['logit_range_local'][1]:.2f}] | **bit-identical**, max abs diff {J['logit_max_abs_diff']:.0f}, identical ranking of all {J['n_frames']} frames | + +So the published R(z) numbers apply to the hub copy as they stand. This is now **check `J`** of the issue's +audit, and it **re-fetches the GitHub source every run**, so it tracks `main` rather than pinning itself to +a frozen snapshot of it. Its negative control is what makes the pass worth reading: with the two sources' +features shifted by 0.1 -- a features-only change, checkpoint untouched -- the delivered head's logit moves +by **{SEL['s1']['logit_max_abs_diff']:.2f}** and the ranking of the {J['n_frames']} frames breaks. + +**The page.** `rise_stack/REWARDS.md` described scheme C as *"not published yet -- in training"*. All four C +heads finished at step 110000; they are off the hub **by decision** -- the rule is "the default, plus any +head that beats its own permuted control", and no C head does -- which `CHECKPOINTS.md` already stated per +file, with each one's five-draw number. The same page said the two deciding diagnostics "are in progress": +they are finished and did **not** decide it, which is why both `*_best` keys are `null`. Fixed in `{sha}`, +plus a new "Reproducing R(z) off the hub copy" section carrying the table above; the Hugging Face card +gains the generated paragraph **(1f)** with the same numbers. + +**Guarded against recurrence.** New **check `K`**: for every `successor_rsm_real_*.pt` named on any of the +12 shipped pages, the surrounding sentence may not call a live head pending, and must mark a +declared-but-not-uploaded head as not downloadable. `K` as first written **would not have caught the bug +above** -- the stale row named no filename at all, which is why it survived ten checks -- so it also sweeps +this issue's own pages for a pending claim that names no head. Its control is not synthetic: it runs `K` +against the **real pre-fix `REWARDS.md`** and requires it to fail there, naming that exact row. The audit is +**{n_checks}/{n_checks} PASS** at clone `{AUD['clone_head'][:8]}`. + +""" + +anchor = "" +assert b.count(anchor) == 1, "s11end marker not found exactly once" +assert "" not in b, "section 12 already present" +b2 = b.replace(anchor, anchor + "\n\n" + sec.rstrip("\n")) +idx = [b2.index(m) for m in ("", "", "", + "", "", "", + "", "", "", + "")] +assert idx == sorted(idx), idx +out.write_text(b2) +print(f"[pr1] {len(b)} B -> {len(b2)} B, section (12) spliced after s11end") diff --git a/rsm_rise/scripts/real/build_rankctrl_comment.py b/rsm_rise/scripts/real/build_rankctrl_comment.py new file mode 100644 index 0000000000000000000000000000000000000000..1b093b2468a2fa6a860686b366d35f353b8623d3 --- /dev/null +++ b/rsm_rise/scripts/real/build_rankctrl_comment.py @@ -0,0 +1,203 @@ +"""Build the gen_q#276 comment for stream RANK_CTRL from the measured cells. Pure json -- login-node safe.""" +import json, os + +D = "/proj/dmfexp/zwhong/rsm_rise/status/real/rankctrl" +NICE = {"pose": "**pose continuity (0 params, no model)**", "bc": "BC log-lik (hop head)", + "knn": "kNN-in-latent", "rsm": "**RSM (beta-chain, the claim)**", + "rsm_d1": "rsm depth-1 (no chain)", "permuted:rsm": "permuted:rsm (the old control)", + "reward": "reward head @ anchor (flat by construction)"} +ORDER = ["pose", "bc", "knn", "rsm", "rsm_d1", "permuted:rsm", "reward"] + + +def L(c): + p = f"{D}/{c}/logged_action_rank.json" + return json.load(open(p)) if os.path.exists(p) else None + + +def get(cells, m, target="correct", stage=2): + """Find scorer m for this arm across the cells that carry it (the pose cells are separate runs).""" + for c in cells: + j = L(c) + if j and f"{m}|{target}|S{stage}" in j["by"]: + return j["by"][f"{m}|{target}|S{stage}"], j + return None, None + + +def fmt(r, key="top1_tie", ci=True): + if r is None: + return "--" + s = f"{r[key]:.3f}" + if ci: + b = r.get("boot_top1_tie") or {} + if b.get("lo") is not None: + s += f" [{b['lo']:.2f}, {b['hi']:.2f}]" + return s + + +def table(cols, target="correct", stage=2, extra=""): + """cols = [(label, [cell, pose_cell...])]""" + hd = "| scorer | " + " | ".join(l for l, _ in cols) + " |" + sep = "|---|" + "---|" * len(cols) + out = [hd, sep] + for m in ORDER: + row = [get(cs, m, target, stage)[0] for _, cs in cols] + if all(r is None for r in row): + continue + out.append(f"| {NICE[m]} | " + " | ".join(fmt(r) for r in row) + " |") + ch = [] + for _, cs in cols: + j = next((L(c) for c in cs if L(c)), None) + ch.append(f"{j['chance_top1']:.3f}" if j else "--") + out.append("| _chance_ | " + " | ".join(ch) + " |") + if extra: + out.append("") + out.append(extra) + return "\n".join(out) + + +def nfo(cells, stage=2, target="correct"): + j = next((L(c) for c in cells if L(c)), None) + if not j: + return "" + r, _ = get(cells, "rsm", target, stage) + n = r["n"] if r else j["n_anchors"] + return f"n={n} anchors / {j['n_anchor_episodes']} episodes" + + +P = print +P("## The 96.9 % is action plausibility, and specifically it is **kinematic continuity**. It is not evidence " + "for goal-directedness.") +P() +P("Stream RANK_CTRL. Everything below is one script, `scripts/real/logged_action_rank.py` (extended, backup " + "kept), run on H100s as `rr_pack4_rankctrl{,2,3,4}` (LSF 1881366 / 1881385 / 1881400 / 1881422). Raw cells: " + "`status/real/rankctrl//logged_action_rank.json` (+ `per_anchor.npz` with the full score matrix). " + "Notes: `status/real/RANK_CTRL.md`.") +P() +P("### 0. Regression first: the original number reproduces bit-for-bit") +P() +P("`REG_fail31` vs `logged_action_rank_G999`: `rsm|S2` top-1 **0.96875**, rank_pct **0.998656**, " + "s_correct **0.520118**, s_distract **0.148531**; `permuted:rsm` **0.06250** / **0.478495**. Identical to " + "the last digit. The RSM also has **no ties** (ties@max 1.00, score CV 0.49), so the 0.969 is a genuine " + "ordering and is not a saturation artefact.") +P() +P("### 1. Task 3 — three goal-blind baselines match or beat the RSM on its own arm") +P() +P(f"Same anchors, same candidates, K=31, original `failure` distractors. {nfo(['F_fail31'])}. " + "95 % CIs are bootstrapped over the **5 episodes**, not the 96 anchors.") +P() +P(table([("failure distractors (the original arm)", ["F_fail31", "P_fail31"])])) +P() +P("**A scorer with zero parameters gets 1.000.** The reason is structural: this dataset's action is the " + "**absolute 10-d end-effector pose** (`scripts/real/relabel_dino_lerobot.py:9`, `meta.adim=10`), and the " + "*same pose* is the proprio block of the 1546-d state (`cache/real_cooking_v5/proprio.f32.npy`, asserted " + "equal to the hdf5 `obs/ee_state` in `actcond_audit.py:122`). So `-||a_chunk[0] − pose_now||` decides " + "\"which of these 32 logged chunks belongs to this frame\" perfectly, before any value function is " + "consulted — **1.000 on all 5 episodes, at S2 and S3, on both the failure and the goal distractor source**. " + "The candidate set is linearly separable by kinematics. No read-out of any value function can be credited " + "for a number a distance already saturates.") +P() +P("### 2. Task 1 — the three distractor sources at matched anchors and matched K=31") +P() +P(table([("failure (original)", ["F_fail31", "P_fail31"]), + ("**goal** (discriminating)", ["F_goal31", "P_goal31"]), + ("shuffled-time (same ep)", ["F_shuf31", "P_shuf31"])])) +P() +P("Read the RSM row against the BC row. When the distractors become equally on-route (`goal`) the RSM loses " + "**29 points** and BC loses **1**; when they come from the same episode at other times (`shuffled-time`) " + "the RSM loses **56 points** and BC loses **4**. The RSM is a *noisier* plausibility detector, not a " + "better-informed one. `permuted:rsm` stays at chance everywhere, so the old control was working — it just " + "never tested this.") +P() +P("**Bonus coverage:** the `goal` and `shuffled-time` pools contain **S3** chunks (1200 / 1356) where the " + "failure pool has none, so these arms test S3 for the first time.") +P() +P(table([("goal, S3", ["F_goal31", "P_goal31"]), ("shuffled-time, S3", ["F_shuf31", "P_shuf31"])], stage=3)) +P() +P("### 3. Task 2 — the reverse-anchor test. **The RSM fails it.**") +P() +P("Anchor at S2 *inside a `0->2->6` failure episode* — the same junction the goal route passes through. " + "Candidate 0 = a goal-route chunk; candidate 1 = the anchor's **own** next chunk (failure route); the rest " + "= chunks from other `0->2->6` episodes. A goal-directed value ranks candidate 0 **first** (the goal-bound " + "action is better from the junction regardless of which episode you are in). A plausibility detector ranks " + "it **last**, because it did not come from this trajectory.") +P() +for lbl, cell, pc in (("validation episodes only (RSM never trained on these)", "R_val31", "P_rev31"), + ("ALL 50 `0->2->6` episodes", "R_all31", "P_revall31")): + P(f"**{lbl}** — {nfo([cell], target='goal')}, K=31") + P() + hd = "| scorer | top-1, GOAL chunk | rank pct of the GOAL chunk | top-1, the anchor's OWN chunk |" + P(hd); P("|---|---|---|---|") + for m in ORDER: + rg, _ = get([cell, pc], m, "goal") + ro, _ = get([cell, pc], m, "own") + if rg is None: + continue + P(f"| {NICE[m]} | {fmt(rg)} | **{rg['rank_pct_mid']:.3f}** | {fmt(ro)} |") + P("| _chance / neutral_ | 0.031 | 0.500 | 0.031 |") + P() +P("The RSM puts the goal-bound action in the **bottom fifth** (rank percentile 0.192 over 50 episodes, " + "0.234 over the 5 validation ones) — *below* the permuted control's 0.500 — and prefers the chunk that " + "continues the failure trajectory. It has the same sign and nearly the same magnitude as the " + "zero-parameter pose score and as BC. This is the cleanest single discriminator available and the RSM is " + "on the wrong side of it.") +P() +P("### 4. Task 4 — statistics, ties, and a read-out bug the flat baseline exposed") +P() +P("**A bug worth fixing regardless of the verdict.** The original read-out used `np.argmax` (which returns " + "the *first* maximum) and `rank = (scores < scores[0]).sum()/(n−1)`. Candidate 0 is always the target, so a " + "perfectly **flat** scorer scored `top1 = 1.000` and `rank = 0.000`. The reward-head-at-the-anchor baseline " + "is flat by construction (the head's forward signature takes no action) and would have \"beaten\" the RSM " + "on that artefact: it reads `ties@max = 32.00`, `CV = 0.00e+00`, `top1_argmax = 1.000`, " + "`top1_tie = 0.031 = chance`. Every number above is now random-tie-broken with a mid-rank percentile. " + "**The 0.969 itself is unaffected** (the RSM has no ties). The flat baseline also confirms there is no " + "candidate-identity leak into the state.") +P() +P("**K sweep** (top-1, tie-corrected; the RSM decays with K, BC does not decay at all):") +P() +P(table([("K=7", ["K007_fail", "P_fail07"]), ("K=31", ["F_fail31", "P_fail31"]), + ("K=127", ["K127_fail", "P_fail127"])])) +P() +P("**Episode-level bootstrap.** All 96 forward anchors come from **5** validation episodes, so the effective " + "sample size is ~5 and anchor-level error bars would be ~4× too tight. All CIs above resample episodes. " + "Per-episode RSM top-1 on the failure arm: 0.88 / 1.00 / 1.00 / 1.00 / 0.95.") +P() +P("**Chain truncation.** One `CAP ALARM` fired on a single anchor in the goal arm " + "(`capped_frac 0.125, hops_mean 14.75, cap 67`); zero alarms in the other three slots. Not systemic, " + "flagged for completeness.") +P() +P("### 5. Coverage — the S0 gap, and why it is a stitching question by construction") +P() +P("Route census (`data/derived/cooking_v5_split.json`), 248 episodes, 5 routes × 50 (45 train / 5 valid): " + "`2->3->4` is the **only** goal-reaching route and it **starts at state 2**, so it has zero S0 frames; the " + "four routes that do contain S0 (`0->5`, `0->2->6`, `0->2->3`, `0->1->3`) all end without reaching state 4. " + "**No logged episode spans S0 and S4.** So S0 cannot be tested as \"rank the chunk this trajectory took\" — " + "there is no such trajectory. Every anchor in this issue is S2 (plus S3 in the two new arms).") +P() +P("Proposed (**not run** — Tasks 1–3 had to decide whether the S2 number means anything first):") +P() +P("* **S0-forward.** Anchors = S0 frames of `0->2->3` validation episodes (they take the 0->2 edge toward the " + "junction). Candidate 0 = that episode's own next chunk; distractors = S0 chunks from `0->5` (dead end). " + "Preferring candidate 0 requires *composing* the 0->2 edge (seen only in non-goal episodes) with 2->3->4 " + "(seen only in goal episodes) — i.e. it is a genuine stitching test.") +P("* **The same three distractor sources**, or S0-forward reproduces the identical confound this issue just " + "found.") +P("* **S0-reverse**, mirroring §3.") +P("* **A prerequisite S0 only has:** at S2 every episode has already reached the same junction; at S0 the " + "route is not yet determined, so if S0 frames of `0->5` and `0->2->3` are separable *from the state alone*, " + "the test measures initial-condition classification. Run a logistic route probe on the S0 features first " + "and, if it beats chance, pair anchors to distractors by nearest neighbour and report only the matched " + "number.") +P("* `0->2->3` **shares the 2->3 edge with the goal route** and `0->1->3` is a fifth route through S1; both " + "are sharper distractor sources than `0->5` and should be added to the S2 arms too.") +P() +P("### Verdict") +P() +P("The permuted control ruled out an index/magnitude artefact. It did not rule out the confound that was " + "actually present. Candidate 0 was the only candidate kinematically consistent with the anchor frame, and " + "in an absolute-pose action space that is decidable with no model at all.") +P() +P("**The 96.9 % is not evidence that the RSM is goal-directed.** A zero-parameter pose-continuity score does " + "the same job perfectly (1.000); BC log-likelihood does it perfectly at every K (1.000 at K=7, 31 and 127); " + "and when the test is inverted so that plausibility and goal-direction point in opposite directions, the " + "RSM ranks the goal-bound action in the bottom fifth. Handing this to REAL_REPORT for " + "`rise_stack/FINDINGS.md` with that wording.") diff --git a/rsm_rise/scripts/real/build_rankctrl_tables.py b/rsm_rise/scripts/real/build_rankctrl_tables.py new file mode 100644 index 0000000000000000000000000000000000000000..64604c28d59c4cdd75a9a75c2a117ba5c984ea46 --- /dev/null +++ b/rsm_rise/scripts/real/build_rankctrl_tables.py @@ -0,0 +1,114 @@ +"""Collect the RANK_CTRL cells (status/real/rankctrl//logged_action_rank.json) into the markdown +tables for gen_q#276. Pure json reading -- safe on the login node.""" +import json, os, sys, glob + +ROOT = "/proj/dmfexp/zwhong/rsm_rise" +D = f"{ROOT}/status/real/rankctrl" +SC = ["rsm", "permuted:rsm", "rsm_d1", "bc", "knn", "pose", "reward"] +NICE = {"rsm": "**RSM (beta-chain)**", "permuted:rsm": "permuted:rsm (control)", "rsm_d1": "rsm depth-1 (no chain)", + "bc": "BC log-lik (hop head)", "knn": "kNN-in-latent", "pose": "**pose continuity (0 params)**", "reward": "reward head @ anchor (flat)"} + + +def load(cell): + p = f"{D}/{cell}/logged_action_rank.json" + return json.load(open(p)) if os.path.exists(p) else None + + +def ci(row, key="boot_top1_tie"): + b = row.get(key) or {} + return "n/a" if b.get("lo") is None else f"[{b['lo']:.2f}, {b['hi']:.2f}]" + + +def block(cells, target="correct", stage=2, title=""): + """One markdown table: rows = scorers, columns = cells.""" + got = [(n, c, load(c)) for n, c in cells] + got = [(n, c, j) for n, c, j in got if j] + if not got: + return f"_{title}: no cell measured yet._\n" + out = [f"**{title}**", "", + "| scorer | " + " | ".join(n for n, _, _ in got) + " |", + "|---|" + "---|" * len(got)] + chance = got[0][2]["chance_top1"] + for m in SC: + cells_txt = [] + any_ = False + for _, _, j in got: + r = j["by"].get(f"{m}|{target}|S{stage}") + if not r: + cells_txt.append("--"); continue + any_ = True + cells_txt.append(f"{r['top1_tie']:.3f} {ci(r)}") + if any_: + out.append(f"| {NICE.get(m, m)} | " + " | ".join(cells_txt) + " |") + out.append(f"| _chance_ | " + " | ".join(f"{j['chance_top1']:.3f}" for _, _, j in got) + " |") + out += ["", "| cell | n anchors | n episodes | K | pool |", "|---|---|---|---|---|"] + for n, c, j in got: + out.append(f"| {n} | {j['n_anchors']} | {j['n_anchor_episodes']} | {j['K']} | {j['pool_desc']} |") + return "\n".join(out) + "\n" + + +def detail(cell, target="correct", stage=2): + j = load(cell) + if not j: + return f"_{cell}: not measured yet._\n" + out = [f"**`{cell}`** -- arm={j['arm']} source={j['distractor_source']} K={j['K']} " + f"n={j['n_anchors']} anchors from {j['n_anchor_episodes']} episodes " + f"(split={j.get('anchor_split','valid')}), chance top-1 {j['chance_top1']:.3f}", "", + "| scorer | top1 (tie-corr) | 95% CI (episode boot) | top1 (argmax, old) | top1 strict | " + "rank pct (mid) | ties@max | score CV | s(target) | s(others) |", + "|---|---|---|---|---|---|---|---|---|---|"] + for m in SC: + r = j["by"].get(f"{m}|{target}|S{stage}") + if not r: + continue + out.append(f"| {NICE.get(m, m)} | {r['top1_tie']:.3f} | {ci(r)} | {r['top1_argmax']:.3f} | " + f"{r['top1_strict']:.3f} | {r['rank_pct_mid']:.3f} | {r['ties_at_max']:.2f} | " + f"{r['score_cv']:.2e} | {r['s_target']:.4f} | {r['s_others']:.4f} |") + return "\n".join(out) + "\n" + + +def per_ep(cell, target="correct", stage=2): + j = load(cell) + if not j: + return "" + out = ["| scorer | " + " | ".join(f"ep {e}" for e in + sorted((j["by"].get(f"rsm|{target}|S{stage}") or {}) + .get("boot_top1_tie", {}).get("per_episode", {}))) + " |"] + keys = sorted((j["by"].get(f"rsm|{target}|S{stage}") or {}).get("boot_top1_tie", {}) + .get("per_episode", {})) + if not keys: + return "" + out.append("|---|" + "---|" * len(keys)) + for m in SC: + r = j["by"].get(f"{m}|{target}|S{stage}") + if not r: + continue + pe = r["boot_top1_tie"].get("per_episode", {}) + out.append(f"| {NICE.get(m, m)} | " + " | ".join(f"{pe.get(str(e), pe.get(e, float('nan'))):.2f}" + for e in keys) + " |") + return "\n".join(out) + "\n" + + +if __name__ == "__main__": + have = sorted(os.path.basename(os.path.dirname(p)) for p in glob.glob(f"{D}/*/logged_action_rank.json")) + print(f"\n") + print("## Task 1 -- the plausibility control: three distractor sources, matched anchors, matched K=31\n") + print(block([("failure (original)", "F_fail31"), ("goal (DISCRIMINATING)", "F_goal31"), + ("shuffled-time gap8", "F_shuf31"), ("shuffled-time gap50", "F_shuf31_g50")], + title="top-1 (tie-corrected), 95 % CI bootstrapped over the 5 anchor EPISODES")) + for c in ("F_fail31", "F_goal31", "F_shuf31", "F_shuf31_g50"): + print(); print(detail(c)) + print("\n## Task 2 -- the reverse-anchor test (anchor in a 0->2->6 failure episode at S2)\n") + for c in ("R_val31", "R_all31", "R_val07"): + print(f"*goal-route chunk (candidate 0):*"); print(detail(c, target="goal")) + print(f"*the anchor's OWN next chunk (candidate 1):*"); print(detail(c, target="own")); print() + print("\n## Task 4 -- K sweep\n") + print(block([("K=7", "K007_fail"), ("K=31", "F_fail31"), ("K=127", "K127_fail")], + title="failure distractors")) + print() + print(block([("K=7", "K007_goal"), ("K=31", "F_goal31"), ("K=127", "K127_goal")], + title="goal distractors")) + print("\n### per-episode top-1 (tie-corrected), failure arm K=31\n") + print(per_ep("F_fail31")) + print("\n### per-episode top-1 (tie-corrected), goal arm K=31\n") + print(per_ep("F_goal31")) diff --git a/rsm_rise/scripts/real/build_reader271_tex.py b/rsm_rise/scripts/real/build_reader271_tex.py new file mode 100644 index 0000000000000000000000000000000000000000..79b4caa981e918d8ff5fd8f3611ef3dd5d3546cd --- /dev/null +++ b/rsm_rise/scripts/real/build_reader271_tex.py @@ -0,0 +1,42 @@ +#!/usr/bin/env python +"""gen_q #271, run 21: emit docs/tex/_reader271.tex -- do the published R(z) numbers reproduce with +the DINOv2 a READER builds, rather than the one on the training cluster? + +Every number is READ from status/real/AUDIT271_J_DINO.json (audit check J) and the script REFUSES to +emit anything unless J passed EXACTLY -- a document must not carry a bit-identical claim that the +check behind it does not currently support. +""" +from __future__ import annotations +import json +from pathlib import Path + +ROOT = Path("/proj/dmfexp/zwhong/rsm_rise") +J = json.loads((ROOT / "status/real/AUDIT271_J_DINO.json").read_text()) +assert J["ok"], f"check J did not pass; refusing to write its numbers into the PDF: {J['failures']}" +assert J["z_max_abs_diff"] == 0.0 and J["logit_max_abs_diff"] == 0.0, \ + f"J passed within tolerance but not exactly; the paragraph claims bit-identical: {J}" +ST = J["source_trees"] +assert ST["same_snapshot"], "the two DINOv2 source trees differ; the paragraph would be wrong" +esc = lambda s: s.replace("_", r"\_") + +tex = rf"""\paragraph{{Do these numbers reproduce with the reader's DINOv2?}} Every $R(z)$ in this +document was measured on the training cluster, where the DINOv2 backbone is built from a local archive of +\texttt{{facebookresearch/dinov2}}; \texttt{{dino\_hub\_dir:}} in \texttt{{rise\_stack/configs/baselines.yaml}} +is an absolute path a reader does not have, so a reader's clone fetches that source from GitHub instead. A +reward head is only as reproducible as the features it consumes, and the checkpoint is bit-identical either +way, so a divergence in the two copies of the \emph{{model code}} would invalidate every number here while +leaving the name, the table row and the file's bytes untouched --- and those are what the other consistency +checks verify. It is therefore measured, not assumed. On the ${J['n_frames']}$ frames of the shipped replay +fixture, featurised through both sources with the clone's own featuriser: the two source trees are the same +snapshot (${ST['n_py_local']}$ of ${ST['n_py_local']}$ \texttt{{.py}} files identical by \textsc{{sha}}256), +$z$ is bit-identical, and \texttt{{{esc(J['head_hub_name'])}}} returns bit-identical logits over a range of +$[{J['logit_range_local'][0]:.2f}, {J['logit_range_local'][1]:.2f}]$, with the identical ranking of all +${J['n_frames']}$ frames ($\max|\Delta z| = 0$, $\max|\Delta R| = 0$). The published numbers therefore apply +to the hub copy as they stand. This is re-checked on every audit of \#271 with the GitHub source re-fetched +each time, so the check follows \texttt{{main}} rather than pinning itself to a snapshot of it; a future +divergence fails the check instead of silently moving the numbers. +""" +out = ROOT / "docs/tex/_reader271.tex" +out.write_text(tex) +print(f"[reader271] wrote {out} ({len(tex)} B), n_frames={J['n_frames']}, " + f"py={ST['n_py_local']}, head={J['head_hub_name']}") diff --git a/rsm_rise/scripts/real/build_real_report_tables.py b/rsm_rise/scripts/real/build_real_report_tables.py new file mode 100644 index 0000000000000000000000000000000000000000..8de5e299d6698031f201a9296980235148b9110c --- /dev/null +++ b/rsm_rise/scripts/real/build_real_report_tables.py @@ -0,0 +1,270 @@ +"""Emit the LaTeX table fragments for docs/tex/real_proposal_report.tex (owner request 2026-09-22, gen_q #263). + +Every number is read from a file on disk; nothing is typed in by hand except the hold-still baseline, which is +quoted from logs/lsf/rr_cpu_actnorm.1836483.out (scripts/tmp/action_norms_real.py, validation split). + +Sources + pi0.5 : the `EVAL step N:` lines of logs/lsf/rr_openpi_.*.out (same parser as plot_proposal_curves.py) + robomimic: /replay_e/replay_eval.json and runs/real/replay//replay_eval.json -> + pooled_episode_mean.{xyz_l2_first_cm,xyz_l2_chunk_cm,...} (rise_replay_eval.py, stride 10, 25 eps) + open-loop: status/real/openloop_S0Aidql_*/scorer_openloop.json (scorer_openloop.py, fixed harness) + W&B : status/real/wandb_runs.json (scripts/tmp/wandb_public_and_list.py) + the per-run wandb_id.txt files +Writes docs/tex/_real_tables.tex and status/real/report_numbers.json. +""" +import glob, json, os, re, collections + +ROOT = "/proj/dmfexp/zwhong/rsm_rise" +HOLD_FIRST, HOLD_CHUNK, HOLD_STEP = 0.81, 1.53, 0.22 # rr_cpu_actnorm.1836483.out, validation split +ENT_PROJ = "richardrl/rsm_rise" + +def tex(s): + return s.replace("_", r"\_") + +def path_tex(p): + """A long absolute path typeset so it can break after every separator (\path{} never breaks).""" + return r"\texttt{%s}" % (tex(p).replace("/", r"/\allowbreak ") + .replace(r"\_", r"\_\allowbreak ")) + +# ----------------------------------------------------------------- pi0.5 EVAL lines +PAT = re.compile(r"EVAL step (\d+): val: xyz_first=([0-9.]+)cm xyz_chunk=([0-9.]+)cm loss=([0-9.e-]+) " + r"grip_acc=([0-9.]+), train_eval: xyz_first=([0-9.]+)cm xyz_chunk=([0-9.]+)cm") +openpi = {} +for run in ("stock_s0", "stock_s1", "rise_s0", "rise_s1", "riseadv_s0", "riseadv_s1"): + pts = {} + for f in glob.glob(f"{ROOT}/logs/lsf/rr_openpi_{run}.*.out"): + for m in PAT.finditer(open(f, errors="ignore").read()): + s = int(m.group(1)); s -= s % 500 + pts[s] = tuple(float(x) for x in m.groups()[1:]) + if pts: + openpi[run] = sorted(pts.items()) + +# Display names + HF mirror file names. Every checkpoint here is trained on rsm_cooking_v5, this +# project's own FR3 data; "robomimic" is only the framework RISE ships in (the .pth file format), so the +# register names the checkpoint by ROLE and DATA, not by library (owner, 2026-09-22). +HF_REPO = "https://huggingface.co/rli14/rsm_cooking_v5_checkpoints" +DISPLAY = {"S0Aidql_seed0": r"RISE actor (rsm\_real)", "S0Aidql_seed1": r"RISE actor (rsm\_real)", + "S0B_seed0": r"BC-union (rsm\_real)", "S0B_seed1": r"BC-union (rsm\_real)"} +PLAIN = {k: v.replace(r"\_", "_") for k, v in DISPLAY.items()} # for rows that pass through tex() +HF_NAME = {"S0Aidql_seed0": "rise_actor_rsm_real_s0_e3000.pth", + "S0Aidql_seed1": "rise_actor_rsm_real_s1_e3000.pth", + "S0B_seed0": "bc_union_rsm_real_s0_e5000.pth", + "S0B_seed1": None, # second BC-union seed is not in the mirror + "stock_s1": "pi05_bc_rsm_real_stock_s1_29999/"} + +# ----------------------------------------------------------------- robomimic replay evals +def load_replay(p): + d = json.load(open(p)) + m = d["pooled_episode_mean"] + return dict(path=p, ckpt=d["ckpt"], stride=d["stride"], n_episodes=d["n_episodes"], + first=m["xyz_l2_first_cm"], chunk=m["xyz_l2_chunk_cm"], + first_max=m.get("xyz_l2_first_max_cm"), grip=m.get("grip_bin_acc")) + +robo = collections.defaultdict(dict) # robo["S0Aidql_seed1"][3000] = {...} +for p in glob.glob(f"{ROOT}/runs/cooking_v5_expert_suboptimal/policy/*/replay_e*/replay_eval.json"): + fam = p.split("/policy/")[1].split("/")[0] + e = int(re.search(r"replay_e(\d+)/", p).group(1)) + robo[fam][e] = load_replay(p) +for p in glob.glob(f"{ROOT}/runs/real/replay/*/replay_eval.json"): + tag = p.split("/replay/")[1].split("/")[0] # e.g. S0Aidql_s1_e2500 + m = re.match(r"(S0Aidql|S0B)_s(\d)_e(\d+)$", tag) + if not m: + continue + fam, e = f"{m.group(1)}_seed{m.group(2)}", int(m.group(3)) + robo[fam].setdefault(e, load_replay(p)) # the replay_e copy wins if both exist + +# ----------------------------------------------------------------- W&B urls +wb = {} # display name -> url (the surviving run, see below) +wb_rows = [] +wbjson = f"{ROOT}/status/real/wandb_runs.json" +wb_meta = {} +if os.path.exists(wbjson): + blob = json.load(open(wbjson)) + wb_meta = {k: v for k, v in blob.items() if k != "runs"} + wb_rows = blob["runs"] + # a cell that was preempted and resumed leaves several W&B runs under one display name; the one to link is the + # newest that is not `crashed`/`failed` (that is the run the current job is still writing to). Sorted so the + # preferred run is assigned LAST and therefore wins the dict slot. + for r in sorted(wb_rows, key=lambda d: (d["state"] not in ("crashed", "failed"), d["created"])): + wb[r["name"]] = r["url"] +def wb_url_for(sub): + for n, u in wb.items(): + if sub in n: + return u + return None +openpi_ids = {} +for f in glob.glob(f"{ROOT}/runs/openpi/checkpoints/*/*/wandb_id.txt"): + openpi_ids[f.split("/")[-2]] = open(f).read().strip() + +# ----------------------------------------------------------------- the policy / checkpoint table +def latest_dir(fam): + """Absolute path of the models/ dir holding the highest-epoch checkpoint of a robomimic family.""" + best = (None, -1) + for p in glob.glob(f"{ROOT}/runs/cooking_v5_expert_suboptimal/policy/{fam}/*/*/models/model_epoch_*.pth"): + e = int(re.search(r"model_epoch_(\d+)\.pth", p).group(1)) + if e > best[1]: + best = (p, e) + return best + +POLICIES = [] # (role, policy, recipe, seed, steps, abspath, wandb url) +for run, cfg in (("stock_s0", "pi05_cooking_stock"), ("stock_s1", "pi05_cooking_stock"), + ("rise_s0", "pi05_cooking_rise"), ("rise_s1", "pi05_cooking_rise"), + ("riseadv_s0", "pi05_cooking_riseadv")): + d = f"{ROOT}/runs/openpi/checkpoints/{cfg}/{run}" + steps = sorted(int(x) for x in os.listdir(d) if x.isdigit()) if os.path.isdir(d) else [] + last = steps[-1] if steps else None + rid = openpi_ids.get(run) + url = f"https://wandb.ai/{ENT_PROJ}/runs/{rid}" if rid else None + role = "BC" if run.startswith("stock") else "RISE actor" + POLICIES.append((role, "pi0.5 " + run.rsplit("_s", 1)[0], cfg, run[-1], f"{last} steps", + f"{d}/{last}", url, HF_NAME.get(run))) +for fam, role in (("S0B_seed0", "BC"), ("S0B_seed1", "BC"), + ("S0Aidql_seed0", "RISE actor"), ("S0Aidql_seed1", "RISE actor")): + p, e = latest_dir(fam) + POLICIES.append((role, DISPLAY[fam], "cooking_v5_expert_suboptimal", fam[-1], + f"epoch {e}", p, wb_url_for(f"{fam}"), HF_NAME.get(fam))) + +L = [] +A = L.append +A(r"% generated by scripts/real/build_real_report_tables.py -- do not edit by hand") +A(r"\newcommand{\holdfirst}{%.2f}" % HOLD_FIRST) +A(r"\newcommand{\holdchunk}{%.2f}" % HOLD_CHUNK) +A(r"\newcommand{\holdstep}{%.2f}" % HOLD_STEP) + +A(r"\begin{table}[htbp]\centering\small") +A(r"\caption{Real-world (\texttt{rsm\_cooking\_v5}) proposal policies: role, recipe, seed, training length, " + r"absolute checkpoint path, W\&B run and the file name in the Hugging Face mirror. Every row is fine-tuned " + r"on \texttt{rsm\_cooking\_v5}, this project's own FR3 cooking data (\emph{robomimic}, where it appears " + r"elsewhere, is the training framework RISE ships in --- a file format, not a data source). \emph{BC} rows are plain " + r"behaviour cloning; \emph{RISE actor} rows carry the RISE/IDQL actor recipe and ship their co-trained IQL " + r"critic in the same file. Epochs are the latest on disk at the time of writing. The \emph{HF mirror} column " + r"gives the file name in the public Hugging Face repo (Sec.~\ref{sec:hf}); \emph{--} means that seed was not " + r"mirrored.}") +A(r"\label{tab:ckpt}") +A(r"\begin{tabular}{@{}lllp{13mm}p{46mm}lp{30mm}@{}}\toprule") +A(r"role & policy & seed & length & checkpoint (absolute) & W\&B & HF mirror name \\ \midrule") +for role, pol, recipe, seed, steps, p, url, hfn in POLICIES: + link = r"\href{%s}{run}" % url if url else "--" + hf = (r"{\tiny \texttt{%s}}" % tex(hfn)) if hfn else "--" + A(r"%s & %s & %s & %s & {\tiny %s} & %s & %s \\[2pt]" + % (role, pol, seed, tex(steps), path_tex(p or "--"), link, hf)) +A(r"\bottomrule\end{tabular}\end{table}") + +# ----------------------------------------------------------------- the fit table (ratios to hold-still) +A(r"\begin{table}[htbp]\centering\small") +A(r"\caption{Held-out fit on the 25 validation episodes, quoted as a ratio to the hold-still predictor " + r"(copy the current end-effector xyz: \holdfirst~cm first action, \holdchunk~cm 8-step chunk mean; per-step " + r"motion \holdstep~cm). Ratio $>1$ means better than hold-still. pi0.5 rows are the run's own " + r"\texttt{EVAL step} lines at the last step; RISE-stack rows are " + r"\texttt{replay\_eval.json:pooled\_episode\_mean} (stride 10, 25 episodes).}") +A(r"\label{tab:fit}") +A(r"\begin{tabular}{@{}llrrrrp{38mm}@{}}\toprule") +A(r"policy & at & first (cm) & chunk (cm) & first ratio & chunk ratio & source \\ \midrule") +A(r"hold-still & -- & %.2f & %.2f & 1.00 & 1.00 & \texttt{action\_norms\_real.py} \\ \midrule" % (HOLD_FIRST, HOLD_CHUNK)) +fitrows = [] +for run, pts in sorted(openpi.items()): + s, v = pts[-1] + fitrows.append((f"pi0.5 {run}", f"{s} steps", v[0], v[1], f"logs/lsf/rr_openpi_{run}.*.out")) +for fam in ("S0Aidql_seed0", "S0Aidql_seed1", "S0B_seed0", "S0B_seed1"): + if not robo[fam]: + continue + e = max(robo[fam]) + r = robo[fam][e] + fitrows.append((f"{PLAIN[fam]} s{fam[-1]}", f"epoch {e}", r["first"], r["chunk"], + r["path"].replace(ROOT + "/", ""))) +for nm, at, f0, c0, src in fitrows: + A(r"%s & %s & %.2f & %.2f & %.2f$\times$ & %.2f$\times$ & {\tiny %s} \\" + % (tex(nm), tex(at), f0, c0, HOLD_FIRST / f0, HOLD_CHUNK / c0, path_tex(src))) +A(r"\bottomrule\end{tabular}\end{table}") + +# ----------------------------------------------------------------- per-epoch RISE-stack table +A(r"\begin{table}[htbp]\centering\small") +A(r"\caption{Per-epoch held-out fit of the RISE-stack actors (\texttt{replay\_eval.json}, stride 10, 25 " + r"validation episodes). Empty cells have no replay eval on disk.}") +A(r"\label{tab:perepoch}") +eps = sorted({e for fam in robo for e in robo[fam] if e >= 500}) +A(r"\begin{tabular}{@{}l" + "r" * len(eps) + r"@{}}\toprule") +A(r"policy (first / chunk cm) & " + " & ".join(str(e) for e in eps) + r" \\ \midrule") +for fam in ("S0Aidql_seed0", "S0Aidql_seed1", "S0B_seed0", "S0B_seed1"): + cells = [] + for e in eps: + r = robo[fam].get(e) + cells.append(r"\tiny %.2f/%.2f" % (r["first"], r["chunk"]) if r else "--") + A(tex(f"{PLAIN[fam]} s{fam[-1]}") + " & " + " & ".join(cells) + r" \\") +A(r"\bottomrule\end{tabular}\end{table}") + +# ----------------------------------------------------------------- open-loop scorer comparison +ol = [] +for d in sorted(glob.glob(f"{ROOT}/status/real/openloop_S0Aidql_*")): + p = f"{d}/scorer_openloop.json" + if os.path.exists(p): + ol.append(json.load(open(p))) +A(r"\begin{table}[htbp]\centering\small") +if ol: + A(r"\caption{Open-loop selection on the \texttt{S0Aidql} proposers' 128 candidates (fixed harness, " + r"\texttt{scorer\_openloop.py}; stride 25, 25 episodes). \emph{greedy} is the proposer's own first " + r"sample; \emph{permuted} rows are the score-shuffling controls. Lower is better.}") + A(r"\label{tab:openloop}") + A(r"\begin{tabular}{@{}llrrrr@{}}\toprule") + A(r"cell & scorer & first (cm) & chunk (cm) & $\Delta$ vs greedy & win rate \\ \midrule") + for d in ol: + first = True + for k in ("greedy", "idql", "rsm", "permuted:idql", "permuted:rsm", "random"): + s = d["scorers"].get(k) + if not s: + continue + A(r"%s & %s & %.3f & %.3f & %+.3f & %.3f \\" + % (tex(d["tag"]) if first else "", tex(k), s["first_mean_cm"], s["chunk_mean_cm"], + s["delta_vs_greedy_cm"], s["win_rate_vs_greedy"])) + first = False + A(r"\midrule") + A(r"\bottomrule\end{tabular}") +else: + A(r"\caption{Open-loop selection comparison: pending.}\label{tab:openloop}") + A(r"\begin{tabular}{@{}l@{}}\toprule pending \\ \bottomrule\end{tabular}") +A(r"\end{table}") + + +# ----------------------------------------------------------------- the W&B section +W = [] +if wb_meta: + W.append(r"The project is \href{%s}{\texttt{%s}}." % (wb_meta["project_url"], tex(wb_meta["project"]))) + ab, aa = wb_meta["access_before"], wb_meta["access_after"] + W.append(r"The project's \texttt{access} field read back \texttt{%s} \emph{before} this run and \texttt{%s} " + r"\emph{after}. \texttt{USER\_READ} is W\&B's \emph{public: anyone with the link can view}, so the " + r"project %s. The reader/mutation script is \texttt{scripts/tmp/wandb\_public\_and\_list.py} " + r"(run on a CPU node; it issues \texttt{upsertModel(access: USER\_READ)} only when the project is not " + r"already public, and it was, so no mutation was sent)." + % (tex(ab), tex(aa), + r"was \textbf{already public} and needed no change" if ab == "USER_READ" + else r"was made public by this run")) + if wb_meta.get("upsert_error"): + W.append(r"\textbf{The mutation was refused.} The exact API error was:") + W.append(r"\begin{quote}\ttfamily\small %s \end{quote}" % tex(wb_meta["upsert_error"][:600])) + W.append(r"The owner can flip it by hand in the project settings " + r"(\emph{Settings} $\to$ \emph{Privacy} $\to$ \emph{Public}).") + W.append(r"All %d cooking runs and their URLs are listed in \path{status/real/wandb_runs.json}; the " + r"per-policy links are in Table~\ref{tab:ckpt}." % len(wb_rows)) + if wb: + W.append(r"\begin{table}[htbp]\centering\small\caption{Every \texttt{cooking} run in the project.}" + r"\label{tab:wandb}\begin{tabular}{@{}llll@{}}\toprule") + W.append(r"run & state & created & URL \\ \midrule") + for r in sorted(wb_rows, key=lambda d: (d["name"], d["created"])): + W.append(r"{\tiny %s} & %s & %s & {\tiny \href{%s}{%s}} \\" + % (tex(r["name"]), tex(r["state"]), tex(r["created"]), r["url"], + tex(r["url"].split("/runs/")[-1]))) + W.append(r"\bottomrule\end{tabular}\end{table}") +else: + W.append(r"\textbf{Pending:} \texttt{scripts/tmp/wandb\_public\_and\_list.py} had not written " + r"\path{status/real/wandb_runs.json} when this PDF was built.") +open(f"{ROOT}/docs/tex/_real_wandb.tex", "w").write("\n".join(W) + "\n") + +open(f"{ROOT}/docs/tex/_real_tables.tex", "w").write("\n".join(L) + "\n") +json.dump(dict(hold=dict(first=HOLD_FIRST, chunk=HOLD_CHUNK, step=HOLD_STEP), + openpi={k: v[-1] for k, v in openpi.items()}, + robomimic={f: {str(e): r for e, r in v.items()} for f, v in robo.items()}, + policies=[dict(zip(("role", "policy", "recipe", "seed", "length", "ckpt", "wandb"), p)) for p in POLICIES], + openloop=[d["tag"] for d in ol], wandb=wb_meta), + open(f"{ROOT}/status/real/report_numbers.json", "w"), indent=1) +print("wrote docs/tex/_real_tables.tex and status/real/report_numbers.json") +print("openpi runs:", sorted(openpi)); print("robomimic epochs:", {f: sorted(v) for f, v in robo.items()}) +print("open-loop cells:", [d["tag"] for d in ol]); print("wandb runs indexed:", len(wb)) diff --git a/rsm_rise/scripts/real/build_reward_matrix_v2.py b/rsm_rise/scripts/real/build_reward_matrix_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..a99b9fe5dc3cfc63c532caeee98a8eb105d9382f --- /dev/null +++ b/rsm_rise/scripts/real/build_reward_matrix_v2.py @@ -0,0 +1,199 @@ +#!/usr/bin/env python3 +"""THE REWARD MATRIX, v2 -- rebuilt so that every METRIC-1 number is quoted at FAMILY level in sd and every +METRIC-2 number is quoted beside its own permuted line, its own measured oracle ceiling and its own +candidate-level label oracle. Rows are reward heads. Nothing is ever compared across rows. + +WHY v2 REPLACES status/real/SQUARE_MATRIX.txt (reduce_square_matrix.py, run 36). +That table prints ONE CELL PER SEED per head ("RSM stitch_A (seed0 / seed1)"). Runs 47 and 48 then +measured the replicate floor at n=5-6 and found: + * `rsm_R_M_ft_v1` 6 draws spanning -0.0522..+0.1466, sd 0.0682 = 1.15x the whole IQL baseline; + * `rsm_R_M_ft_C10` 6 draws spanning +0.0427..+0.1644, weakest draw -0.0164 BELOW the baseline, + after run 44 had reported the better of its first two draws (+0.0726 margin) as a result. +So a single-cell stitch_A is a draw from a spread that in four families reaches the opposite side of the +baseline. Every per-cell METRIC-1 verdict this stream reported is withdrawn (run 47 s1, run 48 s1), and a +table that still shows per-seed cells invites exactly the reading that was wrong. v2 therefore prints, per +head, the FAMILY: n, mean, sd, the weakest draw's signed delta from the baseline, and one of four verdict +classes -- REPRODUCIBLE / DIRECTIONAL / NO_SEPARATION / SIGN_FLIP (#281 correction (H)). + +WHAT MAKES A HEAD UNREPORTABLE HERE, and it is most of them. + (1) NO MEASURED FLOOR. A head whose every cell is n=1 has no sd, so no per-cell verdict on it is + reportable (#281 correction (C)). That is EXPERT_EPISODE, RISE_PROVENANCE, GOAL_WINDOW_100 and + GOAL_WINDOW_400 as of run 48 -- stated as a precondition for any future row, not as a retraction. + (2) LABELS GROUP A. If the head's own label marks the 0->1->3 arrivals as 1.000, METRIC 1's numerator + is the head reading its own label back and the test has no content on that head at all. + (3) METRIC 2 without its own oracle row, or with its CI reaching its own ceiling. + +INPUTS, all machine-readable, none parsed out of markdown (run 49 added the JSON side-outputs): + status/real/METRIC1_FAMILIES.json reduce_replicate_families.py with RRF_JSON set + status/real/m2json/.json reduce_metric2_square.py --json + status/real/m2json/oracle_.json metric2_label_oracle.py --json +A missing input is reported as a missing SECTION with the command that would produce it. It is never +silently skipped, because a narrower table looks exactly like a complete one. +""" +import json, os, glob, argparse, collections + +ROOT = "/proj/dmfexp/zwhong/rsm_rise" +STITCH = f"{ROOT}/status/real/stitch" +ALIAS = {"GOAL_SEGMENT_CONTRASTIVE": "GOAL_SEGMENT", "RISE_PROVENANCE": "EXPERT_EPISODE"} +LABELS_GROUP_A = {"EXPERT_EPISODE": True, "RISE_PROVENANCE": True, "GOAL_EPISODE": False, + "GOAL_SEGMENT": False, "GOAL_SEGMENT_CONTRASTIVE": False, + "GOAL_WINDOW_400": False, "GOAL_WINDOW_100": False} +SEES_RANK_LABEL = {"EXPERT_EPISODE": "YES", "RISE_PROVENANCE": "YES", "GOAL_EPISODE": "no", + "GOAL_SEGMENT": "no", "GOAL_SEGMENT_CONTRASTIVE": "no", + "GOAL_WINDOW_400": "unmeasured", "GOAL_WINDOW_100": "unmeasured"} +HEAD_ORDER = ["GOAL_EPISODE", "GOAL_SEGMENT", "GOAL_SEGMENT_CONTRASTIVE", "EXPERT_EPISODE", + "RISE_PROVENANCE", "GOAL_WINDOW_400", "GOAL_WINDOW_100"] + +ap = argparse.ArgumentParser() +ap.add_argument("--fam", default=f"{ROOT}/status/real/METRIC1_FAMILIES.json") +ap.add_argument("--m2dir", default=f"{ROOT}/status/real/m2json") +ap.add_argument("--split", default="confirm", choices=["select", "confirm"]) +a = ap.parse_args() + +missing = [] + +# ---------------------------------------------------------------- METRIC 1 +fam = None +if os.path.exists(a.fam): + fam = json.load(open(a.fam)) +else: + missing.append((a.fam, "RRF_JSON=%s venv_rsm/bin/python scripts/real/reduce_replicate_families.py" % a.fam)) + +# cells on disk per head, so a head with no family can be told apart from a head with no cells +cells = collections.Counter() +for p in glob.glob(f"{STITCH}/*/rsm_*/stitch_value.json"): + cells[p.split("/")[-3]] += 1 + +print("=" * 132) +print("THE REWARD MATRIX v2 -- one row per reward head, BOTH scorers on THAT head's label.") +print("METRIC 1 is quoted at FAMILY level (n exact-config draws, sd = the measured replicate floor).") +print("METRIC 2 is quoted beside its OWN permuted line AND its OWN measured oracle ceiling (job 1884695).") +print("Measured label aliases (0 frames differ over all 181530): GOAL_SEGMENT_CONTRASTIVE == GOAL_SEGMENT,") +print("RISE_PROVENANCE == EXPERT_EPISODE -- one label, so one reward-matched critic serves both.") +print("=" * 132) + +print("\n## METRIC 1 -- stitch value test, family level. Floor = sample sd over the family's n draws.") +print("A claim is REPRODUCIBLE only if all n draws are on one side of that head's strongest reportable") +print("reward-matched IQL baseline with disjoint CIs AND the worst margin is >= 2 sd.\n") +print("| head | sees S0 rank label? | labels group A? | RSM family | n | RSM mean +- sd | weakest draw " + "vs baseline | reward-matched IQL baseline [CI] | sd/base | verdict |") +print("|" + "---|" * 10) + +m1_by_head = collections.defaultdict(list) +if fam: + for f in fam["families"]: + m1_by_head[f["head"]].append(f) + +for head in HEAD_ORDER: + ga = LABELS_GROUP_A[head] + fs = sorted(m1_by_head.get(head, []), key=lambda f: f["family"]) + if ga: + print(f"| {head} | {SEES_RANK_LABEL[head]} | **YES** | -- | -- | -- | -- | -- | -- | " + f"**METRIC 1 NOT TESTABLE ON THIS HEAD** -- its own label marks the 0->1->3 arrivals 1.000, " + f"so the numerator is label read-back ({cells[head]} cells on disk, none reportable) |") + continue + if not fs: + print(f"| {head} | {SEES_RANK_LABEL[head]} | no | *no replicate family* | 1 | -- | -- | -- | -- | " + f"**UNREPORTABLE PER CELL -- NO MEASURED FLOOR** ({cells[head]} cells on disk, every one n=1; " + f"#281 correction (C)). A floor needs >=2 exact-config draws of one cell. |") + continue + for f in fs: + b = f.get("baseline") + mu = sum(f["draws"]) / f["n"] + bt = ("**NO REPORTABLE IQL CELL**" if not b else + f"{b['A']:+.4f} [{b['ci'][0]:+.4f},{b['ci'][1]:+.4f}] [{b['cell']}" + + (f" VIA ALIAS {b['via_alias']}" if b.get("via_alias") else "") + "]") + vc = f["verdict_class"] + extra = "" + if vc == "REPRODUCIBLE": + extra = f" -- worst margin {f['margin_sd']:.2f} sd" + elif vc == "DIRECTIONAL": + extra = f" -- same side but worst margin only {f['margin_sd']:.2f} sd" + elif vc == "SIGN_FLIP": + extra = f" -- {f['n_above']} above / {f['n_below']} below with disjoint CIs" + elif vc == "NO_SEPARATION": + extra = f" -- {f['n_straddle']} of {f['n']} draws indistinguishable from the baseline" + if f.get("sd_exceeds_baseline"): + extra += f"; sd is {f['sd_over_baseline']:.2f}x the whole baseline, NO single cell interpretable" + print(f"| {head} | {SEES_RANK_LABEL[head]} | no | `{f['family']}` | {f['n']} | " + f"{mu:+.4f} +- {f['sd']:.4f} | {f['worst_draw_delta']:+.4f} | {bt} | " + f"{f['sd_over_baseline']:.2f}x | **{vc}**{extra} |") + +# ---------------------------------------------------------------- METRIC 2 +print(f"\n## METRIC 2 -- S2 uprank AUC, {a.split.upper()} split, gate of record (anchors within 100 frames") +print("of S2 ENTRY). Every row prints its own permuted line, its own MEASURED ceiling, ties-at-max, score") +print("CV, kept anchors and kept episodes. A CI reaching the ceiling is label exploitation, NOT a pass.\n") + +def load_m2(tag): + p = f"{a.m2dir}/{tag}.json" + if os.path.exists(p): return json.load(open(p)) + return None + +ARMS = [("unrestricted", "no route control -- CONSISTENT WITH LABEL READ-BACK"), + ("restricted", "route-restricted to 0->2->3 / 0->2->6, where every goal head writes 0.0000 on BOTH")] +for arm, note in ARMS: + tag = f"{a.split}_{arm}" + d = load_m2(tag); o = load_m2(f"oracle_{tag}") + if d is None: + missing.append((f"{a.m2dir}/{tag}.json", + f"reduce_metric2_square.py --split {a.split} --json {a.m2dir}/{tag}.json")) + if o is None: + missing.append((f"{a.m2dir}/oracle_{tag}.json", + f"metric2_label_oracle.py --split {a.split} --json {a.m2dir}/oracle_{tag}.json")) + print(f"\n### {arm.upper()} arm -- {note}") + if d is None or o is None: + print("**SECTION NOT REPORTABLE -- input missing** (listed at the end with the command that makes it).") + continue + # oracle index: (head, W) -> GEOM_LABEL row. A METRIC-2 row with no oracle row is UNDEFINED per #281 (A). + orc = {} + for r in o["rows"]: + for k in [k for k in r if k.startswith("score_") and not k.endswith("__perm")]: + orc[(r["head"], r["W"], k)] = (r.get(k), r.get(k + "__perm"), r["ceil"]) + print("| head | sees rank label? | window | anchors | eps | ceiling | IQL AUC [CI] (own perm) t cv | " + "RSM AUC [CI] (own perm) t cv | GEOM_LABEL oracle | reportable verdict |") + print("|" + "---|" * 10) + for r in sorted(d["rows"], key=lambda r: (HEAD_ORDER.index(r["head"]) if r["head"] in HEAD_ORDER else 99, + r["W"])): + W = "all" if r["W"] > 10 ** 8 else r["W"] + def col(k, pk): + if k not in r or pk not in r: return "--", None, None, None + m, lo, hi, ti, cv = r[k]; pm = r[pk][0] + return f"{m:.3f} [{lo:.3f},{hi:.3f}] (perm {pm:.3f}) t={ti:.2f} cv={cv:.3f}", lo, hi, pm + itxt, ilo, ihi, ipm = col("score_idql", "score_permuted__idql") + rtxt, rlo, rhi, rpm = col("score_rsm", "score_permuted__rsm") + og = orc.get((r["head"], r["W"], "score_GEOM_LABEL")) + if og is None or og[0] is None or og[1] is None: + otxt = "**NO ORACLE ROW**"; o_above = None; o_ties = None + else: + (om, olo, ohi, oti, ocv), (pm_, plo, phi, pti, pcv), oc = og + o_above = olo > phi + o_ties = oti + otxt = (f"{om:.3f} [{olo:.3f},{ohi:.3f}] vs own perm {pm_:.3f} [{plo:.3f},{phi:.3f}] " + f"t={oti:.2f} -> {'ABOVE (read-back POSSIBLE)' if o_above else 'straddles/below'}") + verds = [] + for nm, lo, hi, pm in (("IQL", ilo, ihi, ipm), ("RSM", rlo, rhi, rpm)): + if lo is None: verds.append(f"{nm}: --"); continue + c = r["ceil"] + if o_above is None: verds.append(f"{nm}: **UNDEFINED** (no oracle row for this anchor set)") + elif hi >= c: verds.append(f"{nm}: CI REACHES CEILING -> label exploitation") + elif o_above: verds.append(f"{nm}: NOT A PASS -- own oracle is above its line here") + elif o_ties is not None and o_ties >= 0.95: + verds.append(f"{nm}: NOT A PASS -- oracle ties@max {o_ties:.2f}, arm has no power") + elif lo > pm: verds.append(f"{nm}: **PASS**") + elif hi < pm: verds.append(f"{nm}: BELOW its own permuted line") + else: verds.append(f"{nm}: straddles its own permuted line -- no effect") + print(f"| {r['head']} | {SEES_RANK_LABEL.get(r['head'],'?')} | <={W} | {r['n']} | {r['eps']} | " + f"{r['ceil']:.3f} | {itxt} | {rtxt} | {otxt} | " + "; ".join(verds) + " |") + +# ---------------------------------------------------------------- what is not here +print("\n## INPUTS NOT PRESENT (nothing above was narrowed silently to work around these)") +if not missing: + print("none -- every section above was built from a machine-readable input.") +for p, cmd in missing: + print(f"* MISSING `{p}` -> produce with: `{cmd}`") +print("\n## READING RULES THAT BIND THIS TABLE") +print("* Never compare a row against a number from a differently-labelled row.") +print("* A METRIC-1 head with no measured floor has NO reportable per-cell verdict, in either direction.") +print("* A METRIC-2 row is quoted only beside its own permuted line; a nominal 0.500 is never the zero line.") +print("* The stitch value test uses logged chunks and route membership with NO direction clustering, so it") +print(" is unaffected by the retraction of the direction proxy (2026-09-23 18:15Z).") diff --git a/rsm_rise/scripts/real/build_reward_screen.py b/rsm_rise/scripts/real/build_reward_screen.py new file mode 100644 index 0000000000000000000000000000000000000000..a6ae1492899ef12c5f27a90b806d7e7449464c9a --- /dev/null +++ b/rsm_rise/scripts/real/build_reward_screen.py @@ -0,0 +1,125 @@ +#!/usr/bin/env python +"""Diagnostic 4 of gen_q #271: reduce the open-loop RISE-recipe screen to one number per head. + +For each proposer seed we have a scorer_openloop run in which EVERY reward head scored the SAME +N=128 candidates at the same decisions, so the comparison against the control is paired. The +statistic is `oracle_rank_pct` -- the fraction of the 128 candidates that the head's argmax pick +beats on first-step error -- and the control is `permuted:rsm` (the base head's scores, shuffled). +Shuffling destroys all information, so the same control is the right null for every head; `greedy` +is an independent second draw of it. + +Writes status/real/REWARD_SCREEN.json: per seed and per head the mean, the paired delta against the +control and a 95% bootstrap CI over decisions, plus a `combined` block that pools the seeds. +""" +from __future__ import annotations +import json +from pathlib import Path +import numpy as np + +ROOT = Path("/proj/dmfexp/zwhong/rsm_rise") +ST = ROOT / "status/real" +# Proposer seed -> screen directory. The tag is env-overridable because run 5 had to REDO both +# seeds after the stale-checkpoint fix (RW271 -> RW271b); pointing this at the old tag silently +# re-publishes the numbers in which B_s1/v0lit/v0lit_s1 were really the base head. +SCREEN_TAG = __import__("os").environ.get("RW_SCREEN_TAG", "RW271c") # run 8: RW271c is the first screen in which every column is a real 110k checkpoint +RUNS = { # proposer seed -> screen directory + "s0": ST / f"openloop_{SCREEN_TAG}_S0Aidql_s0_e2000_d1_T25", + "s1": ST / f"openloop_{SCREEN_TAG}_S0Aidql_s1_e2500_d1_T25", +} +CONTROL = "permuted_rsm" +NBOOT = 4000 +# openloop scorer column -> #271 scheme name +CELL = {"rsm": "base_R_M", "rsm@ft_v0": "v0", "rsm@ft_v0_s1": "v0_s1", "rsm@ft_v0lit": "v0lit", + "rsm@ft_v0lit_s1": "v0lit_s1", "rsm@ft_v1": "A", "rsm@ft_v1_s1": "A_s1", + "rsm@ft_v2": "v2", "rsm@ft_v2_s1": "v2_s1", "rsm@ft_v3": "v3", "rsm@ft_v3_s1": "v3_s1", + "rsm@ft_B": "B", "rsm@ft_B_s1": "B_s1", "rsm@ft_B400": "B400", "rsm@ft_B400_s1": "B400_s1", + "rsm@ft_C3": "C3", "rsm@ft_C3_s1": "C3_s1", "rsm@ft_C10": "C10", "rsm@ft_C10_s1": "C10_s1", + "idql": "idql", "permuted_idql": "permuted:idql", "permuted_rsm": "permuted:rsm"} + + +def oracle_rank_pct(score: np.ndarray, order: np.ndarray) -> np.ndarray: + """Per decision: the fraction of candidates the argmax-of-`score` pick beats. 1.0 = the oracle's pick.""" + D, N = score.shape + pick = np.argmax(score, axis=1) + return 1.0 - order[np.arange(D), pick] / (N - 1) + + +def one(npz_path: Path, rng) -> dict: + z = np.load(npz_path) + err = z["err_first"] # (D, N), lower = better + order = np.argsort(np.argsort(err, axis=1), axis=1) # rank 0 = best candidate + D = err.shape[0] + per = {k[6:]: oracle_rank_pct(z[k], order) for k in z.files if k.startswith("score_")} + base = per[CONTROL] + idx = rng.integers(0, D, (NBOOT, D)) # one resample of DECISIONS, shared by all heads + # `greedy` and `oracle` are not score columns -- take their reported means from the run's JSON + ref = json.loads((npz_path.parent / "scorer_openloop.json").read_text())["scorers"] + out = {"n_decisions": int(D), "n_candidates": int(err.shape[1]), + "reference": {k: ref[k]["oracle_rank_pct_mean"] for k in ("oracle", "greedy") if k in ref}, + "heads": {}} + for name, v in per.items(): + d = v - base + bs = d[idx].mean(axis=1) + lo, hi = np.percentile(bs, [2.5, 97.5]) + out["heads"][CELL.get(name, name)] = { + "oracle_rank_pct_mean": float(v.mean()), + "delta_vs_permuted": float(d.mean()), + "ci95": [float(lo), float(hi)], + "beats_control": bool(lo > 0.0), + } + return out, {CELL.get(k, k): v for k, v in per.items()} + + +def main(): + rng = np.random.default_rng(0) + res, pooled = {"control": "permuted:rsm", "statistic": "oracle_rank_pct", "n_bootstrap": NBOOT, + "seeds": {}}, {} + for seed, d in RUNS.items(): + p = d / "scores.npz" + if not p.exists(): + print(f"[screen] SKIP {seed}: no {p}") + continue + r, per = one(p, rng) + res["seeds"][seed] = r + print(f"[screen] {seed}: {r['n_decisions']} decisions x {r['n_candidates']} candidates") + for k, v in sorted(r["heads"].items(), key=lambda x: -x[1]["oracle_rank_pct_mean"]): + print(" %-14s %.4f d=%+.4f [%+.4f, %+.4f]%s" % ( + k, v["oracle_rank_pct_mean"], v["delta_vs_permuted"], *v["ci95"], + " BEATS CONTROL" if v["beats_control"] else "")) + for k, v in per.items(): + pooled.setdefault(k, []).append(v) + + # pooled across proposer seeds: decisions are disjoint, so concatenating is the right pooling + seeds_in = list(res["seeds"]) + if len(seeds_in) > 1: + cat = {k: np.concatenate(v) for k, v in pooled.items() if len(v) == len(seeds_in)} + base, D = cat[CELL[CONTROL]], len(cat[CELL[CONTROL]]) + idx = rng.integers(0, D, (NBOOT, D)) + blk = {} + for k, v in cat.items(): + d = v - base + lo, hi = np.percentile(d[idx].mean(axis=1), [2.5, 97.5]) + blk[k] = {"oracle_rank_pct_mean": float(v.mean()), "delta_vs_permuted": float(d.mean()), + "ci95": [float(lo), float(hi)], "beats_control": bool(lo > 0.0)} + ncand = {res["seeds"][k]["n_candidates"] for k in seeds_in} + res["combined"] = {"seeds": seeds_in, "n_decisions": int(D), + # pooling only makes sense at a common N; assert rather than average it away + "n_candidates": int(ncand.pop()) if len(ncand) == 1 else None, + "reference": {"oracle": 1.0}, "heads": blk} + print(f"[screen] combined over {seeds_in}: {D} decisions") + for k, v in sorted(blk.items(), key=lambda x: -x[1]["oracle_rank_pct_mean"]): + print(" %-14s %.4f d=%+.4f [%+.4f, %+.4f]%s" % ( + k, v["oracle_rank_pct_mean"], v["delta_vs_permuted"], *v["ci95"], + " BEATS CONTROL" if v["beats_control"] else "")) + else: + print("[screen] only one proposer seed present -- no combined block " + "(the decision rule needs BOTH seeds)") + + res["screen_tag"] = SCREEN_TAG + res["screen_dirs"] = {k: str(v) for k, v in RUNS.items()} + (ST / "REWARD_SCREEN.json").write_text(json.dumps(res, indent=1) + "\n") + print(f"[screen] wrote {ST/'REWARD_SCREEN.json'}") + + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/real/build_reward_study2.py b/rsm_rise/scripts/real/build_reward_study2.py new file mode 100644 index 0000000000000000000000000000000000000000..654e1becaadc07d518d2fa01875745685011e48d --- /dev/null +++ b/rsm_rise/scripts/real/build_reward_study2.py @@ -0,0 +1,199 @@ +#!/usr/bin/env python +"""LaTeX tables + JSON for the FINE-TUNED reward-head study (gen_q #261). + +Sources, all named in the PDF: + status/real/GOAL_REWARD.json label counts v0..v3 (make_goal_reward.py) + status/real/SUCCESS_TAIL.json label counts v4 (make_v4_reward.py) + runs/real_cooking_v5/rsm/R_M_ft_v*/history.json reward-head calibration at step 110000 + status/real/stitch_multihop_R_M_ft_v*.json stitch control + reward head on rolled-out states + status/real/openloop_FT_*/scorer_openloop.json+.npz open-loop screen on identical candidates +Writes docs/tex/_reward_tables2.tex and status/real/REWARD_FT_NUMBERS.json. +""" +import json, glob, os +from pathlib import Path +import numpy as np + +ROOT = Path("/proj/dmfexp/zwhong/rsm_rise") +RUNS = ROOT / "runs/real_cooking_v5/rsm" +ST = ROOT / "status/real" +VERS = ["v0", "v1", "v2", "v3"] +SEEDS = ["", "_s1"] +LBL = {"v0": "v0 provenance", "v1": "v1 goal transition", "v2": "v2 arrival", "v3": "v3 final segment"} +RULE = { + "v0": "+1 on EVERY frame of a successful episode, 0 on every frame of a failed one", + "v1": "+1 on every frame of the last run heading into state 4 (the whole 3->4 segment: approach, pour, pan return)", + "v2": "+1 only on the single frame where the operator declares state 4 (the last frame of the episode)", + "v3": "+1 on the final segment of EVERY episode, successful or not", +} +NPY = {"v0": "reward_v0_provenance.f32.npy", "v1": "reward_v1_goaltrans.f32.npy", + "v2": "reward_v2_arrival.f32.npy", "v3": "reward_v3_finalseg.f32.npy"} +KEY = {"v0": "v0_provenance_dense", "v1": "v1_goal_transition", "v2": "v2_arrival_only", + "v3": "v3_final_segment_all_episodes"} +OUT = {} + + +def esc(s): + return str(s).replace("_", r"\_").replace("%", r"\%").replace("->", r"$\to$") + + +G = json.load(open(ST / "GOAL_REWARD.json")); by = {v["name"]: v for v in G["versions"]} +T4 = json.load(open(ST / "SUCCESS_TAIL.json")) +OUT["labels"] = {v: by[KEY[v]] for v in VERS}; OUT["v4_success_tail"] = T4 +L = [] + +# ---------- 1. the reward table: one row per variant, plain words + counts -------------------- +L.append(r"\begin{table}[htbp]\centering\footnotesize") +L.append(r"\caption{\textbf{The reward rule, in one sentence per variant.} Counts over the whole cache " + r"(181{,}530 frames / 248 episodes, of which 50 succeed). \texttt{status/real/GOAL\_REWARD.json}; " + r"v4 in \texttt{status/real/SUCCESS\_TAIL.json}.}\label{tab:rewardrule}") +L.append(r"\begin{tabular}{p{0.10\linewidth}p{0.52\linewidth}rrr}\toprule") +L.append(r"variant & which frames are $+1$ & $+1$ frames & \% & eps.\ with a $+1$ \\\midrule") +for v in VERS: + d = by[KEY[v]] + L.append(f"{esc(LBL[v])} & {esc(RULE[v])} & {d['pos_frames']} & {100*d['frac_frames']:.3f} & " + f"{d['episodes_with_any_positive']}/248 \\\\") +L.append(r"v4 success tail & $+1$ from the success marker to the end of a successful episode " + r"--- \emph{identically equal to v2 here}: the marker IS the last frame in all 50 " + r"(\texttt{SUCCESS\_TAIL.json}, tail $=1$ frame for every episode) & " + f"{T4['v4']['pos_frames']} & {100*T4['v4']['frac_frames']:.3f} & " + f"{T4['v4']['episodes_with_any_positive']}/248 \\\\") +L.append(r"\bottomrule\end{tabular}\end{table}") + +# ---------- 2. reward-head calibration after the fine-tune ------------------------------------ +cal = {} +for v in VERS: + for s in SEEDS: + p = RUNS / f"R_M_ft_{v}{s}/history.json" + if p.exists(): + h = json.load(open(p))[-1] + cal[v + s] = {k: h.get(k) for k in + ("step", "rhead_auc_val", "rhead_auc_train", "rhead_mae_val", + "rhead_pred_mean_pos_val", "rhead_pred_mean_neg_val", + "rhead_pos_rate_val", "cfm_val", "nnl1_ratio_val", + "nnl1_ratio_vs_stay_val", "q_success_auc")} + cal[v + s]["success_auc"] = h["per_task"]["0"]["success_auc"] +OUT["calibration"] = cal +L.append(r"\begin{table}[htbp]\centering\footnotesize") +L.append(r"\caption{\textbf{Reward head after the 10k-step warm-start fine-tune} (step 110000; " + r"\texttt{runs/real\_cooking\_v5/rsm/R\_M\_ft\_[\_s1]/history.json}, last entry). " + r"\emph{AUC} = held-out separation of $+1$ from $0$ frames by $R(z)$; \emph{pos}/\emph{neg} are its " + r"mean predictions on those two sets; \emph{succ AUC} is the value's separation of successful from " + r"failed episodes --- 1.000 for v0 only because v0's label IS episode success.}\label{tab:rheadcal}") +L.append(r"\begin{tabular}{lrrrrrr}\toprule") +L.append(r"cell & $R$ AUC (val) & $R$ MAE & mean $R$ on $+1$ & mean $R$ on $0$ & succ AUC & CFM val \\\midrule") +for v in VERS: + for s in SEEDS: + k = v + s + if k not in cal: + continue + c = cal[k] + L.append(f"R\\_M\\_ft\\_{esc(v+s)} & {c['rhead_auc_val']:.4f} & {c['rhead_mae_val']:.4f} & " + f"{c['rhead_pred_mean_pos_val']:.4f} & {c['rhead_pred_mean_neg_val']:.4f} & " + f"{c['success_auc']:.4f} & {c['cfm_val']:.4f} \\\\") +L.append(r"\bottomrule\end{tabular}\end{table}") + +# ---------- 3. stitch control + reward head on rolled-out states ------------------------------ +sti = {} +for v in VERS: + for s in SEEDS: + p = ST / f"stitch_multihop_R_M_ft_{v}{s}.json" + if p.exists(): + d = json.load(open(p)) + h1 = d["multihop"][0] + sti[v + s] = {"ratio_median": d["splice"]["ratio_median"], + "route1_control_median": d["splice"]["route1_control_median"], + "jump_median": d["splice"]["jump_median"], + "own_future": h1["own_future"], "goal_region": h1["goal_region"], + "random_pool": h1["random_pool"], "rhead_mean": h1["rhead_mean"], + "rhead_logit_mean": h1["rhead_logit_mean"], + "rhead_logit_sat_frac": h1["rhead_logit_sat_frac"]} +OUT["stitch"] = sti +if sti: + L.append(r"\begin{table}[htbp]\centering\footnotesize") + L.append(r"\caption{\textbf{Stitch control and the reward head on rolled-out states} " + r"(\texttt{scripts/real/stitch\_multihop.py} $\to$ " + r"\texttt{status/real/stitch\_multihop\_R\_M\_ft\_.json}). \emph{ratio} = splice jump / one-hop " + r"motion at the cross-trajectory splice; its control is the same measurement inside a single " + r"route (\texttt{route1\_control\_median}, $\approx 1$ means the splice is not special. " + r"Columns 4--6 are one 100-frame hop from held-out states: distance to the model's own future, " + r"to the goal region, and to a random pool. \emph{sat} = fraction of rolled-out states on which " + r"the reward logit is saturated.}\label{tab:stitchft}") + L.append(r"\begin{tabular}{lrrrrrrr}\toprule") + L.append(r"cell & ratio & control & own fut. & goal reg. & rand.\ pool & mean $R$ & sat \\\midrule") + for k, c in sti.items(): + L.append(f"R\\_M\\_ft\\_{esc(k)} & {c['ratio_median']:.4f} & {c['route1_control_median']:.4f} & " + f"{c['own_future']:.3f} & {c['goal_region']:.3f} & {c['random_pool']:.3f} & " + f"{c['rhead_mean']:.2e} & {c['rhead_logit_sat_frac']:.2f} \\\\") + L.append(r"\bottomrule\end{tabular}\end{table}") + +# ---------- 4. the open-loop screen (RISE recipe) --------------------------------------------- +OL = [] +for tag, pretty in [("FT_S0Aidql_s0_e2000_d1_T25", "S0Aidql seed 0 @ epoch 2000"), + ("FT_S0Aidql_s1_e2500_d1_T25", "S0Aidql seed 1 @ epoch 2500")]: + p = ST / f"openloop_{tag}/scorer_openloop.json" + if p.exists(): + OL.append((tag, pretty, json.load(open(p)), ST / f"openloop_{tag}/scores.npz")) +OUT["openloop"] = {} +ORDER = ["greedy", "idql", "permuted:idql", "rsm", "permuted:rsm"] + \ + [f"rsm@ft_{v}{s}" for v in VERS for s in SEEDS] + ["oracle"] +PRETTY = {"greedy": "greedy (plain sample)", "idql": "IDQL critic", + "permuted:idql": "\\quad permuted control", "rsm": "RSM flagship R\\_M (100k, v0 labels)", + "permuted:rsm": "\\quad permuted control", "oracle": "oracle (best of the 128)"} +for v in VERS: + for s in SEEDS: + PRETTY[f"rsm@ft_{v}{s}"] = f"RSM ft {esc(v+s)}" +for tag, pretty, d, npz in OL: + sc = d["scorers"] + # paired per-decision comparison against the v0 fine-tune control + paired = {} + if npz.exists(): + z = np.load(npz, allow_pickle=True) + err = z["err_first"] # (n_dec, n_cand) cm + def pick(name): + key = "score_" + name.replace(":", "_") + return err[np.arange(err.shape[0]), z[key].argmax(1)] if key in z.files else None + base = pick("rsm@ft_v0") + for k in sc: + if k == "oracle": + continue + e = pick(k) if k != "greedy" else err[:, 0] + if e is None or base is None: + continue + dd = e - base + paired[k] = {"mean_cm": float(e.mean()), "delta_vs_ftv0_cm": float(dd.mean()), + "se_cm": float(dd.std(ddof=1) / np.sqrt(len(dd))), + "win_vs_ftv0": float((e < base).mean()), "n": int(len(dd))} + OUT["openloop"][tag] = {"n_episodes": d["n_episodes"], "n_decisions": d["n_decisions"], + "valid_for_results": d["valid_for_results"], "scorers": sc, "paired": paired} + L.append(r"\begin{table}[htbp]\centering\footnotesize") + L.append(r"\caption{\textbf{Open-loop best-of-128 screen, " + esc(pretty) + r"} " + r"(\texttt{scripts/real/scorer\_openloop.py}, N=128 diffusion candidates, argmax, prob read-out, " + r"$T{=}25$, d1, $\beta{=}0.99$; " + f"{d['n_episodes']} held-out episodes, {d['n_decisions']} decisions" + r"). Every scorer ranks the SAME 128 candidates at the SAME state, so the comparison is paired. " + r"\emph{first} = cm between the chosen first action and the logged expert action (lower is closer " + r"to the demonstrator); \emph{$\Delta$ vs ft\_v0} is the paired mean difference $\pm$ s.e.; " + r"\emph{rank} is the chosen candidate's percentile in the oracle ordering (0.5 = chance). Source: " + r"\texttt{status/real/openloop\_" + esc(tag) + r"/}.}\label{tab:ol" + tag.replace("_", "") + "}") + L.append(r"\begin{tabular}{lrrrrr}\toprule") + L.append(r"scorer & first (cm) & $\Delta$ vs ft\_v0 (cm) & win vs ft\_v0 & win vs greedy & rank pct \\\midrule") + for k in ORDER: + if k not in sc: + continue + v_ = sc[k]; p_ = paired.get(k) + dcol = f"{p_['delta_vs_ftv0_cm']:+.4f} $\\pm$ {p_['se_cm']:.4f}" if p_ else "---" + wcol = f"{p_['win_vs_ftv0']:.3f}" if p_ else "---" + L.append(f"{PRETTY.get(k, esc(k))} & {v_['first_mean_cm']:.4f} & {dcol} & {wcol} & " + f"{v_['win_rate_vs_greedy']:.3f} & {v_['oracle_rank_pct_mean']:.4f} \\\\") + if k == "permuted:rsm": + L.append(r"\midrule") + L.append(r"\bottomrule\end{tabular}\end{table}") + +Path(ROOT / "docs/tex/_reward_tables2.tex").write_text("\n".join(L) + "\n") +(ST / "REWARD_FT_NUMBERS.json").write_text(json.dumps(OUT, indent=2, default=float)) +print("[rw2] wrote docs/tex/_reward_tables2.tex", len(L), "lines; open-loop tags:", [t for t, _, _, _ in OL]) +for tag in OUT["openloop"]: + pr = OUT["openloop"][tag]["paired"] + for k in ORDER: + if k in pr: + print(f" {tag} {k:20s} mean={pr[k]['mean_cm']:.4f} d_vs_ftv0={pr[k]['delta_vs_ftv0_cm']:+.4f}" + f" +-{pr[k]['se_cm']:.4f} win={pr[k]['win_vs_ftv0']:.3f}") diff --git a/rsm_rise/scripts/real/build_reward_study_pdf.sh b/rsm_rise/scripts/real/build_reward_study_pdf.sh new file mode 100644 index 0000000000000000000000000000000000000000..46ada059a101051bc3bbfbb9c0c70d2a6e7c203a --- /dev/null +++ b/rsm_rise/scripts/real/build_reward_study_pdf.sh @@ -0,0 +1,28 @@ +#!/usr/bin/env bash +# Compile ONLY docs/tex/real_reward_study.tex -> docs/real_reward_study.pdf (gen_q #271). +# real_successor_report.tex is owned by the REAL_SUCCESSOR worker and is deliberately NOT built here. +set -uo pipefail +ROOT=/proj/dmfexp/zwhong/rsm_rise +cd "$ROOT" || exit 1 +"$ROOT/venv_rsm/bin/python" "$ROOT/scripts/real/build_scheme271_tables.py" || exit 3 +# the open-loop-screen table is regenerated from REWARD_SCREEN.json at every build, so the numbers +# in the PDF can never drift from the JSON the screen wrote. +"$ROOT/venv_rsm/bin/python" "$ROOT/scripts/real/build_screen271_table.py" || exit 3 +# likewise the stitching-number table (diagnostic 3), from STITCH_SIGNIFICANCE.json +"$ROOT/venv_rsm/bin/python" "$ROOT/scripts/real/build_stitch271_table.py" || exit 3 +# the reader-reproducibility paragraph (audit check J); refuses unless J passed exactly +"$ROOT/venv_rsm/bin/python" "$ROOT/scripts/real/build_reader271_tex.py" || exit 3 +for s in build_reward_tables build_reward_study2 build_decisive_tables; do + [ -f "$ROOT/scripts/real/$s.py" ] && "$ROOT/venv_rsm/bin/python" "$ROOT/scripts/real/$s.py" +done +D=$ROOT/docs/tex/_rwbuild; rm -rf "$D"; mkdir -p "$D/figs/real_stages" +cp docs/tex/real_reward_study.tex docs/tex/_*.tex "$D"/ 2>/dev/null +cp docs/figs/real_stages/*.png "$D/figs/real_stages"/ 2>/dev/null +(cd "$D" && tectonic real_reward_study.tex > build.out 2>&1); r=$? +grep -E "^error" "$D/build.out" | head -10 +if [ -f "$D/real_reward_study.pdf" ]; then + cp "$D/real_reward_study.pdf" "$ROOT/docs/real_reward_study.pdf" + echo "PDF written: $ROOT/docs/real_reward_study.pdf ($(stat -c%s "$ROOT/docs/real_reward_study.pdf") bytes, rc=$r)" +else + echo "NO PDF (rc=$r)"; tail -40 "$D/build.out"; exit 1 +fi diff --git a/rsm_rise/scripts/real/build_reward_tables.py b/rsm_rise/scripts/real/build_reward_tables.py new file mode 100644 index 0000000000000000000000000000000000000000..8144ac312bf4b22a362312ca6541ead7d81e3501 --- /dev/null +++ b/rsm_rise/scripts/real/build_reward_tables.py @@ -0,0 +1,276 @@ +#!/usr/bin/env python +"""LaTeX fragments for the reward-head study (gen_q #261): docs/tex/_reward_tables.tex. + +Sources: status/real/GOAL_REWARD.json (label counts, written by scripts/real/make_goal_reward.py), +runs/real_cooking_v5/rsm/R_RW_v*/{ckpt.pt,history.json} (training + health), +status/real/stitch_multihop_R_RW_v*.json (chaining control), +status/real/openloop_RW_*/scorer_openloop.json (open-loop selection on identical candidates). +""" +import json, glob +from pathlib import Path +import numpy as np + +ROOT = Path("/proj/dmfexp/zwhong/rsm_rise") +RUNS = ROOT / "runs/real_cooking_v5/rsm" +TEX = ROOT / "docs/tex/_reward_tables.tex" +VERS = [("R_RW_v0", "v0 provenance (dense)", "reward_v0_provenance.f32.npy"), + ("R_RW_v1", "v1 goal transition", "reward_v1_goaltrans.f32.npy"), + ("R_RW_v2", "v2 arrival only", "reward_v2_arrival.f32.npy"), + ("R_RW_v3", "v3 final segment (all eps)", "reward_v3_finalseg.f32.npy")] +NAME2KEY = {"R_RW_v0": "v0_provenance_dense", "R_RW_v1": "v1_goal_transition", + "R_RW_v2": "v2_arrival_only", "R_RW_v3": "v3_final_segment_all_episodes"} + + +def esc(s): + return str(s).replace("_", "\\_").replace("%", "\\%") + + +G = json.load(open(ROOT / "status/real/GOAL_REWARD.json")) +by = {v["name"]: v for v in G["versions"]} +L = [] + +# ---- label counts ------------------------------------------------------------------------- +L.append(r"\begin{table}[htbp]\centering\small") +L.append(r"\caption{The four reward labels, counted on \texttt{cache/real\_cooking\_v5} " + r"(181{,}530 frames, 248 episodes). \emph{train}/\emph{val} use the SAME split every cell " + r"trains on (\texttt{LiberoRSMData} seed 0, \texttt{val\_frac} 0.1, unstratified: 24 validation " + r"episodes, of which %d are rewarded). Source: \texttt{status/real/GOAL\_REWARD.json}, produced by " + r"\texttt{scripts/real/make\_goal\_reward.py}.}" % by["v0_provenance_dense"]["val_episodes_expert"]) +L.append(r"\label{tab:labels}") +L.append(r"\begin{tabular}{lrrrrrr}\toprule") +L.append(r"label & pos.\ frames & \% of frames & train & val & eps.\ with a pos. & of which suboptimal \\\midrule") +for cell, lbl, _ in VERS: + v = by[NAME2KEY[cell]] + L.append(f"{esc(lbl)} & {v['pos_frames']} & {100*v['frac_frames']:.3f} & {v['pos_frames_train']} & " + f"{v['pos_frames_val']} & {v['episodes_with_any_positive']}/248 & " + f"{v['episodes_with_any_positive_suboptimal']} \\\\") +L.append(r"\bottomrule\end{tabular}\end{table}") + +# ---- per-route breakdown ----------------------------------------------------------------- +L.append(r"\begin{table}[htbp]\centering\small") +L.append(r"\caption{Positive frames by route. Route 3 (\texttt{2->3->4}) is the ONLY route that reaches the " + r"goal state 4, and it is exactly the set of 50 episodes the cache marks \texttt{ep\_success}. " + r"Source: \texttt{status/real/GOAL\_REWARD.json}, \texttt{by\_route}.}") +L.append(r"\label{tab:byroute}") +routes = sorted(by["v0_provenance_dense"]["by_route"], key=int) +L.append(r"\begin{tabular}{lll" + "r" * len(VERS) + r"}\toprule") +L.append(r"route & path & eps & " + " & ".join(esc(l) for _, l, _ in VERS) + r" \\\midrule") +for rt in routes: + row = by["v0_provenance_dense"]["by_route"][rt] + cells = [] + for cell, _, _ in VERS: + b = by[NAME2KEY[cell]]["by_route"][rt] + cells.append(f"{b['pos_frames']}") + L.append(f"{rt} & \\texttt{{{esc(row['path'])}}} & {row['n_eps']} & " + " & ".join(cells) + r" \\") +L.append(r"\bottomrule\end{tabular}\end{table}") + +# ---- FINE-TUNED cells (run 2: the owner's correction -- finetune, do not retrain) --------- +# Every ft cell starts from the flagship successor's own step-100000 checkpoint (R_M for seed 0, +# R_M_s1 for seed 1), swaps in the new per-frame reward labels and runs 10k further steps at the +# checkpoint's final learning rate (3e-4; train_rsm.py has no LR schedule). Mechanics and the +# guard that stops a preempted cell rewinding: scripts/rr_rsm.sh, cells R_M_ft_v*. +FT = [("R_M_ft_v0", "v0 provenance (control)"), ("R_M_ft_v1", "v1 goal transition"), + ("R_M_ft_v2", "v2 arrival only"), ("R_M_ft_v3", "v3 final segment (all eps)"), + ("R_M_ft_v0_s1", "v0 provenance (control), seed 1"), ("R_M_ft_v1_s1", "v1 goal transition, seed 1"), + ("R_M_ft_v2_s1", "v2 arrival only, seed 1"), ("R_M_ft_v3_s1", "v3 final segment, seed 1")] +BASE = [("R_M", "flagship, provenance label (not fine-tuned)"), ("R_M_s1", "flagship seed 1 (not fine-tuned)")] + + +def read_cell(cell, label, stitch_prefix="stitch_multihop_"): + d = RUNS / cell + rec = {"cell": cell, "label": label, "step": None, "hist": {}, "ckpt": None} + ck = sorted(glob.glob(str(d / "ckpt_s*.pt")), key=lambda f: int(f.split("_s")[-1].split(".")[0])) + rec["ckpt"] = ck[-1] if ck else (str(d / "ckpt.pt") if (d / "ckpt.pt").exists() else None) + if (d / "history.json").exists(): + h = json.load(open(d / "history.json")) + if h: + rec["hist"] = h[-1]; rec["step"] = h[-1].get("step") + sm = ROOT / f"status/real/{stitch_prefix}{cell}.json" + rec["stitch"] = json.load(open(sm)) if sm.exists() else None + return rec + + +def health_table(rows, caption, label): + out = [r"\begin{table}[htbp]\centering\small", r"\caption{%s}" % caption, r"\label{%s}" % label, + r"\begin{tabular}{llrrrrrr}\toprule", + r"cell & label & step & r-auc val & r-mae val & pos rate & nnl1 ratio & vs stay \\\midrule"] + for r_ in rows: + h = r_["hist"] + def g(k, f="{:.4f}"): + v = h.get(k) + return f.format(v) if isinstance(v, (int, float)) and np.isfinite(v) else "---" + out.append(f"\\texttt{{{esc(r_['cell'])}}} & {esc(r_['label'])} & " + f"{r_['step'] if r_['step'] is not None else '---'} & {g('rhead_auc_val')} & " + f"{g('rhead_mae_val','{:.2e}')} & {g('rhead_pos_rate_val')} & {g('nnl1_ratio_val')} & " + f"{g('nnl1_ratio_vs_stay_val')} \\\\") + out.append(r"\bottomrule\end{tabular}\end{table}") + return out + + +def chain_table(rows, caption, label): + if not any(r_["stitch"] for r_ in rows): + return [] + out = [r"\begin{table}[htbp]\centering\small", r"\caption{%s}" % caption, r"\label{%s}" % label, + r"\begin{tabular}{lrrrrr}\toprule", + r"cell & splice ratio & rhead @1 hop & @2 & @4 & @8 \\\midrule"] + for r_ in rows: + s_ = r_["stitch"] + if not s_: + continue + mh = {int(x["hops"]): x for x in s_["multihop"]} + def rh(k): + return f"{mh[k]['rhead_mean']:.2e}" if k in mh else "---" + out.append(f"\\texttt{{{esc(r_['cell'])}}} & {s_['splice']['ratio_median']:.4f} & {rh(1)} & " + f"{rh(2)} & {rh(4)} & {rh(8)} \\\\") + out.append(r"\bottomrule\end{tabular}\end{table}") + return out + + +ft_rows = [read_cell(c, l) for c, l in FT if (RUNS / c).exists()] +base_rows = [read_cell(c, l) for c, l in BASE if (RUNS / c).exists()] +L += health_table(base_rows + ft_rows, + r"FINE-TUNED reward heads (the run-2 recipe) and the two un-fine-tuned flagship successors " + r"they start from. Each \texttt{R\_M\_ft\_v*} cell loads \texttt{R\_M}'s (resp.\ " + r"\texttt{R\_M\_s1}'s) step-100000 checkpoint -- weights, EMA target and optimiser state -- " + r"swaps in the new per-frame label and runs 10{,}000 further steps at the same learning rate " + r"($3\times10^{-4}$; \texttt{train\_rsm.py} has no LR schedule, so `the checkpoint's final " + r"learning rate' and `the training learning rate' are the same number). Seed is matched to the " + r"source cell, so the validation split is the source's. Numbers read from each cell's own " + r"\texttt{runs/real\_cooking\_v5/rsm//history.json}.", "tab:fthealth") +L += chain_table(ft_rows, + r"Chained-hop / stitch control re-measured on every fine-tuned checkpoint " + r"(\texttt{scripts/real/stitch\_multihop.py}, $\beta_{hi}{=}0.99$, hop $=100$ frames, 256 " + r"anchors). The reward changed, so this control cannot be inherited from \texttt{R\_M}. " + r"Sources: \texttt{status/real/stitch\_multihop\_R\_M\_ft\_*.json}.", "tab:ftchain") + +# ---- FINE-TUNED open-loop: all variants scored on ONE candidate set ------------------------ +olft = sorted(glob.glob(str(ROOT / "status/real/openloop_FT_*/scorer_openloop.json"))) +if olft: + L.append(r"\begin{table}[htbp]\centering\small") + L.append(r"\caption{Open-loop best-of-128 selection with the RISE recipe, fine-tuned reward heads. " + r"Every column in a block ranks the SAME 128 candidate chunks at the SAME state (one proposal " + r"pass per proposer; \texttt{scorer\_openloop.py --rsm-ckpt-extra}), so the comparison is paired " + r"decision by decision. Settings are exactly the flagship read-out of " + r"\texttt{status/real/openloop\_S0Aidql\_*}: $N{=}128$, argmax, prob read-out, $T{=}25$, mode d1 " + r"depth 1, $\beta{=}0.99$, 16 particles, stride 25, horizon 8, the 25 held-out episodes. " + r"\texttt{rsm} is the un-fine-tuned flagship \texttt{R\_M}, i.e. the tie-back control. Errors are " + r"the first-action xyz error in cm (lower is better); $\Delta$ is against greedy; \emph{rank pct} " + r"is where the pick lands in the oracle's ordering (0.5 = the sampling null). Sources: " + r"\texttt{status/real/openloop\_FT\_*/scorer\_openloop.json}.}") + L.append(r"\label{tab:ftopenloop}") + L.append(r"\begin{tabular}{llrrrr}\toprule") + L.append(r"proposer & scorer & first (cm) & $\Delta$ (cm) & win vs greedy & rank pct \\\midrule") + for f in olft: + d = json.load(open(f)) + order = ["greedy", "idql", "permuted:idql", "rsm", "permuted:rsm"] + \ + sorted(k for k in d["scorers"] if k.startswith("rsm@")) + ["oracle"] + first = True + for s_ in order: + v = d["scorers"].get(s_) + if not v: + continue + L.append(f"{esc(d['tag']) if first else ''} & {esc(s_)} & {v['first_mean_cm']:.4f} & " + f"{v['delta_vs_greedy_cm']:+.4f} & {v['win_rate_vs_greedy']:.3f} & " + f"{v['oracle_rank_pct_mean']:.3f} \\\\") + first = False + L.append(r"\midrule") + L[-1] = r"\bottomrule\end{tabular}\end{table}" +else: + L.append(r"\emph{The fine-tuned open-loop cells had not landed when this PDF was built; their job ids are " + r"in Sec.~\ref{sec:rwstatus}.}") + +# ---- training / health ------------------------------------------------------------------- +rows = [] +for cell, lbl, _ in VERS: + d = RUNS / cell + rec = {"cell": cell, "label": lbl, "step": None, "hist": {}, "ckpt": None} + ck = sorted(glob.glob(str(d / "ckpt_s*.pt")), key=lambda f: int(f.split("_s")[-1].split(".")[0])) + rec["ckpt"] = ck[-1] if ck else (str(d / "ckpt.pt") if (d / "ckpt.pt").exists() else None) + if (d / "history.json").exists(): + h = json.load(open(d / "history.json")) + if h: + rec["hist"] = h[-1]; rec["step"] = h[-1].get("step") + sm = ROOT / f"status/real/stitch_multihop_{cell}.json" + rec["stitch"] = json.load(open(sm)) if sm.exists() else None + rows.append(rec) + +L.append(r"\begin{table}[htbp]\centering\small") +L.append(r"\caption{FROM-SCRATCH control runs (\texttt{R\_RW\_v*}, 100k steps from random init). Health of each reward version at its last evaluated step, read from that cell's own " + r"\texttt{runs/real\_cooking\_v5/rsm/R\_RW\_v*/history.json}. Architecture, cache, optimiser, " + r"$\beta$ band, chunk, seed and step budget are identical to \texttt{R\_M}; ONLY the per-frame " + r"reward label differs. \texttt{pos rate} is the fraction of validation anchors the label marks " + r"positive, and is the denominator the AUC has to be read against.}") +L.append(r"\label{tab:rwhealth}") +L.append(r"\begin{tabular}{llrrrrrr}\toprule") +L.append(r"cell & label & step & r-auc val & r-mae val & pos rate & nnl1 ratio & vs stay \\\midrule") +for r_ in rows: + h = r_["hist"] + def g(k, f="{:.4f}"): + v = h.get(k) + return f.format(v) if isinstance(v, (int, float)) and np.isfinite(v) else "---" + L.append(f"\\texttt{{{esc(r_['cell'])}}} & {esc(r_['label'])} & " + f"{r_['step'] if r_['step'] is not None else '---'} & {g('rhead_auc_val')} & " + f"{g('rhead_mae_val','{:.2e}')} & {g('rhead_pos_rate_val')} & {g('nnl1_ratio_val')} & " + f"{g('nnl1_ratio_vs_stay_val')} \\\\") +L.append(r"\bottomrule\end{tabular}\end{table}") + +# ---- chaining control -------------------------------------------------------------------- +if any(r_["stitch"] for r_ in rows): + L.append(r"\begin{table}[htbp]\centering\small") + L.append(r"\caption{Chained-hop control per reward version (\texttt{scripts/real/stitch\_multihop.py}, " + r"$\beta_{hi}{=}0.99$, hop $=100$ frames, 256 anchors). \texttt{rhead} is the mean reward-head " + r"read-out at the end of the chain: under the provenance label it underflows within a few hops, " + r"which is what leaves a planner with no gradient. Sources: " + r"\texttt{status/real/stitch\_multihop\_R\_RW\_v*.json}.}") + L.append(r"\label{tab:rwchain}") + L.append(r"\begin{tabular}{lrrrrr}\toprule") + L.append(r"cell & splice ratio & rhead @1 hop & @2 & @4 & @8 \\\midrule") + for r_ in rows: + s = r_["stitch"] + if not s: + continue + mh = {int(x["hops"]): x for x in s["multihop"]} + def rh(k): + return f"{mh[k]['rhead_mean']:.2e}" if k in mh else "---" + L.append(f"\\texttt{{{esc(r_['cell'])}}} & {s['splice']['ratio_median']:.4f} & {rh(1)} & " + f"{rh(2)} & {rh(4)} & {rh(8)} \\\\") + L.append(r"\bottomrule\end{tabular}\end{table}") + +# ---- open loop --------------------------------------------------------------------------- +ol = sorted(glob.glob(str(ROOT / "status/real/openloop_RW_*/scorer_openloop.json"))) +if ol: + L.append(r"\begin{table}[htbp]\centering\small") + L.append(r"\caption{Open-loop selection, one row block per reward version, run with " + r"\texttt{scripts/real/scorer\_openloop.py} at the SAME proposer checkpoints, seed, stride, " + r"candidate count and read-out settings as the \texttt{R\_M} cells of the successor report, so " + r"the versions are compared on identical candidate sets. Errors in cm; $\Delta$ against greedy " + r"(negative = better). Sources: \texttt{status/real/openloop\_RW\_*/scorer\_openloop.json}.}") + L.append(r"\label{tab:rwopenloop}") + L.append(r"\begin{tabular}{llrrrr}\toprule") + L.append(r"cell & scorer & first (cm) & $\Delta$ (cm) & win vs greedy & rank pct \\\midrule") + for f in ol: + d = json.load(open(f)) + first = True + for s in ["greedy", "rsm", "permuted:rsm", "oracle"]: + v = d["scorers"].get(s) + if not v: + continue + L.append(f"{esc(d['tag']) if first else ''} & {esc(s)} & {v['first_mean_cm']:.4f} & " + f"{v['delta_vs_greedy_cm']:+.4f} & {v['win_rate_vs_greedy']:.3f} & " + f"{v['oracle_rank_pct_mean']:.3f} \\\\") + first = False + L.append(r"\midrule") + L[-1] = r"\bottomrule\end{tabular}\end{table}" +else: + L.append(r"\emph{The open-loop selection comparison had not landed when this PDF was built; the cells " + r"are listed in Sec.~\ref{sec:rwstatus}.}") + +TEX.write_text("\n".join(L) + "\n") +print("wrote", TEX) +json.dump({"rows": [{k: v for k, v in r_.items() if k != "stitch"} for r_ in rows], + "ft_rows": [{k: v for k, v in r_.items() if k != "stitch"} for r_ in ft_rows], + "base_rows": [{k: v for k, v in r_.items() if k != "stitch"} for r_ in base_rows], + "ft_openloop": {Path(f).parent.name: json.load(open(f))["scorers"] for f in olft}, + "labels": G["versions"]}, + open(ROOT / "status/real/REWARD_STUDY_NUMBERS.json", "w"), indent=2, default=str) +print("wrote", ROOT / "status/real/REWARD_STUDY_NUMBERS.json") diff --git a/rsm_rise/scripts/real/build_scheme271_tables.py b/rsm_rise/scripts/real/build_scheme271_tables.py new file mode 100644 index 0000000000000000000000000000000000000000..03d4ee3787d2719266de9560952cac089b259cc8 --- /dev/null +++ b/rsm_rise/scripts/real/build_scheme271_tables.py @@ -0,0 +1,69 @@ +#!/usr/bin/env python +"""Emit docs/tex/_scheme271.tex: the gen_q #271 scheme table (per-route positive counts) and, when the +diagnostics have run, the diagnostic-1/2 and stitching-number tables. Pure JSON -> LaTeX, no compute.""" +from __future__ import annotations +import json +from pathlib import Path + +ROOT = Path("/proj/dmfexp/zwhong/rsm_rise") +ST = ROOT / "status/real" +OUT = ROOT / "docs/tex/_scheme271.tex" + +# scheme key in REWARD_SCHEMES.json -> (row label, the formula, the cell that holds the trained head) +ROWS = [ + ("v0_shipped_final_eq_S4", r"$v_0^{\mathrm{ship}}$", r"$\mathbf{1}[f_i = S_4]$", r"\texttt{R\_M\_ft\_v0}"), + ("v0lit_final_in_S3_S4", r"$v_0$ (\#271)", r"$\mathbf{1}[f_i \in \{S_3,S_4\}]$", r"\texttt{R\_M\_ft\_v0lit}"), + ("A_to_eq_S4", r"\textbf{A} (default)", r"$\mathbf{1}[\mathrm{to}(t) = S_4]$", r"\texttt{R\_M\_ft\_v1}"), + ("B_window_H100", r"B, $H{=}100$", r"$\mathbf{1}[0 \le a_i - t \le 100]$", r"\texttt{R\_M\_ft\_B}"), + ("B_window_H400", r"B, $H{=}400$", r"$\mathbf{1}[0 \le a_i - t \le 400]$", r"\texttt{R\_M\_ft\_B400}"), + ("C_label_to_eq_S4", r"C (label)", r"$\mathbf{1}[\mathrm{to}(t) = S_4]$, weighted", r"\texttt{R\_M\_ft\_C3/C10}"), + ("C_literal_reached_state_eq_S4", r"C literal", r"$\mathbf{1}[k(t) = S_4]$", r"--- (degenerate)"), +] +ROUTES = ["0", "1", "2", "3", "4"] + + +def main(): + d = json.loads((ST / "REWARD_SCHEMES.json").read_text()) + by = {s["name"]: s for s in d["schemes"]} + L = [r"% generated by scripts/real/build_scheme271_tables.py -- do not edit", + r"\begin{table}[htbp]\centering\small", + r"\caption{\textbf{The \#271 reward schemes on the cached real corpus} " + r"(\texttt{cache/real\_cooking\_v5}, %d frames, %d episodes). Every column is a count of " + r"\emph{positive frames}; a scheme whose positive set is empty, or covers a whole route, is a " + r"labelling bug. All five routes are shown, identified by their state path. " + r"$f_i$ is episode $i$'s final state, $\mathrm{to}(t)$ the state the segment containing frame $t$ " + r"leads into, $k(t)$ the operator's arrival marker, $a_i$ the frame at which $S_4$ is reached. " + r"Built by \texttt{scripts/real/make\_goal\_reward.py}; counts in " + r"\texttt{status/real/REWARD\_SCHEMES.json}.}\label{tab:scheme271}" % (d["n_frames"], d["n_episodes"]), + r"\begin{tabular}{llrrrrrrr}\toprule", + r"scheme & $r_t$ & total & \%\ & " + + " & ".join(r"\texttt{%s}" % d["schemes"][0]["by_route"][k]["path"].replace(">", r"$>$") for k in ROUTES) + + r" \\", + r" & & pos. & frames & " + " & ".join("R%s" % k for k in ROUTES) + r" \\\midrule"] + for key, name, form, cell in ROWS: + s = by.get(key) + if s is None: + continue + L.append("%s & %s & %s & %.2f & %s \\\\" % ( + name, form, "{:,}".format(s["pos_frames"]).replace(",", r"\,"), 100 * s["frac_frames"], + " & ".join("{:,}".format(s["by_route"][k]["pos_frames"]).replace(",", r"\,") for k in ROUTES))) + L += [r"\bottomrule\end{tabular}", r"\end{table}", ""] + + # scheme C's hard negatives + L += [r"\paragraph{Scheme C's weights.} %d frames carry the up-weight $w_{\mathrm{neg}}$ " + r"(label $0$, weight $w_{\mathrm{neg}} \in \{3,10\}$); all other frames carry weight $1$. " + r"By route: %s. The literal $\mathbf{1}[k(t)=S_4]$ has only %d positive frames and %d hard " + r"negatives, because \texttt{reached\_state\_id} is a \emph{sparse one-frame arrival marker} " + r"($-1$ on %d of %d frames), not a per-frame state label." % ( + d["C_hard_negative_frames"], + ", ".join("R%s: %s" % (k, "{:,}".format(v).replace(",", r"\,")) + for k, v in sorted(d["C_hard_negative_frames_by_route"].items()) if v), + d["C_literal_marker_positive_frames"], d["C_literal_hard_negative_frames"], + d["reached_state_id_unlabelled_frames"], d["n_frames"]), ""] + + OUT.write_text("\n".join(L)) + print(f"wrote {OUT} ({len(L)} lines)") + + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/real/build_screen271_table.py b/rsm_rise/scripts/real/build_screen271_table.py new file mode 100644 index 0000000000000000000000000000000000000000..70e2d986db0e62ff83d5ad85b20e342037e29ae3 --- /dev/null +++ b/rsm_rise/scripts/real/build_screen271_table.py @@ -0,0 +1,199 @@ +#!/usr/bin/env python3 +"""Emit docs/tex/_screen271.tex -- the #271 open-loop screen as a LaTeX table. + +Reads status/real/REWARD_SCREEN.json (written by build_reward_screen.py: the paired delta of every +head's oracle_rank_pct against the permuted control, with a bootstrap CI over decisions). One row per +head, sorted by the statistic, so the table cannot silently disagree with the JSON it came from. +""" +import json +from pathlib import Path + +ROOT = Path("/proj/dmfexp/zwhong/rsm_rise") +D = json.loads((ROOT / "status/real/REWARD_SCREEN.json").read_text()) + +# display name -> what the head IS, in the #271 scheme words +LABEL = { + "idql": r"\texttt{idql} (the proposer's own critic)", + "permuted:idql": r"\texttt{permuted:idql} (control for it)", + "base_R_M": r"base successor $R_M$, no fine-tune", + "permuted:rsm": r"\textbf{\texttt{permuted:rsm} --- the control}", + "v0": r"$v_0$ provenance, as shipped", "v0_s1": r"$v_0$ provenance, seed 1", + "v0lit": r"$v_0$ as written in \#271", "v0lit_s1": r"$v_0$ as written in \#271, seed 1", + "A": r"\textbf{A (the default)}", "A_s1": r"\textbf{A}, seed 1", + "B": r"\textbf{B}, $H=100$", "B_s1": r"\textbf{B}, $H=100$, seed 1", + "B400": r"\textbf{B}, $H=400$", "B400_s1": r"\textbf{B}, $H=400$, seed 1", + "C3": r"\textbf{C}, $w_{\mathrm{neg}}=3$", "C3_s1": r"\textbf{C}, $w_{\mathrm{neg}}=3$, seed 1", + "C10": r"\textbf{C}, $w_{\mathrm{neg}}=10$", "C10_s1": r"\textbf{C}, $w_{\mathrm{neg}}=10$, seed 1", + "v2": r"$v_2$ arrival-only (earlier round)", "v2_s1": r"$v_2$ arrival-only, seed 1", + "v3": r"$v_3$ final segment of every episode", "v3_s1": r"$v_3$ final segment, seed 1", +} + +# `combined` is a TOP-LEVEL block in REWARD_SCREEN.json, not an entry of `seeds`; looking for it +# inside `seeds` silently dropped the pooled table from the PDF. +D["seeds"] = dict(D["seeds"]) +if "combined" in D: + D["seeds"]["combined"] = D["combined"] +seeds = [k for k in ("combined", "s0", "s1") if k in D["seeds"]] +out = [] +for sk in seeds: + sv = D["seeds"][sk] + rows = sorted(sv["heads"].items(), key=lambda kv: -kv[1]["oracle_rank_pct_mean"]) + which = ("both proposer seeds pooled" if sk == "combined" + else r"proposer seed %s" % sk[1:]) + out.append(r"\begin{table}[htbp]\centering\small") + out.append(r"\caption{\textbf{The \#271 open-loop screen, %s.} %d held-out decisions $\times$ %d " + r"candidates drawn from the \texttt{S0Aidql} proposer. Every head scores the " + r"\emph{identical} candidate set, so each $\Delta$ against the control is paired decision " + r"by decision; the interval is a %d-resample bootstrap over decisions. The statistic is " + r"\texttt{oracle\_rank\_pct}: the fraction of the %d candidates the head's argmax beats on " + r"first-step error, so $0.5$ is chance. An $\ast$ marks a CI that excludes the control.}" + % (which, sv["n_decisions"], sv["n_candidates"], D["n_bootstrap"], sv["n_candidates"])) + out.append(r"\label{tab:screen271%s}" % sk) + out.append(r"\begin{tabular}{lccc}\toprule") + out.append(r"head & \texttt{oracle\_rank\_pct} & $\Delta$ vs.\ control & 95\,\% CI \\\midrule") + for name, v in rows: + lo, hi = v["ci95"] + mark = r"$^{\ast}$" if v["beats_control"] else "" + if name == "permuted:rsm": + out.append(r"%s & %.3f & $0$ by construction & --- \\" % (LABEL.get(name, name), v["oracle_rank_pct_mean"])) + else: + out.append(r"%s & %.3f & $%+.3f$%s & $[%+.3f, %+.3f]$ \\" + % (LABEL.get(name, name.replace("_", r"\_")), v["oracle_rank_pct_mean"], + v["delta_vs_permuted"], mark, lo, hi)) + out.append(r"\bottomrule\end{tabular}\end{table}") + out.append("") + +# The non-replication paragraph is GENERATED, not prose: run 5's hand-written version quoted +# seed-0 numbers that went stale the moment the screen was rerun on the hardened resolvers. +def _fmt(h, k): + v = h.get(k) + return None if v is None else (v["oracle_rank_pct_mean"], v["delta_vs_permuted"], v["ci95"]) + + +_s0 = D["seeds"].get("s0", {}).get("heads", {}) +_s1 = D["seeds"].get("s1", {}).get("heads", {}) +_comb = D.get("combined", {}) +if _s0 and _s1: + _win = sorted((k for k, v in _s0.items() if v.get("beats_control") + and k not in ("oracle", "idql", "permuted:idql", "permuted:rsm")), + key=lambda k: -_s0[k]["oracle_rank_pct_mean"]) + _ctl0 = _s0["permuted:rsm"]["oracle_rank_pct_mean"] + _ctl1 = _s1["permuted:rsm"]["oracle_rank_pct_mean"] + _pieces = [] + if _win: + _pieces.append("of the \\#271 schemes only the arrival window $B$ ranked above the control (" + + "; ".join(r"\texttt{%s} $%.3f$, $%+.3f$, $[%+.3f,%+.3f]$" + % (w.replace("_", r"\_"), *_fmt(_s0, w)[:2], *_fmt(_s0, w)[2]) + for w in _win) + ")") + else: + _pieces.append("no head cleared the control") + for _nm, _lbl in (("A", "the declared default $A$"), ("v0", "the shipped $v_0$")): + if _nm in _s0: + _pieces.append(r"%s read $%.3f$ ($%+.3f$)" % (_lbl, _s0[_nm]["oracle_rank_pct_mean"], + _s0[_nm]["delta_vs_permuted"])) + _idq0 = _s0.get("idql", {}).get("oracle_rank_pct_mean") + _idq1 = _s1.get("idql", {}).get("oracle_rank_pct_mean") + _nulls = [h[k]["oracle_rank_pct_mean"] for h in (_s0, _s1) + for k in ("permuted:rsm", "permuted:idql") if k in h] + _nulls += [D["seeds"][k]["reference"]["greedy"] for k in ("s0", "s1") + if "greedy" in D["seeds"].get(k, {}).get("reference", {})] + _nlo, _nhi = min(_nulls), max(_nulls) + _nbeat = [k for k, v in (_comb.get("heads") or {}).items() if v.get("beats_control") + and k != "permuted:rsm"] + out.append(r"\newcommand{\screenProse}{%") + out.append(r"On proposer seed 0, against a control at $%.3f$, " % _ctl0 + "; ".join(_pieces) + ". " + + (r"On proposer seed 1 nothing clears, and the informative row is not a reward head at " + r"all: the \texttt{idql} critic---the RISE recipe's own scorer, trained independently " + r"of any of this---falls to $%.3f$ against that seed's control at $%.3f$, having read " + r"$%.3f$ on seed 0. " % (_idq1, _ctl1, _idq0) if _idq0 and _idq1 else "") + + (r"All three nulls---both permutation columns and \texttt{greedy}---stay inside " + r"$[%.3f, %.3f]$ across both seeds, exactly where a null belongs. " % (_nlo, _nhi)) + + r"So on seed 1 \emph{every learned scorer} is " + r"anti-correlated with the oracle and \emph{no} null is, which is a statement about the " + r"screen, not about the labels: the seed-1 proposer's candidate cloud is tighter " + r"($0.217$\,cm versus $0.256$\,cm spread) and its oracle-best candidate is already " + r"essentially on the expert action ($0.111$\,cm versus $0.193$\,cm), so any learned " + r"preference for a \emph{distinctive} candidate carries you off it. " + + (r"Pooled over both seeds ($%d$ decisions) %s beats the control." + % (_comb.get("n_decisions", 0), + "no head and no critic" if not _nbeat else ", ".join(_nbeat) + " still") + if _comb else "")) + out.append(r"}") +else: + out.append(r"\newcommand{\screenProse}{}") +out.append("") + +# The replicate between two complete screen runs: the screen's real noise floor. The pair is read from +# the JSON (run 7 added a third run), never named here. It is emitted as a \newcommand rather than prose +# so the tex can place the sentence and the number can never drift. +_rp = ROOT / "status/real/SCREEN_REPRODUCIBILITY.json" +if _rp.exists(): + R = json.loads(_rp.read_text()) + out.append(r"\newcommand{\screenNoiseFloor}{%.3f}" % R["noise_floor_paired_delta_rms"]) + # The paragraph that INTERPRETS the noise floor is generated too: which pair is being quoted, how + # many heads it excludes, whether pairing against the control actually reduces the spread, and the + # largest head effect the screen ever reported are all measured quantities that can move. + _pd = max(v["paired_delta"]["rms"] for v in R["seeds"].values()) + _rw = max(v["raw"]["rms"] for v in R["seeds"].values()) + _big = max((abs(h.get("delta_vs_permuted", 0.0)) + for blk in D["seeds"].values() for h in blk["heads"].values()), default=0.0) + _ta, _tb = R["tags"] + _nex = len(R.get("excluded_weights_changed", [])) + _allt = R.get("available_tags") or list(R["tags"]) + out.append(r"\newcommand{\screenReproProse}{%") + out.append((r"The whole screen was run end to end %s---on the same held-out decisions and %s, with " + r"the proposer's $128$ candidates re-drawn. Table~\ref{tab:screen271repro} gives the " + r"movement between the two runs. The quoted paired $\Delta$ shifts by an rms of " + r"$\screenNoiseFloor$, and pairing against the control %s (raw level rms $%.3f$)%s. That " + r"noise floor is of the same order as the largest head effect this screen ever reported " + r"($%+.3f$), so the bootstrap intervals above---which hold the candidate draw " + r"fixed---are optimistic.") + % ((r"%d times; the replicate quoted here is the pair \texttt{%s} / \texttt{%s} " + % (len(_allt), _ta.replace("_", r"\_"), _tb.replace("_", r"\_"))) + if len(_allt) > 2 else + (r"twice, as \texttt{%s} and \texttt{%s} " % (_ta.replace("_", r"\_"), _tb.replace("_", r"\_"))), + (r"for every head but %d the same weights" % _nex) if _nex + else r"the same weights for every head", + r"barely reduces it" if _pd > 0.6 * _rw else r"does reduce it", + _rw, + r", because the two runs differ in \emph{which} candidates were offered rather than in a " + r"common difficulty offset" if _pd > 0.6 * _rw else "", + _big)) + out.append(r"}") + out.append(r"\newcommand{\screenReproTable}{%") + out.append(r"\begin{table}[htbp]\centering\small") + # The tags of the PAIR being quoted are generated, never written in: run 7 added a third complete + # screen run (RW271c) and made the primary pair the two most recent ones, so a literal tag list here + # would describe the wrong replicate. + _ta, _tb = R["tags"] + _nex = len(R.get("excluded_weights_changed", [])) + _exs = ("the %d head%s whose weights differed between the runs are excluded" + % (_nex, "" if _nex == 1 else "s")) if _nex else \ + "no head is excluded: the two runs share every head's weights, so only the candidate draw differs" + _allt = R.get("available_tags") or list(R["tags"]) + out.append(r"\caption{\textbf{What the screen can resolve.} The whole screen was run " + + (r"%d times; the replicate quoted here is the pair " % len(_allt) if len(_allt) > 2 + else r"twice ") + + r"(tags \texttt{%s}, \texttt{%s}) on the same held-out decisions and the same " + r"weights, with an \emph{independently re-drawn} candidate set --- a replicate of the " + r"measurement, not of the bootstrap. The paired $\Delta$ against the control moves " + r"between the two runs by the amounts below; %s.}" + % (_ta.replace("_", r"\_"), _tb.replace("_", r"\_"), _exs)) + out.append(r"\label{tab:screen271repro}") + out.append(r"\begin{tabular}{lcccc}\toprule") + out.append(r"proposer seed & heads & control level & raw rms (max) & paired $\Delta$ rms (max) \\\midrule") + for k, v in sorted(R["seeds"].items()): + out.append(r"%s & %d & $%.3f \rightarrow %.3f$ & %.3f (%.3f) & %.3f (%.3f) \\" + % (k, v["n_heads"], v["control_level"][R["tags"][0]], v["control_level"][R["tags"][1]], + v["raw"]["rms"], v["raw"]["max_abs"], + v["paired_delta"]["rms"], v["paired_delta"]["max_abs"])) + out.append(r"\bottomrule\end{tabular}\end{table}}") + out.append("") + print(" + reproducibility block, noise floor %.4f" % R["noise_floor_paired_delta_rms"]) +else: + out.append(r"\newcommand{\screenNoiseFloor}{n/a}") + out.append(r"\newcommand{\screenReproTable}{}") + out.append(r"\newcommand{\screenReproProse}{}") + +Path(ROOT / "docs/tex/_screen271.tex").write_text("\n".join(out)) +print("wrote docs/tex/_screen271.tex (%d seed blocks: %s)" % (len(seeds), ", ".join(seeds))) diff --git a/rsm_rise/scripts/real/build_sk_compare.py b/rsm_rise/scripts/real/build_sk_compare.py new file mode 100644 index 0000000000000000000000000000000000000000..35a85be3e7ac34cc1db1ebc8faa8cb72a6910df2 --- /dev/null +++ b/rsm_rise/scripts/real/build_sk_compare.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python +"""#271 run 12 -- compare the SCORING FUNCTIONALS on the stitching number, at a fixed draw. + +Run 11 left exactly one suspect standing. The endpoint class IS present at the chained latent +(C10_s1 reads it at per-anchor AUC 0.941, means 0.676 GOAL vs 0.052 FAIL) and the read-out's HORIZON +is not why Q loses it (fold-4 vs depth-1 moves the statistic by 0.0028 rms, under the ~0.005 GPU +noise; within-anchor corr 0.977). What remains between R(z_h) and Q is the functional that +compresses R over 16 particles into one ranking scalar. + +This reads the per-cell STITCH_DECOMP-format JSONs and writes ONE comparison JSON. The cells share +the anchors, the candidate draw, the chains and the GOAL/FAIL labels -- `endpoint_match_vs_published` +is reported per cell and must be 1.000 in all of them, or the comparison is not controlled and the +script says so. Everything downstream (PDF, CHECKPOINTS, PR, card) is generated from this file. + +usage: build_sk_compare.py --cell