rli14 commited on
Commit
f5b1784
·
verified ·
1 Parent(s): 086b61f

rsm_rise code snapshot (HF_PUSH_ALL) (part 7)

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. rsm_rise/scripts/real/_patch_gate_run28.py +118 -0
  2. rsm_rise/scripts/real/_pr1_271_run15.sh +5 -0
  3. rsm_rise/scripts/real/_pr1_271_run18.sh +9 -0
  4. rsm_rise/scripts/real/_pr1_271_run21.sh +9 -0
  5. rsm_rise/scripts/real/_px_wrappers/px_ordercost_run13.sh +3 -0
  6. rsm_rise/scripts/real/_px_wrappers/px_ordercost_run14.sh +3 -0
  7. rsm_rise/scripts/real/_px_wrappers/px_ordercost_run15.sh +3 -0
  8. rsm_rise/scripts/real/_px_wrappers/px_qsweight.sh +6 -0
  9. rsm_rise/scripts/real/_px_wrappers/px_setupenv_run13.sh +3 -0
  10. rsm_rise/scripts/real/_px_wrappers/px_sixway_run13.sh +5 -0
  11. rsm_rise/scripts/real/_px_wrappers/px_sixway_run14.sh +5 -0
  12. rsm_rise/scripts/real/_px_wrappers/px_sixway_run15.sh +5 -0
  13. rsm_rise/scripts/real/_px_wrappers/px_whichscorer_run14.sh +3 -0
  14. rsm_rise/scripts/real/_run_actcond_spread_law.sh +6 -0
  15. rsm_rise/scripts/real/_run_all31.sh +27 -0
  16. rsm_rise/scripts/real/_run_clearance.sh +7 -0
  17. rsm_rise/scripts/real/_run_lineage.sh +7 -0
  18. rsm_rise/scripts/real/_run_red31b.sh +16 -0
  19. rsm_rise/scripts/real/_run_red31post.sh +13 -0
  20. rsm_rise/scripts/real/_run_rwprofile.sh +7 -0
  21. rsm_rise/scripts/real/_run_shape.sh +7 -0
  22. rsm_rise/scripts/real/_run_termaudit.sh +7 -0
  23. rsm_rise/scripts/real/_sig_stride25.sh +10 -0
  24. rsm_rise/scripts/real/_sig_stride25_matched.sh +12 -0
  25. rsm_rise/scripts/real/_sk_compare.sh +14 -0
  26. rsm_rise/scripts/real/_sk_logit_T25.sh +17 -0
  27. rsm_rise/scripts/real/_sk_prob_T1.sh +17 -0
  28. rsm_rise/scripts/real/_sk_prob_T100.sh +17 -0
  29. rsm_rise/scripts/real/_sk_prob_log_T25.sh +17 -0
  30. rsm_rise/scripts/real/_sk_smoke.sh +23 -0
  31. rsm_rise/scripts/real/_sn_seed1.sh +11 -0
  32. rsm_rise/scripts/real/_sn_seed2.sh +11 -0
  33. rsm_rise/scripts/real/_sn_seed3.sh +11 -0
  34. rsm_rise/scripts/real/_sn_seed4.sh +11 -0
  35. rsm_rise/scripts/real/_srep.sh +5 -0
  36. rsm_rise/scripts/real/_tmp/pr12_run16.sh +26 -0
  37. rsm_rise/scripts/real/_tmp/pr12_run17.sh +28 -0
  38. rsm_rise/scripts/real/_tmp/pr12_run18.sh +33 -0
  39. rsm_rise/scripts/real/_tmp/pr12_run19.sh +42 -0
  40. rsm_rise/scripts/real/absorption_probe.py +191 -0
  41. rsm_rise/scripts/real/act_json_regress.py +52 -0
  42. rsm_rise/scripts/real/act_mcpredict.py +286 -0
  43. rsm_rise/scripts/real/act_mcstab_read.py +239 -0
  44. rsm_rise/scripts/real/act_pickdist.py +356 -0
  45. rsm_rise/scripts/real/act_referee.py +275 -0
  46. rsm_rise/scripts/real/act_rescore_read.py +357 -0
  47. rsm_rise/scripts/real/act_run21_primary.py +155 -0
  48. rsm_rise/scripts/real/act_sensitivity.py +498 -0
  49. rsm_rise/scripts/real/act_xpick_read.py +162 -0
  50. rsm_rise/scripts/real/actcond_audit.py +339 -0
