rsm_rise code snapshot (HF_PUSH_ALL) (part 7)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- rsm_rise/scripts/real/_patch_gate_run28.pyAdded+118
- rsm_rise/scripts/real/_pr1_271_run15.shAdded+5
- rsm_rise/scripts/real/_pr1_271_run18.shAdded+9
- rsm_rise/scripts/real/_pr1_271_run21.shAdded+9
- rsm_rise/scripts/real/_px_wrappers/px_ordercost_run13.shAdded+3
- rsm_rise/scripts/real/_px_wrappers/px_ordercost_run14.shAdded+3
- rsm_rise/scripts/real/_px_wrappers/px_ordercost_run15.shAdded+3
- rsm_rise/scripts/real/_px_wrappers/px_qsweight.shAdded+6
- rsm_rise/scripts/real/_px_wrappers/px_setupenv_run13.shAdded+3
- rsm_rise/scripts/real/_px_wrappers/px_sixway_run13.shAdded+5
- rsm_rise/scripts/real/_px_wrappers/px_sixway_run14.shAdded+5
- rsm_rise/scripts/real/_px_wrappers/px_sixway_run15.shAdded+5
- rsm_rise/scripts/real/_px_wrappers/px_whichscorer_run14.shAdded+3
- rsm_rise/scripts/real/_run_actcond_spread_law.shAdded+6
- rsm_rise/scripts/real/_run_all31.shAdded+27
- rsm_rise/scripts/real/_run_clearance.shAdded+7
- rsm_rise/scripts/real/_run_lineage.shAdded+7
- rsm_rise/scripts/real/_run_red31b.shAdded+16
- rsm_rise/scripts/real/_run_red31post.shAdded+13
- rsm_rise/scripts/real/_run_rwprofile.shAdded+7
- rsm_rise/scripts/real/_run_shape.shAdded+7
- rsm_rise/scripts/real/_run_termaudit.shAdded+7
- rsm_rise/scripts/real/_sig_stride25.shAdded+10
- rsm_rise/scripts/real/_sig_stride25_matched.shAdded+12
- rsm_rise/scripts/real/_sk_compare.shAdded+14
- rsm_rise/scripts/real/_sk_logit_T25.shAdded+17
- rsm_rise/scripts/real/_sk_prob_T1.shAdded+17
- rsm_rise/scripts/real/_sk_prob_T100.shAdded+17
- rsm_rise/scripts/real/_sk_prob_log_T25.shAdded+17
- rsm_rise/scripts/real/_sk_smoke.shAdded+23
- rsm_rise/scripts/real/_sn_seed1.shAdded+11
- rsm_rise/scripts/real/_sn_seed2.shAdded+11
- rsm_rise/scripts/real/_sn_seed3.shAdded+11
- rsm_rise/scripts/real/_sn_seed4.shAdded+11
- rsm_rise/scripts/real/_srep.shAdded+5
- rsm_rise/scripts/real/_tmp/pr12_run16.shAdded+26
- rsm_rise/scripts/real/_tmp/pr12_run17.shAdded+28
- rsm_rise/scripts/real/_tmp/pr12_run18.shAdded+33
- rsm_rise/scripts/real/_tmp/pr12_run19.shAdded+42
- rsm_rise/scripts/real/absorption_probe.pyAdded+191
- rsm_rise/scripts/real/act_json_regress.pyAdded+52
- rsm_rise/scripts/real/act_mcpredict.pyAdded+286
- rsm_rise/scripts/real/act_mcstab_read.pyAdded+239
- rsm_rise/scripts/real/act_pickdist.pyAdded+356
- rsm_rise/scripts/real/act_referee.pyAdded+275
- rsm_rise/scripts/real/act_rescore_read.pyAdded+357
- rsm_rise/scripts/real/act_run21_primary.pyAdded+155
- rsm_rise/scripts/real/act_sensitivity.pyAdded+498
- rsm_rise/scripts/real/act_xpick_read.pyAdded+162
- rsm_rise/scripts/real/actcond_audit.pyAdded+339
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118#!/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, syssys.argv = ["rise_stack.run"]from rise_stack.run import mainfrom 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))PYPROVecho "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 ss = 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 ss = s.replace(old_sent, new_sent, 1)
assert "for step in range(1, 10):" in ss = s.replace("for step in range(1, 10):", "for step in range(1, 11):", 1)
open(p, "w").write(s)print("patched", p)12345#!/usr/bin/env bashset -uo pipefailcd /proj/dmfexp/zwhong/rsm_riseexec venv_rsm/bin/python scripts/real/build_pr1_271_run11.py \ status/real/pr1_body_live_run15.md status/real/pr1_body_run15_patched.md123456789#!/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 pipefailROOT=/proj/dmfexp/zwhong/rsm_risecd "$ROOT" || exit 1bash 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 3exec bash scripts/tmp/gh_patch_pr.sh jmarangola/rsm_real 1 status/real/pr1_body_run18_patched.md123456789#!/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 pipefailROOT=/proj/dmfexp/zwhong/rsm_risecd "$ROOT" || exit 1bash 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 3exec bash scripts/tmp/gh_patch_pr.sh jmarangola/rsm_real 1 status/real/pr1_body_run21_patched.md123#!/usr/bin/env bashexport SCRATCH=/proj/dmfexp/zwhong/scratch_patchexport/run18exec bash /proj/dmfexp/zwhong/rsm_rise/scripts/real/patchexport_order_cost.sh123#!/usr/bin/env bashexport SCRATCH=/proj/dmfexp/zwhong/scratch_patchexport/run20exec bash /proj/dmfexp/zwhong/rsm_rise/scripts/real/patchexport_order_cost.sh123#!/usr/bin/env bashexport SCRATCH=/proj/dmfexp/zwhong/scratch_patchexport/run22exec bash /proj/dmfexp/zwhong/rsm_rise/scripts/real/patchexport_order_cost.sh123456#!/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/run21export QS_PY=/proj/dmfexp/zwhong/rsm_rise/venv_rsm/bin/pythonexec bash /proj/dmfexp/zwhong/rsm_rise/scripts/real/patchexport_quickstart_weight.sh123#!/usr/bin/env bashexport SCRATCH=/proj/dmfexp/zwhong/scratch_patchexport/run19exec bash /proj/dmfexp/zwhong/rsm_rise/scripts/real/patchexport_setupenv_resolution.sh12345#!/usr/bin/env bashexport SCRATCH=/proj/dmfexp/zwhong/scratch_patchexport/run17export SC_REPO=originexport SC_REF=pull/11/headexec bash /proj/dmfexp/zwhong/rsm_rise/scripts/real/patchexport_sixway_gate.sh12345#!/usr/bin/env bashexport SCRATCH=/proj/dmfexp/zwhong/scratch_patchexport/run19export SC_REPO=originexport SC_REF=pull/11/headexec bash /proj/dmfexp/zwhong/rsm_rise/scripts/real/patchexport_sixway_gate.sh12345#!/usr/bin/env bashexport SCRATCH=/proj/dmfexp/zwhong/scratch_patchexport/run21export SC_REPO=originexport SC_REF=pull/11/headexec bash /proj/dmfexp/zwhong/rsm_rise/scripts/real/patchexport_sixway_gate.sh123#!/usr/bin/env bashexport SCRATCH=/proj/dmfexp/zwhong/scratch_patchexport/run23exec bash /proj/dmfexp/zwhong/rsm_rise/scripts/real/patchexport_whichscorer_resolution.sh123456#!/bin/bashset -euo pipefailcd /proj/dmfexp/zwhong/rsm_risesource wandb_env.sh >/dev/null 2>&1 || trueexec venv_rsm/bin/python scripts/real/actcond_spread_law.py \ --out /proj/dmfexp/zwhong/rsm_rise/status/real/ACT_COND/SPREAD_LAW_run37.json123456789101112131415161718192021222324252627#!/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 -ucd /proj/dmfexp/zwhong/rsm_riseexport MUJOCO_GL=disablePY=venv_rsm/bin/pythonO=status/real/stitch_readout_run31mkdir -p $Oecho "[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/*.errecho "[exit] 0 $(date -u)"1234567#!/bin/bashset -ucd /proj/dmfexp/zwhong/rsm_riseexport MUJOCO_GL=disableecho "[run_env] host=$(hostname) job=${LSB_JOBID:-none} $(date -u)"venv_rsm/bin/python scripts/real/stitch_clearance_tally.pyecho "[exit] $? $(date -u)"1234567#!/bin/bashset -ucd /proj/dmfexp/zwhong/rsm_riseexport MUJOCO_GL=disableecho "[run_env] host=$(hostname) job=${LSB_JOBID:-none} $(date -u)"venv_rsm/bin/python scripts/real/stitch_lineage_tally.pyecho "[exit] $? $(date -u)"12345678910111213141516#!/bin/bashset -ucd /proj/dmfexp/zwhong/rsm_riseexport MUJOCO_GL=disableO=status/real/stitch_readout_run31echo "[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.errecho "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.txtecho "=== 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 | headwc -l $O/reduce.postfix2.txt $O/reduce.postfix2.errecho "[exit] 0 $(date -u)"12345678910111213#!/bin/bashset -ucd /proj/dmfexp/zwhong/rsm_riseexport MUJOCO_GL=disableO=status/real/stitch_readout_run31echo "[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.errecho "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.txtecho "=== diff exit=$? (0 = identical, 1 = differs) ==="wc -l $O/reduce.prefix.txt $O/reduce.postfix.txt $O/reduce.postfix.errecho "[exit] 0 $(date -u)"1234567#!/bin/bashset -ucd /proj/dmfexp/zwhong/rsm_riseexport MUJOCO_GL=disableecho "[run_env] host=$(hostname) job=${LSB_JOBID:-none} $(date -u)"venv_rsm/bin/python scripts/real/reward_head_profile.pyecho "[exit] $? $(date -u)"1234567#!/bin/bashset -ucd /proj/dmfexp/zwhong/rsm_riseexport MUJOCO_GL=disableecho "[run_env] host=$(hostname) job=${LSB_JOBID:-none} $(date -u)"venv_rsm/bin/python scripts/real/stitch_shape_tally.pyecho "[exit] $? $(date -u)"1234567#!/bin/bashset -ucd /proj/dmfexp/zwhong/rsm_riseexport MUJOCO_GL=disableecho "[run_env] host=$(hostname) job=${LSB_JOBID:-none} $(date -u)"venv_rsm/bin/python scripts/real/terminal_handling_audit.pyecho "[exit] $? $(date -u)"12345678910#!/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 pipefailcd /proj/dmfexp/zwhong/rsm_riseexec 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.json123456789101112#!/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 pipefailcd /proj/dmfexp/zwhong/rsm_riseexec 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.json1234567891011121314#!/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 pipefailcd /proj/dmfexp/zwhong/rsm_riseexec 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.json1234567891011121314151617#!/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 pipefailcd /proj/dmfexp/zwhong/rsm_riseDC_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_parts1234567891011121314151617#!/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 pipefailcd /proj/dmfexp/zwhong/rsm_riseDC_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_parts1234567891011121314151617#!/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 pipefailcd /proj/dmfexp/zwhong/rsm_riseDC_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_parts1234567891011121314151617#!/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 pipefailcd /proj/dmfexp/zwhong/rsm_riseDC_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_parts1234567891011121314151617181920212223#!/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 pipefailcd /proj/dmfexp/zwhong/rsm_riserc=0for 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; }doneecho "[smoke] overall rc=$rc"exit $rc1234567891011#!/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 pipefailcd /proj/dmfexp/zwhong/rsm_riseO=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_parts1234567891011#!/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 pipefailcd /proj/dmfexp/zwhong/rsm_riseO=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_parts1234567891011#!/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 pipefailcd /proj/dmfexp/zwhong/rsm_riseO=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_parts1234567891011#!/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 pipefailcd /proj/dmfexp/zwhong/rsm_riseO=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_parts12345#!/usr/bin/env bashset -uo pipefailcd /proj/dmfexp/zwhong/rsm_riseexec scripts/real/run_env.sh scripts/real/stitch_reproducibility.py \ --label-a "stride50 draw" --label-b "stride25 draw, same anchors"1234567891011121314151617181920212223242526#!/usr/bin/env bashset -euo pipefailROOT=/proj/dmfexp/zwhong/rsm_riseWT=/proj/dmfexp/zwhong/scratch_pi05_200k/rsm_realbash $ROOT/scripts/real/pi05_ft50_pr12.shcd $WTgit --no-pager status --shortif ! 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 noisyevals with no noise model. Detrended, every one of the 16 series has z_best 0.62-2.45against ~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 twoBC 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 <noreply@anthropic.com>" git push origin HEAD git --no-pager log --oneline -1else echo "NO CHANGE to CHECKPOINTS.md"fiecho PR12_RUN16_DONE12345678910111213141516171819202122232425262728#!/usr/bin/env bashset -euo pipefailROOT=/proj/dmfexp/zwhong/rsm_riseWT=/proj/dmfexp/zwhong/scratch_pi05_200k/rsm_realbash $ROOT/scripts/real/pi05_ft50_pr12.shcd $WTgit --no-pager status --shortif ! 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 notedonly that the cosine makes that an upper bound. That caveat is now measured ratherthan 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 16series decelerate resolvably (stock_s0 c50/c10, sn1 c10). Re-projected at thelate-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 (margin0.047 cm) deciding it. Also records that stock_s0_ft50 is not merely converged butregressing in the late half (t=+4.3), which strengthens the take-BC-at-50k rule.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>" git push origin HEAD git --no-pager log --oneline -1else echo "NO CHANGE to CHECKPOINTS.md"fiecho PR12_RUN17_DONE123456789101112131415161718192021222324252627282930313233#!/usr/bin/env bashset -euo pipefailROOT=/proj/dmfexp/zwhong/rsm_riseWT=/proj/dmfexp/zwhong/scratch_pi05_200k/rsm_realbash $ROOT/scripts/real/pi05_ft50_pr12.shcd $WTgit --no-pager status --shortif ! 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 thatstep is running (LSF 1917097/1917098). Table refreshed at 100-105k: four of the fiveRISE actors improved their recovered fraction since 89-93k while both BC cells wereflat, the sign the slope fit predicts.
The decay of the warm start's advantage over the from-base control was previouslyderived by differencing two independently fitted lines, one per run -- which inflatesthe uncertainty and can manufacture a slope difference neither curve supports.ft50_initgap_decay.py instead interpolates the control onto the warm cell's eval stepsand fits the PAIRED gap as one series. The conclusion survives: the rate changessignificantly on both metrics (t_diff -3.8 / -4.7), so the whole-plateau line is themisspecified 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 <noreply@anthropic.com>" git push origin HEAD git --no-pager log --oneline -1else echo "NO CHANGE to CHECKPOINTS.md"fiecho PR12_RUN18_DONE123456789101112131415161718192021222324252627282930313233343536373839404142#!/usr/bin/env bashset -euo pipefailROOT=/proj/dmfexp/zwhong/rsm_riseWT=/proj/dmfexp/zwhong/scratch_pi05_200k/rsm_realbash $ROOT/scripts/real/pi05_ft50_pr12.shcd $WTgit --no-pager status --shortif ! 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 of0.004-0.010 cm, picked as the minimum over ~7 correlated rules, with no uncertaintyattached -- a winner's curse rather than a result.
ft50_rule_significance.py adds the three missing pieces: the episode as the unit ofanalysis (a cell's 705 decisions are 25 episodes, and decisions inside an episode sharea scene and the actor's error state), a paired standard error, and a family-wisesign-flip permutation taking min-t over the whole rule family per draw. Thedecision-to-episode map is not stored in scores.npz; it is reconstructed from theper_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 (bestper-cell p = 0.12), and pooled over all eight the best rule is -0.020 +- 0.014 cm atp = 0.25. argmin|z| -- the rule the extremity mechanism predicts should work -- isnegative in all 8 cells, but those are eight readings of the same 25 episodes, noteight 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% ofeach 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 <noreply@anthropic.com>" git push origin HEAD 2>&1 | tail -3 git --no-pager log --oneline -1else echo "NO CHANGE to CHECKPOINTS.md"fiecho PR12_RUN19_DONE123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191#!/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 successorhop 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 atthe 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 alreadysits 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 withthe reference rank_pct. So the SAME split is also run on the reference rank_pct itself, and the twoare reported side by side. If the ceiling split explains as much as the chain-length split, thisprobe 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 spearman0.998-0.999), and every cell is checked anchor-by-anchor on (ep,t,stage) before anything is paired."""import json, os, glob, argparseimport numpy as npfrom 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()12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152"""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 stillproduces 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()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286#!/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") twoindependent particle draws of the SAME 128-candidate cloud at the SAME state pick a DIFFERENTargmax 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 theorthogonal 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 onthe flagged minority and the deployed budget everywhere else. If it does not, instability isunpredictable 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 drawpairs 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 thedraws entering the outcome. That is not circular in a way that manufactures signal (a widecandidate cloud does not mechanically cause argmax disagreement ACROSS draws), but it is not cleaneither. The clean version -- predictor from draw 0, outcome from draws 1..R-1 only -- needs theper-draw argmax indices `top1_idx_prob`, which run 29's patch stores and which therefore exist inthe 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. Thedirection (sign of AUC-0.5) and the chosen predictor are fixed on it; mnt/xlrise/xlnt then confirmor 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 aself-test fails (planted-perfect predictor must give AUC 1.0, a shuffled one must cover 0.5)."""import argparse, json, os, sysimport 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()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239"""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% ofanchors at the deployed cell (5.9 cm of first-step xyz). The SAME cells already carried the controland 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 cellit is 0.568, i.e. the redraw changes the pick on 43.2% of anchors. MC noise is the LARGER source ofpick change. The deployed scorer is twin_rollout.py particles=16 score_kind=prob, so this is not adiagnostic regime: it is the shipped configuration.
This reader consumes the run-29 particle sweep (P = 16 / 32 / 64, two checkpoints, repeats=4) andanswers 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 itshistorical seed, so every REPEAT-0 field of the P=16 cells must reproduce xpick/xpick_<tag>.jsonbit-for-bit. Mismatch => rc=5, nothing else is read. Repeat-DERIVED fields are excluded BY NAME andthe exclusion is printed: R goes 3 -> 4, so they legitimately move. Missing cells => rc=4."""import argparse, json, math, os, sysimport 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()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356"""ACT_COND run 28 (gen_q#278): IS THE READ-OUT'S 23.5% ARGMAX DISAGREEMENT A BEHAVIOUR CHANGE, OR ARELABELLING AMONG NEAR-DUPLICATE CANDIDATES?
Run 27 measured the thing runs 25/26 had not: at the DEPLOYED cell the `prob` and `logit` argmaxes overthe 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-matchedLOGGED chunks, many of which are near-duplicates of each other, so two different indices can be thesame motion to within a millimetre. The quantity that decides whether the eval stream must A/B theswitch 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 27stored `xpick_prob_idx` / `xpick_logit_idx` per anchor. So this script REPLAYS the anchor/candidateconstruction 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 nothingon 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 ownlogged goal-route chunk than the `prob` pick? Bootstrap CI + Wilcoxon over disagreeing anchors."""import argparse, json, os, sys, collectionsimport 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()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275"""ACT_COND run 29 (gen_q#278): WHEN THE TWO READ-OUTS PICK DIFFERENT ACTIONS, DOES AN INDEPENDENTLYTRAINED SUCCESSOR PREFER EITHER PICK?
Where this sits. Run 27 measured that the `prob` -> `logit` read-out switch changes the EXECUTEDcandidate on 47/200 anchors at the deployed cell (argmax agreement 0.765). Run 28 measured that those47 disagreements are real motion, not relabelling (5.9 cm of first-step xyz, 36% of the cloud's ownspread, gripper flipping on 12.8% of them), and that the only quality statistic available -- distanceto the anchor's own logged chunk -- is NULL on all four checkpoints with inconsistent signs. So therun-26 "adopt logit" recommendation was withdrawn. The binding limit on that withdrawal is thatNOTHING 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 trainingseed and/or reward variant and/or width -- that played no part in the selection. For every anchor itre-scores the SAME 128-candidate cloud and reports where each read-out's pick lands in the REFEREE'sown ordering. Both picks are logged goal-route chunks from the same stage, so a referee has nodegenerate 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 thismeasures whether the FAMILY's value ordering prefers a pick -- not task success. If the read-outdisagreement comes from something every member of the family shares, the panel will inherit it andagree 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 thandropped: it shows what a maximally-biased referee looks like (it must rank its own read-out's pickfirst), 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, thisscript 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 ofact_sensitivity.py's, and that gate is what proves the copy consumes the rng identically -- a silentdivergence would move every number here and nothing else would catch it. Missing/short cells rc=4."""import argparse, collections, json, os, sys, timeimport 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()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357"""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-drawpredictor of an unstable executed pick is the top-1-vs-top-2 MARGIN, and it is the only predictor thattransfers to the held-out checkpoint. The indicated fix is therefore a TIE-BREAK (rescore the top-Kcandidates with M particles) rather than a uniform budget -- which is also the only reading consistentwith 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 wouldscore top1_agree 1.000 and look like a triumph. We print the number of DISTINCT picked indices andthe pick entropy for both arms, plus the ts-vs-ctl pick change rate (a no-op tie-break is also apossible and reportable outcome)."""import argparse, json, math, os, sysimport 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()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155#!/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 sameimplementation that produced the run-20 XL numbers, byte-verified identical by job 1889493) andprints the ONE row that runs 21-23 pre-registered, with the two pieces of context without which therow 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.0PER_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()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498"""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 enoughto action to pick actions leading to goal state." A rank number alone cannot answer that -- a value thatis 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 theparticle 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, timeimport 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()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162#!/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 rankstatistics of the LOGGED chunk, replicated on four checkpoints. The closed loop does not executethe logged chunk; it executes argmax over the candidate cloud. So the switch is a closed-loopchange 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 withbyte-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, "<MISSING>") 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()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339"""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 passand 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_<ep> 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 iton the deployed coin-chain read-out and belongs in a packed GPU job."""import argparse, json, os, sys, timeimport 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()rsm_rise/scripts/real/_patch_gate_run28.pyAdded+118
rsm_rise/scripts/real/_pr1_271_run15.shAdded+5
rsm_rise/scripts/real/_pr1_271_run18.shAdded+9
rsm_rise/scripts/real/_pr1_271_run21.shAdded+9
rsm_rise/scripts/real/_px_wrappers/px_ordercost_run13.shAdded+3
rsm_rise/scripts/real/_px_wrappers/px_ordercost_run14.shAdded+3
rsm_rise/scripts/real/_px_wrappers/px_ordercost_run15.shAdded+3
rsm_rise/scripts/real/_px_wrappers/px_qsweight.shAdded+6
rsm_rise/scripts/real/_px_wrappers/px_setupenv_run13.shAdded+3
rsm_rise/scripts/real/_px_wrappers/px_sixway_run13.shAdded+5
rsm_rise/scripts/real/_px_wrappers/px_sixway_run14.shAdded+5
rsm_rise/scripts/real/_px_wrappers/px_sixway_run15.shAdded+5
rsm_rise/scripts/real/_px_wrappers/px_whichscorer_run14.shAdded+3
rsm_rise/scripts/real/_run_actcond_spread_law.shAdded+6
rsm_rise/scripts/real/_run_all31.shAdded+27
rsm_rise/scripts/real/_run_clearance.shAdded+7
rsm_rise/scripts/real/_run_lineage.shAdded+7
rsm_rise/scripts/real/_run_red31b.shAdded+16
rsm_rise/scripts/real/_run_red31post.shAdded+13
rsm_rise/scripts/real/_run_rwprofile.shAdded+7
rsm_rise/scripts/real/_run_shape.shAdded+7
rsm_rise/scripts/real/_run_termaudit.shAdded+7
rsm_rise/scripts/real/_sig_stride25.shAdded+10
rsm_rise/scripts/real/_sig_stride25_matched.shAdded+12
rsm_rise/scripts/real/_sk_compare.shAdded+14
rsm_rise/scripts/real/_sk_logit_T25.shAdded+17
rsm_rise/scripts/real/_sk_prob_T1.shAdded+17
rsm_rise/scripts/real/_sk_prob_T100.shAdded+17
rsm_rise/scripts/real/_sk_prob_log_T25.shAdded+17
rsm_rise/scripts/real/_sk_smoke.shAdded+23
rsm_rise/scripts/real/_sn_seed1.shAdded+11
rsm_rise/scripts/real/_sn_seed2.shAdded+11
rsm_rise/scripts/real/_sn_seed3.shAdded+11
rsm_rise/scripts/real/_sn_seed4.shAdded+11
rsm_rise/scripts/real/_srep.shAdded+5
rsm_rise/scripts/real/_tmp/pr12_run16.shAdded+26
rsm_rise/scripts/real/_tmp/pr12_run17.shAdded+28
rsm_rise/scripts/real/_tmp/pr12_run18.shAdded+33
rsm_rise/scripts/real/_tmp/pr12_run19.shAdded+42
rsm_rise/scripts/real/absorption_probe.pyAdded+191
rsm_rise/scripts/real/act_json_regress.pyAdded+52
rsm_rise/scripts/real/act_mcpredict.pyAdded+286
rsm_rise/scripts/real/act_mcstab_read.pyAdded+239
rsm_rise/scripts/real/act_pickdist.pyAdded+356
rsm_rise/scripts/real/act_referee.pyAdded+275
rsm_rise/scripts/real/act_rescore_read.pyAdded+357
rsm_rise/scripts/real/act_run21_primary.pyAdded+155
rsm_rise/scripts/real/act_sensitivity.pyAdded+498
rsm_rise/scripts/real/act_xpick_read.pyAdded+162
rsm_rise/scripts/real/actcond_audit.pyAdded+339