rsm_rise/scripts/real/_patch_gate_run28.py ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Run-28 edits to scripts/real/selfcont_clean_venv.sh, applied once and kept for the record."""
3
+ import sys
4
+
5
+ p = "scripts/real/selfcont_clean_venv.sh"
6
+ s = open(p).read()
7
+
8
+ old = '''# LSF 1889983 found that `rise_stack.run`/`check` were loading the DINOv2 *source* from
9
+ # /proj/dmfexp/zwhong/rsm_rise/cache/torch/hub/... -- the value of dino_hub_dir: in
10
+ # rise_stack/configs/baselines.yaml -- so on this machine three steps of every previous gate run
11
+ # were quietly reading the research tree. Point it inside $SCRATCH: the first use downloads the
12
+ # repo from github into exactly this path (torch.hub's own cache layout), later steps reuse it,
13
+ # and nothing outside $SCRATCH is readable for it.
14
+ export RISE_DINO_HUB_DIR="$SCRATCH/.torchhome/hub/facebookresearch_dinov2_main"
15
+ '''
16
+ new = '''# NO RISE_DINO_HUB_DIR export, deliberately, since 2026-09-24 (run 28).
17
+ #
18
+ # LSF 1889983 found `rise_stack.run`/`check` loading the DINOv2 *source* from
19
+ # /proj/dmfexp/zwhong/rsm_rise/cache/torch/hub/... -- the shipped value of dino_hub_dir: in
20
+ # rise_stack/configs/baselines.yaml -- and the repair was to export RISE_DINO_HUB_DIR into $SCRATCH.
21
+ # That fixed the GATE and not the file the reader gets: LSF 1905498 found the same 24 `dinov2.*`
22
+ # modules coming from the research tree in a process without the override. A gate that sets a variable
23
+ # QUICKSTART.md never mentions is not testing the reader's path, so the override is gone and
24
+ # `dino_hub_dir:` now ships as null. With null, rise_stack/scorers.py resolves
25
+ # $TORCH_HOME/hub/facebookresearch_dinov2_main -- which, with TORCH_HOME=$SCRATCH/.torchhome above, is
26
+ # byte-for-byte the path this line used to export, downloaded from github on first use.
27
+ # If a future tree reintroduces a research-tree default, STEP 10 must go red. Do not re-add this.
28
+
29
+ # RSM_LIBERO_DIR is exported to a path that does not exist, deliberately.
30
+ #
31
+ # Until 2026-09-24 the vendored scorer defaulted it to /proj/dmfexp/zwhong/rsm_rise/code/gen_q/
32
+ # rsm_libero and `_rsm_modules()` imported `model`, `train_rsm`, `is_ope` and `data` from there. This
33
+ # gate UNSET the variable, which on THIS cluster silently selected that default -- so every green run
34
+ # measured a scorer that raises `ModuleNotFoundError: No module named 'model'` anywhere else
35
+ # (LSF 1905498). Unsetting can no longer distinguish "used the vendored copy" from "found the cluster
36
+ # tree"; an invalid value can, because the only way past it is the vendored copy.
37
+ export RSM_LIBERO_DIR=/nonexistent-rsm-libero-a-clean-machine-has-no-cluster-tree
38
+ '''
39
+ assert old in s, "DINO hub export block not found"
40
+ s = s.replace(old, new, 1)
41
+
42
+ STEP10 = r'''hdr "STEP 10 module provenance: score a decision IN THIS PROCESS, then ask sys.modules where every module came from"
43
+ # The replacement for STEP 9's log grep, and the reason is measured rather than anticipated. STEP 9
44
+ # searches the log for the literal `/proj/dmfexp/zwhong/rsm_rise`. Two independent ways a leak evades
45
+ # that, both realised: `importlib.import_module` prints nothing, so there is no line to grep (the
46
+ # rsm_libero import), and `rsm_rise/code/gen_q` is a SYMLINK to
47
+ # `projs/issue_resolver_richardrl/gen_q_rsm`, so the resolved path does not contain the searched
48
+ # string either. A realpath walk of `sys.modules` after the work is done sees both. STEP 9 stays as
49
+ # well -- it catches a printed path that no module import explains -- but THIS is the binding one.
50
+ #
51
+ # `rise_stack.run.main()` is called in-process with exactly STEP 5's arguments, so the scan looks at
52
+ # an interpreter that scored a decision and not at one that only imported a package. The floor (250
53
+ # module files) is what stops "clean" from meaning "the scan ran before anything was imported".
54
+ python - <<'PYPROV'
55
+ import json, os, sys
56
+ sys.argv = ["rise_stack.run"]
57
+ from rise_stack.run import main
58
+ from rise_stack import module_provenance as mp
59
+
60
+ ck = os.environ["CKPTS"]
61
+ rc_run = main(["--policy", "random", "--scorer", "rsm", "--env", "replay",
62
+ "--hdf5", "rise_stack/fixtures/replay_cooking_v5_ep7.hdf5",
63
+ "--split", "rise_stack/fixtures/split.json",
64
+ "--video-root", "rise_stack/fixtures",
65
+ "--rsm-ckpt", ck + "/successor_rsm_real_RM_s0_100k.pt",
66
+ "--rsm-feat-stats", ck + "/successor_rsm_real_feat_stats.json",
67
+ "--rsm-hop-ckpt", ck + "/hop_head_rsm_real_gauss_r1.pt",
68
+ "--episodes", "1", "--n-cand", "8", "--horizon", "8", "--max-decisions", "1",
69
+ "--out", "runs/provenance"])
70
+ print("in-process rise_stack.run rc =", 0 if rc_run in (0, None) else rc_run)
71
+ # Allowed: the clone, and $SCRATCH (the venv, the pip cache, TORCH_HOME -- everything this gate
72
+ # downloaded). interpreter_roots() adds the base interpreter that stands in for the reader's python3.
73
+ # Nothing else. A checkpoint directory needs no entry: checkpoints are data, not modules.
74
+ allow = [os.environ["REPO"], os.environ["SCRATCH"]] + mp.interpreter_roots()
75
+ rc = mp.report(allow, floor=250)
76
+ ins, out, roots, missing = mp.classify(allow)
77
+ jp = os.path.join(os.environ["SCRATCH"], "provenance.json")
78
+ json.dump({"rc": rc, "n": len(ins) + len(out), "roots": roots, "missing_roots": missing,
79
+ "foreign": [{"module": n, "path": p} for n, p in out]}, open(jp, "w"), indent=1)
80
+ print("provenance json:", jp)
81
+ sys.exit(rc if rc else (0 if rc_run in (0, None) else 4))
82
+ PYPROV
83
+ echo "provenance rc=$?"
84
+
85
+ '''
86
+
87
+ anchor = "# Nine `rc=` labels and three sentinel strings, checked by a machine against an expectation table."
88
+ assert anchor in s, "verdict preamble not found"
89
+ s = s.replace(anchor, STEP10 + anchor, 1)
90
+
91
+ old_expect = ''' "leakscan": 0, "whichscorer": 0,'''
92
+ new_expect = ''' "leakscan": 0, "whichscorer": 0,
93
+ # STEP 10: the in-process sys.modules realpath walk. rc=2 is a NON-RESULT (inspected fewer
94
+ # module files than the floor), rc=3 a leak, rc=4 the decision itself failed; all three
95
+ # must fail the gate, which is why the expectation is exactly 0 and not "non-fatal".
96
+ "provenance": 0,
97
+ "in-process rise_stack.run rc": 0,'''
98
+ assert old_expect in s
99
+ s = s.replace(old_expect, new_expect, 1)
100
+
101
+ old_sent = '''SENTINELS = ["CLEAN: robomimic is not importable in this venv",
102
+ "VENDORED COPY LOADED: True", "LEAK SCAN: clean"]'''
103
+ new_sent = '''SENTINELS = ["CLEAN: robomimic is not importable in this venv",
104
+ "VENDORED COPY LOADED: True", "LEAK SCAN: clean",
105
+ # STEP 10. "clean" alone could in principle be printed by a scan that inspected nothing,
106
+ # so the floor is asserted in-process (rc=2) and the inspected count is printed next to it.
107
+ "MODULE PROVENANCE: clean",
108
+ # ...and the vendored rsm_libero is what resolved, under RSM_LIBERO_DIR=/nonexistent:
109
+ # `_rsm_modules()` announces its directory, so the log carries the provenance of the number.
110
+ "rsm_libero modules from"]'''
111
+ assert old_sent in s
112
+ s = s.replace(old_sent, new_sent, 1)
113
+
114
+ assert "for step in range(1, 10):" in s
115
+ s = s.replace("for step in range(1, 10):", "for step in range(1, 11):", 1)
116
+
117
+ open(p, "w").write(s)
118
+ print("patched", p)
rsm_rise/scripts/real/_pr1_271_run15.sh ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ set -uo pipefail
3
+ cd /proj/dmfexp/zwhong/rsm_rise
4
+ exec venv_rsm/bin/python scripts/real/build_pr1_271_run11.py \
5
+ status/real/pr1_body_live_run15.md status/real/pr1_body_run15_patched.md
rsm_rise/scripts/real/_pr1_271_run18.sh ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # run 18: fetch the LIVE PR-1 body, splice #271 section (11), PATCH it back. Never patches from a copy.
3
+ set -uo pipefail
4
+ ROOT=/proj/dmfexp/zwhong/rsm_rise
5
+ cd "$ROOT" || exit 1
6
+ bash scripts/tmp/gh_get_pr.sh jmarangola/rsm_real 1 status/real/pr1_body_live_run18.md || exit 2
7
+ "$ROOT/venv_rsm/bin/python" scripts/real/build_pr1_271_run18.py \
8
+ status/real/pr1_body_live_run18.md status/real/pr1_body_run18_patched.md || exit 3
9
+ exec bash scripts/tmp/gh_patch_pr.sh jmarangola/rsm_real 1 status/real/pr1_body_run18_patched.md
rsm_rise/scripts/real/_pr1_271_run21.sh ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # run 21: fetch the LIVE PR-1 body, splice #271 section (12), PATCH it back. Never patches from a copy.
3
+ set -uo pipefail
4
+ ROOT=/proj/dmfexp/zwhong/rsm_rise
5
+ cd "$ROOT" || exit 1
6
+ bash scripts/tmp/gh_get_pr.sh jmarangola/rsm_real 1 status/real/pr1_body_live_run21.md || exit 2
7
+ "$ROOT/venv_rsm/bin/python" scripts/real/build_pr1_271_run21.py \
8
+ status/real/pr1_body_live_run21.md status/real/pr1_body_run21_patched.md || exit 3
9
+ exec bash scripts/tmp/gh_patch_pr.sh jmarangola/rsm_real 1 status/real/pr1_body_run21_patched.md
rsm_rise/scripts/real/_px_wrappers/px_ordercost_run13.sh ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ export SCRATCH=/proj/dmfexp/zwhong/scratch_patchexport/run18
3
+ exec bash /proj/dmfexp/zwhong/rsm_rise/scripts/real/patchexport_order_cost.sh
rsm_rise/scripts/real/_px_wrappers/px_ordercost_run14.sh ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ export SCRATCH=/proj/dmfexp/zwhong/scratch_patchexport/run20
3
+ exec bash /proj/dmfexp/zwhong/rsm_rise/scripts/real/patchexport_order_cost.sh
rsm_rise/scripts/real/_px_wrappers/px_ordercost_run15.sh ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ export SCRATCH=/proj/dmfexp/zwhong/scratch_patchexport/run22
3
+ exec bash /proj/dmfexp/zwhong/rsm_rise/scripts/real/patchexport_order_cost.sh
rsm_rise/scripts/real/_px_wrappers/px_qsweight.sh ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # deliberately does NOT source scripts/env.sh: the RISE conda env has robomimic installed, which is
3
+ # exactly the condition under which section D cannot conclude anything.
4
+ export SCRATCH=/proj/dmfexp/zwhong/scratch_patchexport/run21
5
+ export QS_PY=/proj/dmfexp/zwhong/rsm_rise/venv_rsm/bin/python
6
+ exec bash /proj/dmfexp/zwhong/rsm_rise/scripts/real/patchexport_quickstart_weight.sh
rsm_rise/scripts/real/_px_wrappers/px_setupenv_run13.sh ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ export SCRATCH=/proj/dmfexp/zwhong/scratch_patchexport/run19
3
+ exec bash /proj/dmfexp/zwhong/rsm_rise/scripts/real/patchexport_setupenv_resolution.sh
rsm_rise/scripts/real/_px_wrappers/px_sixway_run13.sh ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ export SCRATCH=/proj/dmfexp/zwhong/scratch_patchexport/run17
3
+ export SC_REPO=origin
4
+ export SC_REF=pull/11/head
5
+ exec bash /proj/dmfexp/zwhong/rsm_rise/scripts/real/patchexport_sixway_gate.sh
rsm_rise/scripts/real/_px_wrappers/px_sixway_run14.sh ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ export SCRATCH=/proj/dmfexp/zwhong/scratch_patchexport/run19
3
+ export SC_REPO=origin
4
+ export SC_REF=pull/11/head
5
+ exec bash /proj/dmfexp/zwhong/rsm_rise/scripts/real/patchexport_sixway_gate.sh
rsm_rise/scripts/real/_px_wrappers/px_sixway_run15.sh ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ export SCRATCH=/proj/dmfexp/zwhong/scratch_patchexport/run21
3
+ export SC_REPO=origin
4
+ export SC_REF=pull/11/head
5
+ exec bash /proj/dmfexp/zwhong/rsm_rise/scripts/real/patchexport_sixway_gate.sh
rsm_rise/scripts/real/_px_wrappers/px_whichscorer_run14.sh ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ export SCRATCH=/proj/dmfexp/zwhong/scratch_patchexport/run23
3
+ exec bash /proj/dmfexp/zwhong/rsm_rise/scripts/real/patchexport_whichscorer_resolution.sh
rsm_rise/scripts/real/_run_actcond_spread_law.sh ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ set -euo pipefail
3
+ cd /proj/dmfexp/zwhong/rsm_rise
4
+ source wandb_env.sh >/dev/null 2>&1 || true
5
+ exec venv_rsm/bin/python scripts/real/actcond_spread_law.py \
6
+ --out /proj/dmfexp/zwhong/rsm_rise/status/real/ACT_COND/SPREAD_LAW_run37.json
rsm_rise/scripts/real/_run_all31.sh ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # run 31 (2026-09-24): all four cap-pair stitch reads landed (1894747/1896924/1896925/1896926),
3
+ # plus two GSC x130 cells from 1891659. Re-run the whole read-out stack on the enlarged set:
4
+ # the reducer (owns the `trunc` cap-axis sign convention), the clearance tally, run 29's measured
5
+ # prefix-forest lineage tally and run 30's shape tally. Nothing is re-scored; all four read only
6
+ # JSON already on disk. Each output goes to its own file so the diff against the run-30 numbers
7
+ # is mechanical.
8
+ set -u
9
+ cd /proj/dmfexp/zwhong/rsm_rise
10
+ export MUJOCO_GL=disable
11
+ PY=venv_rsm/bin/python
12
+ O=status/real/stitch_readout_run31
13
+ mkdir -p $O
14
+ echo "[run_env] host=$(hostname) job=${LSB_JOBID:-none} $(date -u)"
15
+
16
+ echo "=== reducer ==="
17
+ $PY scripts/real/reduce_stitch_matrix.py > $O/reduce.txt 2> $O/reduce.err; echo "reduce exit=$?"
18
+ echo "=== clearance ==="
19
+ $PY scripts/real/stitch_clearance_tally.py > $O/clearance.txt 2> $O/clearance.err; echo "clearance exit=$?"
20
+ echo "=== lineage ==="
21
+ $PY scripts/real/stitch_lineage_tally.py > $O/lineage.txt 2> $O/lineage.err; echo "lineage exit=$?"
22
+ echo "=== shape ==="
23
+ $PY scripts/real/stitch_shape_tally.py > $O/shape.txt 2> $O/shape.err; echo "shape exit=$?"
24
+
25
+ echo "=== line counts ==="
26
+ wc -l $O/*.txt $O/*.err
27
+ echo "[exit] 0 $(date -u)"
rsm_rise/scripts/real/_run_clearance.sh ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ set -u
3
+ cd /proj/dmfexp/zwhong/rsm_rise
4
+ export MUJOCO_GL=disable
5
+ echo "[run_env] host=$(hostname) job=${LSB_JOBID:-none} $(date -u)"
6
+ venv_rsm/bin/python scripts/real/stitch_clearance_tally.py
7
+ echo "[exit] $? $(date -u)"
rsm_rise/scripts/real/_run_lineage.sh ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ set -u
3
+ cd /proj/dmfexp/zwhong/rsm_rise
4
+ export MUJOCO_GL=disable
5
+ echo "[run_env] host=$(hostname) job=${LSB_JOBID:-none} $(date -u)"
6
+ venv_rsm/bin/python scripts/real/stitch_lineage_tally.py
7
+ echo "[exit] $? $(date -u)"
rsm_rise/scripts/real/_run_red31b.sh ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ set -u
3
+ cd /proj/dmfexp/zwhong/rsm_rise
4
+ export MUJOCO_GL=disable
5
+ O=status/real/stitch_readout_run31
6
+ echo "[run_env] host=$(hostname) job=${LSB_JOBID:-none} $(date -u)"
7
+ venv_rsm/bin/python scripts/real/reduce_stitch_matrix.py > $O/reduce.postfix2.txt 2> $O/reduce.postfix2.err
8
+ echo "post2 exit=$?"
9
+ echo "=== DIFF postfix (step-suffix flags only) vs postfix2 (+ base_parent strip) ==="
10
+ echo "=== expected: ONLY the 'independent bases' columns of the two cap rows and the pooled trunc row ==="
11
+ diff $O/reduce.postfix.txt $O/reduce.postfix2.txt
12
+ echo "=== diff exit=$? ==="
13
+ echo "=== the two lines that matter, final ==="
14
+ grep -n "independent bases\|^| \`trunc\`\|step-matched @110k\] \[base R_XL\] | 2 " $O/reduce.postfix2.txt | head
15
+ wc -l $O/reduce.postfix2.txt $O/reduce.postfix2.err
16
+ echo "[exit] 0 $(date -u)"
rsm_rise/scripts/real/_run_red31post.sh ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ set -u
3
+ cd /proj/dmfexp/zwhong/rsm_rise
4
+ export MUJOCO_GL=disable
5
+ O=status/real/stitch_readout_run31
6
+ echo "[run_env] host=$(hostname) job=${LSB_JOBID:-none} $(date -u)"
7
+ venv_rsm/bin/python scripts/real/reduce_stitch_matrix.py > $O/reduce.postfix.txt 2> $O/reduce.postfix.err
8
+ echo "post exit=$?"
9
+ echo "=== REGRESSION DIFF pre-fix vs post-fix (expected: ONLY the two @110k R_XL cap rows and the pooled trunc rows) ==="
10
+ diff $O/reduce.prefix.txt $O/reduce.postfix.txt
11
+ echo "=== diff exit=$? (0 = identical, 1 = differs) ==="
12
+ wc -l $O/reduce.prefix.txt $O/reduce.postfix.txt $O/reduce.postfix.err
13
+ echo "[exit] 0 $(date -u)"
rsm_rise/scripts/real/_run_rwprofile.sh ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ set -u
3
+ cd /proj/dmfexp/zwhong/rsm_rise
4
+ export MUJOCO_GL=disable
5
+ echo "[run_env] host=$(hostname) job=${LSB_JOBID:-none} $(date -u)"
6
+ venv_rsm/bin/python scripts/real/reward_head_profile.py
7
+ echo "[exit] $? $(date -u)"
rsm_rise/scripts/real/_run_shape.sh ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ set -u
3
+ cd /proj/dmfexp/zwhong/rsm_rise
4
+ export MUJOCO_GL=disable
5
+ echo "[run_env] host=$(hostname) job=${LSB_JOBID:-none} $(date -u)"
6
+ venv_rsm/bin/python scripts/real/stitch_shape_tally.py
7
+ echo "[exit] $? $(date -u)"
rsm_rise/scripts/real/_run_termaudit.sh ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ set -u
3
+ cd /proj/dmfexp/zwhong/rsm_rise
4
+ export MUJOCO_GL=disable
5
+ echo "[run_env] host=$(hostname) job=${LSB_JOBID:-none} $(date -u)"
6
+ venv_rsm/bin/python scripts/real/terminal_handling_audit.py
7
+ echo "[exit] $? $(date -u)"
rsm_rise/scripts/real/_sig_stride25.sh ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # #271 run 8: the stitching number on the INDEPENDENT anchor set (stride 25, 250 anchors, hops 1,4)
3
+ # produced by run 7's bare run_stitch_number.sh. The published number is the stride-50 / 150-anchor
4
+ # measurement; this one shares no candidate draw with it (anchors are seeded by anchor INDEX), so the
5
+ # two together are a replicate of the whole stitching measurement, not of its bootstrap.
6
+ set -uo pipefail
7
+ cd /proj/dmfexp/zwhong/rsm_rise
8
+ exec scripts/real/run_env.sh scripts/real/stitch_significance.py \
9
+ --parts status/real/REWARD_HEAD_DIAG_STITCH_stride25.json_parts \
10
+ --out status/real/STITCH_SIGNIFICANCE_stride25.json
rsm_rise/scripts/real/_sig_stride25_matched.sh ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # #271 run 8: the stitching number on the stride-25 parts RESTRICTED to the anchors of the published
3
+ # stride-50 measurement (STITCH_SIGNIFICANCE.json as of 09:11, the numbers in CHECKPOINTS.md / the PDF /
4
+ # PR #1 / the HF card / the issue). Same anchor frames, INDEPENDENT candidate draw -- the exact
5
+ # analogue of the open-loop screen's noise floor, and the check that the published significance is not
6
+ # an artefact of one candidate draw.
7
+ set -uo pipefail
8
+ cd /proj/dmfexp/zwhong/rsm_rise
9
+ exec scripts/real/run_env.sh scripts/real/stitch_significance.py \
10
+ --parts status/real/REWARD_HEAD_DIAG_STITCH_stride25.json_parts \
11
+ --restrict-to-parts status/real/STITCH_SIGNIFICANCE.json \
12
+ --out status/real/STITCH_SIGNIFICANCE_matched.json
rsm_rise/scripts/real/_sk_compare.sh ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # run 12: fold the four scoring-functional cells against the flagship prob/T=25 baseline
3
+ # (status/real/STITCH_DECOMP.json, the depth-1 decomposition from run 10) into ONE comparison JSON.
4
+ # Pure JSON arithmetic -- no GPU, no model loading.
5
+ set -uo pipefail
6
+ cd /proj/dmfexp/zwhong/rsm_rise
7
+ exec python3 scripts/real/build_sk_compare.py \
8
+ --cell prob_T25=$PWD/status/real/STITCH_DECOMP.json \
9
+ --cell logit_T25=$PWD/status/real/SK_logit_T25.json \
10
+ --cell prob_log_T25=$PWD/status/real/SK_prob_log_T25.json \
11
+ --cell prob_T1=$PWD/status/real/SK_prob_T1.json \
12
+ --cell prob_T100=$PWD/status/real/SK_prob_T100.json \
13
+ --baseline prob_T25 --hops 2,4 \
14
+ --out $PWD/status/real/SK_COMPARE.json
rsm_rise/scripts/real/_sk_logit_T25.sh ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # run 12, scoring-functional sweep cell: score_kind=logit, temperature=25.0, flagship d1/beta=0.99.
3
+ # WHY this cell exists. Diagnostic 3's Q sits at chance while the SAME heads read the endpoint class
4
+ # at the chained latent at per-anchor AUC up to 0.941 (STITCH_DECOMP.json), and run 11 showed the
5
+ # read-out's HORIZON is not the culprit (fold-4 vs d1 moves the statistic by 0.0028 rms, below the
6
+ # ~0.005 GPU noise; within-anchor corr 0.977). The remaining suspect is the functional that turns
7
+ # 16 particle rewards into one ranking scalar. "prob" is mean sigma(logit/T): at T=25 the flagship
8
+ # de-saturates a head whose sigmoid ties at 1.000, but the surviving between-candidate spread is
9
+ # q_spread_cv ~ 0.0017 -- 4th significant figure. The sweep brackets that functional: "logit" is the
10
+ # T -> infinity linear limit, "prob_log" is gen_q#266's log-complement read-out, T=1 is the saturated
11
+ # end and T=100 the flat end. All 150 published anchors, one GPU, own parts dir so no two cells can
12
+ # share a draw; anchors already on disk are skipped, so the cell is preemption-safe and resumable.
13
+ set -uo pipefail
14
+ cd /proj/dmfexp/zwhong/rsm_rise
15
+ DC_OUT=$PWD/status/real/SK_logit_T25.json bash scripts/real/run_stitch_decompose.sh \
16
+ --with-q --q-score-kind logit --q-temperature 25.0 \
17
+ --parts $PWD/status/real/SK_logit_T25.json_parts
rsm_rise/scripts/real/_sk_prob_T1.sh ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # run 12, scoring-functional sweep cell: score_kind=prob, temperature=1.0, flagship d1/beta=0.99.
3
+ # WHY this cell exists. Diagnostic 3's Q sits at chance while the SAME heads read the endpoint class
4
+ # at the chained latent at per-anchor AUC up to 0.941 (STITCH_DECOMP.json), and run 11 showed the
5
+ # read-out's HORIZON is not the culprit (fold-4 vs d1 moves the statistic by 0.0028 rms, below the
6
+ # ~0.005 GPU noise; within-anchor corr 0.977). The remaining suspect is the functional that turns
7
+ # 16 particle rewards into one ranking scalar. "prob" is mean sigma(logit/T): at T=25 the flagship
8
+ # de-saturates a head whose sigmoid ties at 1.000, but the surviving between-candidate spread is
9
+ # q_spread_cv ~ 0.0017 -- 4th significant figure. The sweep brackets that functional: "logit" is the
10
+ # T -> infinity linear limit, "prob_log" is gen_q#266's log-complement read-out, T=1 is the saturated
11
+ # end and T=100 the flat end. All 150 published anchors, one GPU, own parts dir so no two cells can
12
+ # share a draw; anchors already on disk are skipped, so the cell is preemption-safe and resumable.
13
+ set -uo pipefail
14
+ cd /proj/dmfexp/zwhong/rsm_rise
15
+ DC_OUT=$PWD/status/real/SK_prob_T1.json bash scripts/real/run_stitch_decompose.sh \
16
+ --with-q --q-score-kind prob --q-temperature 1.0 \
17
+ --parts $PWD/status/real/SK_prob_T1.json_parts
rsm_rise/scripts/real/_sk_prob_T100.sh ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # run 12, scoring-functional sweep cell: score_kind=prob, temperature=100.0, flagship d1/beta=0.99.
3
+ # WHY this cell exists. Diagnostic 3's Q sits at chance while the SAME heads read the endpoint class
4
+ # at the chained latent at per-anchor AUC up to 0.941 (STITCH_DECOMP.json), and run 11 showed the
5
+ # read-out's HORIZON is not the culprit (fold-4 vs d1 moves the statistic by 0.0028 rms, below the
6
+ # ~0.005 GPU noise; within-anchor corr 0.977). The remaining suspect is the functional that turns
7
+ # 16 particle rewards into one ranking scalar. "prob" is mean sigma(logit/T): at T=25 the flagship
8
+ # de-saturates a head whose sigmoid ties at 1.000, but the surviving between-candidate spread is
9
+ # q_spread_cv ~ 0.0017 -- 4th significant figure. The sweep brackets that functional: "logit" is the
10
+ # T -> infinity linear limit, "prob_log" is gen_q#266's log-complement read-out, T=1 is the saturated
11
+ # end and T=100 the flat end. All 150 published anchors, one GPU, own parts dir so no two cells can
12
+ # share a draw; anchors already on disk are skipped, so the cell is preemption-safe and resumable.
13
+ set -uo pipefail
14
+ cd /proj/dmfexp/zwhong/rsm_rise
15
+ DC_OUT=$PWD/status/real/SK_prob_T100.json bash scripts/real/run_stitch_decompose.sh \
16
+ --with-q --q-score-kind prob --q-temperature 100.0 \
17
+ --parts $PWD/status/real/SK_prob_T100.json_parts
rsm_rise/scripts/real/_sk_prob_log_T25.sh ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # run 12, scoring-functional sweep cell: score_kind=prob_log, temperature=25.0, flagship d1/beta=0.99.
3
+ # WHY this cell exists. Diagnostic 3's Q sits at chance while the SAME heads read the endpoint class
4
+ # at the chained latent at per-anchor AUC up to 0.941 (STITCH_DECOMP.json), and run 11 showed the
5
+ # read-out's HORIZON is not the culprit (fold-4 vs d1 moves the statistic by 0.0028 rms, below the
6
+ # ~0.005 GPU noise; within-anchor corr 0.977). The remaining suspect is the functional that turns
7
+ # 16 particle rewards into one ranking scalar. "prob" is mean sigma(logit/T): at T=25 the flagship
8
+ # de-saturates a head whose sigmoid ties at 1.000, but the surviving between-candidate spread is
9
+ # q_spread_cv ~ 0.0017 -- 4th significant figure. The sweep brackets that functional: "logit" is the
10
+ # T -> infinity linear limit, "prob_log" is gen_q#266's log-complement read-out, T=1 is the saturated
11
+ # end and T=100 the flat end. All 150 published anchors, one GPU, own parts dir so no two cells can
12
+ # share a draw; anchors already on disk are skipped, so the cell is preemption-safe and resumable.
13
+ set -uo pipefail
14
+ cd /proj/dmfexp/zwhong/rsm_rise
15
+ DC_OUT=$PWD/status/real/SK_prob_log_T25.json bash scripts/real/run_stitch_decompose.sh \
16
+ --with-q --q-score-kind prob_log --q-temperature 25.0 \
17
+ --parts $PWD/status/real/SK_prob_log_T25.json_parts
rsm_rise/scripts/real/_sk_smoke.sh ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # run 12: the SCORING-FUNCTIONAL smoke. Run 11 falsified the horizon explanation (fold-4 moves the
3
+ # stitching number by less than GPU noise) while the endpoint class IS present at the chained latent
4
+ # (C10_s1 per-anchor AUC 0.941). What is left between R(z_h) and Q is the functional that compresses
5
+ # R over 16 particles into one ranking scalar -- "prob" (mean sigma) at T=25, whose between-candidate
6
+ # spread sits in the 4th significant figure (q_spread_cv ~ 0.0017). This checks that the three rival
7
+ # functionals CONSTRUCT and return finite Q on one anchor before a GPU pack is spent on them
8
+ # (rsm_scorer asserts score_kind against the mode/backend, so a bad cell dies at construction).
9
+ # CPU Q values are NOT comparable to the published GPU ones -- loading and finiteness only.
10
+ set -uo pipefail
11
+ cd /proj/dmfexp/zwhong/rsm_rise
12
+ rc=0
13
+ for cell in "logit 25.0" "prob_log 25.0" "prob 1.0" "prob 100.0"; do
14
+ set -- $cell; K=$1; T=$2
15
+ tag="${K}_T${T}"
16
+ echo "=================== smoke cell $tag ==================="
17
+ DC_OUT=$PWD/status/real/_sk_smoke_${tag}.json bash scripts/real/run_stitch_decompose.sh \
18
+ --with-q --anchor-lo 0 --anchor-hi 1 \
19
+ --q-score-kind "$K" --q-temperature "$T" \
20
+ --parts $PWD/status/real/_sk_smoke_${tag}.json_parts || { echo "[smoke] FAILED $tag"; rc=1; }
21
+ done
22
+ echo "[smoke] overall rc=$rc"
23
+ exit $rc
rsm_rise/scripts/real/_sn_seed1.sh ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # #271 run 9: an INDEPENDENT candidate draw of the stitching number at the CANONICAL anchors
3
+ # (stride 50, hops 1,2,4, N=128, 16 heads). --seed changes only the per-anchor candidate draw
4
+ # (stitch_number.py seeds anchor ai with seed*1000003+ai), so seeds 1..4 plus the published seed 0
5
+ # are five replicates with the same anchors, same weights, same endpoints machinery.
6
+ set -uo pipefail
7
+ cd /proj/dmfexp/zwhong/rsm_rise
8
+ O=status/real/STITCH_DRAW_s1.json
9
+ [ -f "$O" ] && { echo "[sn] $O exists, skipping"; exit 0; }
10
+ SN_OUT=$PWD/$O bash scripts/real/run_stitch_number.sh --seed 1 \
11
+ --parts $PWD/status/real/STITCH_DRAW_s1.json_parts
rsm_rise/scripts/real/_sn_seed2.sh ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # #271 run 9: an INDEPENDENT candidate draw of the stitching number at the CANONICAL anchors
3
+ # (stride 50, hops 1,2,4, N=128, 16 heads). --seed changes only the per-anchor candidate draw
4
+ # (stitch_number.py seeds anchor ai with seed*1000003+ai), so seeds 1..4 plus the published seed 0
5
+ # are five replicates with the same anchors, same weights, same endpoints machinery.
6
+ set -uo pipefail
7
+ cd /proj/dmfexp/zwhong/rsm_rise
8
+ O=status/real/STITCH_DRAW_s2.json
9
+ [ -f "$O" ] && { echo "[sn] $O exists, skipping"; exit 0; }
10
+ SN_OUT=$PWD/$O bash scripts/real/run_stitch_number.sh --seed 2 \
11
+ --parts $PWD/status/real/STITCH_DRAW_s2.json_parts
rsm_rise/scripts/real/_sn_seed3.sh ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # #271 run 9: an INDEPENDENT candidate draw of the stitching number at the CANONICAL anchors
3
+ # (stride 50, hops 1,2,4, N=128, 16 heads). --seed changes only the per-anchor candidate draw
4
+ # (stitch_number.py seeds anchor ai with seed*1000003+ai), so seeds 1..4 plus the published seed 0
5
+ # are five replicates with the same anchors, same weights, same endpoints machinery.
6
+ set -uo pipefail
7
+ cd /proj/dmfexp/zwhong/rsm_rise
8
+ O=status/real/STITCH_DRAW_s3.json
9
+ [ -f "$O" ] && { echo "[sn] $O exists, skipping"; exit 0; }
10
+ SN_OUT=$PWD/$O bash scripts/real/run_stitch_number.sh --seed 3 \
11
+ --parts $PWD/status/real/STITCH_DRAW_s3.json_parts
rsm_rise/scripts/real/_sn_seed4.sh ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # #271 run 9: an INDEPENDENT candidate draw of the stitching number at the CANONICAL anchors
3
+ # (stride 50, hops 1,2,4, N=128, 16 heads). --seed changes only the per-anchor candidate draw
4
+ # (stitch_number.py seeds anchor ai with seed*1000003+ai), so seeds 1..4 plus the published seed 0
5
+ # are five replicates with the same anchors, same weights, same endpoints machinery.
6
+ set -uo pipefail
7
+ cd /proj/dmfexp/zwhong/rsm_rise
8
+ O=status/real/STITCH_DRAW_s4.json
9
+ [ -f "$O" ] && { echo "[sn] $O exists, skipping"; exit 0; }
10
+ SN_OUT=$PWD/$O bash scripts/real/run_stitch_number.sh --seed 4 \
11
+ --parts $PWD/status/real/STITCH_DRAW_s4.json_parts
rsm_rise/scripts/real/_srep.sh ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ set -uo pipefail
3
+ cd /proj/dmfexp/zwhong/rsm_rise
4
+ exec scripts/real/run_env.sh scripts/real/stitch_reproducibility.py \
5
+ --label-a "stride50 draw" --label-b "stride25 draw, same anchors"
rsm_rise/scripts/real/_tmp/pr12_run16.sh ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ ROOT=/proj/dmfexp/zwhong/rsm_rise
4
+ WT=/proj/dmfexp/zwhong/scratch_pi05_200k/rsm_real
5
+ bash $ROOT/scripts/real/pi05_ft50_pr12.sh
6
+ cd $WT
7
+ git --no-pager status --short
8
+ if ! git diff --quiet; then
9
+ git add rise_stack/CHECKPOINTS.md
10
+ git commit -m "CHECKPOINTS: ft50 held-out table at 89-93k; withdraw argmin checkpoint selection, add plateau slope test
11
+
12
+ The 'best checkpoint @ step N' readings in this section were argmin over ~80 noisy
13
+ evals with no noise model. Detrended, every one of the 16 series has z_best 0.62-2.45
14
+ against ~2.0 expected from pure noise, so none is distinguishable from the noise band.
15
+ Replaced with the plateau OLS slope and its t-statistic, which splits the set: the two
16
+ BC fine-tunes are converged (stock_s0 t=-0.8) or regressing (stock_s1 t=+2.4 / +10.5)
17
+ and should be taken at ~50k, while the five RISE actors are still improving at 90k
18
+ (t=-4.5 .. -21.5) and should be taken at 200k.
19
+
20
+ Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>"
21
+ git push origin HEAD
22
+ git --no-pager log --oneline -1
23
+ else
24
+ echo "NO CHANGE to CHECKPOINTS.md"
25
+ fi
26
+ echo PR12_RUN16_DONE
rsm_rise/scripts/real/_tmp/pr12_run17.sh ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ ROOT=/proj/dmfexp/zwhong/rsm_rise
4
+ WT=/proj/dmfexp/zwhong/scratch_pi05_200k/rsm_real
5
+ bash $ROOT/scripts/real/pi05_ft50_pr12.sh
6
+ cd $WT
7
+ git --no-pager status --short
8
+ if ! git diff --quiet; then
9
+ git add rise_stack/CHECKPOINTS.md
10
+ git commit -m "CHECKPOINTS: measure whether the plateau slope is decaying; sharpen the 200k prediction to 5/5
11
+
12
+ The 200k projections here extrapolated a 50k-90k plateau slope linearly and noted
13
+ only that the cosine makes that an upper bound. That caveat is now measured rather
14
+ than assumed: ft50_slope_curvature.py splits the plateau at its midpoint in STEP,
15
+ fits an independent OLS line per half and tests the slope difference. Only 3 of 16
16
+ series decelerate resolvably (stock_s0 c50/c10, sn1 c10). Re-projected at the
17
+ late-half rate all four predicted RISE passes survive and sn0p1_knn0p03 flips from
18
+ 'just misses' to a pass, so the 150k check is now a 5-of-5 claim with sn1 (margin
19
+ 0.047 cm) deciding it. Also records that stock_s0_ft50 is not merely converged but
20
+ regressing in the late half (t=+4.3), which strengthens the take-BC-at-50k rule.
21
+
22
+ Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>"
23
+ git push origin HEAD
24
+ git --no-pager log --oneline -1
25
+ else
26
+ echo "NO CHANGE to CHECKPOINTS.md"
27
+ fi
28
+ echo PR12_RUN17_DONE
rsm_rise/scripts/real/_tmp/pr12_run18.sh ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ ROOT=/proj/dmfexp/zwhong/rsm_rise
4
+ WT=/proj/dmfexp/zwhong/scratch_pi05_200k/rsm_real
5
+ bash $ROOT/scripts/real/pi05_ft50_pr12.sh
6
+ cd $WT
7
+ git --no-pager status --short
8
+ if ! git diff --quiet; then
9
+ git add rise_stack/CHECKPOINTS.md
10
+ git commit -m "CHECKPOINTS: refresh the comparable table at 100-105k; fit the init-advantage decay on the paired gap
11
+
12
+ All eight cells now have their 100 000 keep and the 8-cell planning screen at that
13
+ step is running (LSF 1917097/1917098). Table refreshed at 100-105k: four of the five
14
+ RISE actors improved their recovered fraction since 89-93k while both BC cells were
15
+ flat, the sign the slope fit predicts.
16
+
17
+ The decay of the warm start's advantage over the from-base control was previously
18
+ derived by differencing two independently fitted lines, one per run -- which inflates
19
+ the uncertainty and can manufacture a slope difference neither curve supports.
20
+ ft50_initgap_decay.py instead interpolates the control onto the warm cell's eval steps
21
+ and fits the PAIRED gap as one series. The conclusion survives: the rate changes
22
+ significantly on both metrics (t_diff -3.8 / -4.7), so the whole-plateau line is the
23
+ misspecified one, and the late-half rate projects the gap to 0.078 cm (chunk10) /
24
+ 0.035 cm (chunk50) at 200k from 0.194 / 0.156 cm now. Warm start still wins at 200k,
25
+ by a margin 2-4x smaller than today's; the gap is not a stable number.
26
+
27
+ Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>"
28
+ git push origin HEAD
29
+ git --no-pager log --oneline -1
30
+ else
31
+ echo "NO CHANGE to CHECKPOINTS.md"
32
+ fi
33
+ echo PR12_RUN18_DONE
rsm_rise/scripts/real/_tmp/pr12_run19.sh ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ ROOT=/proj/dmfexp/zwhong/rsm_rise
4
+ WT=/proj/dmfexp/zwhong/scratch_pi05_200k/rsm_real
5
+ bash $ROOT/scripts/real/pi05_ft50_pr12.sh
6
+ cd $WT
7
+ git --no-pager status --short
8
+ if ! git diff --quiet; then
9
+ git add rise_stack/CHECKPOINTS.md
10
+ git commit -m "CHECKPOINTS: no selection rule beats greedy -- episode-clustered, family-wise, and now bounded
11
+
12
+ The offline selection-rule sweep judged a rule a winner on the raw sign of
13
+ (rule - greedy). At 50k that read 'beats greedy' in 6 of 8 cells, on margins of
14
+ 0.004-0.010 cm, picked as the minimum over ~7 correlated rules, with no uncertainty
15
+ attached -- a winner's curse rather than a result.
16
+
17
+ ft50_rule_significance.py adds the three missing pieces: the episode as the unit of
18
+ analysis (a cell's 705 decisions are 25 episodes, and decisions inside an episode share
19
+ a scene and the actor's error state), a paired standard error, and a family-wise
20
+ sign-flip permutation taking min-t over the whole rule family per draw. The
21
+ decision-to-episode map is not stored in scores.npz; it is reconstructed from the
22
+ per_episode prefix sums and proven by reproducing each episode's own greedy / oracle /
23
+ rsm mean to 3e-8 cm in every cell, aborting rather than falling back.
24
+
25
+ Result: 0 of 8 cells have a deployable rule that beats greedy family-wise (best
26
+ per-cell p = 0.12), and pooled over all eight the best rule is -0.020 +- 0.014 cm at
27
+ p = 0.25. argmin|z| -- the rule the extremity mechanism predicts should work -- is
28
+ negative in all 8 cells, but those are eight readings of the same 25 episodes, not
29
+ eight independent replications. The deployed argmax is confirmed as the wrong rule:
30
+ +0.122 +- 0.022 cm worse than greedy pooled, t = +5.5, worse in 8 of 8 cells at t > +2.
31
+
32
+ The by-product is a bound: 95% CI on the best rule [-0.048, +0.007] cm, under 7% of
33
+ each cell's greedy-to-oracle headroom. Nothing is left to fix in the selection step;
34
+ the critic has to be retrained at the matched horizon.
35
+
36
+ Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>"
37
+ git push origin HEAD 2>&1 | tail -3
38
+ git --no-pager log --oneline -1
39
+ else
40
+ echo "NO CHANGE to CHECKPOINTS.md"
41
+ fi
42
+ echo PR12_RUN19_DONE
rsm_rise/scripts/real/absorption_probe.py ADDED
@@ -0,0 +1,191 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ """WHERE DOES THE LOW-BETA GAIN COME FROM? A per-anchor mechanism probe (ACT_COND run 16, #278).
3
+
4
+ Run 15 measured the R_M beta ladder RISING then SATURATING: vs logit@0.99 the rank-pct gain is
5
+ +0.0022 at 0.92, +0.0050 at 0.90, +0.0055 at 0.87 -- while the realized chain length keeps growing
6
+ (85 -> 109 -> 147 hops). The hypothesis offered there was ABSORPTION: at ~100 frames per successor
7
+ hop a chain that already runs past the end of the episode sees nothing new when it runs further.
8
+ That was flagged as a hypothesis, and this is the cheapest test of it that needs NO new GPU compute
9
+ -- it reads the per-anchor rows already cached in the snr JSONs.
10
+
11
+ THE PREDICTION THAT SEPARATES THE READINGS. Split anchors by how long their chain ALREADY was at
12
+ the reference beta 0.99 (`chain_hops_mean`, the realized walk):
13
+ * ABSORPTION -> the anchors that were already long have nothing to gain from a longer chain, so
14
+ the gain concentrates in the SHORT-chain tercile and is ~0 in the LONG-chain tercile.
15
+ * UNIFORM EXTRAPOLATION DRIFT -> leaving the trained support perturbs every anchor's field alike,
16
+ so the gain is flat across terciles.
17
+
18
+ THE CONFOUND THIS PROBE MUST NOT FALL FOR. rank_pct is bounded at 1.0 and the reference already
19
+ sits at 0.988, so any anchor that is near the ceiling cannot gain and an anchor that is low has room:
20
+ a split on chain length will reproduce a ceiling effect if chain length happens to correlate with
21
+ the reference rank_pct. So the SAME split is also run on the reference rank_pct itself, and the two
22
+ are reported side by side. If the ceiling split explains as much as the chain-length split, this
23
+ probe says nothing about absorption and the printout says so.
24
+
25
+ All comparisons are the noise-matched logit-vs-logit ones (every logit cell sits at rep spearman
26
+ 0.998-0.999), and every cell is checked anchor-by-anchor on (ep,t,stage) before anything is paired.
27
+ """
28
+ import json, os, glob, argparse
29
+ import numpy as np
30
+ from scipy.stats import spearmanr
31
+
32
+ D = "/proj/dmfexp/zwhong/rsm_rise/status/real/ACT_COND/snr"
33
+ OUT = "/proj/dmfexp/zwhong/rsm_rise/status/real/ACT_COND/ABSORPTION.json"
34
+ REF = "snr_beta99.json"
35
+ READ = "logit"
36
+ STATS = [("rank_pct", +1), ("spearman", -1)]
37
+
38
+
39
+ def akey(r):
40
+ return (int(r["ep"]), int(r["t"]), str(r.get("stage")))
41
+
42
+
43
+ def boot_ci(d, n=20000, seed=0):
44
+ rng = np.random.default_rng(seed)
45
+ d = np.asarray(d, float)
46
+ return tuple(float(x) for x in np.percentile(d[rng.integers(0, len(d), (n, len(d)))].mean(1),
47
+ [2.5, 97.5]))
48
+
49
+
50
+ def terciles(v):
51
+ q = np.quantile(v, [1 / 3, 2 / 3])
52
+ return np.digitize(v, q) # 0 = low, 1 = mid, 2 = high
53
+
54
+
55
+ def main():
56
+ global READ, OUT
57
+ ap = argparse.ArgumentParser()
58
+ ap.add_argument("--read", default=READ, choices=["logit", "prob"],
59
+ help="read-out the whole probe runs under; the RTM-matched contrast is "
60
+ "read-out specific because the two read-outs rank the beta ladder "
61
+ "differently (run 17).")
62
+ ap.add_argument("--out", default=OUT)
63
+ a = ap.parse_args()
64
+ READ, OUT = a.read, a.out
65
+ print(f"READ-OUT = {READ} OUT = {OUT}")
66
+ cells = {}
67
+ for p in sorted(glob.glob(f"{D}/snr_beta*.json")):
68
+ j = json.load(open(p))
69
+ cells[os.path.basename(p)] = j
70
+ ref = cells[REF]
71
+ refkeys = [akey(r) for r in ref["rows"]]
72
+ for c, j in cells.items():
73
+ if len(j["rows"]) != len(refkeys) or any(akey(r) != k for r, k in zip(j["rows"], refkeys)):
74
+ raise SystemExit(f"FAIL {c}: anchors do not match {REF}; NOT pairable.")
75
+ print(f"ANCHOR IDENTITY: {len(cells)} cells x {len(refkeys)} anchors match {REF} EXACTLY.")
76
+
77
+ hops = np.array([r["chain_hops_mean"] for r in ref["rows"]], float)
78
+ base = {s: np.array([r[f"{s}_{READ}"] for r in ref["rows"]], float) for s, _ in STATS}
79
+ stage = np.array([str(r.get("stage")) for r in ref["rows"]])
80
+ print(f"\nreference {READ}@0.99: realized hops per anchor min {hops.min():.1f} "
81
+ f"median {np.median(hops):.1f} max {hops.max():.1f} "
82
+ f"IQR {np.subtract(*np.percentile(hops,[75,25])):.2f}")
83
+
84
+ splits = {"chain hops @0.99": terciles(hops),
85
+ "rank_pct @0.99 (CEILING control)": terciles(base["rank_pct"])}
86
+ # how much do the two splits overlap? If they are nearly the same partition the probe is blind.
87
+ ag = float((splits["chain hops @0.99"] == splits["rank_pct @0.99 (CEILING control)"]).mean())
88
+ rho_hb = float(spearmanr(hops, base["rank_pct"]).statistic)
89
+ print(f"the two splits assign the same tercile to {ag:.1%} of anchors (chance 1/3); "
90
+ f"spearman(hops, ref rank_pct) = {rho_hb:+.3f}")
91
+ print("per-tercile REFERENCE levels (so a ceiling effect is visible directly):")
92
+ for nm, g in splits.items():
93
+ for t, lab in enumerate(("low ", "mid ", "high")):
94
+ m = g == t
95
+ print(f" {nm:<34} {lab} n={m.sum():3d} hops={hops[m].mean():7.1f} "
96
+ f"ref rank_pct={base['rank_pct'][m].mean():.4f} "
97
+ f"ref rho={base['spearman'][m].mean():+.3f} "
98
+ f"stages=" + ",".join(f"{s}:{int((stage[m]==s).sum())}"
99
+ for s in sorted(set(stage))))
100
+
101
+ out = {"n": len(refkeys), "ref": REF, "read": READ, "split_agreement": ag,
102
+ "spearman_hops_vs_ref_rank": rho_hb, "rows": []}
103
+ order = sorted((c for c in cells if c != REF),
104
+ key=lambda c: -float("0." + c.replace("snr_beta", "").replace(".json", "")))
105
+ for stem, sign in STATS:
106
+ hdr = (f"\n{stem} gain vs {READ}@0.99 (sign {'higher' if sign>0 else 'lower'}=better), "
107
+ f"by tercile\n{'cell':<10} {'split':<34} {'low':>18} {'mid':>18} {'high':>18} "
108
+ f"{'rho(gain,split var)':>21}")
109
+ print(hdr); print("-" * 124)
110
+ for c in order:
111
+ y = np.array([r[f"{stem}_{READ}"] for r in cells[c]["rows"]], float)
112
+ gain = y - base[stem]
113
+ for nm, g in splits.items():
114
+ cellstr = []
115
+ rec = {"cell": c, "stat": stem, "split": nm, "overall": float(gain.mean()),
116
+ "tercile": []}
117
+ for t in range(3):
118
+ m = g == t
119
+ lo, hi = boot_ci(gain[m])
120
+ cellstr.append(f"{gain[m].mean():+.4f}[{lo:+.4f},{hi:+.4f}]")
121
+ rec["tercile"].append({"t": t, "n": int(m.sum()), "mean": float(gain[m].mean()),
122
+ "lo": lo, "hi": hi})
123
+ sv = hops if nm.startswith("chain") else base["rank_pct"]
124
+ r = float(spearmanr(sv, gain).statistic)
125
+ rec["spearman_gain_vs_split_var"] = r
126
+ print(f"{c.replace('snr_beta','0.').replace('.json',''):<10} {nm:<34} "
127
+ + " ".join(f"{s:>18}" for s in cellstr) + f" {r:>21.3f}")
128
+ out["rows"].append(rec)
129
+
130
+ # ---- POWER of the chain-hops split, stated before any of its rows is read ----
131
+ th = [hops[splits["chain hops @0.99"] == t].mean() for t in range(3)]
132
+ spread = max(th) - min(th)
133
+ powered = spread > 0.10 * float(np.median(hops))
134
+ print(f"\nPOWER OF THE CHAIN-HOPS SPLIT: tercile means {th[0]:.2f} / {th[1]:.2f} / {th[2]:.2f} "
135
+ f"hops, spread {spread:.2f} = {100*spread/np.median(hops):.1f}% of the median.\n"
136
+ + (" -> POWERED: the terciles are genuinely different chain lengths."
137
+ if powered else
138
+ " -> UNDERPOWERED: E[hops] is set by BETA, not by the anchor -- the three terciles are\n"
139
+ " the same chain length to within a few percent, so this split cannot test absorption\n"
140
+ " at all. Its rows below are reported for completeness and carry NO verdict. Testing\n"
141
+ " absorption needs a probe that varies the horizon WITHIN an anchor (i.e. the beta\n"
142
+ " ladder itself), not a split across anchors."))
143
+
144
+ # ---- RTM-MATCHED CONTRAST ----
145
+ # Terciles are cut on the REFERENCE cell's own rank_pct, which is measured with particle noise,
146
+ # so selection alone drives the low tercile up and the high tercile down in EVERY other cell --
147
+ # regression to the mean, visible above in cells that are an overall TIE (0.95 low +0.0098, high
148
+ # -0.0029). Contrasting each cell against a BASELINE CELL rather than against the reference
149
+ # cancels that: both cells were selected by the same noisy variable and both sit at the same
150
+ # noise level (rep spearman 0.999 across the logit ladder), so the shared selection effect
151
+ # subtracts out and what remains is the effect of BETA.
152
+ BASE = "snr_beta95.json" # the last cell measured as an overall TIE vs logit@0.99
153
+ if BASE in cells:
154
+ gsplit = splits["rank_pct @0.99 (CEILING control)"]
155
+ for stem, sign in STATS:
156
+ b = np.array([r[f"{stem}_{READ}"] for r in cells[BASE]["rows"]], float)
157
+ print(f"\nRTM-MATCHED: {stem} vs the BASELINE CELL {BASE.replace('snr_beta','0.').replace('.json','')} "
158
+ f"(not vs the reference), by tercile of ref rank_pct\n"
159
+ f"{'cell':<10} {'low (n=%d)' % int((gsplit==0).sum()):>20} "
160
+ f"{'mid (n=%d)' % int((gsplit==1).sum()):>20} "
161
+ f"{'high (n=%d)' % int((gsplit==2).sum()):>20} {'overall':>20}")
162
+ print("-" * 94)
163
+ for c in order:
164
+ if c == BASE:
165
+ continue
166
+ y = np.array([r[f"{stem}_{READ}"] for r in cells[c]["rows"]], float)
167
+ d = y - b
168
+ cs, rec = [], {"cell": c, "stat": stem, "vs": BASE, "tercile": []}
169
+ for t in list(range(3)) + [None]:
170
+ m = np.ones(len(d), bool) if t is None else (gsplit == t)
171
+ lo, hi = boot_ci(d[m])
172
+ cs.append(f"{d[m].mean():+.4f}[{lo:+.4f},{hi:+.4f}]")
173
+ rec["tercile"].append({"t": t, "n": int(m.sum()), "mean": float(d[m].mean()),
174
+ "lo": lo, "hi": hi})
175
+ print(f"{c.replace('snr_beta','0.').replace('.json',''):<10} "
176
+ + " ".join(f"{x:>20}" for x in cs))
177
+ out.setdefault("rtm", []).append(rec)
178
+ out["rtm_baseline"] = BASE
179
+ out["hops_split_powered"] = bool(powered)
180
+ out["hops_tercile_means"] = [float(x) for x in th]
181
+
182
+ print("\nREADING. ABSORPTION predicts the gain sits in the LOW-hops tercile and vanishes in the\n"
183
+ "HIGH-hops tercile. A CEILING effect predicts the same shape under the rank_pct split and\n"
184
+ "is the null this probe has to beat: compare the two split rows of the same cell. If both\n"
185
+ "splits separate the gain equally, the chain-length story is not established by this probe.")
186
+ json.dump(out, open(OUT, "w"), indent=1)
187
+ print(f"\nwrote {OUT}")
188
+
189
+
190
+ if __name__ == "__main__":
191
+ main()
rsm_rise/scripts/real/act_json_regress.py ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Diff two JSON result files field-by-field and exit 5 on any difference.
2
+
3
+ ACT_COND (gen_q#278) house rule: a script may only be re-parameterised if the OLD invocation still
4
+ produces bit-identical output. This is that check, factored out so every run can use it.
5
+ Usage: act_json_regress.py --ref A.json --new B.json [--key summary] [--tol 0.0]
6
+ """
7
+ import argparse, json, sys
8
+
9
+
10
+ def flat(o, pre=""):
11
+ out = {}
12
+ if isinstance(o, dict):
13
+ for k, v in o.items():
14
+ out.update(flat(v, f"{pre}.{k}" if pre else str(k)))
15
+ elif isinstance(o, list):
16
+ for i, v in enumerate(o):
17
+ out.update(flat(v, f"{pre}[{i}]"))
18
+ elif isinstance(o, (int, float)) and not isinstance(o, bool):
19
+ out[pre] = float(o)
20
+ return out
21
+
22
+
23
+ def main():
24
+ ap = argparse.ArgumentParser()
25
+ ap.add_argument("--ref", required=True)
26
+ ap.add_argument("--new", required=True)
27
+ ap.add_argument("--key", default=None, help="compare only this top-level key")
28
+ ap.add_argument("--tol", type=float, default=0.0, help="max allowed relative difference")
29
+ a = ap.parse_args()
30
+ ra, rb = json.load(open(a.ref)), json.load(open(a.new))
31
+ if a.key:
32
+ ra, rb = ra[a.key], rb[a.key]
33
+ fa, fb = flat(ra), flat(rb)
34
+ bad, worst = [], 0.0
35
+ for k, v in fa.items():
36
+ if k not in fb:
37
+ bad.append(f"{k}: MISSING in new"); continue
38
+ d = abs(v - fb[k]) / max(abs(v), 1e-12)
39
+ worst = max(worst, d)
40
+ if d > a.tol:
41
+ bad.append(f"{k}: ref={v!r} new={fb[k]!r} rel={d:.3e}")
42
+ print(f"{len(fa)} fields compared (key={a.key}) worst rel {worst:.2e}")
43
+ if bad:
44
+ print(f"*** {len(bad)} MISMATCHES ***")
45
+ for b in bad[:12]:
46
+ print(" " + b)
47
+ sys.exit(5)
48
+ print("IDENTICAL")
49
+
50
+
51
+ if __name__ == "__main__":
52
+ main()
rsm_rise/scripts/real/act_mcpredict.py ADDED
@@ -0,0 +1,286 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """ACT_COND run 30 (gen_q#278) -- IS THE MC INSTABILITY PREDICTABLE FROM A SINGLE DRAW?
3
+
4
+ Run 29 measured that at the DEPLOYED cell (twin_rollout: particles=16, score_kind="prob") two
5
+ independent particle draws of the SAME 128-candidate cloud at the SAME state pick a DIFFERENT
6
+ argmax on 43.2% of anchors -- nearly twice as often as switching the read-out (23.5%, run 28).
7
+ Run 29's job 1892860 asks whether spending MORE particles fixes it. This script asks the
8
+ orthogonal and much cheaper question:
9
+
10
+ does the scorer ALREADY KNOW, from the single draw it has in hand, that this particular
11
+ anchor's argmax is unstable?
12
+
13
+ If it does, the fix is not a uniform particle budget but an ADAPTIVE one: spend the big budget on
14
+ the flagged minority and the deployed budget everywhere else. If it does not, instability is
15
+ unpredictable at runtime and only a uniform budget (or a tie-break) can help.
16
+
17
+ OUTCOME (per anchor): unstable := top1_agree_prob < 1.0, i.e. at least one of the R-choose-2 draw
18
+ pairs picked a different argmax.
19
+
20
+ PREDICTORS, IN TWO TIERS. The tier is the whole point and is pre-registered here:
21
+ TIER 1 -- computed from REPEAT 0 ONLY (act_sensitivity.py:238-254: q/ql = q_rep[0]). A closed-loop
22
+ scorer has exactly these in hand after its single draw, at zero extra cost. These are the only
23
+ ones that can become a runtime rule.
24
+ TIER 2 -- computed from the REPEAT STACK (act_sensitivity.py:287-301), the same stack that defines
25
+ the outcome. CIRCULAR BY CONSTRUCTION: snr/noise_var/rep_spearman and top1_agree are two
26
+ functionals of one set of draws. Reported for completeness and labelled NOT EVIDENCE; a high
27
+ AUC there says nothing about runtime predictability.
28
+
29
+ HONEST LIMIT, stated up front: the tier-1 predictors come from draw 0, which is also one of the
30
+ draws entering the outcome. That is not circular in a way that manufactures signal (a wide
31
+ candidate cloud does not mechanically cause argmax disagreement ACROSS draws), but it is not clean
32
+ either. The clean version -- predictor from draw 0, outcome from draws 1..R-1 only -- needs the
33
+ per-draw argmax indices `top1_idx_prob`, which run 29's patch stores and which therefore exist in
34
+ the mcstab cells (job 1892860) but NOT in these run-27 xpick cells. When those land, rerun with
35
+ --strict-holdout; it costs no GPU. Until then every number here carries that caveat.
36
+
37
+ DISCOVERY / HELD-OUT SPLIT: mrise is the DEPLOYED checkpoint and is the discovery cell. The
38
+ direction (sign of AUC-0.5) and the chosen predictor are fixed on it; mnt/xlrise/xlnt then confirm
39
+ or refute with the rule frozen. A predictor that flips sign across cells is reported as such.
40
+
41
+ FAILS LOUD: rc=4 a cell file is missing (a partial read must not look like a result); rc=5 a
42
+ self-test fails (planted-perfect predictor must give AUC 1.0, a shuffled one must cover 0.5).
43
+ """
44
+ import argparse, json, os, sys
45
+ import numpy as np
46
+
47
+ TIER1 = ["margin12_rel_prob", "margin12_rel_logit", "margin12_prob", "margin12_logit",
48
+ "cv_prob", "tie_frac_prob", "var_a_prob", "asi_prob", "q0",
49
+ "cv_logit", "var_a_logit", "logit0", "stage"]
50
+ TIER2 = ["snr_prob", "snr_robust_prob", "noise_var_prob", "sig_var_prob", "rep_spearman_prob"]
51
+
52
+
53
+ def auc(y, x):
54
+ """Mann-Whitney AUC of predictor x for binary y, midrank tie handling. 0.5 = no information."""
55
+ y = np.asarray(y, float); x = np.asarray(x, float)
56
+ m = np.isfinite(x) & np.isfinite(y)
57
+ y, x = y[m], x[m]
58
+ n1, n0 = float((y == 1).sum()), float((y == 0).sum())
59
+ if n1 == 0 or n0 == 0:
60
+ return float("nan")
61
+ order = np.argsort(x, kind="mergesort")
62
+ xs = x[order]
63
+ ranks = np.empty(len(x), float)
64
+ i = 0
65
+ while i < len(xs): # midranks for ties
66
+ j = i
67
+ while j + 1 < len(xs) and xs[j + 1] == xs[i]:
68
+ j += 1
69
+ ranks[order[i:j + 1]] = 0.5 * (i + j) + 1.0
70
+ i = j + 1
71
+ return float((ranks[y == 1].sum() - n1 * (n1 + 1) / 2.0) / (n1 * n0))
72
+
73
+
74
+ def boot_auc(y, x, n=10000, seed=0):
75
+ rng = np.random.default_rng(seed)
76
+ y = np.asarray(y, float); x = np.asarray(x, float)
77
+ n_a = len(y)
78
+ out = np.empty(n)
79
+ for b in range(n):
80
+ idx = rng.integers(0, n_a, n_a)
81
+ out[b] = auc(y[idx], x[idx])
82
+ out = out[np.isfinite(out)]
83
+ return float(np.percentile(out, 2.5)), float(np.percentile(out, 97.5))
84
+
85
+
86
+ def perm_p(y, x, n=10000, seed=1):
87
+ """Two-sided permutation p for |AUC-0.5| under label exchangeability."""
88
+ rng = np.random.default_rng(seed)
89
+ obs = abs(auc(y, x) - 0.5)
90
+ y = np.asarray(y, float).copy()
91
+ hits = 0
92
+ for _ in range(n):
93
+ rng.shuffle(y)
94
+ if abs(auc(y, x) - 0.5) >= obs - 1e-12:
95
+ hits += 1
96
+ return (hits + 1) / (n + 1)
97
+
98
+
99
+ def load_cell(path):
100
+ if not os.path.exists(path):
101
+ print(f"*** MISSING CELL {path} -- refusing to report a partial read", file=sys.stderr)
102
+ sys.exit(4)
103
+ return json.load(open(path))["rows"]
104
+
105
+
106
+ def col(rows, k):
107
+ return np.array([r.get(k, np.nan) for r in rows], float)
108
+
109
+
110
+ def outcome(rows, key="top1_agree_prob"):
111
+ a = col(rows, key)
112
+ if not np.all(np.isfinite(a)):
113
+ print(f"*** {key} missing/non-finite on {int((~np.isfinite(a)).sum())} rows", file=sys.stderr)
114
+ sys.exit(5)
115
+ return (a < 1.0).astype(float), a
116
+
117
+
118
+ def selftest():
119
+ rng = np.random.default_rng(7)
120
+ y = (rng.random(200) < 0.58).astype(float)
121
+ ok = True
122
+ a_perfect = auc(y, y + 1e-9 * rng.random(200))
123
+ if not (a_perfect > 0.999):
124
+ print(f"*** SELFTEST planted-perfect predictor AUC={a_perfect:.4f} != 1.0"); ok = False
125
+ x = rng.normal(size=200)
126
+ lo, hi = boot_auc(y, x, n=2000, seed=3)
127
+ a_null = auc(y, x)
128
+ if not (lo <= 0.5 <= hi):
129
+ print(f"*** SELFTEST shuffled predictor CI [{lo:.3f},{hi:.3f}] excludes 0.5"); ok = False
130
+ a_const = auc(y, np.zeros(200))
131
+ if abs(a_const - 0.5) > 1e-9:
132
+ print(f"*** SELFTEST constant predictor AUC={a_const:.6f} != 0.5"); ok = False
133
+ a_flip = auc(y, -(y + 1e-9 * rng.random(200)))
134
+ if not (a_flip < 0.001):
135
+ print(f"*** SELFTEST sign convention broken, inverted AUC={a_flip:.4f} != 0.0"); ok = False
136
+ print(f"[selftest] perfect={a_perfect:.4f} inverted={a_flip:.4f} constant={a_const:.4f} "
137
+ f"shuffled={a_null:.3f} CI[{lo:.3f},{hi:.3f}] -> {'PASS' if ok else 'FAIL'}")
138
+ if not ok:
139
+ sys.exit(5)
140
+
141
+
142
+ def main():
143
+ ap = argparse.ArgumentParser()
144
+ ap.add_argument("--xpick-dir", default="status/real/ACT_COND/xpick")
145
+ ap.add_argument("--file-tmpl", default="xpick_{c}.json")
146
+ ap.add_argument("--cells", default="mrise,mnt,xlrise,xlnt")
147
+ ap.add_argument("--discovery", default="mrise")
148
+ ap.add_argument("--flag-frac", type=float, default=0.30)
149
+ ap.add_argument("--boot", type=int, default=10000)
150
+ ap.add_argument("--perm", type=int, default=10000)
151
+ ap.add_argument("--strict-holdout", action="store_true",
152
+ help="outcome from draws 1..R-1 only (needs top1_idx_prob; mcstab cells)")
153
+ ap.add_argument("--out", default="status/real/ACT_COND/MCPREDICT_run30.json")
154
+ a = ap.parse_args()
155
+
156
+ selftest()
157
+ cells = a.cells.split(",")
158
+ data = {}
159
+ for c in cells:
160
+ rows = load_cell(os.path.join(a.xpick_dir, a.file_tmpl.format(c=c)))
161
+ if a.strict_holdout:
162
+ idx = [r.get("top1_idx_prob") for r in rows]
163
+ if any(not isinstance(v, list) or len(v) < 3 for v in idx):
164
+ print("*** --strict-holdout needs top1_idx_prob with >=3 draws per row; "
165
+ "the run-27 xpick cells predate that field (run 29 patch).", file=sys.stderr)
166
+ sys.exit(5)
167
+ y = np.array([float(len(set(v[1:])) > 1) for v in idx])
168
+ raw = np.array([float(np.mean([v[i] == v[j] for i in range(1, len(v))
169
+ for j in range(i + 1, len(v))])) for v in idx])
170
+ else:
171
+ y, raw = outcome(rows)
172
+ data[c] = (rows, y, raw)
173
+
174
+ res = {"args": vars(a), "cells": {}, "note_tier2": "CIRCULAR BY CONSTRUCTION -- not evidence",
175
+ "strict_holdout": bool(a.strict_holdout)}
176
+
177
+ print(f"\n{'='*104}\nOUTCOME: unstable := argmax differs on at least one draw pair"
178
+ f"{' (draws 1.. only, draw 0 held out)' if a.strict_holdout else ''}\n{'='*104}")
179
+ for c in cells:
180
+ rows, y, raw = data[c]
181
+ print(f" {c:<8} n={len(y):<5} unstable={y.mean():.3f} mean top1_agree={raw.mean():.3f}")
182
+ res["cells"][c] = {"n": int(len(y)), "unstable_frac": float(y.mean()),
183
+ "top1_agree_mean": float(raw.mean()), "auc": {}}
184
+
185
+ disc = a.discovery
186
+ for tier, names in (("TIER 1 -- SINGLE DRAW, runtime-available at zero cost", TIER1),
187
+ ("TIER 2 -- repeat-derived, CIRCULAR, NOT EVIDENCE", TIER2)):
188
+ print(f"\n{'-'*104}\n{tier}\n{'-'*104}")
189
+ print(f" {'predictor':<18}" + "".join(f"{c:>22}" for c in cells) + " sign-consistent")
190
+ for k in names:
191
+ line, aucs = f" {k:<20}", {}
192
+ for c in cells:
193
+ rows, y, raw = data[c]
194
+ x = col(rows, k)
195
+ fin = x[np.isfinite(x)]
196
+ if len(fin) == 0:
197
+ line += f"{'absent':>22}"; aucs[c] = None; continue
198
+ if len(np.unique(fin)) < 2:
199
+ line += f"{'DEGEN(const)':>22}"
200
+ aucs[c] = {"auc": 0.5, "ci": [0.5, 0.5], "degenerate": True,
201
+ "const_value": float(fin[0])}
202
+ continue
203
+ v = auc(y, x)
204
+ lo, hi = boot_auc(y, x, n=a.boot, seed=11)
205
+ sig = not (lo <= 0.5 <= hi)
206
+ aucs[c] = {"auc": v, "ci": [lo, hi], "significant": bool(sig)}
207
+ if c == disc:
208
+ aucs[c]["perm_p"] = perm_p(y, x, n=a.perm, seed=12)
209
+ line += f"{v:>8.3f} [{lo:.3f},{hi:.3f}]{'*' if sig else ' '}"
210
+ # A point estimate on the far side of 0.5 with a CI covering it is UNINFORMATIVE, not
211
+ # reversed. Consistency is therefore judged over the cells where the predictor is
212
+ # SIGNIFICANT; "flips" is reserved for two significant cells disagreeing in sign.
213
+ sigc = [c for c in cells if aucs[c] and aucs[c].get("significant")]
214
+ sg = {np.sign(aucs[c]["auc"] - 0.5) for c in sigc}
215
+ flips = len(sg) > 1
216
+ verdict = ("FLIPS" if flips else
217
+ f"sig on {len(sigc)}/{len(cells)}" if sigc else "no signal anywhere")
218
+ line += f" {verdict}"
219
+ print(line)
220
+ for c in cells:
221
+ if aucs[c]:
222
+ res["cells"][c]["auc"][k] = aucs[c]
223
+ res.setdefault("consistency", {})[k] = {
224
+ "significant_cells": sigc, "flips": bool(flips), "verdict": verdict}
225
+
226
+ # ---- decision utility, rule FROZEN on the discovery cell then applied verbatim elsewhere ----
227
+ rows_d, y_d, _ = data[disc]
228
+ best, best_gap = None, 0.0
229
+ for k in TIER1:
230
+ e = res["cells"][disc]["auc"].get(k)
231
+ if not e or e.get("degenerate") or not e.get("significant"):
232
+ continue
233
+ if res["consistency"][k]["flips"]:
234
+ continue
235
+ g = abs(e["auc"] - 0.5)
236
+ if g > best_gap:
237
+ best, best_gap = k, g
238
+ if best is None:
239
+ print("\n*** no tier-1 predictor is significant on the discovery cell -- "
240
+ "MC instability is NOT predictable from a single draw; no rule to freeze.")
241
+ os.makedirs(os.path.dirname(a.out), exist_ok=True)
242
+ json.dump(res, open(a.out, "w"), indent=1)
243
+ print(f"wrote {a.out}")
244
+ return
245
+ direction = np.sign(auc(y_d, col(rows_d, best)) - 0.5) # +1: HIGH value => unstable
246
+ thr = np.nanpercentile(col(rows_d, best),
247
+ (1 - a.flag_frac) * 100 if direction > 0 else a.flag_frac * 100)
248
+ print(f"\n{'-'*104}\nDECISION UTILITY. Rule frozen on the DISCOVERY cell '{disc}': flag when "
249
+ f"{best} {'>=' if direction > 0 else '<='} {thr:.6g}\n"
250
+ f"(threshold = the {a.flag_frac*100:.0f}% of discovery anchors most likely unstable; "
251
+ f"applied VERBATIM to the other cells)\n{'-'*104}")
252
+ print(f" {'cell':<9}{'flagged':>9}{'recall':>9}{'chance':>9}{'lift':>8}"
253
+ f"{'precision':>11}{'base':>8}{'refit-lift':>10} unstable captured")
254
+ res["rule"] = {"predictor": best, "direction": int(direction), "threshold": float(thr),
255
+ "flag_frac_target": a.flag_frac, "frozen_on": disc, "cells": {}}
256
+ for c in cells:
257
+ rows, y, _ = data[c]
258
+ x = col(rows, best)
259
+ fl = (x >= thr) if direction > 0 else (x <= thr)
260
+ fl = fl & np.isfinite(x)
261
+ ff = float(fl.mean())
262
+ rec = float(y[fl].sum() / max(y.sum(), 1))
263
+ prec = float(y[fl].mean()) if fl.sum() else float("nan")
264
+ # REFIT: same predictor, threshold re-taken on THIS cell at the same flag fraction. If the
265
+ # frozen rule fails but the refit works, the threshold does not transfer; if both fail, the
266
+ # predictor carries no signal on this cell.
267
+ thr_c = np.nanpercentile(x, (1 - a.flag_frac) * 100 if direction > 0 else a.flag_frac * 100)
268
+ fl_c = ((x >= thr_c) if direction > 0 else (x <= thr_c)) & np.isfinite(x)
269
+ rec_c = float(y[fl_c].sum() / max(y.sum(), 1))
270
+ lift_c = rec_c / max(float(fl_c.mean()), 1e-9)
271
+ print(f" {c:<9}{ff:>9.3f}{rec:>9.3f}{ff:>9.3f}{rec/max(ff,1e-9):>8.2f}"
272
+ f"{prec:>11.3f}{y.mean():>8.3f}{lift_c:>10.2f} {int(y[fl].sum())}/{int(y.sum())}")
273
+ res["rule"]["cells"][c] = {"flag_frac": ff, "recall": rec, "precision": prec,
274
+ "lift": rec / max(ff, 1e-9), "base_rate": float(y.mean()),
275
+ "captured": int(y[fl].sum()), "total_unstable": int(y.sum()),
276
+ "refit_lift": lift_c, "refit_recall": rec_c,
277
+ "refit_threshold": float(thr_c)}
278
+ print("\n lift 1.00 = the flag is no better than flagging that fraction at random.")
279
+
280
+ os.makedirs(os.path.dirname(a.out), exist_ok=True)
281
+ json.dump(res, open(a.out, "w"), indent=1)
282
+ print(f"\nwrote {a.out}")
283
+
284
+
285
+ if __name__ == "__main__":
286
+ main()
rsm_rise/scripts/real/act_mcstab_read.py ADDED
@@ -0,0 +1,239 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ACT_COND run 29 (gen_q#278): MONTE-CARLO PICK INSTABILITY vs THE READ-OUT, AND CAN PARTICLES FIX IT?
2
+
3
+ Run 28's headline was that swapping the read-out prob->logit moves the executed argmax on 23.5% of
4
+ anchors at the deployed cell (5.9 cm of first-step xyz). The SAME cells already carried the control
5
+ and nobody had read it: `top1_agree_prob` is the identical quantity with the OTHER factor varied --
6
+ two INDEPENDENT PARTICLE DRAWS under ONE read-out, same cloud, same state -- and at the deployed cell
7
+ it is 0.568, i.e. the redraw changes the pick on 43.2% of anchors. MC noise is the LARGER source of
8
+ pick change. The deployed scorer is twin_rollout.py particles=16 score_kind=prob, so this is not a
9
+ diagnostic regime: it is the shipped configuration.
10
+
11
+ This reader consumes the run-29 particle sweep (P = 16 / 32 / 64, two checkpoints, repeats=4) and
12
+ answers the only question that follows: IS IT FIXABLE BY SPENDING PARTICLES?
13
+ * the P-curve of top1_agree (and of rep_spearman / snr) -- does it climb, and towards what;
14
+ * `top1_agree_half`, two DISJOINT 2-draw averages, an effective 2x budget measured inside the P
15
+ cell itself. Pre-registered: it should track top1_agree at 2P. Two independent routes to the
16
+ same number is the check that the curve is estimator noise and not something else;
17
+ * the paired head-to-head at each P: (1 - top1_agree) vs (1 - xpick_agree) on the SAME anchors.
18
+
19
+ IT REFUSES TO PRINT NUMBERS OFF A BROKEN PATCH. The run-29 patch is additive and repeat 0 keeps its
20
+ historical seed, so every REPEAT-0 field of the P=16 cells must reproduce xpick/xpick_<tag>.json
21
+ bit-for-bit. Mismatch => rc=5, nothing else is read. Repeat-DERIVED fields are excluded BY NAME and
22
+ the exclusion is printed: R goes 3 -> 4, so they legitimately move. Missing cells => rc=4.
23
+ """
24
+ import argparse, json, math, os, sys
25
+ import numpy as np
26
+
27
+ ROOT = "/proj/dmfexp/zwhong/rsm_rise"
28
+ # fields computed from the repeat stack; R changed 3 -> 4 so they are NOT part of the regression.
29
+ REPEAT_DERIVED = ("snr_", "top1_agree", "top1_idx", "top1_half_idx", "rep_spearman", "noise_var_",
30
+ "sig_var_", "margin12_rel_draws_")
31
+ # CUMULATIVE ACCUMULATOR fields, excluded BY EXACT NAME (run 31). rsm_scorer.chain_hop_acc is a
32
+ # running accumulator that act_sensitivity never resets (act_sensitivity.py:254), so a repeats=4
33
+ # cell averages realized hops over 4/3 as many decisions as a repeats=3 cell. Same law, different
34
+ # sample -- these two are not repeat-0 statistics and never were. Pre-documented at
35
+ # build_snr_table.py:17, written BEFORE run 29, so this is not a post-hoc excuse.
36
+ # DELIBERATELY BY EXACT NAME, not the "chain_" prefix: chain_cap / chain_p_cont /
37
+ # chain_E_hops_expected are DETERMINISTIC CONFIG and must stay inside the gate -- a silently
38
+ # changed cap is exactly the bug this regression exists to catch.
39
+ ACCUMULATOR_FIELDS = ("chain_hops_mean", "chain_capped_frac")
40
+
41
+
42
+ def wilson(k, n, z=1.96):
43
+ if n <= 0:
44
+ return float("nan"), float("nan")
45
+ p = k / n
46
+ d = 1 + z * z / n
47
+ c = p + z * z / (2 * n)
48
+ h = z * math.sqrt(p * (1 - p) / n + z * z / (4 * n * n))
49
+ return (c - h) / d, (c + h) / d
50
+
51
+
52
+ def boot_ci(d, n=20000, seed=0):
53
+ d = np.asarray(d, float)
54
+ if len(d) < 2:
55
+ return float("nan"), float("nan")
56
+ r = np.random.default_rng(seed)
57
+ m = d[r.integers(0, len(d), size=(n, len(d)))].mean(1)
58
+ return float(np.percentile(m, 2.5)), float(np.percentile(m, 97.5))
59
+
60
+
61
+ def flat(o, pre=""):
62
+ out = {}
63
+ if isinstance(o, dict):
64
+ for k, v in o.items():
65
+ out.update(flat(v, f"{pre}.{k}" if pre else str(k)))
66
+ elif isinstance(o, list):
67
+ for i, v in enumerate(o):
68
+ out.update(flat(v, f"{pre}[{i}]"))
69
+ elif isinstance(o, (int, float)) and not isinstance(o, bool):
70
+ out[pre] = float(o)
71
+ return out
72
+
73
+
74
+ def main():
75
+ ap = argparse.ArgumentParser()
76
+ ap.add_argument("--dir", default=f"{ROOT}/status/real/ACT_COND/mcstab")
77
+ ap.add_argument("--xpick-dir", default=f"{ROOT}/status/real/ACT_COND/xpick")
78
+ ap.add_argument("--cells", default="mrise,mnt")
79
+ ap.add_argument("--particles", default="16,32,64")
80
+ ap.add_argument("--out", default=f"{ROOT}/status/real/ACT_COND/MCSTAB_run29.json")
81
+ a = ap.parse_args()
82
+ cellnames = [c for c in a.cells.split(",") if c]
83
+ PS = [int(x) for x in a.particles.split(",") if x]
84
+
85
+ cells, missing = {}, []
86
+ for c in cellnames:
87
+ for P in PS:
88
+ p = f"{a.dir}/mc_{c}_p{P}.json"
89
+ if not os.path.exists(p):
90
+ missing.append(p)
91
+ else:
92
+ cells[(c, P)] = json.load(open(p))
93
+ if missing:
94
+ print("MISSING CELLS -- a partial job is not a result:")
95
+ [print(" " + m) for m in missing]
96
+ sys.exit(4)
97
+
98
+ # ------------------------------------------------------------------ REGRESSION (rc=5 on fail)
99
+ print("=" * 104)
100
+ print("REGRESSION: the run-29 patch is ADDITIVE and repeat 0 keeps its seed, so every REPEAT-0")
101
+ print("field of the P=16 cells must reproduce the run-27 xpick cell bit-for-bit.")
102
+ print("EXCLUDED BY NAME (repeat-derived, R 3 -> 4): " + ", ".join(REPEAT_DERIVED))
103
+ print("=" * 104)
104
+ Pbase = min(PS)
105
+ nbad = 0
106
+ for c in cellnames:
107
+ ref_p = f"{a.xpick_dir}/xpick_{c}.json"
108
+ if not os.path.exists(ref_p):
109
+ print(f" {c}: no reference {ref_p} -- SKIPPED (cannot regress)")
110
+ continue
111
+ ref = json.load(open(ref_p))["rows"]
112
+ new = cells[(c, Pbase)]["rows"]
113
+ if len(ref) != len(new):
114
+ print(f"*** {c}: {len(ref)} ref rows vs {len(new)} new rows"); nbad += 1; continue
115
+ nf, worst, bad, tally, acc = 0, 0.0, [], {}, {}
116
+ for i, (r0, r1) in enumerate(zip(ref, new)):
117
+ fa, fb = flat(r0), flat(r1)
118
+ for k, v in fa.items():
119
+ if any(k.startswith(x) or f".{x}" in k for x in REPEAT_DERIVED):
120
+ continue
121
+ base = k.split(".")[-1]
122
+ if base in ACCUMULATOR_FIELDS:
123
+ if k in fb:
124
+ acc.setdefault(base, ([], []))[0].append(v)
125
+ acc[base][1].append(fb[k])
126
+ continue
127
+ if k not in fb:
128
+ bad.append(f"({i}).{k}: MISSING in new")
129
+ tally[k + " MISSING"] = tally.get(k + " MISSING", 0) + 1
130
+ continue
131
+ nf += 1
132
+ d = abs(v - fb[k]) / max(abs(v), 1e-12)
133
+ worst = max(worst, d)
134
+ if d > 0:
135
+ bad.append(f"({i}).{k}: ref={v!r} new={fb[k]!r}")
136
+ tally[k] = tally.get(k, 0) + 1
137
+ # The excluded accumulators are PRINTED, not hidden: an exclusion the reader cannot see is
138
+ # indistinguishable from a gate that was quietly turned off. Means only -- they are a
139
+ # different SAMPLE of the same geometric hop law, so equality is not expected and a large
140
+ # shift in the MEAN would still be worth chasing.
141
+ for base, (rv, nv) in sorted(acc.items()):
142
+ print(f" {c} [SAMPLING-ONLY, excluded] {base}: ref mean {np.mean(rv):.4f} "
143
+ f"new mean {np.mean(nv):.4f} (cumulative accumulator, R 3 -> 4; not a repeat-0 stat)")
144
+ if bad:
145
+ print(f"*** {c}: {len(bad)} MISMATCHES over {len(tally)} FIELD(S) ***")
146
+ for k in sorted(tally, key=lambda z: -tally[z]):
147
+ print(f" {k}: {tally[k]} row(s)")
148
+ [print(" e.g. " + b) for b in bad[:5]]
149
+ nbad += 1
150
+ else:
151
+ print(f" {c} P={Pbase}: {nf} fields worst rel {worst:.2e} IDENTICAL")
152
+ if nbad:
153
+ print("\nThe additive patch moved a pre-existing field. The run-29 numbers must not be read "
154
+ "until this is explained.")
155
+ sys.exit(5)
156
+
157
+ # ------------------------------------------------------------------ THE PARTICLE CURVE
158
+ res = {}
159
+ print("\n" + "=" * 104)
160
+ print("PICK REPRODUCIBILITY vs PARTICLE BUDGET. top1_agree = P(two independent particle draws of")
161
+ print("the SAME 128-candidate cloud at the SAME state pick the SAME action). Deployed = P16/prob.")
162
+ print("=" * 104)
163
+ print(f"{'cell':<8}{'P':>5}{'read':>7}{'n':>5}{'top1_agree':>12}{'Wilson95':>20}"
164
+ f"{'half(2x)':>10}{'rep_rho':>9}{'snr':>10}{'xpick_agree':>13}")
165
+ print("-" * 104)
166
+ for c in cellnames:
167
+ for P in PS:
168
+ rows = cells[(c, P)]["rows"]
169
+ n = len(rows)
170
+ xa = float(np.mean([r["xpick_agree"] for r in rows]))
171
+ for kind in ("prob", "logit"):
172
+ t = np.array([r[f"top1_agree_{kind}"] for r in rows])
173
+ h = np.array([r[f"top1_agree_half_{kind}"] for r in rows])
174
+ rr = float(np.mean([r[f"rep_spearman_{kind}"] for r in rows]))
175
+ sn = float(np.mean([r[f"sig_var_{kind}"] for r in rows]) /
176
+ max(np.mean([r[f"noise_var_{kind}"] for r in rows]), 1e-30))
177
+ # top1_agree is a mean over pairs per anchor; the Wilson interval is taken on the
178
+ # effective pair count (n anchors x pairs) -- it is an agreement RATE over pairs.
179
+ npair = n * 6 # R=4 -> 6 ordered-unordered pairs per anchor
180
+ lo, hi = wilson(t.mean() * npair, npair)
181
+ print(f"{c:<8}{P:>5}{kind:>7}{n:>5}{t.mean():>12.3f}{f'[{lo:.3f}, {hi:.3f}]':>20}"
182
+ f"{np.nanmean(h):>10.3f}{rr:>9.4f}{sn:>10.3f}{xa:>13.3f}")
183
+ res[f"{c}_p{P}_{kind}"] = dict(n=n, top1_agree=float(t.mean()), wilson=[lo, hi],
184
+ half=float(np.nanmean(h)), rep_spearman=rr, snr=sn,
185
+ xpick_agree=xa)
186
+ print("-" * 104)
187
+
188
+ # ------------- PRE-REGISTERED CHECK: half(P) should track top1_agree(2P) -------------
189
+ print("\nPRE-REGISTERED: `half` at P averages two draws, an effective 2x budget, so it should")
190
+ print("track top1_agree at 2P. Two independent routes to the same number; a large gap means the")
191
+ print("curve is not simple estimator noise.")
192
+ print(f"{'cell':<8}{'read':>7}{'P':>5}{'half(P)':>10}{'top1(2P)':>10}{'gap':>9}")
193
+ print("-" * 104)
194
+ for c in cellnames:
195
+ for kind in ("prob", "logit"):
196
+ for P in PS:
197
+ if 2 * P not in PS:
198
+ continue
199
+ hp = res[f"{c}_p{P}_{kind}"]["half"]
200
+ t2 = res[f"{c}_p{2*P}_{kind}"]["top1_agree"]
201
+ print(f"{c:<8}{kind:>7}{P:>5}{hp:>10.3f}{t2:>10.3f}{hp-t2:>+9.3f}")
202
+
203
+ # ------------- PAIRED HEAD-TO-HEAD: MC redraw vs read-out switch, same anchors -------------
204
+ print("\nPAIRED HEAD-TO-HEAD on the SAME anchors: which factor changes the executed pick more,")
205
+ print("redrawing the particles (same read-out) or switching the read-out (same draw)?")
206
+ print("d = (1 - top1_agree_prob) - (1 - xpick_agree) > 0 means MC NOISE DOMINATES.")
207
+ print(f"{'cell':<8}{'P':>5}{'n':>5}{'MC disagree':>13}{'readout dis':>13}{'d':>9}{'bootCI95':>22}"
208
+ f"{'dominant':>10}")
209
+ print("-" * 104)
210
+ for c in cellnames:
211
+ for P in PS:
212
+ rows = cells[(c, P)]["rows"]
213
+ mc = 1 - np.array([r["top1_agree_prob"] for r in rows])
214
+ ro = 1 - np.array([r["xpick_agree"] for r in rows])
215
+ d = mc - ro
216
+ lo, hi = boot_ci(d)
217
+ dom = "MC" if lo > 0 else ("read-out" if hi < 0 else "ns")
218
+ print(f"{c:<8}{P:>5}{len(rows):>5}{mc.mean():>13.3f}{ro.mean():>13.3f}{d.mean():>+9.3f}"
219
+ f"{f'[{lo:+.3f}, {hi:+.3f}]':>22}{dom:>10}")
220
+ res[f"{c}_p{P}_prob"].update(mc_disagree=float(mc.mean()), ro_disagree=float(ro.mean()),
221
+ d_mc_minus_ro=float(d.mean()), d_ci=[lo, hi], dominant=dom)
222
+
223
+ # ------------- per-stage, deployed cell -------------
224
+ print("\nPER-STAGE top1_agree_prob (deployed read-out):")
225
+ for c in cellnames:
226
+ for P in PS:
227
+ rows = cells[(c, P)]["rows"]
228
+ by = sorted({r["stage"] for r in rows})
229
+ line = " ".join(f"S{s}: {np.mean([r['top1_agree_prob'] for r in rows if r['stage']==s]):.3f}"
230
+ for s in by)
231
+ print(f" {c:<8} P={P:<4} {line}")
232
+
233
+ os.makedirs(os.path.dirname(a.out) or ".", exist_ok=True)
234
+ json.dump(res, open(a.out, "w"), indent=1)
235
+ print(f"\nwrote {a.out}")
236
+
237
+
238
+ if __name__ == "__main__":
239
+ main()
rsm_rise/scripts/real/act_pickdist.py ADDED
@@ -0,0 +1,356 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ACT_COND run 28 (gen_q#278): IS THE READ-OUT'S 23.5% ARGMAX DISAGREEMENT A BEHAVIOUR CHANGE, OR A
2
+ RELABELLING AMONG NEAR-DUPLICATE CANDIDATES?
3
+
4
+ Run 27 measured the thing runs 25/26 had not: at the DEPLOYED cell the `prob` and `logit` argmaxes over
5
+ the 128-candidate cloud disagree on 47/200 anchors (agree 0.765). That kills the "closed-loop no-op"
6
+ reading. But an INDEX disagreement is not yet a BEHAVIOUR difference: the cloud is 128 stage-matched
7
+ LOGGED chunks, many of which are near-duplicates of each other, so two different indices can be the
8
+ same motion to within a millimetre. The quantity that decides whether the eval stream must A/B the
9
+ switch is the DISTANCE IN ACTION SPACE between the two picks, measured against the cloud's own spread.
10
+
11
+ NO GPU AND NO MODEL. The candidate cloud is built from the hdf5 + a fixed-seed rng stream, and run 27
12
+ stored `xpick_prob_idx` / `xpick_logit_idx` per anchor. So this script REPLAYS the anchor/candidate
13
+ construction of act_sensitivity.py exactly (same code path, same rng consumption order: choice(cands)
14
+ -> permutation(states) -> probe_target), indexes the two picks, and measures them. It computes nothing
15
+ on the network.
16
+
17
+ IT REFUSES TO PRINT NUMBERS OFF A MISALIGNED REPLAY. Two gates, both fatal (rc=5):
18
+ * every anchor's (ep, t, stage, route) must match the stored row, in order;
19
+ * every anchor's `probe_src` must match. probe_src is drawn AFTER the candidate draw, so matching
20
+ it on all anchors proves the rng stream was aligned at the moment the candidates were drawn --
21
+ the only thing that could silently corrupt this measurement.
22
+ * free internal check: on AGREEING anchors (prob_idx == logit_idx) every distance must be exactly 0.
23
+
24
+ Distances are reported three ways, because they answer different questions:
25
+ * FIRST-STEP xyz in cm -- the closed loop replans, so step 0 is what actually gets executed;
26
+ * whole-chunk L2 in trainer-NORMALISED units (2*(a-lo)/(hi-lo)-1), all 10 coords on one scale;
27
+ * GRIPPER at step 0 -- a discrete decision (open vs close); a flip there is the most consequential
28
+ single-coordinate difference the switch can make.
29
+ Each is normalised by the CLOUD's own spread (mean pairwise distance over the 128 candidates), so
30
+ "different index, same motion" and "different index, different motion" are distinguishable.
31
+ PLUS the paired quality proxy that needs no model: is the `logit` pick CLOSER to the anchor's own
32
+ logged goal-route chunk than the `prob` pick? Bootstrap CI + Wilcoxon over disagreeing anchors.
33
+ """
34
+ import argparse, json, os, sys, collections
35
+ import numpy as np
36
+
37
+ ROOT = "/proj/dmfexp/zwhong/rsm_rise"
38
+ GOAL_PATH = "2->3->4"
39
+ FAIL_PATHS = ("0->5", "0->2->6")
40
+ CELLS = ["mrise", "mnt", "xlrise", "xlnt"]
41
+
42
+
43
+ def boot_ci(d, n=20000, seed=0):
44
+ d = np.asarray(d, float)
45
+ if len(d) < 2:
46
+ return float("nan"), float("nan")
47
+ r = np.random.default_rng(seed)
48
+ m = d[r.integers(0, len(d), size=(n, len(d)))].mean(1)
49
+ return float(np.percentile(m, 2.5)), float(np.percentile(m, 97.5))
50
+
51
+
52
+ def wilcoxon(d):
53
+ d = np.asarray(d, float); d = d[d != 0]
54
+ n = len(d)
55
+ if n < 6:
56
+ return float("nan")
57
+ a = np.abs(d); o = np.argsort(a, kind="mergesort")
58
+ rk = np.empty(n, float); rk[o] = np.arange(1, n + 1)
59
+ s = np.sort(a); i = 0
60
+ while i < n:
61
+ j = i
62
+ while j + 1 < n and s[j + 1] == s[i]:
63
+ j += 1
64
+ if j > i:
65
+ rk[o[i:j + 1]] = np.arange(i + 1, j + 2).mean()
66
+ i = j + 1
67
+ W = rk[d > 0].sum()
68
+ mu = n * (n + 1) / 4.0
69
+ sd = np.sqrt(n * (n + 1) * (2 * n + 1) / 24.0)
70
+ if sd <= 0:
71
+ return float("nan")
72
+ from math import erfc, sqrt
73
+ return float(erfc(abs(W - mu) / sd / sqrt(2.0)))
74
+
75
+
76
+ def replay(a):
77
+ """Rebuild the anchor list and, per anchor, the 128 candidate chunks -- CPU only, no model."""
78
+ import h5py
79
+ split = json.load(open(a.split))["episodes"]
80
+ meta = np.load(f"{a.cache}/meta.npz", allow_pickle=True)
81
+ ep_from = np.asarray(meta["ep_from"])
82
+ f = h5py.File(a.hdf5, "r"); d = f["data"]
83
+ lo = np.array(json.loads(d.attrs["action_min"]), np.float32)
84
+ hi = np.array(json.loads(d.attrs["action_max"]), np.float32)
85
+ spl = lambda k: split.get(str(int(k.split("_")[1])), {}).get("split", "")
86
+ path = lambda k: str(d[k].attrs.get("path", ""))
87
+ train = [k for k in d if spl(k) == "train"]
88
+ rng = np.random.default_rng(a.seed)
89
+ chunk_pool = collections.defaultdict(list)
90
+ state_pool = collections.defaultdict(list)
91
+ fail_pool = collections.defaultdict(list)
92
+ anchors = []
93
+ for k in train:
94
+ g = d[k]; ep = int(k.split("_")[1])
95
+ A = np.asarray((g["actions_raw"] if "actions_raw" in g else g["actions"])[()], np.float32)
96
+ stg = np.asarray(g["annot"]["edge_from"][()])
97
+ for t in range(0, len(A) - a.horizon, a.stride):
98
+ s0 = int(stg[t]); ch = A[t:t + a.horizon]
99
+ chunk_pool[s0].append(ch)
100
+ state_pool[s0].append(int(ep_from[ep] + t))
101
+ if path(k) in FAIL_PATHS:
102
+ fail_pool[s0].append(ch)
103
+ if a.anchor_routes == "all" or path(k) == GOAL_PATH:
104
+ anchors.append((ep, t, s0, path(k)))
105
+ by_stage = collections.defaultdict(list)
106
+ for x in anchors:
107
+ by_stage[x[2]].append(x)
108
+ if len(anchors) > a.max_anchors:
109
+ stages = sorted(by_stage)
110
+ quota = {s: a.max_anchors // len(stages) for s in stages}
111
+ left = a.max_anchors - sum(min(quota[s], len(by_stage[s])) for s in stages)
112
+ for s in sorted(stages, key=lambda s: -len(by_stage[s])):
113
+ take = min(left, max(0, len(by_stage[s]) - quota[s]))
114
+ quota[s] += take; left -= take
115
+ picked = []
116
+ for s in stages:
117
+ v = by_stage[s]; n = min(quota[s], len(v))
118
+ picked += [v[i] for i in sorted(rng.choice(len(v), size=n, replace=False))]
119
+ anchors = sorted(picked, key=lambda x: (x[0], x[1]))
120
+ fail_stages = [s for s, v in fail_pool.items() if v]
121
+
122
+ def probe_target(s0):
123
+ if fail_pool[s0]:
124
+ rng.integers(len(fail_pool[s0])); return "failure_same_stage"
125
+ if fail_stages:
126
+ sp = fail_stages[int(rng.integers(len(fail_stages)))]
127
+ rng.integers(len(fail_pool[sp])); return "failure_other_stage"
128
+ others = [s for s, v in chunk_pool.items() if s != s0 and v]
129
+ sp = others[int(rng.integers(len(others)))]
130
+ rng.integers(len(chunk_pool[sp])); return "offstage"
131
+
132
+ NC, NS = a.n_cand, a.n_state
133
+ out = []
134
+ for (ep, t, s0, route) in anchors:
135
+ if len(chunk_pool[s0]) < NC or len(state_pool[s0]) < NS + 1:
136
+ continue # consumes no rng -- mirrors the measurer
137
+ gi = int(ep_from[ep] + t)
138
+ g = d[f"demo_{ep}"]
139
+ a0 = np.asarray((g["actions_raw"] if "actions_raw" in g else g["actions"])[t:t + a.horizon], np.float32)
140
+ ci = rng.choice(len(chunk_pool[s0]), size=NC, replace=False)
141
+ cands = np.stack([chunk_pool[s0][i] for i in ci])
142
+ [j for j in rng.permutation(len(state_pool[s0])) if state_pool[s0][j] != gi][:NS]
143
+ psrc = probe_target(s0)
144
+ out.append(dict(ep=ep, t=t, stage=s0, route=route, probe_src=psrc, cands=cands, a0=a0))
145
+ f.close()
146
+ return out, lo, hi
147
+
148
+
149
+ def main():
150
+ ap = argparse.ArgumentParser()
151
+ ap.add_argument("--hdf5", default=f"{ROOT}/data/raw/cooking_v5_expert_suboptimal.hdf5")
152
+ ap.add_argument("--split", default=f"{ROOT}/data/derived/cooking_v5_split.json")
153
+ ap.add_argument("--cache", default=f"{ROOT}/cache/real_cooking_v5")
154
+ ap.add_argument("--xpick-dir", default=f"{ROOT}/status/real/ACT_COND/xpick")
155
+ ap.add_argument("--horizon", type=int, default=8)
156
+ ap.add_argument("--stride", type=int, default=25)
157
+ ap.add_argument("--n-cand", type=int, default=128)
158
+ ap.add_argument("--n-state", type=int, default=128)
159
+ ap.add_argument("--max-anchors", type=int, default=200)
160
+ ap.add_argument("--anchor-routes", default="all")
161
+ ap.add_argument("--seed", type=int, default=0)
162
+ ap.add_argument("--out", required=True)
163
+ # ---- run 29 (gen_q#278), ADDITIVE: the same replay answers "how far apart are two picks?" for
164
+ # ANY pair of stored index fields, not just prob-vs-logit. Run 29 needs it for the MC pair
165
+ # (two independent particle draws under ONE read-out), which run 28's numbers must be compared
166
+ # against. Every default below reproduces the run-28 invocation byte-for-byte.
167
+ # A field may be "name" (scalar) or "name:i" (i-th element of a stored list).
168
+ ap.add_argument("--cells", default=",".join(CELLS))
169
+ ap.add_argument("--file-tmpl", default="xpick_{c}.json")
170
+ ap.add_argument("--idx-a", default="xpick_prob_idx")
171
+ ap.add_argument("--idx-b", default="xpick_logit_idx")
172
+ ap.add_argument("--label-a", default="prob")
173
+ ap.add_argument("--label-b", default="logit")
174
+ a = ap.parse_args()
175
+ CELLS[:] = [c for c in a.cells.split(",") if c]
176
+ LA, LB = a.label_a, a.label_b
177
+
178
+ def getidx(r, spec):
179
+ nm, _, k = spec.partition(":")
180
+ v = r.get(nm)
181
+ if v is None:
182
+ return None
183
+ if k != "":
184
+ v = v[int(k)] if int(k) < len(v) else None
185
+ return v
186
+
187
+ cells = {}
188
+ missing = []
189
+ for c in CELLS:
190
+ p = f"{a.xpick_dir}/{a.file_tmpl.format(c=c)}"
191
+ if not os.path.exists(p):
192
+ missing.append(p); continue
193
+ cells[c] = json.load(open(p))
194
+ if missing:
195
+ print("MISSING CELLS -- a partial job is not a result:"); [print(" " + m) for m in missing]
196
+ sys.exit(4)
197
+
198
+ rep, lo, hi = replay(a)
199
+ span = (hi - lo).astype(np.float64)
200
+ print(f"[replay] rebuilt {len(rep)} anchors, action span xyz(cm) "
201
+ f"{np.round(100*span[:3],2)} gripper span {span[-1]:.3f}", flush=True)
202
+
203
+ # ---------------- GATE 1/2: the replay must line up with every stored row ----------------
204
+ fatal = 0
205
+ for c, cd in cells.items():
206
+ rows = cd["rows"]
207
+ if len(rows) != len(rep):
208
+ print(f"*** {c}: replay has {len(rep)} anchors, cell has {len(rows)}"); fatal += 1; continue
209
+ bad = []
210
+ for i, (r, q) in enumerate(zip(rows, rep)):
211
+ if (int(r["ep"]), int(r["t"]), int(r["stage"]), str(r["route"])) != \
212
+ (q["ep"], q["t"], q["stage"], q["route"]):
213
+ bad.append(f"{i}:anchor {r['ep']},{r['t']} vs {q['ep']},{q['t']}")
214
+ elif str(r["probe_src"]) != q["probe_src"]:
215
+ bad.append(f"{i}:probe_src {r['probe_src']} vs {q['probe_src']}")
216
+ if len(bad) > 5:
217
+ break
218
+ if bad:
219
+ print(f"*** {c}: REPLAY MISALIGNED ({len(bad)}+ mismatches): " + "; ".join(bad)); fatal += 1
220
+ else:
221
+ print(f"[gate] {c}: {len(rows)} anchors + probe_src ALIGNED "
222
+ f"(rng stream proven aligned at the candidate draw)")
223
+ if fatal:
224
+ print("\nThe rng replay does not reproduce the measured cells. Every distance below would be "
225
+ "computed off the WRONG candidate cloud. Nothing is printed.")
226
+ sys.exit(5)
227
+
228
+ def nrm(ch): # trainer-normalised [-1,1] chunk
229
+ return (2.0 * (ch.astype(np.float64) - lo) / span - 1.0)
230
+
231
+ res = {}
232
+ for c, cd in cells.items():
233
+ rows = cd["rows"]
234
+ per = []
235
+ for r, q in zip(rows, rep):
236
+ pi, li = getidx(r, a.idx_a), getidx(r, a.idx_b)
237
+ if pi is None or li is None or not np.isfinite(pi) or not np.isfinite(li):
238
+ continue
239
+ pi, li = int(pi), int(li)
240
+ C, a0 = q["cands"], q["a0"]
241
+ Cn = nrm(C)
242
+ cp, cl, an = Cn[pi], Cn[li], nrm(a0)
243
+ # cloud spread: mean pairwise distance over the 128 candidates (same metric, same units)
244
+ flat = Cn.reshape(len(Cn), -1)
245
+ G = flat @ flat.T
246
+ sq = np.diag(G)
247
+ D2 = np.maximum(sq[:, None] + sq[None, :] - 2 * G, 0.0)
248
+ cloud_full = float(np.sqrt(D2)[np.triu_indices(len(Cn), 1)].mean())
249
+ xyz = C[:, 0, :3].astype(np.float64) * 100.0 # cm, first step
250
+ dx = xyz[:, None, :] - xyz[None, :, :]
251
+ cloud_xyz = float(np.sqrt((dx ** 2).sum(-1))[np.triu_indices(len(xyz), 1)].mean())
252
+ per.append(dict(
253
+ stage=int(r["stage"]), agree=bool(pi == li),
254
+ d_full=float(np.linalg.norm(cp - cl)),
255
+ d_xyz_cm=float(np.linalg.norm(xyz[pi] - xyz[li])),
256
+ # gripper flip judged on the NORMALISED coordinate, i.e. relative to the midpoint of
257
+ # [action_min, action_max] -- sign() on the RAW value would be identically positive if
258
+ # the corpus encodes the gripper on [0,1] and the column would silently read 0.000.
259
+ grip_flip=bool(np.sign(cp[0, -1]) != np.sign(cl[0, -1])),
260
+ d_grip=float(abs(cp[0, -1] - cl[0, -1])),
261
+ cloud_full=cloud_full, cloud_xyz_cm=cloud_xyz,
262
+ # paired quality proxy: which pick is closer to the anchor's own logged chunk?
263
+ p_to_log=float(np.linalg.norm(cp - an)), l_to_log=float(np.linalg.norm(cl - an)),
264
+ p_to_log_xyz=float(np.linalg.norm(xyz[pi] - 100.0 * a0[0, :3].astype(np.float64))),
265
+ l_to_log_xyz=float(np.linalg.norm(xyz[li] - 100.0 * a0[0, :3].astype(np.float64))),
266
+ # per-coordinate |diff| at step 0, normalised units: says WHICH of the 10 coords the
267
+ # read-out switch actually moves, so "gripper" is not taken on faith.
268
+ dcoord=[float(abs(cp[0, k] - cl[0, k])) for k in range(C.shape[2])],
269
+ ))
270
+ # ---- free internal check: agreeing anchors must have exactly zero distance ----
271
+ bad0 = [p for p in per if p["agree"] and (p["d_full"] != 0.0 or p["d_xyz_cm"] != 0.0)]
272
+ if bad0:
273
+ print(f"*** {c}: {len(bad0)} AGREEING anchors with non-zero pick distance -- indexing bug")
274
+ sys.exit(5)
275
+ res[c] = per
276
+
277
+ dis = {c: [p for p in v if not p["agree"]] for c, v in res.items()}
278
+ print("\n" + "=" * 108)
279
+ print(f"PICK DISTANCE: when {LA} and {LB} pick DIFFERENT candidates, how different is the MOTION?")
280
+ print("=" * 108)
281
+ print(f"{'cell':<9}{'n_dis':>6}{'d_xyz cm':>10}{'cloud cm':>10}{'ratio':>8}"
282
+ f"{'d_full':>9}{'cloud':>8}{'ratio':>8}{'grip flip':>11}{'d_grip':>8}")
283
+ print("-" * 108)
284
+ summ = {}
285
+ for c in CELLS:
286
+ v = dis[c]
287
+ if not v:
288
+ print(f"{c:<9}{0:>6} (no disagreeing anchors)"); continue
289
+ m = lambda k: float(np.mean([p[k] for p in v]))
290
+ s = dict(n_dis=len(v), d_xyz_cm=m("d_xyz_cm"), cloud_xyz_cm=m("cloud_xyz_cm"),
291
+ ratio_xyz=m("d_xyz_cm") / m("cloud_xyz_cm"), d_full=m("d_full"),
292
+ cloud_full=m("cloud_full"), ratio_full=m("d_full") / m("cloud_full"),
293
+ grip_flip_frac=float(np.mean([p["grip_flip"] for p in v])), d_grip=m("d_grip"),
294
+ med_xyz_cm=float(np.median([p["d_xyz_cm"] for p in v])))
295
+ summ[c] = s
296
+ print(f"{c:<9}{s['n_dis']:>6}{s['d_xyz_cm']:>10.3f}{s['cloud_xyz_cm']:>10.3f}"
297
+ f"{s['ratio_xyz']:>8.3f}{s['d_full']:>9.3f}{s['cloud_full']:>8.3f}{s['ratio_full']:>8.3f}"
298
+ f"{s['grip_flip_frac']:>11.3f}{s['d_grip']:>8.3f}")
299
+ print("\nratio = mean pick-to-pick distance / mean PAIRWISE distance inside the same 128-candidate")
300
+ print("cloud. ~0 => different index, same motion (a relabelling: the change is behaviourally")
301
+ print("inert). ~1 => the two picks are as different as two random candidates in the cloud.")
302
+
303
+ print(f"\nPAIRED QUALITY PROXY (no model): is the `{LB}` pick CLOSER to the anchor's own LOGGED")
304
+ print(f"goal-route chunk than the `{LA}` pick? d = ({LA}->logged) - ({LB}->logged), over the")
305
+ print(f"disagreeing anchors only. d > 0 favours {LB}.")
306
+ print(f"{'cell':<9}{'n':>5}{'d_full':>10}{'bootCI95':>22}{'wilcox p':>11}{'d_xyz cm':>10}"
307
+ f"{'bootCI95':>22}{'favours':>10}")
308
+ print("-" * 108)
309
+ for c in CELLS:
310
+ v = dis[c]
311
+ if not v:
312
+ continue
313
+ df = np.array([p["p_to_log"] - p["l_to_log"] for p in v])
314
+ dxy = np.array([p["p_to_log_xyz"] - p["l_to_log_xyz"] for p in v])
315
+ lo1, hi1 = boot_ci(df); lo2, hi2 = boot_ci(dxy)
316
+ pw = wilcoxon(df)
317
+ fav = LB if lo1 > 0 else (LA if hi1 < 0 else "ns")
318
+ summ[c].update(d_tolog_full=float(df.mean()), d_tolog_full_ci=[lo1, hi1], d_tolog_full_p=pw,
319
+ d_tolog_xyz_cm=float(dxy.mean()), d_tolog_xyz_ci=[lo2, hi2], favours=fav)
320
+ print(f"{c:<9}{len(v):>5}{df.mean():>10.4f}{f'[{lo1:.4f}, {hi1:.4f}]':>22}{pw:>11.2e}"
321
+ f"{dxy.mean():>10.4f}{f'[{lo2:.4f}, {hi2:.4f}]':>22}{fav:>10}")
322
+
323
+ print("\nPER-COORDINATE mean |diff| at step 0 (normalised units, disagreeing anchors), and the same")
324
+ print("for a RANDOM candidate pair in the same cloud would be ~the cloud spread per coord:")
325
+ for c in CELLS:
326
+ v = dis[c]
327
+ if not v:
328
+ continue
329
+ M = np.array([p["dcoord"] for p in v]).mean(0)
330
+ print(f" {c:<9} " + " ".join(f"c{k}:{M[k]:.3f}" for k in range(len(M))))
331
+ summ[c]["dcoord_mean"] = [float(x) for x in M]
332
+
333
+ print("\nPER-STAGE pick distance ratio (xyz, first step), deployed cell first:")
334
+ for c in CELLS:
335
+ v = dis[c]
336
+ if not v:
337
+ continue
338
+ by = collections.defaultdict(list)
339
+ for p in v:
340
+ by[p["stage"]].append(p)
341
+ 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} "
342
+ f"(n={len(by[s])})" for s in sorted(by))
343
+ print(f" {c:<9} {cells_s}")
344
+ summ[c]["by_stage_ratio_xyz"] = {f"S{s}": float(np.mean([p['d_xyz_cm'] for p in by[s]]) /
345
+ np.mean([p['cloud_xyz_cm'] for p in by[s]]))
346
+ for s in sorted(by)}
347
+
348
+ os.makedirs(os.path.dirname(a.out) or ".", exist_ok=True)
349
+ json.dump(dict(args=vars(a), summary=summ,
350
+ per_anchor={c: [{k: v2 for k, v2 in p.items()} for p in res[c]] for c in res}),
351
+ open(a.out, "w"), indent=1)
352
+ print(f"\nwrote {a.out}")
353
+
354
+
355
+ if __name__ == "__main__":
356
+ main()
rsm_rise/scripts/real/act_referee.py ADDED
@@ -0,0 +1,275 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ACT_COND run 29 (gen_q#278): WHEN THE TWO READ-OUTS PICK DIFFERENT ACTIONS, DOES AN INDEPENDENTLY
2
+ TRAINED SUCCESSOR PREFER EITHER PICK?
3
+
4
+ Where this sits. Run 27 measured that the `prob` -> `logit` read-out switch changes the EXECUTED
5
+ candidate on 47/200 anchors at the deployed cell (argmax agreement 0.765). Run 28 measured that those
6
+ 47 disagreements are real motion, not relabelling (5.9 cm of first-step xyz, 36% of the cloud's own
7
+ spread, gripper flipping on 12.8% of them), and that the only quality statistic available -- distance
8
+ to the anchor's own logged chunk -- is NULL on all four checkpoints with inconsistent signs. So the
9
+ run-26 "adopt logit" recommendation was withdrawn. The binding limit on that withdrawal is that
10
+ NOTHING has ever scored the two picks with an instrument that did not itself choose them.
11
+
12
+ This script is that instrument. A REFEREE is a DIFFERENT successor checkpoint -- a different training
13
+ seed and/or reward variant and/or width -- that played no part in the selection. For every anchor it
14
+ re-scores the SAME 128-candidate cloud and reports where each read-out's pick lands in the REFEREE's
15
+ own ordering. Both picks are logged goal-route chunks from the same stage, so a referee has no
16
+ degenerate way to prefer one: it must actually rank them.
17
+
18
+ WHAT IT IS NOT. A referee is another RSM trained on the same corpus with the same objective, so this
19
+ measures whether the FAMILY's value ordering prefers a pick -- not task success. If the read-out
20
+ disagreement comes from something every member of the family shares, the panel will inherit it and
21
+ agree for the wrong reason. That is why the panel spans two seeds, two reward variants and two widths,
22
+ and why the diagonal (referee == the cell's own model) is carried as a CALIBRATION row rather than
23
+ dropped: it shows what a maximally-biased referee looks like (it must rank its own read-out's pick
24
+ first), so an off-diagonal effect can be read against that ceiling.
25
+
26
+ PRE-REGISTERED DECISION RULE (written before the panel ran):
27
+ * "logit's picks are better" requires d_rank > 0 with a bootstrap CI excluding 0 for a MAJORITY of
28
+ the held-out referees under BOTH referee read-outs. Symmetrically for prob.
29
+ * Anything else -- ns, or split across referees, or split across referee read-outs -- is NULL, the
30
+ run-28 withdrawal stands, `prob` stays deployed, and the run reports the tightest bound achieved.
31
+ * The primary panel is the DEPLOYED width/family; different-width referees are reported as a
32
+ robustness row and cannot by themselves carry the claim.
33
+
34
+ GATE, FATAL (rc=5). Run with --ref-ckpt equal to the cell's own checkpoint and the same seed, this
35
+ script must reproduce run 27's stored numbers BIT-IDENTICALLY: q0, rank_pct_prob, rank_pct_logit,
36
+ xpick_prob_idx, xpick_logit_idx. The anchor/candidate/state/interp construction below is a copy of
37
+ act_sensitivity.py's, and that gate is what proves the copy consumes the rng identically -- a silent
38
+ divergence would move every number here and nothing else would catch it. Missing/short cells rc=4.
39
+ """
40
+ import argparse, collections, json, os, sys, time
41
+ import numpy as np
42
+
43
+ ROOT = "/proj/dmfexp/zwhong/rsm_rise"
44
+ sys.path.insert(0, f"{ROOT}/scripts/real")
45
+ GOAL_PATH = "2->3->4"
46
+ FAIL_PATHS = ("0->5", "0->2->6")
47
+
48
+ # The four run-27 cells, with the exact checkpoints their payloads used.
49
+ CELL_CKPT = {
50
+ "mrise": f"{ROOT}/runs/real_cooking_v5/rsm/R_M_ft_v0_rise/ckpt_s120000.pt",
51
+ "mnt": f"{ROOT}/runs/real_cooking_v5/rsm/R_M_ft_v0_nt/ckpt_s120000.pt",
52
+ "xlrise": f"{ROOT}/runs/real_cooking_v5/rsm/R_XL_ft_rise/ckpt_s110000.pt",
53
+ "xlnt": f"{ROOT}/runs/real_cooking_v5/rsm/R_XL_ft_nt/ckpt_s110000.pt",
54
+ }
55
+
56
+
57
+ def main():
58
+ ap = argparse.ArgumentParser()
59
+ ap.add_argument("--hdf5", default=f"{ROOT}/data/raw/cooking_v5_expert_suboptimal.hdf5")
60
+ ap.add_argument("--split", default=f"{ROOT}/data/derived/cooking_v5_split.json")
61
+ ap.add_argument("--cache", default=f"{ROOT}/cache/real_cooking_v5")
62
+ ap.add_argument("--xpick-dir", default=f"{ROOT}/status/real/ACT_COND/xpick")
63
+ ap.add_argument("--cell", required=True, choices=sorted(CELL_CKPT))
64
+ ap.add_argument("--ref-ckpt", required=True)
65
+ ap.add_argument("--ref-tag", required=True)
66
+ ap.add_argument("--hop-ckpt", default=f"{ROOT}/runs/real_cooking_v5/hop/gauss/policy_r1.pt")
67
+ # every knob below is the run-27 cell's value; they are arguments only so the gate can prove it.
68
+ ap.add_argument("--mode", default="chain")
69
+ ap.add_argument("--beta", type=float, default=0.99)
70
+ ap.add_argument("--gamma", type=float, default=0.999)
71
+ ap.add_argument("--particles", type=int, default=16)
72
+ ap.add_argument("--temperature", type=float, default=25.0)
73
+ ap.add_argument("--chain-cap", type=int, default=0)
74
+ ap.add_argument("--n-cand", type=int, default=128)
75
+ ap.add_argument("--n-state", type=int, default=128)
76
+ ap.add_argument("--n-interp", type=int, default=10)
77
+ ap.add_argument("--horizon", type=int, default=8)
78
+ ap.add_argument("--stride", type=int, default=25)
79
+ ap.add_argument("--max-anchors", type=int, default=200)
80
+ ap.add_argument("--anchor-routes", default="all", choices=["all", "goal"])
81
+ ap.add_argument("--seed", type=int, default=0)
82
+ ap.add_argument("--out", required=True)
83
+ a = ap.parse_args()
84
+ t0 = time.time()
85
+ import h5py, torch
86
+ from twin_rollout import Scorer
87
+
88
+ xp = f"{a.xpick_dir}/xpick_{a.cell}.json"
89
+ if not os.path.exists(xp):
90
+ print(f"MISSING run-27 cell {xp} -- a referee row without the picks it judges is not a result")
91
+ sys.exit(4)
92
+ stored = json.load(open(xp))["rows"]
93
+ self_ref = os.path.realpath(a.ref_ckpt) == os.path.realpath(CELL_CKPT[a.cell])
94
+ print(f"[ref] cell={a.cell} referee={a.ref_tag} self_referee={self_ref} "
95
+ f"stored_rows={len(stored)}", flush=True)
96
+
97
+ rng = np.random.default_rng(a.seed)
98
+ os.makedirs(os.path.dirname(a.out) or ".", exist_ok=True)
99
+ split = json.load(open(a.split))["episodes"]
100
+ meta = np.load(f"{a.cache}/meta.npz", allow_pickle=True)
101
+ ep_from = np.asarray(meta["ep_from"])
102
+ zf = np.load(f"{a.cache}/z.f16.npy", mmap_mode="r")
103
+ pf = np.load(f"{a.cache}/proprio.f32.npy", mmap_mode="r")
104
+ st = np.load(f"{a.cache}/feat_stats.npz")
105
+ dd = int(zf.shape[1] + pf.shape[1])
106
+ mu, sd = st["mu"][:dd].astype(np.float32), st["sd"][:dd].astype(np.float32)
107
+ zclip = float(st["z_clip"]) if "z_clip" in st.files else 10.0
108
+
109
+ f = h5py.File(a.hdf5, "r"); d = f["data"]
110
+ lo = np.array(json.loads(d.attrs["action_min"]), np.float32)
111
+ hi = np.array(json.loads(d.attrs["action_max"]), np.float32)
112
+ spl = lambda k: split.get(str(int(k.split("_")[1])), {}).get("split", "")
113
+ path = lambda k: str(d[k].attrs.get("path", ""))
114
+ train = [k for k in d if spl(k) == "train"]
115
+
116
+ # ---- VERBATIM from act_sensitivity.py: pools, anchors, stratification, per-anchor draws ----
117
+ chunk_pool = collections.defaultdict(list)
118
+ state_pool = collections.defaultdict(list)
119
+ fail_pool = collections.defaultdict(list)
120
+ anchors = []
121
+ for k in train:
122
+ g = d[k]; ep = int(k.split("_")[1])
123
+ A = np.asarray((g["actions_raw"] if "actions_raw" in g else g["actions"])[()], np.float32)
124
+ stg = np.asarray(g["annot"]["edge_from"][()])
125
+ for t in range(0, len(A) - a.horizon, a.stride):
126
+ s0 = int(stg[t]); ch = A[t:t + a.horizon]
127
+ chunk_pool[s0].append(ch)
128
+ state_pool[s0].append(int(ep_from[ep] + t))
129
+ if path(k) in FAIL_PATHS:
130
+ fail_pool[s0].append(ch)
131
+ if a.anchor_routes == "all" or path(k) == GOAL_PATH:
132
+ anchors.append((ep, t, s0, path(k)))
133
+ by_stage = collections.defaultdict(list)
134
+ for x in anchors:
135
+ by_stage[x[2]].append(x)
136
+ if len(anchors) > a.max_anchors:
137
+ stages = sorted(by_stage)
138
+ quota = {s: a.max_anchors // len(stages) for s in stages}
139
+ left = a.max_anchors - sum(min(quota[s], len(by_stage[s])) for s in stages)
140
+ for s in sorted(stages, key=lambda s: -len(by_stage[s])):
141
+ take = min(left, max(0, len(by_stage[s]) - quota[s]))
142
+ quota[s] += take; left -= take
143
+ picked = []
144
+ for s in stages:
145
+ v = by_stage[s]; n = min(quota[s], len(v))
146
+ picked += [v[i] for i in sorted(rng.choice(len(v), size=n, replace=False))]
147
+ anchors = sorted(picked, key=lambda x: (x[0], x[1]))
148
+ fail_stages = [s for s, v in fail_pool.items() if v]
149
+
150
+ def probe_target(s0):
151
+ if fail_pool[s0]:
152
+ return fail_pool[s0][int(rng.integers(len(fail_pool[s0])))], "failure_same_stage"
153
+ if fail_stages:
154
+ sp = fail_stages[int(rng.integers(len(fail_stages)))]
155
+ return fail_pool[sp][int(rng.integers(len(fail_pool[sp])))], "failure_other_stage"
156
+ others = [s for s, v in chunk_pool.items() if s != s0 and v]
157
+ sp = others[int(rng.integers(len(others)))]
158
+ return chunk_pool[sp][int(rng.integers(len(chunk_pool[sp])))], "offstage"
159
+
160
+ sc = Scorer("rsm", lo, hi, rsm_ckpt=a.ref_ckpt, seed=a.seed, rsm_mode=a.mode, rsm_beta=a.beta,
161
+ rsm_gamma=a.gamma, rsm_particles=a.particles, rsm_dim=dd,
162
+ rsm_temperature=a.temperature, rsm_hop_ckpt=a.hop_ckpt)
163
+ if a.chain_cap:
164
+ sc.rsm.backend.chain_cap_override = int(a.chain_cap)
165
+ rsm = sc.rsm; dev = rsm.device
166
+
167
+ def feat(gi):
168
+ z = np.concatenate([np.asarray(zf[gi], np.float32), np.asarray(pf[gi], np.float32)])
169
+ return np.clip((z - mu) / sd, -zclip, zclip).astype(np.float32)
170
+
171
+ NC, NS, NI = a.n_cand, a.n_state, a.n_interp
172
+ rows, gate_fail, aligned = [], [], 0
173
+ for ai, (ep, t, s0, route) in enumerate(anchors):
174
+ if len(chunk_pool[s0]) < NC or len(state_pool[s0]) < NS + 1:
175
+ continue
176
+ gi = int(ep_from[ep] + t)
177
+ x0 = feat(gi)
178
+ g = d[f"demo_{ep}"]
179
+ a0 = np.asarray((g["actions_raw"] if "actions_raw" in g else g["actions"])[t:t + a.horizon],
180
+ np.float32)
181
+ ci = rng.choice(len(chunk_pool[s0]), size=NC, replace=False)
182
+ cands = np.stack([chunk_pool[s0][i] for i in ci])
183
+ si = [j for j in rng.permutation(len(state_pool[s0])) if state_pool[s0][j] != gi][:NS]
184
+ states = np.stack([feat(state_pool[s0][j]) for j in si])
185
+ af, probe_src = probe_target(s0)
186
+ lam = np.linspace(0.0, 1.0, NI, dtype=np.float32)
187
+ interp = np.stack([(1 - l) * a0 + l * af for l in lam])
188
+ X = np.concatenate([np.repeat(x0[None], NC, 0), states,
189
+ np.repeat(x0[None], NI + 1, 0)], 0)
190
+ A = np.concatenate([cands, np.repeat(a0[None], NS, 0), interp, a0[None]], 0)
191
+ with torch.no_grad():
192
+ rsm.score(torch.as_tensor(X, dtype=torch.float32, device=dev), A,
193
+ seed=a.seed + 7919 * (ai + 1))
194
+ q = rsm.last_q.double().cpu().numpy()
195
+ ql = rsm.last_q_logit
196
+ ql = np.full_like(q, np.nan) if ql is None else ql.double().cpu().numpy()
197
+ qa, la = q[:NC], ql[:NC]
198
+ q00, l00 = q[-1], ql[-1]
199
+
200
+ # ---- alignment with the stored row: the rng stream must be where run 27 left it ----
201
+ sr = stored[len(rows)] if len(rows) < len(stored) else None
202
+ if sr is None or (int(sr["ep"]), int(sr["t"]), int(sr["stage"]), str(sr["route"]),
203
+ str(sr["probe_src"])) != (ep, t, s0, route, probe_src):
204
+ gate_fail.append(f"row{len(rows)}: replay ({ep},{t},S{s0},{route},{probe_src}) vs stored "
205
+ + (f"({sr['ep']},{sr['t']},S{sr['stage']},{sr['route']},{sr['probe_src']})"
206
+ if sr else "MISSING"))
207
+ if len(gate_fail) > 5:
208
+ break
209
+ continue
210
+ aligned += 1
211
+ p_idx, l_idx = int(sr["xpick_prob_idx"]), int(sr["xpick_logit_idx"])
212
+ r = {"ep": ep, "t": t, "stage": s0, "route": route, "probe_src": probe_src,
213
+ "prob_idx": p_idx, "logit_idx": l_idx, "agree": int(p_idx == l_idx),
214
+ # referee scores of the two picks, both referee read-outs
215
+ "ref_q_prob_at_probpick": float(qa[p_idx]), "ref_q_prob_at_logitpick": float(qa[l_idx]),
216
+ "ref_q_logit_at_probpick": float(la[p_idx]), "ref_q_logit_at_logitpick": float(la[l_idx]),
217
+ # where each pick lands in the REFEREE's own ordering (strict-less, run-27 convention)
218
+ "ref_rank_prob_probpick": float((qa < qa[p_idx]).mean()),
219
+ "ref_rank_prob_logitpick": float((qa < qa[l_idx]).mean()),
220
+ "ref_rank_logit_probpick": float((la < la[p_idx]).mean()),
221
+ "ref_rank_logit_logitpick": float((la < la[l_idx]).mean()),
222
+ # the referee's own pick, and the cloud scale it is measured against
223
+ "ref_argmax_prob": int(np.argmax(qa)), "ref_argmax_logit": int(np.argmax(la)),
224
+ "ref_cloud_mean_prob": float(qa.mean()), "ref_cloud_std_prob": float(qa.std()),
225
+ "ref_cloud_mean_logit": float(la.mean()), "ref_cloud_std_logit": float(la.std()),
226
+ # free: the referee's own version of the run-25/26 logged-chunk statistic
227
+ "ref_q0_prob": float(q00), "ref_q0_logit": float(l00),
228
+ "ref_rank_pct_logged_prob": float((qa < q00).mean()),
229
+ "ref_rank_pct_logged_logit": float((la < l00).mean())}
230
+ # ---- the bit-identity gate, only meaningful when the referee IS the cell's own model ----
231
+ if self_ref:
232
+ chk = [("q0", float(q00), float(sr["q0"])), ("logit0", float(l00), float(sr["logit0"])),
233
+ ("rank_pct_prob", float((qa < q00).mean()), float(sr["rank_pct_prob"])),
234
+ ("rank_pct_logit", float((la < l00).mean()), float(sr["rank_pct_logit"])),
235
+ ("xpick_prob_idx", float(np.argmax(qa)), float(p_idx)),
236
+ ("xpick_logit_idx", float(np.argmax(la)), float(l_idx))]
237
+ for nm, got, want in chk:
238
+ if not (got == want or abs(got - want) <= 1e-12 * max(1.0, abs(want))):
239
+ gate_fail.append(f"row{len(rows)} {nm}: got {got!r} stored {want!r}")
240
+ rows.append(r)
241
+ if len(rows) % 25 == 0:
242
+ print(f" [{len(rows)}/{len(anchors)}] ep{ep} t{t} S{s0} "
243
+ f"agree={r['agree']} ({time.time()-t0:.0f}s)", flush=True)
244
+
245
+ out = {"args": vars(a), "cell": a.cell, "ref_tag": a.ref_tag, "ref_ckpt": a.ref_ckpt,
246
+ "self_referee": self_ref, "n_anchors": len(rows), "n_aligned": aligned,
247
+ "rows": rows, "host": os.uname().nodename, "seconds": time.time() - t0}
248
+ if gate_fail:
249
+ out["GATE_FAIL"] = gate_fail
250
+ json.dump(out, open(a.out + ".GATEFAIL", "w"), indent=1)
251
+ print("\n*** GATE FAILED -- refusing to write a readable result ***")
252
+ for m in gate_fail[:10]:
253
+ print(" " + m)
254
+ f.close()
255
+ sys.exit(5)
256
+ if len(rows) != len(stored):
257
+ print(f"*** short: {len(rows)} rows vs {len(stored)} stored -- partial is not a result")
258
+ f.close()
259
+ sys.exit(4)
260
+ json.dump(out, open(a.out, "w"), indent=1)
261
+ dis = [r for r in rows if not r["agree"]]
262
+ d_prob = np.array([r["ref_rank_prob_logitpick"] - r["ref_rank_prob_probpick"] for r in dis])
263
+ d_logit = np.array([r["ref_rank_logit_logitpick"] - r["ref_rank_logit_probpick"] for r in dis])
264
+ print(f"\n[ref] {a.cell} <- {a.ref_tag}: {len(rows)} anchors, {len(dis)} disagreeing"
265
+ f"{' (SELF-REFEREE, calibration row -- gate PASSED bit-identical)' if self_ref else ''}")
266
+ print(f" d_rank(referee prob) mean {d_prob.mean():+.4f} median {np.median(d_prob):+.4f} "
267
+ f"logit-pick better on {float((d_prob > 0).mean()):.3f}")
268
+ print(f" d_rank(referee logit) mean {d_logit.mean():+.4f} median {np.median(d_logit):+.4f} "
269
+ f"logit-pick better on {float((d_logit > 0).mean()):.3f}")
270
+ print(f"\nwrote {a.out} ({time.time()-t0:.0f}s)", flush=True)
271
+ f.close()
272
+
273
+
274
+ if __name__ == "__main__":
275
+ main()
rsm_rise/scripts/real/act_rescore_read.py ADDED
@@ -0,0 +1,357 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ACT_COND run 32 (gen_q#278): READ THE TWO-STAGE TIE-BREAK CELLS (job 1893988).
2
+
3
+ Run 31 resolved the pre-registered fork toward NEAR-TIE: under a strict hold-out the best single-draw
4
+ predictor of an unstable executed pick is the top-1-vs-top-2 MARGIN, and it is the only predictor that
5
+ transfers to the held-out checkpoint. The indicated fix is therefore a TIE-BREAK (rescore the top-K
6
+ candidates with M particles) rather than a uniform budget -- which is also the only reading consistent
7
+ with the uniform curve, where 4x particles bought just +6.7 points of top-1 agreement.
8
+
9
+ PRE-REGISTERED READ (run 31 section 5, written BEFORE the cells existed):
10
+ two-stage at K=16 costs 128*16 + 16*64 = 3072 particle-evals = 1.5x the deployed 2048, and the
11
+ UNIFORM curve needed 2x (P=32) to reach top1_agree 0.590 from 0.557. THE TIE-BREAK WINS IFF IT
12
+ BEATS 0.590. If it lands at or below the uniform curve at matched compute, the near-tie reading
13
+ predicted the wrong fix and that is what gets reported.
14
+ CORRECTION TO RUN 31's ARITHMETIC, carried here rather than quietly fixed: K=32 costs
15
+ 128*16 + 32*64 = 4096 = 2.00x, not the 1.75x the run-31 text stated (measured `rs_cost_ts` agrees:
16
+ 3072 / 4096). So K=32's matched-compute bar is EXACTLY the uniform P=32 point, 0.590.
17
+
18
+ IT REFUSES TO PRINT NUMBERS OFF A BROKEN PATCH. Three gates, each rc-distinct:
19
+ rc=4 a cell is missing (a partial job is not a result).
20
+ rc=5 REGRESSION: the run-31 rescore patch is ADDITIVE and issues its own seeds, so every non-`rs_`
21
+ field must reproduce the run-29 mcstab P=16 cell BIT-FOR-BIT -- including the repeat-derived
22
+ fields, since repeats=4 on both sides. Excluded by exact name: chain_hops_mean /
23
+ chain_capped_frac, the cumulative accumulator of run 31 section 0/1 -- the tie-break's extra
24
+ score() calls legitimately feed it -- and the exclusion is PRINTED with both means.
25
+ rc=6 PAIRED CONTROL: `rs_ctl_*` is the tie-break-OFF arm at the same seed and the same
26
+ candidates-only batch shape, so it CANNOT depend on K. If it differs between the K=16 and
27
+ K=32 cells the pairing is broken and the ts-vs-ctl contrast is not attributable to the
28
+ rescore. This gate is the reason the control was run at all.
29
+
30
+ DEGENERACY GUARD, printed before the verdict: a tie-break that collapsed onto a fixed candidate would
31
+ score top1_agree 1.000 and look like a triumph. We print the number of DISTINCT picked indices and
32
+ the pick entropy for both arms, plus the ts-vs-ctl pick change rate (a no-op tie-break is also a
33
+ possible and reportable outcome).
34
+ """
35
+ import argparse, json, math, os, sys
36
+ import numpy as np
37
+
38
+ ROOT = "/proj/dmfexp/zwhong/rsm_rise"
39
+ ACCUMULATOR_FIELDS = ("chain_hops_mean", "chain_capped_frac")
40
+ RS_PREFIX = "rs_"
41
+
42
+
43
+ def wilson(k, n, z=1.96):
44
+ if n <= 0:
45
+ return float("nan"), float("nan")
46
+ p = k / n
47
+ d = 1 + z * z / n
48
+ c = p + z * z / (2 * n)
49
+ h = z * math.sqrt(p * (1 - p) / n + z * z / (4 * n * n))
50
+ return (c - h) / d, (c + h) / d
51
+
52
+
53
+ def boot_ci(d, n=20000, seed=0):
54
+ d = np.asarray(d, float)
55
+ if len(d) < 2:
56
+ return float("nan"), float("nan")
57
+ r = np.random.default_rng(seed)
58
+ m = d[r.integers(0, len(d), size=(n, len(d)))].mean(1)
59
+ return float(np.percentile(m, 2.5)), float(np.percentile(m, 97.5))
60
+
61
+
62
+ def flat(o, pre=""):
63
+ out = {}
64
+ if isinstance(o, dict):
65
+ for k, v in o.items():
66
+ out.update(flat(v, f"{pre}.{k}" if pre else str(k)))
67
+ elif isinstance(o, list):
68
+ for i, v in enumerate(o):
69
+ out.update(flat(v, f"{pre}[{i}]"))
70
+ elif isinstance(o, (int, float)) and not isinstance(o, bool):
71
+ out[pre] = float(o)
72
+ return out
73
+
74
+
75
+ def agree(idx):
76
+ """top1_agree, the run-29 definition verbatim: mean over the C(R,2) unordered pairs of draws of
77
+ (argmax_i == argmax_j). act_sensitivity.py:336."""
78
+ idx = list(idx)
79
+ pr = [(i, j) for i in range(len(idx)) for j in range(i + 1, len(idx))]
80
+ return float(np.mean([idx[i] == idx[j] for i, j in pr])) if pr else float("nan")
81
+
82
+
83
+ def entropy(idx):
84
+ _, cnt = np.unique(np.asarray(idx), return_counts=True)
85
+ p = cnt / cnt.sum()
86
+ return float(-(p * np.log2(p)).sum())
87
+
88
+
89
+ def main():
90
+ ap = argparse.ArgumentParser()
91
+ ap.add_argument("--dir", default=f"{ROOT}/status/real/ACT_COND/rescore")
92
+ ap.add_argument("--mcstab-dir", default=f"{ROOT}/status/real/ACT_COND/mcstab")
93
+ ap.add_argument("--cells", default="mrise,mnt")
94
+ ap.add_argument("--ks", default="16,32")
95
+ ap.add_argument("--uniform-ps", default="16,32,64")
96
+ ap.add_argument("--out", default=f"{ROOT}/status/real/ACT_COND/RESCORE_run32.json")
97
+ a = ap.parse_args()
98
+ cellnames = [c for c in a.cells.split(",") if c]
99
+ KS = [int(x) for x in a.ks.split(",") if x]
100
+ PS = [int(x) for x in a.uniform_ps.split(",") if x]
101
+
102
+ cells, missing = {}, []
103
+ for c in cellnames:
104
+ for K in KS:
105
+ p = f"{a.dir}/rs_{c}_K{K}.json"
106
+ if not os.path.exists(p):
107
+ missing.append(p)
108
+ else:
109
+ cells[(c, K)] = json.load(open(p))
110
+ if missing:
111
+ print("MISSING CELLS -- a partial job is not a result:")
112
+ [print(" " + m) for m in missing]
113
+ sys.exit(4)
114
+
115
+ # ------------------------------------------------------------- GATE 1: REGRESSION (rc=5)
116
+ print("=" * 112)
117
+ print("GATE 1 / REGRESSION: the run-31 rescore block is ADDITIVE, runs AFTER the chain section and")
118
+ print("issues its own seeds, so every NON-`rs_` field must reproduce the run-29 mcstab P=16 cell")
119
+ print("bit-for-bit -- repeat-derived fields INCLUDED (repeats=4 on both sides).")
120
+ print("EXCLUDED BY EXACT NAME (cumulative accumulator, run 31 s0/s1): " + ", ".join(ACCUMULATOR_FIELDS))
121
+ print("=" * 112)
122
+ nbad = 0
123
+ for c in cellnames:
124
+ ref_p = f"{a.mcstab_dir}/mc_{c}_p16.json"
125
+ if not os.path.exists(ref_p):
126
+ print(f" {c}: no reference {ref_p} -- SKIPPED (cannot regress)")
127
+ continue
128
+ ref = json.load(open(ref_p))["rows"]
129
+ for K in KS:
130
+ new = cells[(c, K)]["rows"]
131
+ if len(ref) != len(new):
132
+ print(f"*** {c} K={K}: {len(ref)} ref rows vs {len(new)} new rows"); nbad += 1; continue
133
+ nf, worst, bad, tally, acc = 0, 0.0, [], {}, {}
134
+ for i, (r0, r1) in enumerate(zip(ref, new)):
135
+ fa, fb = flat(r0), flat(r1)
136
+ for k, v in fa.items():
137
+ if k.startswith(RS_PREFIX):
138
+ continue
139
+ base = k.split(".")[-1].split("[")[0]
140
+ if base in ACCUMULATOR_FIELDS:
141
+ if k in fb:
142
+ acc.setdefault(base, ([], []))[0].append(v)
143
+ acc[base][1].append(fb[k])
144
+ continue
145
+ if k not in fb:
146
+ bad.append(f"({i}).{k}: MISSING in new")
147
+ tally[k + " MISSING"] = tally.get(k + " MISSING", 0) + 1
148
+ continue
149
+ nf += 1
150
+ d = abs(v - fb[k]) / max(abs(v), 1e-12)
151
+ worst = max(worst, d)
152
+ if d > 0:
153
+ bad.append(f"({i}).{k}: ref={v!r} new={fb[k]!r}")
154
+ tally[k] = tally.get(k, 0) + 1
155
+ for base, (rv, nv) in sorted(acc.items()):
156
+ print(f" {c} K={K} [SAMPLING-ONLY, excluded] {base}: ref mean {np.mean(rv):.4f} "
157
+ f"new mean {np.mean(nv):.4f} (tie-break score() calls feed the same accumulator)")
158
+ if bad:
159
+ print(f"*** {c} K={K}: {len(bad)} MISMATCHES over {len(tally)} FIELD(S) ***")
160
+ for k in sorted(tally, key=lambda z: -tally[z]):
161
+ print(f" {k}: {tally[k]} row(s)")
162
+ [print(" e.g. " + b) for b in bad[:5]]
163
+ nbad += 1
164
+ else:
165
+ print(f" {c} K={K}: {nf} fields worst rel {worst:.2e} IDENTICAL to mc_{c}_p16")
166
+ if nbad:
167
+ print("\nThe additive tie-break patch moved a pre-existing field. Nothing else is read.")
168
+ sys.exit(5)
169
+
170
+ # ------------------------------------------------------------- GATE 2: PAIRED CONTROL (rc=6)
171
+ print("\n" + "=" * 112)
172
+ print("GATE 2 / PAIRED CONTROL: `rs_ctl_*` is the tie-break-OFF arm at the same seed and the same")
173
+ print("candidates-only batch shape. It cannot depend on K; if it does, the pairing is broken and")
174
+ print("the ts-vs-ctl contrast is not attributable to the rescore.")
175
+ print("=" * 112)
176
+ nbad = 0
177
+ for c in cellnames:
178
+ if len(KS) < 2:
179
+ print(f" {c}: only one K -- gate inapplicable"); continue
180
+ base = cells[(c, KS[0])]["rows"]
181
+ for K in KS[1:]:
182
+ oth = cells[(c, K)]["rows"]
183
+ diff = 0
184
+ for r0, r1 in zip(base, oth):
185
+ for k in r0:
186
+ if k.startswith("rs_ctl_") and flat({k: r0[k]}) != flat({k: r1[k]}):
187
+ diff += 1
188
+ if diff:
189
+ print(f"*** {c}: rs_ctl_* differs between K={KS[0]} and K={K} in {diff} field(s) ***")
190
+ nbad += 1
191
+ else:
192
+ print(f" {c}: rs_ctl_* IDENTICAL between K={KS[0]} and K={K} -- pairing intact")
193
+ if nbad:
194
+ sys.exit(6)
195
+
196
+ # ------------------------------------------------------------- DEGENERACY GUARD
197
+ print("\n" + "=" * 112)
198
+ print("DEGENERACY GUARD. A tie-break that collapsed onto a fixed candidate would score")
199
+ print("top1_agree 1.000 and look like a triumph. distinct = # distinct picked indices over all")
200
+ print("anchors x draws (out of 128 candidates); H = entropy of that pick distribution in bits.")
201
+ print("chg = fraction of anchor-draws where the two-stage pick DIFFERS from the control pick")
202
+ print("(chg = 0 would mean the tie-break is a NO-OP, also a reportable outcome).")
203
+ print("=" * 112)
204
+ print(f"{'cell':<8}{'K':>4}{'read':>7}{'ctl distinct':>14}{'ctl H':>8}{'ts distinct':>13}{'ts H':>7}{'chg':>8}")
205
+ print("-" * 112)
206
+ deg = {}
207
+ for c in cellnames:
208
+ for K in KS:
209
+ rows = cells[(c, K)]["rows"]
210
+ for kind in ("prob", "logit"):
211
+ ci = [i for r in rows for i in r[f"rs_ctl_top1_idx_{kind}"]]
212
+ ti = [i for r in rows for i in r[f"rs_ts_top1_idx_{kind}"]]
213
+ chg = float(np.mean([x != y for x, y in zip(ci, ti)]))
214
+ print(f"{c:<8}{K:>4}{kind:>7}{len(set(ci)):>14}{entropy(ci):>8.2f}"
215
+ f"{len(set(ti)):>13}{entropy(ti):>7.2f}{chg:>8.3f}")
216
+ deg[f"{c}_K{K}_{kind}"] = dict(ctl_distinct=len(set(ci)), ctl_H=entropy(ci),
217
+ ts_distinct=len(set(ti)), ts_H=entropy(ti),
218
+ ts_vs_ctl_change=chg)
219
+ print("-" * 112)
220
+
221
+ # ------------------------------------------------------------- THE UNIFORM REFERENCE CURVE
222
+ uni = {}
223
+ for c in cellnames:
224
+ for P in PS:
225
+ p = f"{a.mcstab_dir}/mc_{c}_p{P}.json"
226
+ if os.path.exists(p):
227
+ rows = json.load(open(p))["rows"]
228
+ for kind in ("prob", "logit"):
229
+ uni[(c, P, kind)] = float(np.mean([r[f"top1_agree_{kind}"] for r in rows]))
230
+
231
+ # ------------------------------------------------------------- MAIN: ts vs ctl, PAIRED
232
+ print("\n" + "=" * 112)
233
+ print("TIE-BREAK vs CONTROL, PAIRED on the same anchors and the same seed. top1_agree = P(two")
234
+ print("independent particle draws pick the SAME action). cost is in particle-evals, measured")
235
+ print("(`rs_cost_*`), not assumed. Deployed = prob.")
236
+ print("=" * 112)
237
+ print(f"{'cell':<8}{'K':>4}{'read':>7}{'n':>5}{'ctl':>8}{'ts':>8}{'delta':>9}{'bootCI95':>22}"
238
+ f"{'cost x':>8}{'uniform@cost':>14}{'verdict':>10}")
239
+ print("-" * 112)
240
+ res = {"degeneracy": deg, "uniform": {f"{c}_p{P}_{k}": v for (c, P, k), v in uni.items()}}
241
+ for c in cellnames:
242
+ for K in KS:
243
+ rows = cells[(c, K)]["rows"]
244
+ n = len(rows)
245
+ cx = float(np.mean([r["rs_cost_ts"] for r in rows]) /
246
+ max(np.mean([r["rs_cost_ctl"] for r in rows]), 1e-30))
247
+ for kind in ("prob", "logit"):
248
+ ac = np.array([agree(r[f"rs_ctl_top1_idx_{kind}"]) for r in rows])
249
+ at = np.array([agree(r[f"rs_ts_top1_idx_{kind}"]) for r in rows])
250
+ d = at - ac
251
+ lo, hi = boot_ci(d)
252
+ # matched-compute bar: the uniform point at the SAME multiple of the deployed budget.
253
+ # cost 1.5x and 2.0x -> the nearest uniform point AT OR BELOW the tie-break's cost is
254
+ # P=16 (1x) for 1.5x, but run 31 pre-registered the STRICTER bar, P=32 (2x) = the
255
+ # uniform curve's 2x point, for BOTH K. Printed as `uniform@cost`; the stricter bar
256
+ # is the one the verdict uses, and it is quoted from the same file, not hardcoded.
257
+ bar = uni.get((c, 32, kind), float("nan"))
258
+ lo_t, hi_t = wilson(at.mean() * n * 6, n * 6)
259
+ if not np.isfinite(bar):
260
+ vd = "no-ref"
261
+ elif lo_t > bar:
262
+ vd = "WIN"
263
+ elif hi_t < bar:
264
+ vd = "LOSE"
265
+ else:
266
+ vd = "ns"
267
+ print(f"{c:<8}{K:>4}{kind:>7}{n:>5}{ac.mean():>8.3f}{at.mean():>8.3f}{d.mean():>+9.3f}"
268
+ f"{f'[{lo:+.3f}, {hi:+.3f}]':>22}{cx:>8.2f}{bar:>14.3f}{vd:>10}")
269
+ res[f"{c}_K{K}_{kind}"] = dict(
270
+ n=n, ctl=float(ac.mean()), ts=float(at.mean()), delta=float(d.mean()),
271
+ delta_ci=[lo, hi], ts_wilson=[lo_t, hi_t], cost_x=cx, uniform_2x_bar=bar,
272
+ verdict=vd)
273
+ print("-" * 112)
274
+
275
+ # ------------------------------------------------------------- PAIRED matched-compute verdict
276
+ # The point-bar verdict above compares a mean against a NUMBER. The uniform P=32 cell was run on
277
+ # the SAME 200 anchors (same stratification, same seed), so the comparison can be PAIRED, which
278
+ # removes anchor-to-anchor variance -- by far the largest term here. The pre-registered verdict
279
+ # stays the point bar (that is what was written down before the cells existed); this is the
280
+ # stronger version of the same test and both are printed. Alignment is CHECKED, not assumed:
281
+ # if (ep, t, stage, route) does not match row-for-row the pairing is skipped and said so.
282
+ print("\n" + "=" * 112)
283
+ print("PAIRED matched-compute verdict: ts(K) vs the UNIFORM 2x cell (P=32) on the SAME anchors.")
284
+ print("d = top1_agree(ts) - top1_agree(uniform P=32); d > 0 means the tie-break beats uniform 2x.")
285
+ print("=" * 112)
286
+ print(f"{'cell':<8}{'K':>4}{'read':>7}{'n':>5}{'ts':>8}{'uni2x':>8}{'d':>9}{'bootCI95':>22}{'verdict':>10}")
287
+ print("-" * 112)
288
+ for c in cellnames:
289
+ up = f"{a.mcstab_dir}/mc_{c}_p32.json"
290
+ if not os.path.exists(up):
291
+ print(f" {c}: no uniform P=32 cell -- SKIPPED"); continue
292
+ urows = json.load(open(up))["rows"]
293
+ for K in KS:
294
+ rows = cells[(c, K)]["rows"]
295
+ key = lambda r: (r["ep"], r["t"], r["stage"], r["route"])
296
+ if len(urows) != len(rows) or any(key(x) != key(y) for x, y in zip(rows, urows)):
297
+ print(f" {c} K={K}: anchors DO NOT ALIGN with the P=32 cell -- pairing skipped")
298
+ continue
299
+ for kind in ("prob", "logit"):
300
+ at = np.array([agree(r[f"rs_ts_top1_idx_{kind}"]) for r in rows])
301
+ au = np.array([u[f"top1_agree_{kind}"] for u in urows])
302
+ d = at - au
303
+ lo, hi = boot_ci(d)
304
+ vd = "WIN" if lo > 0 else ("LOSE" if hi < 0 else "ns")
305
+ print(f"{c:<8}{K:>4}{kind:>7}{len(rows):>5}{at.mean():>8.3f}{au.mean():>8.3f}"
306
+ f"{d.mean():>+9.3f}{f'[{lo:+.3f}, {hi:+.3f}]':>22}{vd:>10}")
307
+ res[f"{c}_K{K}_{kind}"].update(paired_uni2x=float(au.mean()),
308
+ paired_delta=float(d.mean()),
309
+ paired_ci=[lo, hi], paired_verdict=vd)
310
+ print("-" * 112)
311
+
312
+ # replication check: the ctl arm is a fresh 128-row candidates-only measurement of the SAME
313
+ # quantity the uniform P=16 cell reports off its first 128 rows of a 267-row call. They are not
314
+ # required to be equal (different batch composition => different draws) but a large gap would
315
+ # mean the candidates-only call is not the deployed cloud.
316
+ print("\nREPLICATION: ctl (candidates-only call, this job) vs uniform P=16 (first 128 rows of the")
317
+ print("267-row call, run 29). Same quantity, different batch composition -- a large gap means the")
318
+ print("tie-break is not being measured on the deployed cloud.")
319
+ for c in cellnames:
320
+ for kind in ("prob", "logit"):
321
+ u = uni.get((c, 16, kind), float("nan"))
322
+ v = res[f"{c}_K{KS[0]}_{kind}"]["ctl"]
323
+ print(f" {c:<8}{kind:>7} ctl {v:.3f} uniform P=16 {u:.3f} gap {v-u:+.3f}")
324
+
325
+ # ------------------------------------------------------------- PER STAGE (deployed read-out)
326
+ print("\nPER-STAGE ctl -> ts, prob (deployed). Run 31: S3 is the worst stage at every budget.")
327
+ for c in cellnames:
328
+ for K in KS:
329
+ rows = cells[(c, K)]["rows"]
330
+ st = sorted({r["stage"] for r in rows})
331
+ line = " ".join(
332
+ f"S{s}: {np.mean([agree(r['rs_ctl_top1_idx_prob']) for r in rows if r['stage']==s]):.3f}"
333
+ f"->{np.mean([agree(r['rs_ts_top1_idx_prob']) for r in rows if r['stage']==s]):.3f}"
334
+ for s in st)
335
+ print(f" {c:<8} K={K:<4} {line}")
336
+
337
+ # ------------------------------------------------------------- MARGIN (mechanical, flagged)
338
+ print("\nMARGIN top1-vs-top2 (relative). FLAGGED AS MECHANICAL: rescoring the top-K with 4x the")
339
+ print("particles sharpens the head of the score vector BY CONSTRUCTION, so a larger ts margin is")
340
+ print("NOT independent evidence of a better pick. Printed because run 31's fork was decided on")
341
+ print("the margin and the reader should see what the tie-break did to it.")
342
+ for c in cellnames:
343
+ for K in KS:
344
+ rows = cells[(c, K)]["rows"]
345
+ for kind in ("prob",):
346
+ mc = float(np.mean([r[f"rs_ctl_margin12_rel_{kind}"] for r in rows]))
347
+ mt = float(np.mean([r[f"rs_ts_margin12_rel_{kind}"] for r in rows]))
348
+ print(f" {c:<8} K={K:<4} {kind}: ctl {mc:.4f} -> ts {mt:.4f} (x{mt/max(mc,1e-12):.2f})")
349
+ res[f"{c}_K{K}_{kind}"].update(margin_ctl=mc, margin_ts=mt)
350
+
351
+ os.makedirs(os.path.dirname(a.out) or ".", exist_ok=True)
352
+ json.dump(res, open(a.out, "w"), indent=1)
353
+ print(f"\nwrote {a.out}")
354
+
355
+
356
+ if __name__ == "__main__":
357
+ main()
rsm_rise/scripts/real/act_run21_primary.py ADDED
@@ -0,0 +1,155 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """ACT_COND run 21/24 PRIMARY READ (gen_q#278) -- the registered deployed-width table.
3
+
4
+ This script COMPUTES NOTHING. It reads the JSON that `xl2x2_test.py` already wrote (the same
5
+ implementation that produced the run-20 XL numbers, byte-verified identical by job 1889493) and
6
+ prints the ONE row that runs 21-23 pre-registered, with the two pieces of context without which the
7
+ row has burned us before:
8
+
9
+ * the XL reference contrast (rise@0.90 minus rise@0.99 at width 4096): +0.0358 rank pct,
10
+ -0.0684 monotone rho, +14.378 margin z (mean). TRANSFERS = the deployed-width contrast lands
11
+ within ~2x of these; HEADROOM = at or below a third.
12
+ * the ATTAINABLE MAXIMUM of every bounded statistic at the deployed-width baseline. Run 23 found
13
+ mrise@0.99 already at rank pct 0.9859, so the largest contrast rank_pct can express is +0.0141 --
14
+ BELOW the +0.0179 TRANSFERS threshold. A small rank_pct contrast here is CENSORING, NOT
15
+ evidence for HEADROOM, and this script refuses to print the row without its ceiling.
16
+
17
+ margin_z is unbounded above and is therefore the PRIMARY statistic at this width (registered run 23,
18
+ before the test cells existed). rank_pct and spearman are printed with `max_attainable` and a
19
+ `censored` flag beside them.
20
+ """
21
+ import argparse, json, sys
22
+
23
+ XL_REF = { # rise@0.90 minus rise@0.99 at width 4096 (run 20, reproduced in run 23)
24
+ "rank_pct": 0.0358,
25
+ "spearman": -0.0684,
26
+ "margin_z": 14.378,
27
+ }
28
+ TRANSFERS_FRAC = 0.5 # "within ~2x of XL" -> |contrast| >= 0.5 * |XL|
29
+ HEADROOM_FRAC = 1.0 / 3.0 # "at or below a third"
30
+ SIGN = {"rank_pct": +1, "spearman": -1, "margin_z": +1} # direction of "better"
31
+ BOUND = {"rank_pct": 1.0, "spearman": -1.0} # hard bound; margin_z has none
32
+
33
+
34
+ def ceiling(stem, base):
35
+ """Largest contrast the statistic can express from this baseline, in the better direction."""
36
+ if stem not in BOUND:
37
+ return None
38
+ return BOUND[stem] - base
39
+
40
+
41
+ def classify(stem, obs, cap):
42
+ xl = XL_REF[stem]
43
+ frac = obs / xl if xl else float("nan")
44
+ if cap is not None and abs(cap) < abs(xl) * TRANSFERS_FRAC:
45
+ return "CENSORED (cannot reach TRANSFERS even in principle)", frac
46
+ if frac >= TRANSFERS_FRAC:
47
+ return "TRANSFERS", frac
48
+ if frac <= HEADROOM_FRAC:
49
+ return "HEADROOM", frac
50
+ return "between TRANSFERS and HEADROOM", frac
51
+
52
+
53
+ # --- run 25 addition, justified by ONE number ---------------------------------------------------
54
+ # The prob/margin_z row of the deployed-width read came back as +2,229,259 ("frac XL 155046,
55
+ # TRANSFERS"). It is ONE anchor: at beta=0.90 the prob read-out underflows and that anchor's
56
+ # candidate-cloud sd is 1.75e-10, so its margin_z is 4.4e8 and it alone sets the mean. The paired
57
+ # MEDIAN of the same 200 differences is +0.1434. A mean that disagrees with its own median by
58
+ # 1.6e7x is not a measurement, so this reader now prints the paired median beside the mean and
59
+ # stamps TAIL-DRIVEN over any verdict where they disagree by more than TAIL_RATIO.
60
+ TAIL_RATIO = 3.0
61
+ PER_ANCHOR = {"rank_pct": "rank_pct_{read}", "spearman": "spearman_{read}", "margin_z": None}
62
+
63
+
64
+ def per_anchor_diff(cell_dir, stem, read, beta, ref_beta="99"):
65
+ """Paired per-anchor contrast (test minus ref) straight off the cell JSONs; None if unavailable."""
66
+ import os
67
+ b = beta.replace("0.", "").rstrip(".")
68
+ fa = os.path.join(cell_dir, f"snr_beta{b}.json")
69
+ fb = os.path.join(cell_dir, f"snr_beta{ref_beta}.json")
70
+ if not (os.path.exists(fa) and os.path.exists(fb)):
71
+ return None
72
+ def vals(f):
73
+ rows = json.load(open(f))["rows"]
74
+ if stem == "margin_z":
75
+ s0 = "q0" if read == "prob" else "logit0"
76
+ return [(r[s0] - r[f"mean_a_{read}"]) / max(r[f"var_a_{read}"] ** 0.5, 1e-300)
77
+ for r in rows]
78
+ return [r[PER_ANCHOR[stem].format(read=read)] for r in rows]
79
+ va, vb = vals(fa), vals(fb)
80
+ if len(va) != len(vb):
81
+ return None
82
+ d = sorted(x - y for x, y in zip(va, vb))
83
+ n = len(d)
84
+ return d[n // 2] if n % 2 else 0.5 * (d[n // 2 - 1] + d[n // 2])
85
+
86
+
87
+ def main():
88
+ ap = argparse.ArgumentParser()
89
+ ap.add_argument("--src", default="status/real/ACT_COND/M2X2_raw_run21.json",
90
+ help="output of xl2x2_test.py --scale raw on the deployed-width dirs")
91
+ ap.add_argument("--arm", default="rise")
92
+ ap.add_argument("--beta", default="0.90")
93
+ ap.add_argument("--out", default="status/real/ACT_COND/PRIMARY_run21.json")
94
+ ap.add_argument("--cell-dir", default=None,
95
+ help="arm dir holding snr_beta{90,95,99}.json; enables the paired-median column")
96
+ ap.add_argument("--label", default="deployed width (1024)",
97
+ help="what family --src describes; printed verbatim in the header")
98
+ a = ap.parse_args()
99
+
100
+ j = json.load(open(a.src))
101
+ if j.get("scale") != "raw":
102
+ sys.exit(f"FAIL: --src was written on scale {j.get('scale')!r}; the registered levels are RAW")
103
+ rows = [w for w in j["within"] if w["arm"] == a.arm and w["beta"] == a.beta]
104
+ if not rows:
105
+ sys.exit(f"FAIL: no within-arm rows for {a.arm}@{a.beta} in {a.src}")
106
+
107
+ print(f"PRIMARY READ -- {a.label}, {a.arm}@{a.beta} MINUS {a.arm}@0.99, same paired "
108
+ f"anchors (n={j['n']})")
109
+ print(f"scope limit: v0_provenance-reward family at {a.label}, never 'R_M'.\n")
110
+ hdr = (f"{'read':<6} {'statistic':<10} {'base(0.99)':>11} {'test(0.90)':>11} {'contrast':>10} "
111
+ f"{'bootCI95':>21} {'wilcox_p':>10} {'XL ref':>9} {'frac XL':>8} {'med d':>9} "
112
+ f"{'max att':>9} verdict")
113
+ print(hdr + "\n" + "-" * len(hdr))
114
+ out = []
115
+ for read in ("logit", "prob"):
116
+ for stem in ("margin_z", "rank_pct", "spearman"): # primary first
117
+ w = next((r for r in rows if r["read"] == read and r["stat"] == stem), None)
118
+ if w is None:
119
+ continue
120
+ base, test, obs = w["ref_mean_raw"], w["mean_raw"], w["dmean"]
121
+ cap = ceiling(stem, base)
122
+ verdict, frac = classify(stem, obs, cap)
123
+ censored = cap is not None and abs(cap) < abs(XL_REF[stem]) * TRANSFERS_FRAC
124
+ med = per_anchor_diff(a.cell_dir, stem, read, a.beta) if a.cell_dir else None
125
+ # the tail guard applies ONLY to unbounded statistics. rank_pct and spearman live in
126
+ # a compact interval and cannot blow up; a mean/median gap there is skew (and they
127
+ # already carry `max att`). XL prob/spearman tripped the unscoped guard at ratio 10.1
128
+ # with both numbers inside [-1, 1], which is exactly the false positive this excludes.
129
+ tail = (stem not in BOUND and med is not None and abs(med) > 0
130
+ and abs(obs / med) > TAIL_RATIO)
131
+ if tail:
132
+ verdict = f"TAIL-DRIVEN (mean/median={obs / med:.3g}) -- {verdict} NOT READABLE"
133
+ print(f"{read:<6} {stem:<10} {base:>11.4f} {test:>11.4f} {obs:>10.4f} "
134
+ f"[{w['boot_lo']:>9.4f},{w['boot_hi']:>9.4f}] {w['wilcoxon_p']:>10.2e} "
135
+ f"{XL_REF[stem]:>9.4f} {frac:>8.2f} "
136
+ f"{('%9.4f' % med) if med is not None else ' n/a'} "
137
+ f"{('%9.4f' % cap) if cap is not None else ' none'} {verdict}")
138
+ out.append({"read": read, "stat": stem, "base": base, "test": test, "contrast": obs,
139
+ "boot_lo": w["boot_lo"], "boot_hi": w["boot_hi"],
140
+ "wilcoxon_p": w["wilcoxon_p"], "paired_verdict": w["verdict"],
141
+ "xl_ref": XL_REF[stem], "frac_of_xl": frac,
142
+ "max_attainable": cap, "censored": bool(censored),
143
+ "paired_median_contrast": med, "tail_driven": bool(tail),
144
+ "transfers_verdict": verdict})
145
+ print("\nPRIMARY = margin_z (unbounded above). rank_pct and spearman are read ONLY beside "
146
+ "'max att';\nwhere 'max att' is smaller than half the XL reference the row is CENSORED and "
147
+ "carries NO\nevidence either way -- it is not a null. A row stamped TAIL-DRIVEN has a mean that "
148
+ f"disagrees with\nits own paired median by more than {TAIL_RATIO}x and carries no verdict at all.")
149
+ json.dump({"src": a.src, "label": a.label, "arm": a.arm, "beta": a.beta, "n": j["n"],
150
+ "xl_ref": XL_REF, "rows": out}, open(a.out, "w"), indent=1)
151
+ print(f"\nwrote {a.out}")
152
+
153
+
154
+ if __name__ == "__main__":
155
+ main()
rsm_rise/scripts/real/act_sensitivity.py ADDED
@@ -0,0 +1,498 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ACT_COND Task 2 (gen_q#278): HOW MUCH of the successor's score is action-driven?
2
+
3
+ The owner asked for sensitivity, not for a rank: "All we need is for the network to be sensitive enough
4
+ to action to pick actions leading to goal state." A rank number alone cannot answer that -- a value that
5
+ is 99% state and 1% action can still rank correctly at an easy anchor and be useless in the loop.
6
+
7
+ Per anchor (a real TRAIN-split frame, stage-labelled), ONE score() call carries three populations so the
8
+ particle noise is common (CRN) across all of them and the comparison is paired:
9
+
10
+ ACTION-SENSITIVITY INDEX asi = Var_a q(x0, a_j) / Var_s q(x_i, a0)
11
+ numerator : 128 stage-matched LOGGED candidate chunks at the anchor's FIXED state
12
+ denominator : the anchor's own LOGGED chunk at 128 stage-matched OTHER states
13
+ Near zero => the value is a state function and cannot rank actions (the COLLAPSE_ANALYSIS failure
14
+ mode, and exactly what the RISE/IQL critic did in sim: Q(s,a) ~ V(s), rank-pct ~0.5).
15
+ TIE STRUCTURE fraction of the 128 candidates tied at the max (rel tol) and the CV of the
16
+ scores, reported BESIDE every rank number: the prob read-out saturates on this corpus and a rank
17
+ without its tie count has burned this project before.
18
+ MONOTONE PROBE a(lam) = (1-lam) a_logged + lam a_failure, lam over 10 steps at the same
19
+ state. q should FALL monotonically; Spearman(lam, q) is the cheapest direct test that the net is
20
+ sensitive in the right DIRECTION and not merely sensitive.
21
+ READ-OUT prob and logit come out of the same call (`.last_q` / `.last_q_logit`), so
22
+ every number above is reported under both. There is no general read-out rule.
23
+
24
+ Sharding: --shard i --n-shard k splits the anchor list, one payload per GPU of a packed job.
25
+ """
26
+ import argparse, json, os, sys, collections, time
27
+ import numpy as np
28
+
29
+ ROOT = "/proj/dmfexp/zwhong/rsm_rise"
30
+ sys.path.insert(0, f"{ROOT}/scripts/real")
31
+ GOAL_PATH = "2->3->4"
32
+ FAIL_PATHS = ("0->5", "0->2->6")
33
+
34
+
35
+ def spearman(x, y):
36
+ def rank(v):
37
+ o = np.argsort(v, kind="mergesort"); r = np.empty(len(v), float); r[o] = np.arange(len(v))
38
+ # average ties
39
+ s = np.sort(v); i = 0
40
+ while i < len(v):
41
+ j = i
42
+ while j + 1 < len(v) and s[j + 1] == s[i]:
43
+ j += 1
44
+ if j > i:
45
+ r[o[i:j + 1]] = np.arange(i, j + 1).mean()
46
+ i = j + 1
47
+ return r
48
+ rx, ry = rank(np.asarray(x, float)), rank(np.asarray(y, float))
49
+ if rx.std() < 1e-12 or ry.std() < 1e-12:
50
+ return 0.0
51
+ return float(np.corrcoef(rx, ry)[0, 1])
52
+
53
+
54
+ def tie_stats(s, rtol=1e-9):
55
+ s = np.asarray(s, np.float64)
56
+ mx = s.max()
57
+ scale = max(abs(mx), 1e-30)
58
+ tied = int((s >= mx - rtol * scale).sum())
59
+ mu = s.mean()
60
+ cv = float(s.std() / abs(mu)) if abs(mu) > 1e-30 else float("nan")
61
+ return tied / len(s), cv
62
+
63
+
64
+ def margin_stats(s):
65
+ """Top1-minus-top2 margin of a candidate cloud, absolute and scale-free.
66
+
67
+ WHY (run 30, gen_q#278). `tie_stats` counts EXACT ties and is measured CONSTANT at 1/128 on
68
+ all 800 anchors of all four run-27 cells, both read-outs -- so the stream's mandated tie
69
+ statistic carries ZERO information about whether the executed pick is stable. Run 29 measured
70
+ that the argmax moves on 43.2% of anchors at the deployed cell while `rep_spearman` stays
71
+ 0.98, and diagnosed NEAR-ties at the top of the cloud; nothing in the instrument could see a
72
+ near-tie. This is that field. `rel` divides by the cloud's own spread, so it is comparable
73
+ ACROSS checkpoints and read-outs (prob and logit live on wildly different scales) -- which is
74
+ exactly where run 30 found the raw spread statistics stop transferring.
75
+ ADDITIVE: computed from arrays already in hand, no rng consumed, no extra forward pass.
76
+ """
77
+ s = np.asarray(s, np.float64)
78
+ o = np.sort(s)
79
+ m12 = float(o[-1] - o[-2])
80
+ sd = float(s.std())
81
+ return m12, (m12 / sd if sd > 1e-30 else float("nan"))
82
+
83
+
84
+ def main():
85
+ ap = argparse.ArgumentParser()
86
+ ap.add_argument("--hdf5", default=f"{ROOT}/data/raw/cooking_v5_expert_suboptimal.hdf5")
87
+ ap.add_argument("--split", default=f"{ROOT}/data/derived/cooking_v5_split.json")
88
+ ap.add_argument("--cache", default=f"{ROOT}/cache/real_cooking_v5")
89
+ ap.add_argument("--ckpt", default=f"{ROOT}/runs/real_cooking_v5/rsm/R_M/ckpt_s100000.pt")
90
+ ap.add_argument("--hop-ckpt", default=f"{ROOT}/runs/real_cooking_v5/hop/gauss/policy_r1.pt")
91
+ ap.add_argument("--mode", default="chain")
92
+ ap.add_argument("--beta", type=float, default=0.99)
93
+ ap.add_argument("--gamma", type=float, default=0.999)
94
+ ap.add_argument("--particles", type=int, default=16)
95
+ ap.add_argument("--temperature", type=float, default=25.0)
96
+ # CHAIN-LENGTH LEVER (gen_q#278 carry-forward). 0 = the legitimate cap, computed from
97
+ # (beta, gamma) by chain_cap() so P(N>cap)<=1e-3. A non-zero override TRUNCATES the walk:
98
+ # it is a different (biased-short) estimator, not a cheaper one, and is used here ONLY to
99
+ # measure how chain length dilutes action sensitivity -- never to tune a success number.
100
+ ap.add_argument("--chain-cap", type=int, default=0)
101
+ ap.add_argument("--n-cand", type=int, default=128)
102
+ ap.add_argument("--n-state", type=int, default=128)
103
+ ap.add_argument("--n-interp", type=int, default=10)
104
+ ap.add_argument("--horizon", type=int, default=8)
105
+ ap.add_argument("--stride", type=int, default=25)
106
+ ap.add_argument("--max-anchors", type=int, default=240)
107
+ ap.add_argument("--anchor-routes", default="all", choices=["all", "goal"],
108
+ help="which episodes anchors come from. The goal route 2->3->4 never visits S0/S1, "
109
+ "so `goal` can only report S2/S3; the sensitivity index is a property of the "
110
+ "VALUE AT A STATE and is well defined at a failure-route anchor too, so `all` "
111
+ "is the default and the anchor's route is recorded on every row.")
112
+ ap.add_argument("--shard", type=int, default=0)
113
+ ap.add_argument("--n-shard", type=int, default=1)
114
+ ap.add_argument("--seed", type=int, default=0)
115
+ ap.add_argument("--repeats", type=int, default=1,
116
+ help="independent PARTICLE draws of the SAME score() call per anchor. 1 (default) "
117
+ "is the historical behaviour and is byte-identical: repeat 0 always uses the "
118
+ "historical seed and every headline stat is taken from repeat 0. >1 adds the "
119
+ "read-out NOISE FLOOR -- between-candidate spread vs across-draw spread (SNR) "
120
+ "and top-1 agreement. ASI is signal/signal and says nothing about whether the "
121
+ "spread survives the estimator noise; SNR is the quantity that decides whether "
122
+ "the read-out can actually PICK an action.")
123
+ ap.add_argument("--rescore-top", type=int, default=0,
124
+ help="run 31: TWO-STAGE TIE-BREAK. Score all n_cand candidates with --particles, "
125
+ "keep the top-K by q_logit, rescore ONLY those with --rescore-particles. 0 "
126
+ "(default) is OFF and the whole block is skipped, so every cell measured "
127
+ "before this flag existed is byte-identical. Motivated by run 31: the "
128
+ "near-tie margin predicts pick instability better than any spread statistic "
129
+ "and transfers to the held-out checkpoint, while a UNIFORM 4x particle budget "
130
+ "buys only +6.7 points of top-1 agreement.")
131
+ ap.add_argument("--rescore-particles", type=int, default=0,
132
+ help="M in the two-stage tie-break; needs --rescore-top.")
133
+ ap.add_argument("--out", required=True)
134
+ a = ap.parse_args()
135
+ if bool(a.rescore_top) != bool(a.rescore_particles):
136
+ sys.exit("--rescore-top and --rescore-particles must be given together")
137
+ t0 = time.time()
138
+ import h5py, torch
139
+ from twin_rollout import Scorer
140
+ rng = np.random.default_rng(a.seed)
141
+ os.makedirs(os.path.dirname(a.out) or ".", exist_ok=True)
142
+
143
+ split = json.load(open(a.split))["episodes"]
144
+ meta = np.load(f"{a.cache}/meta.npz", allow_pickle=True)
145
+ ep_from, ep_to = np.asarray(meta["ep_from"]), np.asarray(meta["ep_to"])
146
+ zf = np.load(f"{a.cache}/z.f16.npy", mmap_mode="r")
147
+ pf = np.load(f"{a.cache}/proprio.f32.npy", mmap_mode="r")
148
+ st = np.load(f"{a.cache}/feat_stats.npz")
149
+ dd = int(zf.shape[1] + pf.shape[1])
150
+ mu, sd = st["mu"][:dd].astype(np.float32), st["sd"][:dd].astype(np.float32)
151
+ zclip = float(st["z_clip"]) if "z_clip" in st.files else 10.0
152
+
153
+ f = h5py.File(a.hdf5, "r"); d = f["data"]
154
+ lo = np.array(json.loads(d.attrs["action_min"]), np.float32)
155
+ hi = np.array(json.loads(d.attrs["action_max"]), np.float32)
156
+ spl = lambda k: split.get(str(int(k.split("_")[1])), {}).get("split", "")
157
+ path = lambda k: str(d[k].attrs.get("path", ""))
158
+ train = [k for k in d if spl(k) == "train"]
159
+
160
+ # ---- pools, keyed by stage: logged chunks (all train routes), states (train), failure chunks ----
161
+ chunk_pool = collections.defaultdict(list) # stage -> [H,10] chunks
162
+ state_pool = collections.defaultdict(list) # stage -> global cache index
163
+ fail_pool = collections.defaultdict(list)
164
+ anchors = [] # (ep, t, stage) on TRAIN goal-route episodes
165
+ for k in train:
166
+ g = d[k]; ep = int(k.split("_")[1])
167
+ A = np.asarray((g["actions_raw"] if "actions_raw" in g else g["actions"])[()], np.float32)
168
+ stg = np.asarray(g["annot"]["edge_from"][()])
169
+ for t in range(0, len(A) - a.horizon, a.stride):
170
+ s0 = int(stg[t]); ch = A[t:t + a.horizon]
171
+ chunk_pool[s0].append(ch)
172
+ state_pool[s0].append(int(ep_from[ep] + t))
173
+ if path(k) in FAIL_PATHS:
174
+ fail_pool[s0].append(ch)
175
+ if a.anchor_routes == "all" or path(k) == GOAL_PATH:
176
+ anchors.append((ep, t, s0, path(k)))
177
+ print(f"[sens] train eps {len(train)}; anchors({a.anchor_routes}) {len(anchors)} "
178
+ f"{dict(collections.Counter(f'S{x[2]}' for x in anchors))}; "
179
+ f"pool per stage {{{', '.join(f'S{s}:{len(v)}' for s, v in sorted(chunk_pool.items()))}}}; "
180
+ f"fail pool {{{', '.join(f'S{s}:{len(v)}' for s, v in sorted(fail_pool.items()))}}}", flush=True)
181
+ # STRATIFY BY STAGE. The corpus spends most of its frames in S0/S2, so a uniform draw would put
182
+ # ~10 anchors in S3 and the per-stage row for it would be noise. Equal quota per stage, the
183
+ # leftover redistributed to the stages that still have anchors.
184
+ by_stage = collections.defaultdict(list)
185
+ for x in anchors:
186
+ by_stage[x[2]].append(x)
187
+ if len(anchors) > a.max_anchors:
188
+ stages = sorted(by_stage)
189
+ quota = {s: a.max_anchors // len(stages) for s in stages}
190
+ left = a.max_anchors - sum(min(quota[s], len(by_stage[s])) for s in stages)
191
+ for s in sorted(stages, key=lambda s: -len(by_stage[s])):
192
+ take = min(left, max(0, len(by_stage[s]) - quota[s]))
193
+ quota[s] += take; left -= take
194
+ picked = []
195
+ for s in stages:
196
+ v = by_stage[s]; n = min(quota[s], len(v))
197
+ picked += [v[i] for i in sorted(rng.choice(len(v), size=n, replace=False))]
198
+ anchors = sorted(picked, key=lambda x: (x[0], x[1]))
199
+ print(f"[sens] after stratification: {dict(collections.Counter(f'S{x[2]}' for x in anchors))}", flush=True)
200
+ anchors = anchors[a.shard::a.n_shard]
201
+ print(f"[sens] shard {a.shard}/{a.n_shard}: {len(anchors)} anchors", flush=True)
202
+
203
+ sc = Scorer("rsm", lo, hi, rsm_ckpt=a.ckpt, seed=a.seed, rsm_mode=a.mode, rsm_beta=a.beta,
204
+ rsm_gamma=a.gamma, rsm_particles=a.particles, rsm_dim=dd,
205
+ rsm_temperature=a.temperature, rsm_hop_ckpt=a.hop_ckpt)
206
+ if a.chain_cap:
207
+ # THE OVERRIDE LIVES ON THE BACKEND, NOT THE SCORER. RSMScorer.score() delegates to
208
+ # self.backend.q(...), and it is MLPBackend._q that reads getattr(self,"chain_cap_override").
209
+ # Setting it on the RSMScorer is a SILENT no-op: cap 2, cap 9 and the default cap 67 then
210
+ # return bit-identical q (measured, 2026-09-23). Asserted below against the realized cap.
211
+ sc.rsm.backend.chain_cap_override = int(a.chain_cap)
212
+ print(f"[sens] CHAIN CAP OVERRIDE = {a.chain_cap} on {type(sc.rsm.backend).__name__} "
213
+ f"(truncated estimator)", flush=True)
214
+ rsm = sc.rsm; dev = rsm.device
215
+
216
+ def feat(gi):
217
+ z = np.concatenate([np.asarray(zf[gi], np.float32), np.asarray(pf[gi], np.float32)])
218
+ return np.clip((z - mu) / sd, -zclip, zclip).astype(np.float32)
219
+
220
+ NC, NS, NI = a.n_cand, a.n_state, a.n_interp
221
+ # MONOTONE-PROBE TARGET. The failure routes (0->5, 0->2->6) never enter stages 1 and 3, so a
222
+ # same-stage failure chunk does not exist there. Dropping those anchors would have left the whole
223
+ # measurement on S2 (which is what the first launch did: 33 of 80 anchors, S2 only). Fall back,
224
+ # in order, to a failure chunk from ANOTHER stage, then to any other-stage logged chunk -- both are
225
+ # still "an action this state should not take" -- and record WHICH source each anchor used so the
226
+ # Spearman is aggregated per source and no fallback is silently mixed into the headline.
227
+ fail_stages = [s for s, v in fail_pool.items() if v]
228
+ def probe_target(s0):
229
+ if fail_pool[s0]:
230
+ return fail_pool[s0][int(rng.integers(len(fail_pool[s0])))], "failure_same_stage"
231
+ if fail_stages:
232
+ sp = fail_stages[int(rng.integers(len(fail_stages)))]
233
+ return fail_pool[sp][int(rng.integers(len(fail_pool[sp])))], "failure_other_stage"
234
+ others = [s for s, v in chunk_pool.items() if s != s0 and v]
235
+ sp = others[int(rng.integers(len(others)))]
236
+ return chunk_pool[sp][int(rng.integers(len(chunk_pool[sp])))], "offstage"
237
+ rows = []
238
+ skipped = collections.Counter()
239
+ for ai, (ep, t, s0, route) in enumerate(anchors):
240
+ if len(chunk_pool[s0]) < NC or len(state_pool[s0]) < NS + 1:
241
+ skipped[f"S{s0}:pool<{NC}"] += 1
242
+ continue
243
+ gi = int(ep_from[ep] + t)
244
+ x0 = feat(gi)
245
+ g = d[f"demo_{ep}"]
246
+ a0 = np.asarray((g["actions_raw"] if "actions_raw" in g else g["actions"])[t:t + a.horizon], np.float32)
247
+ ci = rng.choice(len(chunk_pool[s0]), size=NC, replace=False)
248
+ cands = np.stack([chunk_pool[s0][i] for i in ci]) # [NC,H,10]
249
+ si = [j for j in rng.permutation(len(state_pool[s0])) if state_pool[s0][j] != gi][:NS]
250
+ states = np.stack([feat(state_pool[s0][j]) for j in si]) # [NS,D]
251
+ af, probe_src = probe_target(s0)
252
+ lam = np.linspace(0.0, 1.0, NI, dtype=np.float32)
253
+ interp = np.stack([(1 - l) * a0 + l * af for l in lam]) # [NI,H,10]
254
+ # one call: [128 cands @ x0 | a0 @ 128 states | 10 interpolants @ x0 | a0 @ x0]
255
+ X = np.concatenate([np.repeat(x0[None], NC, 0), states,
256
+ np.repeat(x0[None], NI + 1, 0)], 0)
257
+ A = np.concatenate([cands, np.repeat(a0[None], NS, 0), interp, a0[None]], 0)
258
+ # REPEATS = independent particle draws of the same call. Repeat 0 keeps the historical
259
+ # seed, so --repeats 1 is byte-identical to every cell measured before this flag existed and
260
+ # --repeats R leaves every headline stat below (which reads q/ql = repeat 0) comparable to them.
261
+ q_rep, l_rep = [], []
262
+ for rep in range(max(1, a.repeats)):
263
+ with torch.no_grad():
264
+ rsm.score(torch.as_tensor(X, dtype=torch.float32, device=dev), A,
265
+ seed=a.seed + 7919 * (ai + 1) + 104729 * rep)
266
+ cs = getattr(rsm, "chain_hop_acc", None) or {}
267
+ qr = rsm.last_q.double().cpu().numpy()
268
+ lr = rsm.last_q_logit
269
+ lr = np.full_like(qr, np.nan) if lr is None else lr.double().cpu().numpy()
270
+ q_rep.append(qr); l_rep.append(lr)
271
+ q, ql = q_rep[0], l_rep[0]
272
+ qa, qs, qi, q00 = q[:NC], q[NC:NC + NS], q[NC + NS:NC + NS + NI], q[-1]
273
+ la, ls, li, l00 = ql[:NC], ql[NC:NC + NS], ql[NC + NS:NC + NS + NI], ql[-1]
274
+ r = {"ep": ep, "t": t, "stage": s0, "route": route, "probe_src": probe_src,
275
+ "q0": float(q00), "logit0": float(l00),
276
+ "var_a_prob": float(qa.var()), "var_s_prob": float(qs.var()),
277
+ "var_a_logit": float(la.var()), "var_s_logit": float(ls.var()),
278
+ "mean_a_prob": float(qa.mean()), "mean_s_prob": float(qs.mean()),
279
+ "mean_a_logit": float(la.mean()), "mean_s_logit": float(ls.mean()),
280
+ "spearman_prob": spearman(lam, qi), "spearman_logit": spearman(lam, li),
281
+ "interp_drop_prob": float(qi[0] - qi[-1]), "interp_drop_logit": float(li[0] - li[-1]),
282
+ "rank_pct_prob": float((qa < q00).mean()), "rank_pct_logit": float((la < l00).mean())}
283
+ r["tie_frac_prob"], r["cv_prob"] = tie_stats(qa)
284
+ r["tie_frac_logit"], r["cv_logit"] = tie_stats(la)
285
+ # NEAR-TIE MARGIN (run 30). Single-draw (repeat 0), so a closed-loop scorer has these in
286
+ # hand at zero extra cost -- the pre-registered candidate for an ADAPTIVE particle budget.
287
+ r["margin12_prob"], r["margin12_rel_prob"] = margin_stats(qa)
288
+ r["margin12_logit"], r["margin12_rel_logit"] = margin_stats(la)
289
+ r["asi_prob"] = r["var_a_prob"] / max(r["var_s_prob"], 1e-30)
290
+ r["asi_logit"] = r["var_a_logit"] / max(r["var_s_logit"], 1e-30)
291
+ # ---- READ-OUT CROSS-PICK (run 27, gen_q#278). ADDITIVE ONLY: computed from `qa`/`la`, the
292
+ # SAME 128 candidate scores of the SAME score() call (prob = rsm.last_q, logit =
293
+ # rsm.last_q_logit), so it consumes no rng, issues no extra forward pass, and cannot move any
294
+ # field above. WHY IT EXISTS: runs 25/26 recommended switching the deployed read-out from
295
+ # `prob` to `logit` on RANK statistics of the LOGGED chunk. The closed loop does not execute
296
+ # the logged chunk -- it executes argmax over the candidate cloud. A read-out switch is only
297
+ # a closed-loop change to the extent the two ARGMAXES DIFFER, and that number was never
298
+ # measured. `xpick_agree` is it; the two cross-ranks say how bad the loser is under the
299
+ # winner's own metric when they do differ (1.0 = the loser was the winner's top choice too).
300
+ if np.all(np.isfinite(la)) and np.all(np.isfinite(qa)):
301
+ ip, il = int(np.argmax(qa)), int(np.argmax(la))
302
+ r["xpick_prob_idx"], r["xpick_logit_idx"] = ip, il
303
+ r["xpick_agree"] = float(ip == il)
304
+ # rank pct of EACH read-out's pick under the OTHER read-out's scores (strict-less, the
305
+ # same convention as rank_pct_* above so the two columns are directly comparable).
306
+ r["xpick_probpick_rank_under_logit"] = float((la < la[ip]).mean())
307
+ r["xpick_logitpick_rank_under_prob"] = float((qa < qa[il]).mean())
308
+ # whole-ordering agreement of the two read-outs over the candidate cloud. If this is
309
+ # ~1.0 the read-out is a monotone relabelling here and the switch is a closed-loop no-op.
310
+ r["xpick_spearman_cand"] = spearman(qa, la)
311
+ else:
312
+ r["xpick_agree"] = float("nan")
313
+ # NOISE FLOOR. ASI is var(candidates)/var(states) -- a ratio of two SIGNALS, so it is blind
314
+ # to a regime where both collapse into the estimator noise. With R independent particle
315
+ # draws of the same 128 candidates at the same state: signal = var ACROSS candidates of the
316
+ # per-candidate mean over draws; noise = mean ACROSS candidates of the var over draws.
317
+ # top1_agree is the decision-level version: does the read-out pick the SAME action twice?
318
+ if len(q_rep) > 1:
319
+ for nm, reps in (("prob", q_rep), ("logit", l_rep)):
320
+ M = np.stack([z[:NC] for z in reps]) # [R, NC], candidates only
321
+ sig = float(M.mean(0).var())
322
+ noi = float(M.var(0, ddof=1).mean())
323
+ pairs = [(i, j) for i in range(len(M)) for j in range(i + 1, len(M))]
324
+ top1 = [int(np.argmax(z)) for z in M]
325
+ # ROBUST DENOMINATOR (run 10). `noi` is the MEAN over candidates of the
326
+ # per-candidate variance across draws. Under `logit` the scores are unbounded
327
+ # (q_logit = mean_i logit_i; the reward head reaches logits ~ +121, rsm_scorer.py:33),
328
+ # so a few extreme candidates can set both sig and noi -- which is exactly the regime
329
+ # where the measured logit SNRcorr was 0.03 while the rank correlation between draws
330
+ # was +0.998. The median denominator says whether that is heteroscedasticity or a
331
+ # genuinely flat field. Additive only: it consumes no rng and changes no other field.
332
+ r[f"noise_var_med_{nm}"] = float(np.median(M.var(0, ddof=1)))
333
+ r[f"snr_robust_{nm}"] = sig / max(r[f"noise_var_med_{nm}"], 1e-30)
334
+ r[f"sig_var_{nm}"], r[f"noise_var_{nm}"] = sig, noi
335
+ r[f"snr_{nm}"] = sig / max(noi, 1e-30)
336
+ r[f"top1_agree_{nm}"] = float(np.mean([top1[i] == top1[j] for i, j in pairs]))
337
+ # run 30: the margin of EACH draw, so "did the margin predict the disagreement"
338
+ # can be asked without draw 0 (the strict hold-out: predictor from draw 0, outcome
339
+ # from draws 1.. only). Read off M, no rng, no extra forward pass.
340
+ r[f"margin12_rel_draws_{nm}"] = [margin_stats(z)[1] for z in M]
341
+ r[f"rep_spearman_{nm}"] = float(np.mean([spearman(M[i], M[j]) for i, j in pairs]))
342
+ # ---- MC PICK INSTABILITY (run 29, gen_q#278). ADDITIVE ONLY: read off `M`, the
343
+ # repeat scores already stacked above -- no extra forward pass, no rng consumed.
344
+ # WHY: run 28 showed the prob->logit switch moves the executed pick on 23.5% of
345
+ # anchors at the deployed cell. `top1_agree_{nm}` is the SAME quantity with the
346
+ # OTHER factor varied (redraw the particles, hold the read-out), and it is LOWER.
347
+ # To compare the two on distance as well as on rate, act_pickdist needs the indices,
348
+ # so store them. `top1_agree_half_{nm}` is the deployable question: does AVERAGING
349
+ # draws stabilise the pick? Two disjoint half-averages of floor(R/2) draws each are
350
+ # two independent picks at an effective 2x particle budget, so it predicts the
351
+ # particle curve this run measures directly. NaN for R < 4 (no disjoint halves).
352
+ r[f"top1_idx_{nm}"] = [int(v) for v in top1]
353
+ h = len(M) // 2
354
+ r[f"top1_agree_half_{nm}"] = (
355
+ float(int(np.argmax(M[:h].mean(0))) == int(np.argmax(M[h:2 * h].mean(0))))
356
+ if len(M) >= 4 else float("nan"))
357
+ r[f"top1_half_idx_{nm}"] = ([int(np.argmax(M[:h].mean(0))), int(np.argmax(M[h:2 * h].mean(0)))]
358
+ if len(M) >= 4 else None)
359
+ # realized walk length: the x-axis of the dilution curve must be ACTUAL hops, not the
360
+ # nominal cap (the coin usually stops long before a loose cap binds).
361
+ for k in ("cap", "p_cont", "E_hops_expected"):
362
+ if cs.get(k) is not None:
363
+ r[f"chain_{k}"] = float(cs[k])
364
+ if cs.get("decisions"):
365
+ r["chain_hops_mean"] = float(cs["hops_sum"]) / float(cs["decisions"])
366
+ r["chain_capped_frac"] = float(cs["capped_sum"]) / float(cs["decisions"])
367
+ # FAIL LOUD: a requested cap that does not reach the walk is the exact silent bug this
368
+ # sweep was built to avoid measuring through.
369
+ if a.chain_cap and r.get("chain_cap") is not None and int(r["chain_cap"]) != int(a.chain_cap):
370
+ raise RuntimeError(f"chain cap override NOT APPLIED: requested {a.chain_cap}, "
371
+ f"walk ran at cap {r['chain_cap']}")
372
+ # ---- TWO-STAGE TIE-BREAK (run 31, gen_q#278).
373
+ # PLACED HERE, AFTER the chain-stat section, DELIBERATELY: `cs` above is a live REFERENCE to
374
+ # rsm.chain_hop_acc, a cumulative accumulator mutated in place by every score() call, so a
375
+ # block of extra calls placed before it would silently inflate chain_hops_mean /
376
+ # chain_capped_frac for rescore cells only. (That accumulator is also what made run 30's
377
+ # "[CAP ALARM] capped_frac=0.0312" a false alarm -- it fired on a 32-decision prefix.)
378
+ # ENTIRELY SKIPPED unless --rescore-top, so
379
+ # every cell measured before this flag is byte-identical: the block below issues its own
380
+ # score() calls with their OWN seeds, and RSMScorer builds a fresh generator per seed
381
+ # (dwm_readout.q: `self._gen(crn_seed)`), so it consumes no rng from the loop above.
382
+ #
383
+ # THE TRAP, and the reason this cannot reuse the call above: `rescore_top` takes the top-K of
384
+ # the WHOLE input array (dwm_readout.py:180-183, `torch.topk(ql, K)` over all rows). The
385
+ # packed call above carries NC candidates + NS STATES + NI interpolants + 1 = 267 rows, so a
386
+ # rescore on it would rank candidates against STATES and spend the big budget on whichever
387
+ # mixture scored high. The tie-break has to see the 128 candidates ALONE, hence its own call.
388
+ #
389
+ # PAIRED CONTROL, same batch shape and the SAME seed: `ctl` is the identical candidates-only
390
+ # call with the tie-break OFF. Stage 1 is therefore bit-identical between ctl and two-stage
391
+ # and the ONLY difference is the top-K rescore -- so a change in pick stability is attributable
392
+ # to the tie-break and not to the batch shape. Comparing against the 267-row call instead
393
+ # would confound the two.
394
+ if a.rescore_top:
395
+ Xc = np.repeat(x0[None], NC, 0)
396
+ for tag, K, M in (("ctl", 0, 0), ("ts", int(a.rescore_top), int(a.rescore_particles))):
397
+ rq, rl = [], []
398
+ for rep in range(max(1, a.repeats)):
399
+ with torch.no_grad():
400
+ rsm.score(torch.as_tensor(Xc, dtype=torch.float32, device=dev), cands,
401
+ seed=a.seed + 31337 + 7919 * (ai + 1) + 104729 * rep,
402
+ rescore_top=K, n_particles_rescore=M)
403
+ qq = rsm.last_q.double().cpu().numpy()
404
+ ll = rsm.last_q_logit
405
+ ll = np.full_like(qq, np.nan) if ll is None else ll.double().cpu().numpy()
406
+ rq.append(qq); rl.append(ll)
407
+ for nm, S in (("prob", np.stack(rq)), ("logit", np.stack(rl))):
408
+ r[f"rs_{tag}_top1_idx_{nm}"] = [int(np.argmax(v)) for v in S]
409
+ r[f"rs_{tag}_margin12_{nm}"], r[f"rs_{tag}_margin12_rel_{nm}"] = margin_stats(S[0])
410
+ # COST, recorded per anchor so the curve is read against compute and not against K:
411
+ # stage 1 is NC*particles particle-evals, the rescore adds K*M.
412
+ r["rs_cost_ctl"] = float(NC * a.particles)
413
+ r["rs_cost_ts"] = float(NC * a.particles + a.rescore_top * a.rescore_particles)
414
+ rows.append(r)
415
+ if ai == 0 or len(rows) % 10 == 0:
416
+ print(f" [{len(rows)}] ep{ep} t{t} S{s0} asi_logit={r['asi_logit']:.3f} "
417
+ f"asi_prob={r['asi_prob']:.3f} rho_logit={r['spearman_logit']:+.2f} "
418
+ f"ties_prob={r['tie_frac_prob']*NC:.0f}/{NC} ({time.time()-t0:.0f}s)", flush=True)
419
+
420
+ out = {"args": vars(a), "n_anchors": len(rows), "rows": rows,
421
+ "host": os.uname().nodename, "seconds": time.time() - t0}
422
+ # aggregate, per stage and pooled. The index is a RATIO, so the pooled number is the ratio of the
423
+ # pooled variances, not the mean of per-anchor ratios; both are reported (the mean of ratios is
424
+ # dominated by anchors with a near-zero state variance).
425
+ def agg(sub):
426
+ if not sub:
427
+ return {}
428
+ z = {}
429
+ for kind in ("prob", "logit"):
430
+ va = np.array([r[f"var_a_{kind}"] for r in sub]); vs = np.array([r[f"var_s_{kind}"] for r in sub])
431
+ asi = np.array([r[f"asi_{kind}"] for r in sub])
432
+ z[kind] = {"n": len(sub),
433
+ "asi_pooled": float(va.mean() / max(vs.mean(), 1e-30)),
434
+ "asi_median": float(np.median(asi)), "asi_mean": float(asi.mean()),
435
+ "var_a_mean": float(va.mean()), "var_s_mean": float(vs.mean()),
436
+ "spearman_mean": float(np.mean([r[f"spearman_{kind}"] for r in sub])),
437
+ "spearman_frac_neg1": float(np.mean([r[f"spearman_{kind}"] <= -0.99 for r in sub])),
438
+ "spearman_by_probe_src": {
439
+ src: {"n": sum(1 for r in sub if r["probe_src"] == src),
440
+ "mean": float(np.mean([r[f"spearman_{kind}"] for r in sub
441
+ if r["probe_src"] == src]))}
442
+ for src in sorted({r["probe_src"] for r in sub})},
443
+ "interp_drop_mean": float(np.mean([r[f"interp_drop_{kind}"] for r in sub])),
444
+ "tie_frac_mean": float(np.mean([r[f"tie_frac_{kind}"] for r in sub])),
445
+ "cv_mean": float(np.nanmean([r[f"cv_{kind}"] for r in sub])),
446
+ "rank_pct_mean": float(np.mean([r[f"rank_pct_{kind}"] for r in sub])),
447
+ "rank_pct_mean_goal_route": (
448
+ float(np.mean([r[f"rank_pct_{kind}"] for r in sub if r["route"] == GOAL_PATH]))
449
+ if any(r["route"] == GOAL_PATH for r in sub) else None),
450
+ "n_goal_route": sum(1 for r in sub if r["route"] == GOAL_PATH)}
451
+ if all(f"snr_{kind}" in r for r in sub):
452
+ sg = np.array([r[f"sig_var_{kind}"] for r in sub])
453
+ nz = np.array([r[f"noise_var_{kind}"] for r in sub])
454
+ z[kind].update({
455
+ # pooled like ASI: ratio of the pooled variances, not the mean of the ratios.
456
+ "snr_pooled": float(sg.mean() / max(nz.mean(), 1e-30)),
457
+ "snr_median": float(np.median([r[f"snr_{kind}"] for r in sub])),
458
+ "sig_var_mean": float(sg.mean()), "noise_var_mean": float(nz.mean()),
459
+ "top1_agree_mean": float(np.mean([r[f"top1_agree_{kind}"] for r in sub])),
460
+ "top1_agree_half_mean": (
461
+ float(np.mean([r[f"top1_agree_half_{kind}"] for r in sub]))
462
+ if all(f"top1_agree_half_{kind}" in r for r in sub)
463
+ and np.all(np.isfinite([r[f"top1_agree_half_{kind}"] for r in sub])) else None),
464
+ "rep_spearman_mean": float(np.mean([r[f"rep_spearman_{kind}"] for r in sub]))})
465
+ return z
466
+ out["by_stage"] = {f"S{s}": agg([r for r in rows if r["stage"] == s])
467
+ for s in sorted({r["stage"] for r in rows})}
468
+ out["pooled"] = agg(rows)
469
+ out["skipped"] = dict(skipped)
470
+ hm = [r["chain_hops_mean"] for r in rows if "chain_hops_mean" in r]
471
+ if hm:
472
+ out["chain"] = {"hops_mean": float(np.mean(hm)), "hops_min": float(np.min(hm)),
473
+ "hops_max": float(np.max(hm)),
474
+ "cap": rows[0].get("chain_cap"), "p_cont": rows[0].get("chain_p_cont"),
475
+ "capped_frac_mean": float(np.mean([r.get("chain_capped_frac", 0.0) for r in rows]))}
476
+ print(f"[sens] realized chain: {out['chain']}", flush=True)
477
+ out["probe_src_counts"] = dict(collections.Counter(r["probe_src"] for r in rows))
478
+ print(f"[sens] skipped {dict(skipped)}; probe sources {out['probe_src_counts']}", flush=True)
479
+ json.dump(out, open(a.out, "w"), indent=1)
480
+ print(f"\n{'scope':>8}{'read':>7}{'n':>5}{'asi_pool':>10}{'asi_med':>9}{'var_a':>11}{'var_s':>11}"
481
+ f"{'rho':>7}{'rho=-1':>8}{'ties/128':>10}{'cv':>10}{'rankpct':>9}")
482
+ for scope, z in list(out["by_stage"].items()) + [("POOLED", out["pooled"])]:
483
+ for kind in ("prob", "logit"):
484
+ if kind not in z:
485
+ continue
486
+ v = z[kind]
487
+ print(f"{scope:>8}{kind:>7}{v['n']:>5}{v['asi_pooled']:>10.3f}{v['asi_median']:>9.3f}"
488
+ f"{v['var_a_mean']:>11.3e}{v['var_s_mean']:>11.3e}{v['spearman_mean']:>7.2f}"
489
+ f"{v['spearman_frac_neg1']:>8.2f}{v['tie_frac_mean']*a.n_cand:>10.1f}"
490
+ f"{v['cv_mean']:>10.2e}{v['rank_pct_mean']:>9.3f}"
491
+ + (f" snr={v['snr_pooled']:8.3f} top1={v['top1_agree_mean']:.3f} "
492
+ f"reprho={v['rep_spearman_mean']:+.3f}" if "snr_pooled" in v else ""))
493
+ print(f"\nwrote {a.out} ({len(rows)} anchors, {time.time()-t0:.0f}s)", flush=True)
494
+ f.close()
495
+
496
+
497
+ if __name__ == "__main__":
498
+ main()
rsm_rise/scripts/real/act_xpick_read.py ADDED
@@ -0,0 +1,162 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """ACT_COND run 27 (gen_q#278) -- READ the read-out cross-pick cells. Computes nothing on the model.
3
+
4
+ WHY. Runs 25/26 recommended switching the deployed read-out from `prob` to `logit`, on rank
5
+ statistics of the LOGGED chunk, replicated on four checkpoints. The closed loop does not execute
6
+ the logged chunk; it executes argmax over the candidate cloud. So the switch is a closed-loop
7
+ change ONLY to the extent the two ARGMAXES DIFFER. This reads that number.
8
+
9
+ It also runs a REGRESSION CHECK: the run-27 cells re-run the run-21/run-14 beta=0.99 cells with
10
+ byte-identical arguments and a purely additive patch, so every PRE-EXISTING field must reproduce.
11
+ A mismatch means the additive patch was not additive, and this script exits non-zero.
12
+ """
13
+ import argparse, json, math, os, sys
14
+
15
+ def load(p):
16
+ with open(p) as f:
17
+ return json.load(f)
18
+
19
+ def mean(v):
20
+ return float(sum(v) / len(v)) if v else float("nan")
21
+
22
+ def median(v):
23
+ if not v:
24
+ return float("nan")
25
+ s = sorted(v); n = len(s)
26
+ return float(s[n // 2] if n % 2 else 0.5 * (s[n // 2 - 1] + s[n // 2]))
27
+
28
+ def wilson(k, n, z=1.96):
29
+ """Binomial CI. argmax agreement is a PROPORTION and at k=n the normal interval is [1,1],
30
+ which would read as certainty off 200 anchors; Wilson keeps an honest lower bound."""
31
+ if n == 0:
32
+ return (float("nan"), float("nan"))
33
+ p = k / n
34
+ d = 1 + z * z / n
35
+ c = (p + z * z / (2 * n)) / d
36
+ h = z * math.sqrt(max(p * (1 - p) / n + z * z / (4 * n * n), 0.0)) / d
37
+ return (max(0.0, c - h), min(1.0, c + h))
38
+
39
+ NEW = ("xpick_prob_idx", "xpick_logit_idx", "xpick_agree",
40
+ "xpick_probpick_rank_under_logit", "xpick_logitpick_rank_under_prob",
41
+ "xpick_spearman_cand")
42
+
43
+ def regress(new_rows, ref_rows, tol):
44
+ """Every field the reference already had must reproduce. Anchors are matched on (ep,t)."""
45
+ ref = {(r["ep"], r["t"]): r for r in ref_rows}
46
+ bad, worst, nfield = [], 0.0, 0
47
+ for r in new_rows:
48
+ k = (r["ep"], r["t"])
49
+ if k not in ref:
50
+ bad.append(f"anchor {k} absent from reference"); continue
51
+ for f, v in ref[k].items():
52
+ if f in NEW:
53
+ continue
54
+ w = r.get(f, "<MISSING>")
55
+ nfield += 1
56
+ if isinstance(v, float) and isinstance(w, float):
57
+ if math.isnan(v) and math.isnan(w):
58
+ continue
59
+ d = abs(v - w)
60
+ rel = d / max(abs(v), 1e-30)
61
+ worst = max(worst, rel)
62
+ if d > tol and rel > tol:
63
+ bad.append(f"{k}.{f}: ref={v!r} new={w!r}")
64
+ elif v != w:
65
+ bad.append(f"{k}.{f}: ref={v!r} new={w!r}")
66
+ return bad, worst, nfield
67
+
68
+ def main():
69
+ ap = argparse.ArgumentParser()
70
+ ap.add_argument("--dir", default="/proj/dmfexp/zwhong/rsm_rise/status/real/ACT_COND")
71
+ ap.add_argument("--cells", default="mrise,mnt,xlrise,xlnt")
72
+ ap.add_argument("--tol", type=float, default=1e-9)
73
+ ap.add_argument("--out", default="")
74
+ a = ap.parse_args()
75
+
76
+ tags = [t for t in a.cells.split(",") if t]
77
+ missing = [t for t in tags if not os.path.exists(f"{a.dir}/xpick/xpick_{t}.json")]
78
+ if missing:
79
+ print("MISSING CELLS (nothing to read yet): " + " ".join(missing))
80
+ sys.exit(4)
81
+
82
+ out, rc = {"cells": {}}, 0
83
+ print("=" * 108)
84
+ print("READ-OUT CROSS-PICK: does switching prob -> logit change the ACTION the closed loop executes?")
85
+ print("=" * 108)
86
+ hdr = (f"{'cell':<9}{'n':>5}{'agree':>8}{'wilsonCI95':>18}{'rho(cand)':>11}"
87
+ f"{'probpick|logit':>16}{'logitpick|prob':>16}{'n_disagree':>12}")
88
+ print(hdr); print("-" * len(hdr))
89
+ for t in tags:
90
+ d = load(f"{a.dir}/xpick/xpick_{t}.json")
91
+ rows = [r for r in d["rows"] if "xpick_agree" in r and not math.isnan(r["xpick_agree"])]
92
+ n = len(rows)
93
+ k = int(sum(r["xpick_agree"] for r in rows))
94
+ lo, hi = wilson(k, n)
95
+ dis = [r for r in rows if r["xpick_agree"] == 0.0]
96
+ # cross-ranks are only meaningful where the picks DIFFER: where they agree both are 1.0 by
97
+ # construction and averaging them in would dilute the number toward 1.
98
+ c = {"n": n, "n_agree": k, "agree": k / n if n else float("nan"),
99
+ "agree_ci95": [lo, hi], "n_disagree": len(dis),
100
+ "spearman_cand_mean": mean([r["xpick_spearman_cand"] for r in rows]),
101
+ "spearman_cand_median": median([r["xpick_spearman_cand"] for r in rows]),
102
+ "probpick_rank_under_logit_disagree_mean": mean(
103
+ [r["xpick_probpick_rank_under_logit"] for r in dis]),
104
+ "logitpick_rank_under_prob_disagree_mean": mean(
105
+ [r["xpick_logitpick_rank_under_prob"] for r in dis]),
106
+ "probpick_rank_under_logit_disagree_median": median(
107
+ [r["xpick_probpick_rank_under_logit"] for r in dis]),
108
+ "logitpick_rank_under_prob_disagree_median": median(
109
+ [r["xpick_logitpick_rank_under_prob"] for r in dis]),
110
+ "by_stage": {}}
111
+ for s in sorted({r["stage"] for r in rows}):
112
+ sub = [r for r in rows if r["stage"] == s]
113
+ c["by_stage"][f"S{s}"] = {"n": len(sub),
114
+ "agree": mean([r["xpick_agree"] for r in sub])}
115
+ ref_p = f"{a.dir}/snr_{t}/snr_beta99.json"
116
+ if os.path.exists(ref_p):
117
+ bad, worst, nf = regress(d["rows"], load(ref_p)["rows"], a.tol)
118
+ c["regression"] = {"ref": ref_p, "n_fields": nf, "worst_rel": worst,
119
+ "n_mismatch": len(bad), "mismatch_head": bad[:8]}
120
+ if bad:
121
+ rc = 5
122
+ else:
123
+ c["regression"] = {"ref": ref_p, "status": "reference absent"}
124
+ out["cells"][t] = c
125
+ print(f"{t:<9}{n:>5}{c['agree']:>8.3f} [{lo:.3f}, {hi:.3f}]"
126
+ f"{c['spearman_cand_mean']:>11.4f}"
127
+ f"{c['probpick_rank_under_logit_disagree_mean']:>16.4f}"
128
+ f"{c['logitpick_rank_under_prob_disagree_mean']:>16.4f}"
129
+ f"{len(dis):>12d}")
130
+ print()
131
+ print("cross-rank columns are over the DISAGREEING anchors only (where they agree both are 1.0 "
132
+ "by construction).")
133
+ print()
134
+ print("REGRESSION vs the run-21/run-14 beta=0.99 cells (the additive patch must move nothing):")
135
+ for t in tags:
136
+ r = out["cells"][t]["regression"]
137
+ if "n_mismatch" in r:
138
+ v = ("IDENTICAL" if r["n_mismatch"] == 0
139
+ else f"*** {r['n_mismatch']} MISMATCHES ***")
140
+ print(f" {t:<9} {r['n_fields']:>6d} fields worst rel {r['worst_rel']:.2e} {v}")
141
+ for m in r["mismatch_head"]:
142
+ print(f" {m}")
143
+ else:
144
+ print(f" {t:<9} {r['status']}")
145
+ print()
146
+ print("STAGE BREAKDOWN of argmax agreement:")
147
+ for t in tags:
148
+ bs = out["cells"][t]["by_stage"]
149
+ print(f" {t:<9} " + " ".join(f"{s}: {v['agree']:.3f} (n={v['n']})"
150
+ for s, v in sorted(bs.items())))
151
+ if a.out:
152
+ os.makedirs(os.path.dirname(a.out), exist_ok=True)
153
+ with open(a.out, "w") as f:
154
+ json.dump(out, f, indent=1)
155
+ print(f"\nwrote {a.out}")
156
+ if rc:
157
+ print("\nFAIL: the additive patch changed a pre-existing field. "
158
+ "The run-27 numbers must not be read until this is explained.")
159
+ sys.exit(rc)
160
+
161
+ if __name__ == "__main__":
162
+ main()
rsm_rise/scripts/real/actcond_audit.py ADDED
@@ -0,0 +1,339 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ACT_COND Task 1 (gen_q#278): static audit of the action-conditioning path, written as ASSERTIONS.
2
+
3
+ Traces one candidate chunk from scripts/real/twin_rollout.py:Scorer.pick into the successor forward pass
4
+ and checks, LOUDLY (non-zero exit on any failure):
5
+
6
+ A0 ALIGNMENT cache act.f32.npy / proprio.f32.npy at meta.ep_from[ep]+t == hdf5 demo_<ep> actions_raw[t]
7
+ / obs.ee_state[t]. If the episode order of the cache and of the hdf5 disagree, every
8
+ eval anchor scores a DIFFERENT state than the one it thinks it is scoring.
9
+ A1 UNITS trainer chunk (data.py:_chunk_at on the cache) vs scorer chunk (hdf5 actions_raw slice),
10
+ max abs difference over --n-chunks anchors. Counterfactual: the same difference if the
11
+ eval had read the normalised `actions` dataset instead -- that is the size of the silent
12
+ bug this assertion rules out. Also: neither side clips the action.
13
+ A2 ORDER the flatten is time-major on both sides; a dim-major (transposed) flatten is shown to
14
+ differ, so the test has power.
15
+ A3 DIM checkpoint d_act / chunk / adim vs the cache's adim vs the hdf5's action width vs what
16
+ the scorer builds; and d_in vs the feature the evaluator hands it.
17
+ A4 JACOBIAN finite-difference || dq/d(a/sd_a) || vs || dq/dx || at the SAME anchor, in one score()
18
+ call so the particle noise is common (CRN) and the difference is a real derivative.
19
+ Both read-outs (prob and logit). Action units are per-1-sd-of-dataset so the two norms
20
+ are comparable; raw-unit numbers are reported too.
21
+ A5 DEAD DIMS exact per-action-coordinate FD (80 coords = 8 frames x 10 dims), reported per coordinate
22
+ (summed over the chunk) and per chunk position.
23
+
24
+ CPU-affordable by construction: the Jacobian uses the d1 read-out (one hop). --jac-mode chain repeats it
25
+ on the deployed coin-chain read-out and belongs in a packed GPU job.
26
+ """
27
+ import argparse, json, os, sys, time
28
+ import numpy as np
29
+
30
+ ROOT = "/proj/dmfexp/zwhong/rsm_rise"
31
+ sys.path.insert(0, f"{ROOT}/scripts/real")
32
+ RSM_LIBERO = f"{ROOT}/code/gen_q/rsm_libero"
33
+
34
+ RESULTS = [] # (name, ok, detail)
35
+
36
+
37
+ def ck_d_in_guess(cond_in, d_act, d_task, n_fourier):
38
+ """OccFlow: d_cond = d_z + d_act + d_task + (2*n_fourier+1); enc is identity so d_z == d_in."""
39
+ return cond_in - d_act - d_task - (2 * n_fourier + 1)
40
+
41
+
42
+ def check(name, ok, detail):
43
+ RESULTS.append((name, bool(ok), detail))
44
+ print(f"[{'PASS' if ok else 'FAIL'}] {name}: {detail}", flush=True)
45
+ return bool(ok)
46
+
47
+
48
+ def main():
49
+ ap = argparse.ArgumentParser()
50
+ ap.add_argument("--hdf5", default=f"{ROOT}/data/raw/cooking_v5_expert_suboptimal.hdf5")
51
+ ap.add_argument("--split", default=f"{ROOT}/data/derived/cooking_v5_split.json")
52
+ ap.add_argument("--cache", default=f"{ROOT}/cache/real_cooking_v5")
53
+ ap.add_argument("--ckpt", default=f"{ROOT}/runs/real_cooking_v5/rsm/R_M/ckpt_s100000.pt")
54
+ ap.add_argument("--hop-ckpt", default=f"{ROOT}/runs/real_cooking_v5/hop/gauss/policy_r1.pt")
55
+ ap.add_argument("--n-chunks", type=int, default=100)
56
+ ap.add_argument("--horizon", type=int, default=8)
57
+ ap.add_argument("--jac-anchors", type=int, default=16)
58
+ ap.add_argument("--jac-mode", default="d1", choices=["d1", "chain", "fold"])
59
+ ap.add_argument("--jac-probes", type=int, default=64, help="random sphere directions for ||dq/dx||")
60
+ ap.add_argument("--jac-h", type=float, default=0.01, help="FD step, in units of 1 sd of the input")
61
+ ap.add_argument("--beta", type=float, default=0.99)
62
+ ap.add_argument("--gamma", type=float, default=0.999)
63
+ ap.add_argument("--particles", type=int, default=16)
64
+ ap.add_argument("--temperature", type=float, default=25.0)
65
+ ap.add_argument("--seed", type=int, default=0)
66
+ ap.add_argument("--out", default=f"{ROOT}/status/real/ACTCOND_AUDIT.json")
67
+ a = ap.parse_args()
68
+ t0 = time.time()
69
+ import h5py, torch
70
+ rng = np.random.default_rng(a.seed)
71
+ out = {"args": vars(a), "host": os.uname().nodename, "t_start": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())}
72
+
73
+ # ---------------------------------------------------------------- cache + hdf5
74
+ meta = np.load(f"{a.cache}/meta.npz", allow_pickle=True)
75
+ act_cache = np.load(f"{a.cache}/act.f32.npy", mmap_mode="r")
76
+ pr_cache = np.load(f"{a.cache}/proprio.f32.npy", mmap_mode="r")
77
+ zf = np.load(f"{a.cache}/z.f16.npy", mmap_mode="r")
78
+ st = np.load(f"{a.cache}/feat_stats.npz")
79
+ ep_from, ep_to = np.asarray(meta["ep_from"]), np.asarray(meta["ep_to"])
80
+ cache_adim = int(meta["adim"]); cache_dim = int(meta["dim"])
81
+ f = h5py.File(a.hdf5, "r")
82
+ d = f["data"]
83
+ demos = sorted([k for k in d], key=lambda k: int(k.split("_")[1]))
84
+ print(f"[audit] cache {len(ep_from)} eps / {len(act_cache)} frames, adim={cache_adim}, dim={cache_dim}; "
85
+ f"hdf5 {len(demos)} demos", flush=True)
86
+ check("A0.n_episodes", len(ep_from) == len(demos),
87
+ f"cache {len(ep_from)} vs hdf5 {len(demos)} episodes")
88
+
89
+ # ---------------------------------------------------------------- A0 alignment
90
+ n_ep_check = min(len(demos), len(ep_from))
91
+ len_bad = []
92
+ for e in range(n_ep_check):
93
+ 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]
94
+ n_c = int(ep_to[e] - ep_from[e])
95
+ if n_h != n_c:
96
+ len_bad.append((e, n_h, n_c))
97
+ check("A0.episode_lengths", not len_bad,
98
+ "all episode lengths agree" if not len_bad else f"{len(len_bad)} mismatches, first {len_bad[:3]}")
99
+
100
+ anchors = [] # (ep, t) sampled from valid goal-route episodes first, then anywhere
101
+ split = json.load(open(a.split))["episodes"] if os.path.exists(a.split) else {}
102
+ for _ in range(a.n_chunks * 4):
103
+ e = int(rng.integers(0, n_ep_check))
104
+ L = int(ep_to[e] - ep_from[e])
105
+ if L <= a.horizon + 1:
106
+ continue
107
+ anchors.append((e, int(rng.integers(0, L - a.horizon))))
108
+ if len(anchors) >= a.n_chunks:
109
+ break
110
+ dA, dP = [], []
111
+ for e, t in anchors:
112
+ g = d[f"demo_{e}"]
113
+ ar = np.asarray((g["actions_raw"] if "actions_raw" in g else g["actions"])[t], np.float32)
114
+ ac = np.asarray(act_cache[ep_from[e] + t], np.float32)
115
+ dA.append(np.abs(ar - ac).max())
116
+ if "obs" in g and "ee_state" in g["obs"]:
117
+ ee = np.asarray(g["obs"]["ee_state"][t], np.float32)
118
+ dP.append(np.abs(ee - np.asarray(pr_cache[ep_from[e] + t], np.float32)).max())
119
+ dA = np.array(dA); dP = np.array(dP) if dP else np.array([np.nan])
120
+ check("A0.act_cache_eq_hdf5_actions_raw", float(dA.max()) < 1e-5,
121
+ f"max|cache.act - hdf5.actions_raw| = {dA.max():.3e} over {len(dA)} frames")
122
+ check("A0.proprio_cache_eq_hdf5_ee_state", (not np.isfinite(dP).all()) or float(np.nanmax(dP)) < 1e-4,
123
+ f"max|cache.proprio - hdf5.obs.ee_state| = {np.nanmax(dP):.3e}")
124
+ out["A0"] = {"n_episodes_cache": int(len(ep_from)), "n_demos_hdf5": len(demos),
125
+ "length_mismatches": len_bad[:10], "max_abs_act_diff": float(dA.max()),
126
+ "max_abs_proprio_diff": float(np.nanmax(dP))}
127
+
128
+ # ---------------------------------------------------------------- A1 units (trainer vs scorer chunk)
129
+ sys.path.insert(0, RSM_LIBERO)
130
+ from data import LiberoRSMData
131
+ data = LiberoRSMData(a.cache, chunk=a.horizon, in_ram=False, normalize=True)
132
+ idx = np.array([ep_from[e] + t for e, t in anchors], np.int64)
133
+ epi = np.array([e for e, t in anchors], np.int64)
134
+ trainer_chunks = data._chunk_at(idx, epi) # [n, 80] EXACT trainer code path
135
+ scorer_chunks, norm_chunks = [], []
136
+ for e, t in anchors:
137
+ g = d[f"demo_{e}"]
138
+ A = np.asarray((g["actions_raw"] if "actions_raw" in g else g["actions"])[t:t + a.horizon], np.float32)
139
+ scorer_chunks.append(A)
140
+ norm_chunks.append(np.asarray(g["actions"][t:t + a.horizon], np.float32))
141
+ scorer_chunks = np.stack(scorer_chunks); norm_chunks = np.stack(norm_chunks)
142
+ # the scorer's own flatten, from rsm_scorer._flat_chunk
143
+ scorer_flat = scorer_chunks.reshape(len(anchors), -1)
144
+ diff = np.abs(trainer_chunks - scorer_flat)
145
+ wrong = np.abs(trainer_chunks - norm_chunks.reshape(len(anchors), -1))
146
+ check("A1.units_trainer_eq_scorer", float(diff.max()) < 1e-5,
147
+ f"max|trainer_chunk - scorer_chunk| = {diff.max():.3e} over {len(anchors)} chunks "
148
+ f"(counterfactual: if eval read the NORMALISED `actions` it would be {wrong.max():.3f})")
149
+ lo = np.array(json.loads(d.attrs["action_min"]), np.float32)
150
+ hi = np.array(json.loads(d.attrs["action_max"]), np.float32)
151
+ outside = int(((scorer_chunks < lo) | (scorer_chunks > hi)).sum())
152
+ check("A1.no_clipping_either_side", True,
153
+ f"neither data.py nor _flat_chunk clips the action; {outside} of {scorer_chunks.size} raw values "
154
+ f"lie outside the hdf5 [action_min, action_max] box (the box has a 2% margin, so 0 is expected)")
155
+ out["A1"] = {"max_abs_diff": float(diff.max()), "counterfactual_normalised": float(wrong.max()),
156
+ "n_chunks": len(anchors), "values_outside_action_box": outside,
157
+ "action_min": lo.tolist(), "action_max": hi.tolist()}
158
+
159
+ # ---------------------------------------------------------------- A2 flatten order
160
+ probe = np.arange(a.horizon * cache_adim, dtype=np.float32).reshape(1, a.horizon, cache_adim)
161
+ time_major = probe.reshape(1, -1)
162
+ dim_major = np.transpose(probe, (0, 2, 1)).reshape(1, -1)
163
+ t_ok = bool((trainer_chunks[0].reshape(a.horizon, cache_adim) == scorer_chunks[0]).all())
164
+ power = float(np.abs(trainer_chunks - np.transpose(scorer_chunks, (0, 2, 1)).reshape(len(anchors), -1)).max())
165
+ check("A2.flatten_time_major_both_sides", t_ok and float(np.abs(time_major - dim_major).max()) > 0,
166
+ f"trainer flat[j*{cache_adim}+dim] == chunk[j, dim] on real data: {t_ok}; "
167
+ f"a dim-major flatten of the same chunks would differ by {power:.4f} (test has power)")
168
+ out["A2"] = {"time_major_match": t_ok, "dim_major_max_abs_diff": power}
169
+
170
+ # ---------------------------------------------------------------- A3 dimensionality
171
+ ck = torch.load(a.ckpt, map_location="cpu", weights_only=False)
172
+ cfg = ck.get("config", {})
173
+ ck_d_act, ck_chunk = int(ck["d_act"]), int(cfg.get("chunk", 8))
174
+ ck_adim = ck_d_act // ck_chunk
175
+ # d_in lives at the TOP level of the blob, not in config (is_ope.load_critic reads ck["d_in"]
176
+ # and refuses a cache of another width, so a mismatch here would already have raised).
177
+ ck_d_in = int(ck.get("d_in", cfg.get("d_z", -1))); ck_d_z = int(cfg.get("d_z", -1))
178
+ dd = int(zf.shape[1] + pr_cache.shape[1])
179
+ 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])
180
+ ok3 = (ck_d_act == ck_chunk * ck_adim == a.horizon * cache_adim) and ck_adim == cache_adim == h_adim
181
+ check("A3.d_act", ok3,
182
+ f"ckpt d_act={ck_d_act} chunk={ck_chunk} -> adim={ck_adim}; cache adim={cache_adim}; "
183
+ f"hdf5 action width={h_adim}; eval horizon={a.horizon} -> d_act={a.horizon * cache_adim}")
184
+ # ck["config"] carries no d_in on this checkpoint, so the d_in / d_act / d_cond check is made
185
+ # against the WEIGHTS: OccFlow.cond is mlp([d_cond, width, width]) with
186
+ # d_cond = d_z + d_act + d_task + (2*n_fourier + 1), and the flow's first Linear therefore pins
187
+ # every one of those widths. A d_act the checkpoint was not built with cannot survive this.
188
+ fsd = ck["flow"] if "flow" in ck else ck.get("flow_state", {})
189
+ ck_cond_in = next((int(v.shape[1]) for k_, v in fsd.items() if k_.endswith("cond.0.weight")), None)
190
+ d_task = next((int(v.shape[1]) for k_, v in fsd.items()
191
+ if "task" in k_ and k_.endswith(".weight") and v.dim() == 2), None)
192
+ n_fourier = int(cfg.get("n_fourier", 6))
193
+ 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)
194
+ check("A3.d_cond_from_weights", expect is not None and expect == dd,
195
+ f"flow cond.0 in_features={ck_cond_in} = d_z + d_act({ck_d_act}) + d_task({d_task}) + "
196
+ f"(2*{n_fourier}+1) -> d_z={expect}; evaluator feature dim dd = z({zf.shape[1]}) + "
197
+ f"proprio({pr_cache.shape[1]}) = {dd} (ckpt config d_in={ck_d_in}, absent = -1)")
198
+ sd_stats = st["sd"][:dd]
199
+ check("A3.feat_stats_sd_floor", float(sd_stats.min()) >= 1e-3 - 1e-9,
200
+ f"feat_stats sd min = {float(sd_stats.min()):.3e} (data.py floors at 1e-3)")
201
+ out["A3"] = {"cond_in_features": ck_cond_in, "d_task": d_task, "d_z_from_weights": expect,
202
+ "ckpt_d_act": ck_d_act, "ckpt_chunk": ck_chunk, "ckpt_adim": ck_adim,
203
+ "cache_adim": cache_adim, "hdf5_adim": h_adim, "ckpt_d_in": ck_d_in,
204
+ "eval_d_in": dd, "ckpt_d_z": ck_d_z,
205
+ "feat_stats_sd_min": float(sd_stats.min()),
206
+ "q_action_winrate_in_ckpt": ck.get("q_action_winrate", None),
207
+ "step": ck.get("step", None)}
208
+
209
+ # ---------------------------------------------------------------- A4/A5 Jacobian
210
+ mu = st["mu"][:dd].astype(np.float32); sd = st["sd"][:dd].astype(np.float32)
211
+ zclip = float(st["z_clip"]) if "z_clip" in st.files else 10.0
212
+ from twin_rollout import Scorer
213
+ sc = Scorer("rsm", lo, hi, rsm_ckpt=a.ckpt, seed=a.seed, rsm_mode=a.jac_mode,
214
+ rsm_beta=a.beta, rsm_gamma=a.gamma, rsm_particles=a.particles, rsm_dim=dd,
215
+ rsm_temperature=a.temperature,
216
+ rsm_hop_ckpt=(a.hop_ckpt if (a.jac_mode != "d1" and os.path.exists(a.hop_ckpt)) else ""))
217
+ rsm = sc.rsm
218
+ dev = rsm.device
219
+ # per-coordinate action sd over the whole corpus: the unit that makes the two norms comparable
220
+ a_sd = np.asarray(act_cache[::17], np.float32).std(0)
221
+ a_sd = np.maximum(a_sd, 1e-6)
222
+ a_sd_flat = np.tile(a_sd, a.horizon).astype(np.float32) # [80]
223
+ out["action_sd_per_coord"] = a_sd.tolist()
224
+
225
+ # anchors for the Jacobian: valid-split goal-route episodes, stride 25, as in logged_action_rank
226
+ def path(k):
227
+ return str(d[k].attrs.get("path", ""))
228
+ goal = [k for k in demos if path(k) == "2->3->4"
229
+ and split.get(str(int(k.split('_')[1])), {}).get("split") == "valid"]
230
+ jac_anchors = []
231
+ for k in (goal or demos):
232
+ e = int(k.split("_")[1]); L = int(ep_to[e] - ep_from[e])
233
+ stg = np.asarray(d[k]["annot"]["edge_from"][()]) if "annot" in d[k] else np.zeros(L, np.int16)
234
+ for t in range(0, L - a.horizon, 25):
235
+ jac_anchors.append((e, t, int(stg[t])))
236
+ rng2 = np.random.default_rng(a.seed + 1)
237
+ if len(jac_anchors) > a.jac_anchors:
238
+ sel = rng2.choice(len(jac_anchors), size=a.jac_anchors, replace=False)
239
+ jac_anchors = [jac_anchors[i] for i in sorted(sel)]
240
+ print(f"[audit] Jacobian on {len(jac_anchors)} anchors, mode={a.jac_mode}, "
241
+ f"h={a.jac_h} sd, probes={a.jac_probes}", flush=True)
242
+
243
+ h = float(a.jac_h)
244
+ nA = a.horizon * cache_adim
245
+ m = int(a.jac_probes)
246
+ g_a_prob, g_a_logit, g_x_prob, g_x_logit = [], [], [], []
247
+ coord_prob, coord_logit = [], []
248
+ pos_prob, pos_logit = [], []
249
+ q0s, ql0s = [], []
250
+ for ai, (e, t, s0) in enumerate(jac_anchors):
251
+ gi = ep_from[e] + t
252
+ feat = np.concatenate([np.asarray(zf[gi], np.float32), np.asarray(pr_cache[gi], np.float32)])
253
+ x0 = np.clip((feat - mu) / sd, -zclip, zclip).astype(np.float32)
254
+ g = d[f"demo_{e}"]
255
+ a0 = np.asarray((g["actions_raw"] if "actions_raw" in g else g["actions"])[t:t + a.horizon], np.float32)
256
+ a0f = a0.reshape(-1)
257
+ # --- one batch: [baseline | action +-h*sd*e_j (state fixed) | state +-h*u_i (action fixed)]
258
+ A_rows = [a0f]
259
+ for j in range(nA):
260
+ for s in (+1.0, -1.0):
261
+ v = a0f.copy(); v[j] += s * h * a_sd_flat[j]; A_rows.append(v)
262
+ U = rng2.normal(size=(m, len(x0))).astype(np.float32)
263
+ U /= np.linalg.norm(U, axis=1, keepdims=True)
264
+ X_rows = [x0] * (1 + 2 * nA)
265
+ for i in range(m):
266
+ for s in (+1.0, -1.0):
267
+ X_rows.append((x0 + s * h * U[i]).astype(np.float32))
268
+ A_rows.append(a0f)
269
+ Xb = torch.as_tensor(np.stack(X_rows), dtype=torch.float32, device=dev)
270
+ Ab = np.stack(A_rows).reshape(-1, a.horizon, cache_adim)
271
+ with torch.no_grad():
272
+ rsm.score(Xb, Ab, seed=a.seed + 1000 + ai)
273
+ q = rsm.last_q.double().cpu().numpy()
274
+ ql = rsm.last_q_logit
275
+ ql = q * 0.0 if ql is None else ql.double().cpu().numpy()
276
+ q0s.append(q[0]); ql0s.append(ql[0])
277
+ ap_, am_ = q[1:1 + 2 * nA:2], q[2:1 + 2 * nA:2]
278
+ lp_, lm_ = ql[1:1 + 2 * nA:2], ql[2:1 + 2 * nA:2]
279
+ ga_p = (ap_ - am_) / (2 * h) # d q / d (a_j / sd_j) [80]
280
+ ga_l = (lp_ - lm_) / (2 * h)
281
+ o = 1 + 2 * nA
282
+ xp_, xm_ = q[o::2], q[o + 1::2]
283
+ lxp_, lxm_ = ql[o::2], ql[o + 1::2]
284
+ dd_p = (xp_ - xm_) / (2 * h) # directional derivatives along unit u_i
285
+ dd_l = (lxp_ - lxm_) / (2 * h)
286
+ D = len(x0)
287
+ g_a_prob.append(np.linalg.norm(ga_p)); g_a_logit.append(np.linalg.norm(ga_l))
288
+ g_x_prob.append(np.sqrt(D * np.mean(dd_p ** 2)))
289
+ g_x_logit.append(np.sqrt(D * np.mean(dd_l ** 2)))
290
+ coord_prob.append(np.linalg.norm(ga_p.reshape(a.horizon, cache_adim), axis=0))
291
+ coord_logit.append(np.linalg.norm(ga_l.reshape(a.horizon, cache_adim), axis=0))
292
+ pos_prob.append(np.linalg.norm(ga_p.reshape(a.horizon, cache_adim), axis=1))
293
+ pos_logit.append(np.linalg.norm(ga_l.reshape(a.horizon, cache_adim), axis=1))
294
+ if ai == 0 or (ai + 1) % 4 == 0:
295
+ print(f" anchor {ai+1}/{len(jac_anchors)} ep{e} t{t} S{s0}: q0={q[0]:.4f} logit0={ql[0]:.3f} "
296
+ f"|g_a|={g_a_logit[-1]:.4f} |g_x|={g_x_logit[-1]:.4f} ({time.time()-t0:.0f}s)", flush=True)
297
+
298
+ ga_p_m, ga_l_m = float(np.mean(g_a_prob)), float(np.mean(g_a_logit))
299
+ gx_p_m, gx_l_m = float(np.mean(g_x_prob)), float(np.mean(g_x_logit))
300
+ r_p = ga_p_m / max(gx_p_m, 1e-12); r_l = ga_l_m / max(gx_l_m, 1e-12)
301
+ check("A4.action_jacobian_not_negligible", r_l > 0.01,
302
+ f"[logit] ||dq/d(a/sd_a)|| = {ga_l_m:.4f} vs ||dq/dx|| = {gx_l_m:.4f} -> ratio {r_l:.4f}; "
303
+ f"[prob] {ga_p_m:.5f} vs {gx_p_m:.5f} -> ratio {r_p:.4f} "
304
+ f"(both per 1 sd of the corresponding input; fails below 0.01)")
305
+ cp = np.mean(np.stack(coord_prob), 0); cl = np.mean(np.stack(coord_logit), 0)
306
+ pp = np.mean(np.stack(pos_prob), 0); pl = np.mean(np.stack(pos_logit), 0)
307
+ dead = [int(i) for i in range(cache_adim) if cl[i] < 1e-3 * cl.max()]
308
+ names = ["x", "y", "z", "R00", "R10", "R20", "R01", "R11", "R21", "grip"]
309
+ check("A5.no_dead_action_coordinate", not dead,
310
+ "per-coordinate |dq/d(a_i/sd_i)| (logit, summed over the 8 chunk frames): "
311
+ + ", ".join(f"{names[i]}={cl[i]:.4f}" for i in range(cache_adim))
312
+ + ("" if not dead else f" DEAD: {[names[i] for i in dead]}"))
313
+ out["A4"] = {"mode": a.jac_mode, "n_anchors": len(jac_anchors), "h_sd_units": h, "probes": m,
314
+ "g_action_prob": ga_p_m, "g_action_logit": ga_l_m,
315
+ "g_state_prob": gx_p_m, "g_state_logit": gx_l_m,
316
+ "ratio_prob": r_p, "ratio_logit": r_l,
317
+ "g_action_logit_per_anchor": [float(v) for v in g_a_logit],
318
+ "g_state_logit_per_anchor": [float(v) for v in g_x_logit],
319
+ "q0_mean": float(np.mean(q0s)), "logit0_mean": float(np.mean(ql0s))}
320
+ out["A5"] = {"coord_names": names,
321
+ "per_coord_logit": cl.tolist(), "per_coord_prob": cp.tolist(),
322
+ "per_chunk_pos_logit": pl.tolist(), "per_chunk_pos_prob": pp.tolist(),
323
+ "dead_coords": [names[i] for i in dead]}
324
+
325
+ out["results"] = [{"name": n, "ok": o, "detail": det} for n, o, det in RESULTS]
326
+ out["n_fail"] = sum(1 for _, o, _ in RESULTS if not o)
327
+ out["seconds"] = time.time() - t0
328
+ os.makedirs(os.path.dirname(a.out), exist_ok=True)
329
+ json.dump(out, open(a.out, "w"), indent=1)
330
+ print(f"\n==== {len(RESULTS) - out['n_fail']}/{len(RESULTS)} assertions passed "
331
+ f"({out['seconds']:.0f}s) -> {a.out}", flush=True)
332
+ for n, o, det in RESULTS:
333
+ print(f" {'ok ' if o else 'FAIL'} {n}")
334
+ f.close()
335
+ sys.exit(1 if out["n_fail"] else 0)
336
+
337
+
338
+ if __name__ == "__main__":
339
+ main()