diff --git a/rsm_rise/scripts/real/payloads_r42/rung_cov_sn1_knn0p03_T20.sh b/rsm_rise/scripts/real/payloads_r42/rung_cov_sn1_knn0p03_T20.sh new file mode 100644 index 0000000000000000000000000000000000000000..81ea38f393b5f57fa008519dcf6e079a464be15b --- /dev/null +++ b/rsm_rise/scripts/real/payloads_r42/rung_cov_sn1_knn0p03_T20.sh @@ -0,0 +1,4 @@ +#!/usr/bin/env bash +set -uo pipefail +export PT_NOISE_SCALE=2.0 PT_NAME=cov_sn1_knn0p03_T20 +exec /proj/dmfexp/zwhong/rsm_rise/scripts/real/pt_temp_screen.sh 0 1 diff --git a/rsm_rise/scripts/real/payloads_r42/rung_cov_sn1_knn0p03_T25.sh b/rsm_rise/scripts/real/payloads_r42/rung_cov_sn1_knn0p03_T25.sh new file mode 100644 index 0000000000000000000000000000000000000000..b7a0f8f48ad0da5031e81f0738b2e8c52d1014c6 --- /dev/null +++ b/rsm_rise/scripts/real/payloads_r42/rung_cov_sn1_knn0p03_T25.sh @@ -0,0 +1,4 @@ +#!/usr/bin/env bash +set -uo pipefail +export PT_NOISE_SCALE=2.5 PT_NAME=cov_sn1_knn0p03_T25 +exec /proj/dmfexp/zwhong/rsm_rise/scripts/real/pt_temp_screen.sh 0 1 diff --git a/rsm_rise/scripts/real/payloads_r42/rung_cov_sn1_knn0p03_T30.sh b/rsm_rise/scripts/real/payloads_r42/rung_cov_sn1_knn0p03_T30.sh new file mode 100644 index 0000000000000000000000000000000000000000..e26a16ca0c2c83f2da80c5669d5dc7df503f6ced --- /dev/null +++ b/rsm_rise/scripts/real/payloads_r42/rung_cov_sn1_knn0p03_T30.sh @@ -0,0 +1,4 @@ +#!/usr/bin/env bash +set -uo pipefail +export PT_NOISE_SCALE=3.0 PT_NAME=cov_sn1_knn0p03_T30 +exec /proj/dmfexp/zwhong/rsm_rise/scripts/real/pt_temp_screen.sh 0 1 diff --git a/rsm_rise/scripts/real/payloads_r42/rung_cov_sn1_knn0p03_T40.sh b/rsm_rise/scripts/real/payloads_r42/rung_cov_sn1_knn0p03_T40.sh new file mode 100644 index 0000000000000000000000000000000000000000..bdc994f646519ee36d390d50b27a32f0696ea0b9 --- /dev/null +++ b/rsm_rise/scripts/real/payloads_r42/rung_cov_sn1_knn0p03_T40.sh @@ -0,0 +1,4 @@ +#!/usr/bin/env bash +set -uo pipefail +export PT_NOISE_SCALE=4.0 PT_NAME=cov_sn1_knn0p03_T40 +exec /proj/dmfexp/zwhong/rsm_rise/scripts/real/pt_temp_screen.sh 0 1 diff --git a/rsm_rise/scripts/real/payloads_r42/rung_cov_sn1_knn0p03_T60.sh b/rsm_rise/scripts/real/payloads_r42/rung_cov_sn1_knn0p03_T60.sh new file mode 100644 index 0000000000000000000000000000000000000000..28b01ddc09030b4cd90daea917c5cf1a46046089 --- /dev/null +++ b/rsm_rise/scripts/real/payloads_r42/rung_cov_sn1_knn0p03_T60.sh @@ -0,0 +1,4 @@ +#!/usr/bin/env bash +set -uo pipefail +export PT_NOISE_SCALE=6.0 PT_NAME=cov_sn1_knn0p03_T60 +exec /proj/dmfexp/zwhong/rsm_rise/scripts/real/pt_temp_screen.sh 0 1 diff --git a/rsm_rise/scripts/real/payloads_r42/rung_cov_sn1_knn0p03_T80.sh b/rsm_rise/scripts/real/payloads_r42/rung_cov_sn1_knn0p03_T80.sh new file mode 100644 index 0000000000000000000000000000000000000000..18669fd4cd42137249aa6d9a41b46b8eb8832f77 --- /dev/null +++ b/rsm_rise/scripts/real/payloads_r42/rung_cov_sn1_knn0p03_T80.sh @@ -0,0 +1,4 @@ +#!/usr/bin/env bash +set -uo pipefail +export PT_NOISE_SCALE=8.0 PT_NAME=cov_sn1_knn0p03_T80 +exec /proj/dmfexp/zwhong/rsm_rise/scripts/real/pt_temp_screen.sh 0 1 diff --git a/rsm_rise/scripts/real/payloads_r43/rep_1.sh b/rsm_rise/scripts/real/payloads_r43/rep_1.sh new file mode 100644 index 0000000000000000000000000000000000000000..624c67102d42e9ca78d63ba37b4dc8912516d70e --- /dev/null +++ b/rsm_rise/scripts/real/payloads_r43/rep_1.sh @@ -0,0 +1,7 @@ +#!/usr/bin/env bash +# PROPOSAL_TEST run 43 -- replicate 1 of the scale-1.0 rung, for the DETERMINISM FLOOR measurement +# pre-registered in gen_q#280 5822858562 / rsm_real#2 5822859924. Identical config and seed to +# pt_cov_sn1_knn0p03; only PT_NAME differs, so the four replicates are the same nominal computation. +set -uo pipefail +export PT_NOISE_SCALE=1.0 PT_NAME=cov_sn1_knn0p03_REP1 +exec /proj/dmfexp/zwhong/rsm_rise/scripts/real/pt_temp_screen.sh 2 8 diff --git a/rsm_rise/scripts/real/payloads_r43/rep_2.sh b/rsm_rise/scripts/real/payloads_r43/rep_2.sh new file mode 100644 index 0000000000000000000000000000000000000000..07744ba5fed403398fee10892742f87634bfff85 --- /dev/null +++ b/rsm_rise/scripts/real/payloads_r43/rep_2.sh @@ -0,0 +1,7 @@ +#!/usr/bin/env bash +# PROPOSAL_TEST run 43 -- replicate 2 of the scale-1.0 rung, for the DETERMINISM FLOOR measurement +# pre-registered in gen_q#280 5822858562 / rsm_real#2 5822859924. Identical config and seed to +# pt_cov_sn1_knn0p03; only PT_NAME differs, so the four replicates are the same nominal computation. +set -uo pipefail +export PT_NOISE_SCALE=1.0 PT_NAME=cov_sn1_knn0p03_REP2 +exec /proj/dmfexp/zwhong/rsm_rise/scripts/real/pt_temp_screen.sh 2 8 diff --git a/rsm_rise/scripts/real/payloads_r43/rep_3.sh b/rsm_rise/scripts/real/payloads_r43/rep_3.sh new file mode 100644 index 0000000000000000000000000000000000000000..36bc402cd8b4e5e189577df24e53f4e9c5900f23 --- /dev/null +++ b/rsm_rise/scripts/real/payloads_r43/rep_3.sh @@ -0,0 +1,7 @@ +#!/usr/bin/env bash +# PROPOSAL_TEST run 43 -- replicate 3 of the scale-1.0 rung, for the DETERMINISM FLOOR measurement +# pre-registered in gen_q#280 5822858562 / rsm_real#2 5822859924. Identical config and seed to +# pt_cov_sn1_knn0p03; only PT_NAME differs, so the four replicates are the same nominal computation. +set -uo pipefail +export PT_NOISE_SCALE=1.0 PT_NAME=cov_sn1_knn0p03_REP3 +exec /proj/dmfexp/zwhong/rsm_rise/scripts/real/pt_temp_screen.sh 2 8 diff --git a/rsm_rise/scripts/real/payloads_r43/rep_4.sh b/rsm_rise/scripts/real/payloads_r43/rep_4.sh new file mode 100644 index 0000000000000000000000000000000000000000..b615059c918d3ec1550a5dc583f72bc8718450ae --- /dev/null +++ b/rsm_rise/scripts/real/payloads_r43/rep_4.sh @@ -0,0 +1,7 @@ +#!/usr/bin/env bash +# PROPOSAL_TEST run 43 -- replicate 4 of the scale-1.0 rung, for the DETERMINISM FLOOR measurement +# pre-registered in gen_q#280 5822858562 / rsm_real#2 5822859924. Identical config and seed to +# pt_cov_sn1_knn0p03; only PT_NAME differs, so the four replicates are the same nominal computation. +set -uo pipefail +export PT_NOISE_SCALE=1.0 PT_NAME=cov_sn1_knn0p03_REP4 +exec /proj/dmfexp/zwhong/rsm_rise/scripts/real/pt_temp_screen.sh 2 8 diff --git a/rsm_rise/scripts/real/payloads_r45/rung_T10.sh b/rsm_rise/scripts/real/payloads_r45/rung_T10.sh new file mode 100644 index 0000000000000000000000000000000000000000..0b9c80286c2e22f7fcbbfddd13faad382e0a0e58 --- /dev/null +++ b/rsm_rise/scripts/real/payloads_r45/rung_T10.sh @@ -0,0 +1,9 @@ +#!/usr/bin/env bash +# PROPOSAL_TEST run 45 -- CORRECTED noise-scale ladder rung (scale 1.0). +# The run-42 ladder was INERT: proposal_test.py:274 overwrote pol.rng per episode and destroyed the +# _ScaledNormal wrapper, so all 8 rungs sampled one setting (displacement spread 0.0234 mm over 8x). +# pt_proposer_temp.py now installs the scale via an rng PROPERTY that survives that reseed +# (regression-tested, LSF 1907558). NEW tag prefix R45 so the inert caches cannot be mistaken for these. +set -uo pipefail +export PT_NOISE_SCALE=1.0 PT_NAME=R45_cov_sn1_knn0p03_T10 +exec /proj/dmfexp/zwhong/rsm_rise/scripts/real/pt_temp_screen.sh 0 1 diff --git a/rsm_rise/scripts/real/payloads_r45/rung_T15.sh b/rsm_rise/scripts/real/payloads_r45/rung_T15.sh new file mode 100644 index 0000000000000000000000000000000000000000..25eeeb0dca731bdf219fa61c75ac0f6ee5fae93e --- /dev/null +++ b/rsm_rise/scripts/real/payloads_r45/rung_T15.sh @@ -0,0 +1,9 @@ +#!/usr/bin/env bash +# PROPOSAL_TEST run 45 -- CORRECTED noise-scale ladder rung (scale 1.5). +# The run-42 ladder was INERT: proposal_test.py:274 overwrote pol.rng per episode and destroyed the +# _ScaledNormal wrapper, so all 8 rungs sampled one setting (displacement spread 0.0234 mm over 8x). +# pt_proposer_temp.py now installs the scale via an rng PROPERTY that survives that reseed +# (regression-tested, LSF 1907558). NEW tag prefix R45 so the inert caches cannot be mistaken for these. +set -uo pipefail +export PT_NOISE_SCALE=1.5 PT_NAME=R45_cov_sn1_knn0p03_T15 +exec /proj/dmfexp/zwhong/rsm_rise/scripts/real/pt_temp_screen.sh 0 1 diff --git a/rsm_rise/scripts/real/payloads_r45/rung_T20.sh b/rsm_rise/scripts/real/payloads_r45/rung_T20.sh new file mode 100644 index 0000000000000000000000000000000000000000..b212ebd01b5299d1942b9d6d284b689d69b985e7 --- /dev/null +++ b/rsm_rise/scripts/real/payloads_r45/rung_T20.sh @@ -0,0 +1,9 @@ +#!/usr/bin/env bash +# PROPOSAL_TEST run 45 -- CORRECTED noise-scale ladder rung (scale 2.0). +# The run-42 ladder was INERT: proposal_test.py:274 overwrote pol.rng per episode and destroyed the +# _ScaledNormal wrapper, so all 8 rungs sampled one setting (displacement spread 0.0234 mm over 8x). +# pt_proposer_temp.py now installs the scale via an rng PROPERTY that survives that reseed +# (regression-tested, LSF 1907558). NEW tag prefix R45 so the inert caches cannot be mistaken for these. +set -uo pipefail +export PT_NOISE_SCALE=2.0 PT_NAME=R45_cov_sn1_knn0p03_T20 +exec /proj/dmfexp/zwhong/rsm_rise/scripts/real/pt_temp_screen.sh 0 1 diff --git a/rsm_rise/scripts/real/payloads_r45/rung_T25.sh b/rsm_rise/scripts/real/payloads_r45/rung_T25.sh new file mode 100644 index 0000000000000000000000000000000000000000..530ce2ba7f5dacadc576d58f183a7c26017d76c9 --- /dev/null +++ b/rsm_rise/scripts/real/payloads_r45/rung_T25.sh @@ -0,0 +1,9 @@ +#!/usr/bin/env bash +# PROPOSAL_TEST run 45 -- CORRECTED noise-scale ladder rung (scale 2.5). +# The run-42 ladder was INERT: proposal_test.py:274 overwrote pol.rng per episode and destroyed the +# _ScaledNormal wrapper, so all 8 rungs sampled one setting (displacement spread 0.0234 mm over 8x). +# pt_proposer_temp.py now installs the scale via an rng PROPERTY that survives that reseed +# (regression-tested, LSF 1907558). NEW tag prefix R45 so the inert caches cannot be mistaken for these. +set -uo pipefail +export PT_NOISE_SCALE=2.5 PT_NAME=R45_cov_sn1_knn0p03_T25 +exec /proj/dmfexp/zwhong/rsm_rise/scripts/real/pt_temp_screen.sh 0 1 diff --git a/rsm_rise/scripts/real/payloads_r45/rung_T30.sh b/rsm_rise/scripts/real/payloads_r45/rung_T30.sh new file mode 100644 index 0000000000000000000000000000000000000000..6e297eb8cf3c3fa9b16f94d2535a7b59e4f568e8 --- /dev/null +++ b/rsm_rise/scripts/real/payloads_r45/rung_T30.sh @@ -0,0 +1,9 @@ +#!/usr/bin/env bash +# PROPOSAL_TEST run 45 -- CORRECTED noise-scale ladder rung (scale 3.0). +# The run-42 ladder was INERT: proposal_test.py:274 overwrote pol.rng per episode and destroyed the +# _ScaledNormal wrapper, so all 8 rungs sampled one setting (displacement spread 0.0234 mm over 8x). +# pt_proposer_temp.py now installs the scale via an rng PROPERTY that survives that reseed +# (regression-tested, LSF 1907558). NEW tag prefix R45 so the inert caches cannot be mistaken for these. +set -uo pipefail +export PT_NOISE_SCALE=3.0 PT_NAME=R45_cov_sn1_knn0p03_T30 +exec /proj/dmfexp/zwhong/rsm_rise/scripts/real/pt_temp_screen.sh 0 1 diff --git a/rsm_rise/scripts/real/payloads_r45/rung_T40.sh b/rsm_rise/scripts/real/payloads_r45/rung_T40.sh new file mode 100644 index 0000000000000000000000000000000000000000..d06306594be7a271440e7c7ebcee3c430b1486fb --- /dev/null +++ b/rsm_rise/scripts/real/payloads_r45/rung_T40.sh @@ -0,0 +1,9 @@ +#!/usr/bin/env bash +# PROPOSAL_TEST run 45 -- CORRECTED noise-scale ladder rung (scale 4.0). +# The run-42 ladder was INERT: proposal_test.py:274 overwrote pol.rng per episode and destroyed the +# _ScaledNormal wrapper, so all 8 rungs sampled one setting (displacement spread 0.0234 mm over 8x). +# pt_proposer_temp.py now installs the scale via an rng PROPERTY that survives that reseed +# (regression-tested, LSF 1907558). NEW tag prefix R45 so the inert caches cannot be mistaken for these. +set -uo pipefail +export PT_NOISE_SCALE=4.0 PT_NAME=R45_cov_sn1_knn0p03_T40 +exec /proj/dmfexp/zwhong/rsm_rise/scripts/real/pt_temp_screen.sh 0 1 diff --git a/rsm_rise/scripts/real/payloads_r45/rung_T60.sh b/rsm_rise/scripts/real/payloads_r45/rung_T60.sh new file mode 100644 index 0000000000000000000000000000000000000000..1637ad302bec62889aab21245c5bd184ef822af0 --- /dev/null +++ b/rsm_rise/scripts/real/payloads_r45/rung_T60.sh @@ -0,0 +1,9 @@ +#!/usr/bin/env bash +# PROPOSAL_TEST run 45 -- CORRECTED noise-scale ladder rung (scale 6.0). +# The run-42 ladder was INERT: proposal_test.py:274 overwrote pol.rng per episode and destroyed the +# _ScaledNormal wrapper, so all 8 rungs sampled one setting (displacement spread 0.0234 mm over 8x). +# pt_proposer_temp.py now installs the scale via an rng PROPERTY that survives that reseed +# (regression-tested, LSF 1907558). NEW tag prefix R45 so the inert caches cannot be mistaken for these. +set -uo pipefail +export PT_NOISE_SCALE=6.0 PT_NAME=R45_cov_sn1_knn0p03_T60 +exec /proj/dmfexp/zwhong/rsm_rise/scripts/real/pt_temp_screen.sh 0 1 diff --git a/rsm_rise/scripts/real/payloads_r45/rung_T80.sh b/rsm_rise/scripts/real/payloads_r45/rung_T80.sh new file mode 100644 index 0000000000000000000000000000000000000000..d040053e719fd250d7330174b9aa90b47e2b099d --- /dev/null +++ b/rsm_rise/scripts/real/payloads_r45/rung_T80.sh @@ -0,0 +1,9 @@ +#!/usr/bin/env bash +# PROPOSAL_TEST run 45 -- CORRECTED noise-scale ladder rung (scale 8.0). +# The run-42 ladder was INERT: proposal_test.py:274 overwrote pol.rng per episode and destroyed the +# _ScaledNormal wrapper, so all 8 rungs sampled one setting (displacement spread 0.0234 mm over 8x). +# pt_proposer_temp.py now installs the scale via an rng PROPERTY that survives that reseed +# (regression-tested, LSF 1907558). NEW tag prefix R45 so the inert caches cannot be mistaken for these. +set -uo pipefail +export PT_NOISE_SCALE=8.0 PT_NAME=R45_cov_sn1_knn0p03_T80 +exec /proj/dmfexp/zwhong/rsm_rise/scripts/real/pt_temp_screen.sh 0 1 diff --git a/rsm_rise/scripts/real/payloads_r46/rung_F105.sh b/rsm_rise/scripts/real/payloads_r46/rung_F105.sh new file mode 100644 index 0000000000000000000000000000000000000000..5f04f46997e29bd87617b3e36ae3f4351bc151bf --- /dev/null +++ b/rsm_rise/scripts/real/payloads_r46/rung_F105.sh @@ -0,0 +1,10 @@ +#!/usr/bin/env bash +# PROPOSAL_TEST run 46 -- FINE noise-scale ladder rung (scale 1.05), inside the cliff. +# Run 46b measured the coarse ladder as a CLIFF: K_real jumps 1.00 -> 7.43 between scale 1.0 and 1.5 and +# saturates, while median candidate displacement goes 7.63 mm -> 95.82 mm, 3.0x past the pre-registered +# 32.2 mm PLAUSIBILITY DISQUALIFIER. Every rung >= 1.5 is disqualified, so the only open question is +# whether a plausible foothold exists BETWEEN 1.0 and 1.5. ONE CHANGE from run 45: the scale grid. +# Pre-registered gen_q#280 5825155807 / rsm_real#2 5825156755 before submission. +set -uo pipefail +export PT_NOISE_SCALE=1.05 PT_NAME=R46_cov_sn1_knn0p03_F105 +exec /proj/dmfexp/zwhong/rsm_rise/scripts/real/pt_temp_screen.sh 0 1 diff --git a/rsm_rise/scripts/real/payloads_r46/rung_F110.sh b/rsm_rise/scripts/real/payloads_r46/rung_F110.sh new file mode 100644 index 0000000000000000000000000000000000000000..478b33a134bab5b704dc12d2c17ac01845eb0b0d --- /dev/null +++ b/rsm_rise/scripts/real/payloads_r46/rung_F110.sh @@ -0,0 +1,10 @@ +#!/usr/bin/env bash +# PROPOSAL_TEST run 46 -- FINE noise-scale ladder rung (scale 1.10), inside the cliff. +# Run 46b measured the coarse ladder as a CLIFF: K_real jumps 1.00 -> 7.43 between scale 1.0 and 1.5 and +# saturates, while median candidate displacement goes 7.63 mm -> 95.82 mm, 3.0x past the pre-registered +# 32.2 mm PLAUSIBILITY DISQUALIFIER. Every rung >= 1.5 is disqualified, so the only open question is +# whether a plausible foothold exists BETWEEN 1.0 and 1.5. ONE CHANGE from run 45: the scale grid. +# Pre-registered gen_q#280 5825155807 / rsm_real#2 5825156755 before submission. +set -uo pipefail +export PT_NOISE_SCALE=1.10 PT_NAME=R46_cov_sn1_knn0p03_F110 +exec /proj/dmfexp/zwhong/rsm_rise/scripts/real/pt_temp_screen.sh 0 1 diff --git a/rsm_rise/scripts/real/payloads_r46/rung_F115.sh b/rsm_rise/scripts/real/payloads_r46/rung_F115.sh new file mode 100644 index 0000000000000000000000000000000000000000..b70befac1f96e08288d649ae5857e21b20940e09 --- /dev/null +++ b/rsm_rise/scripts/real/payloads_r46/rung_F115.sh @@ -0,0 +1,10 @@ +#!/usr/bin/env bash +# PROPOSAL_TEST run 46 -- FINE noise-scale ladder rung (scale 1.15), inside the cliff. +# Run 46b measured the coarse ladder as a CLIFF: K_real jumps 1.00 -> 7.43 between scale 1.0 and 1.5 and +# saturates, while median candidate displacement goes 7.63 mm -> 95.82 mm, 3.0x past the pre-registered +# 32.2 mm PLAUSIBILITY DISQUALIFIER. Every rung >= 1.5 is disqualified, so the only open question is +# whether a plausible foothold exists BETWEEN 1.0 and 1.5. ONE CHANGE from run 45: the scale grid. +# Pre-registered gen_q#280 5825155807 / rsm_real#2 5825156755 before submission. +set -uo pipefail +export PT_NOISE_SCALE=1.15 PT_NAME=R46_cov_sn1_knn0p03_F115 +exec /proj/dmfexp/zwhong/rsm_rise/scripts/real/pt_temp_screen.sh 0 1 diff --git a/rsm_rise/scripts/real/payloads_r46/rung_F120.sh b/rsm_rise/scripts/real/payloads_r46/rung_F120.sh new file mode 100644 index 0000000000000000000000000000000000000000..8a1fd3f16765cb75a5ebf2d139dbc79dbd690f0e --- /dev/null +++ b/rsm_rise/scripts/real/payloads_r46/rung_F120.sh @@ -0,0 +1,10 @@ +#!/usr/bin/env bash +# PROPOSAL_TEST run 46 -- FINE noise-scale ladder rung (scale 1.20), inside the cliff. +# Run 46b measured the coarse ladder as a CLIFF: K_real jumps 1.00 -> 7.43 between scale 1.0 and 1.5 and +# saturates, while median candidate displacement goes 7.63 mm -> 95.82 mm, 3.0x past the pre-registered +# 32.2 mm PLAUSIBILITY DISQUALIFIER. Every rung >= 1.5 is disqualified, so the only open question is +# whether a plausible foothold exists BETWEEN 1.0 and 1.5. ONE CHANGE from run 45: the scale grid. +# Pre-registered gen_q#280 5825155807 / rsm_real#2 5825156755 before submission. +set -uo pipefail +export PT_NOISE_SCALE=1.20 PT_NAME=R46_cov_sn1_knn0p03_F120 +exec /proj/dmfexp/zwhong/rsm_rise/scripts/real/pt_temp_screen.sh 0 1 diff --git a/rsm_rise/scripts/real/payloads_r46/rung_F125.sh b/rsm_rise/scripts/real/payloads_r46/rung_F125.sh new file mode 100644 index 0000000000000000000000000000000000000000..9ecc4dc75f09f67ac273f9dc68e4a7d00d59f34b --- /dev/null +++ b/rsm_rise/scripts/real/payloads_r46/rung_F125.sh @@ -0,0 +1,10 @@ +#!/usr/bin/env bash +# PROPOSAL_TEST run 46 -- FINE noise-scale ladder rung (scale 1.25), inside the cliff. +# Run 46b measured the coarse ladder as a CLIFF: K_real jumps 1.00 -> 7.43 between scale 1.0 and 1.5 and +# saturates, while median candidate displacement goes 7.63 mm -> 95.82 mm, 3.0x past the pre-registered +# 32.2 mm PLAUSIBILITY DISQUALIFIER. Every rung >= 1.5 is disqualified, so the only open question is +# whether a plausible foothold exists BETWEEN 1.0 and 1.5. ONE CHANGE from run 45: the scale grid. +# Pre-registered gen_q#280 5825155807 / rsm_real#2 5825156755 before submission. +set -uo pipefail +export PT_NOISE_SCALE=1.25 PT_NAME=R46_cov_sn1_knn0p03_F125 +exec /proj/dmfexp/zwhong/rsm_rise/scripts/real/pt_temp_screen.sh 0 1 diff --git a/rsm_rise/scripts/real/payloads_r46/rung_F130.sh b/rsm_rise/scripts/real/payloads_r46/rung_F130.sh new file mode 100644 index 0000000000000000000000000000000000000000..c844648443775fe8199104c81b6462791c6aaee4 --- /dev/null +++ b/rsm_rise/scripts/real/payloads_r46/rung_F130.sh @@ -0,0 +1,10 @@ +#!/usr/bin/env bash +# PROPOSAL_TEST run 46 -- FINE noise-scale ladder rung (scale 1.30), inside the cliff. +# Run 46b measured the coarse ladder as a CLIFF: K_real jumps 1.00 -> 7.43 between scale 1.0 and 1.5 and +# saturates, while median candidate displacement goes 7.63 mm -> 95.82 mm, 3.0x past the pre-registered +# 32.2 mm PLAUSIBILITY DISQUALIFIER. Every rung >= 1.5 is disqualified, so the only open question is +# whether a plausible foothold exists BETWEEN 1.0 and 1.5. ONE CHANGE from run 45: the scale grid. +# Pre-registered gen_q#280 5825155807 / rsm_real#2 5825156755 before submission. +set -uo pipefail +export PT_NOISE_SCALE=1.30 PT_NAME=R46_cov_sn1_knn0p03_F130 +exec /proj/dmfexp/zwhong/rsm_rise/scripts/real/pt_temp_screen.sh 0 1 diff --git a/rsm_rise/scripts/real/payloads_r46/rung_F140.sh b/rsm_rise/scripts/real/payloads_r46/rung_F140.sh new file mode 100644 index 0000000000000000000000000000000000000000..e76b5a9c6f0f7693f3c8c8e2e7f70c57c6c2cbc8 --- /dev/null +++ b/rsm_rise/scripts/real/payloads_r46/rung_F140.sh @@ -0,0 +1,10 @@ +#!/usr/bin/env bash +# PROPOSAL_TEST run 46 -- FINE noise-scale ladder rung (scale 1.40), inside the cliff. +# Run 46b measured the coarse ladder as a CLIFF: K_real jumps 1.00 -> 7.43 between scale 1.0 and 1.5 and +# saturates, while median candidate displacement goes 7.63 mm -> 95.82 mm, 3.0x past the pre-registered +# 32.2 mm PLAUSIBILITY DISQUALIFIER. Every rung >= 1.5 is disqualified, so the only open question is +# whether a plausible foothold exists BETWEEN 1.0 and 1.5. ONE CHANGE from run 45: the scale grid. +# Pre-registered gen_q#280 5825155807 / rsm_real#2 5825156755 before submission. +set -uo pipefail +export PT_NOISE_SCALE=1.40 PT_NAME=R46_cov_sn1_knn0p03_F140 +exec /proj/dmfexp/zwhong/rsm_rise/scripts/real/pt_temp_screen.sh 0 1 diff --git a/rsm_rise/scripts/real/payloads_r46/rung_T10.sh b/rsm_rise/scripts/real/payloads_r46/rung_T10.sh new file mode 100644 index 0000000000000000000000000000000000000000..646c58257c2d04ff86470ae60a72bf94da4e8e63 --- /dev/null +++ b/rsm_rise/scripts/real/payloads_r46/rung_T10.sh @@ -0,0 +1,10 @@ +#!/usr/bin/env bash +# PROPOSAL_TEST run 46 -- FINE noise-scale ladder rung (scale 1.00), inside the cliff. +# Run 46b measured the coarse ladder as a CLIFF: K_real jumps 1.00 -> 7.43 between scale 1.0 and 1.5 and +# saturates, while median candidate displacement goes 7.63 mm -> 95.82 mm, 3.0x past the pre-registered +# 32.2 mm PLAUSIBILITY DISQUALIFIER. Every rung >= 1.5 is disqualified, so the only open question is +# whether a plausible foothold exists BETWEEN 1.0 and 1.5. ONE CHANGE from run 45: the scale grid. +# Pre-registered gen_q#280 5825155807 / rsm_real#2 5825156755 before submission. +set -uo pipefail +export PT_NOISE_SCALE=1.00 PT_NAME=R46_cov_sn1_knn0p03_T10 +exec /proj/dmfexp/zwhong/rsm_rise/scripts/real/pt_temp_screen.sh 0 1 diff --git a/rsm_rise/scripts/real/pi05_200k_prep.sh b/rsm_rise/scripts/real/pi05_200k_prep.sh new file mode 100644 index 0000000000000000000000000000000000000000..d2fcdf963a46c44896c03ce11c389262c8bcdcac --- /dev/null +++ b/rsm_rise/scripts/real/pi05_200k_prep.sh @@ -0,0 +1,92 @@ +#!/usr/bin/env bash +# One-shot prep for the PI05_200K stream (owner 2026-09-25: run the five 30k cooking fine-tunes to 200k). +# Idempotent: re-running it is safe and skips anything already done. +# 1. symlink runs/openpi/assets/_200k -> (assets_dirs = assets_base_dir/) +# 2. seed runs/openpi/checkpoints/_200k/_200k/29999 as HARDLINKS of the parent 29999 +# (42 GB each; the fs is at 100%. orbax never rewrites a step dir in place, and when it rmtree's the +# copy after the first new save the parent's inodes survive.) +# 3. pre-create the fresh W&B run for each continuation (name _200k, config note resumed_from=...) +# and write its id to /wandb_id.txt -- scripts/train.py:init_wandb(resuming=True) does +# wandb.init(id=, resume="must") and passes neither name nor config, so it must exist already. +# 4. print the resolved _200k TrainConfigs and the LR the new cosine gives at the resume step. +set -uo pipefail +ROOT=/proj/dmfexp/zwhong/rsm_rise +CK=$ROOT/runs/openpi/checkpoints +AS=$ROOT/runs/openpi/assets +source $ROOT/wandb_env.sh +export HF_HUB_OFFLINE=1 TOKENIZERS_PARALLELISM=false PYTHONUNBUFFERED=1 +export JAX_PLATFORMS=cpu # login-free CPU node: do not try to grab a GPU +export OPENPI_DATA_HOME=$ROOT/.openpi_assets HF_LEROBOT_HOME=$ROOT/data/real/lerobot_home +PY=$ROOT/third_party/openpi/.venv/bin/python + +PAIRS="pi05_cooking_stock:stock_s0 pi05_cooking_stock:stock_s1 pi05_cooking_rise:rise_s0 pi05_cooking_rise:rise_s1 pi05_cooking_riseadv:riseadv_s0" + +echo "[prep] ==== 1. assets symlinks ====" +for cfg in pi05_cooking_stock pi05_cooking_rise pi05_cooking_riseadv; do + if [ -e "$AS/${cfg}_200k" ]; then echo " exists: $AS/${cfg}_200k"; else + ln -s "$cfg" "$AS/${cfg}_200k" && echo " linked: ${cfg}_200k -> $cfg"; fi +done + +echo "[prep] ==== 2. hardlink-seed the new exp dirs from 29999 ====" +for p in $PAIRS; do + cfg=${p%%:*}; exp=${p##*:} + src=$CK/$cfg/$exp/29999 + dst=$CK/${cfg}_200k/${exp}_200k + if [ ! -d "$src" ]; then echo " MISSING PARENT $src"; continue; fi + if [ -d "$dst/29999" ]; then echo " exists: $dst/29999"; continue; fi + mkdir -p "$dst" + cp -al "$src" "$dst/29999" || { echo " HARDLINK FAILED for $src"; continue; } + echo " seeded: $dst/29999 (files=$(find "$dst/29999" | wc -l))" +done +echo "[prep] parent 29999 dirs still intact:" +for p in $PAIRS; do cfg=${p%%:*}; exp=${p##*:}; echo " $(ls -d $CK/$cfg/$exp/29999) params=$(ls $CK/$cfg/$exp/29999/params | wc -l)"; done + +echo "[prep] ==== 3. pre-create fresh W&B runs ====" +$PY - <<'PYEOF' +import os, pathlib, wandb +CK = pathlib.Path("/proj/dmfexp/zwhong/rsm_rise/runs/openpi/checkpoints") +PAIRS = [("pi05_cooking_stock","stock_s0"),("pi05_cooking_stock","stock_s1"), + ("pi05_cooking_rise","rise_s0"),("pi05_cooking_rise","rise_s1"), + ("pi05_cooking_riseadv","riseadv_s0")] +for cfg, exp in PAIRS: + d = CK / f"{cfg}_200k" / f"{exp}_200k" + idf = d / "wandb_id.txt" + if idf.exists(): + print(f"[wandb] exists {d.name}: {idf.read_text().strip()}", flush=True); continue + d.mkdir(parents=True, exist_ok=True) + parent_id = (CK / cfg / exp / "wandb_id.txt").read_text().strip() + run = wandb.init( + project="rsm_rise", entity="richardrl", name=f"{exp}_200k", + config={"resumed_from": f"{cfg}/{exp}/29999", + "resumed_from_wandb_id": parent_id, + "train_config": f"{cfg}_200k", + "num_train_steps": 200_000, "keep_period": 50_000, "save_interval": 500, + "lr_schedule": "cosine warmup=1000 peak=5e-5 decay_steps=200000 floor=5e-6 " + "(warm restart from the 30k floor; no re-warmup)", + "devices": "8x H100 data parallel (fsdp_devices=1), global batch 32 = 4/GPU"}, + notes=f"200k continuation of {cfg}/{exp} (stopped at 29999). Parent W&B run {parent_id}.", + tags=["pi05_cooking", "200k_continuation"], + ) + idf.write_text(run.id) + print(f"[wandb] created {exp}_200k id={run.id} url={run.url}", flush=True) + run.finish() +PYEOF + +echo "[prep] ==== 4. resolved _200k configs + LR check ====" +cd $ROOT/third_party/openpi +$PY - <<'PYEOF' +import jax, numpy as np +from openpi.training import config as _c +for name in ("pi05_cooking_stock_200k","pi05_cooking_rise_200k","pi05_cooking_riseadv_200k"): + cfg = _c.get_config(name) + s = cfg.lr_schedule + print(f"--- {name}: steps={cfg.num_train_steps} keep_period={cfg.keep_period} save_interval={cfg.save_interval} " + f"batch={cfg.batch_size} workers={cfg.num_workers} fsdp={cfg.fsdp_devices} ema={cfg.ema_decay} " + f"enc_lr_scale={cfg.encoder_lr_scale} img_aug={cfg.image_aug}") + print(f" lr_schedule={s}") + print(f" assets_dirs={cfg.assets_dirs} exists={cfg.assets_dirs.exists()}") + sch = s.create() + for st in (0, 1000, 29999, 30000, 30500, 100000, 199999): + print(f" lr(step={st:>6}) = {float(sch(st)):.6e}") +PYEOF +echo "[prep] done rc=$?" diff --git a/rsm_rise/scripts/real/pi05_200k_pytest.sh b/rsm_rise/scripts/real/pi05_200k_pytest.sh new file mode 100644 index 0000000000000000000000000000000000000000..c321046ab5f9923c32812ff7bc856787a3cb416c --- /dev/null +++ b/rsm_rise/scripts/real/pi05_200k_pytest.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +cd /proj/dmfexp/zwhong/scratch_pi05_200k/rsm_real_scaffold +/proj/dmfexp/zwhong/rsm_rise/third_party/openpi/.venv/bin/python -m pytest tests/test_rise_stack_openpi_patch_numbers.py -q 2>&1 | tail -25 diff --git a/rsm_rise/scripts/real/pi05_200k_rebuild_patch.sh b/rsm_rise/scripts/real/pi05_200k_rebuild_patch.sh new file mode 100644 index 0000000000000000000000000000000000000000..29407d5650e809011ce0e1bf82f962d6c2937c70 --- /dev/null +++ b/rsm_rise/scripts/real/pi05_200k_rebuild_patch.sh @@ -0,0 +1,107 @@ +#!/usr/bin/env bash +# Rebuild rsm_real's vendored openpi patch so it also carries the three `pi05_cooking_*_200k` +# TrainConfigs (PI05_200K stream, owner 2026-09-25), WITHOUT dragging in anything else. +# +# Why not just `git diff` the rsm_rise openpi tree: the shipped patch is NOT that diff. It carries the +# rsm_real#5 inference-split fix (`episodes_required_from`, the `split_json` missing-file fallback) that was +# never back-ported into rsm_rise, and the rsm_rise tree carries run-54 factorial configs the patch has never +# shipped. Regenerating wholesale would silently revert the first and publish the second. So: replay the +# SHIPPED patch onto pristine upstream, apply ONLY the _200k block on top, and re-diff. +set -euo pipefail +ROOT=/proj/dmfexp/zwhong/rsm_rise +WT=${1:-/proj/dmfexp/zwhong/scratch_pi05_200k/rsm_real_scaffold} +PATCH=$WT/rise_stack/openpi/rise_on_pi05.patch +PIN=$(head -1 $WT/rise_stack/openpi/UPSTREAM_COMMIT.txt) +WORK=/proj/dmfexp/zwhong/scratch_pi05_200k/openpi_rebuild +rm -rf $WORK; mkdir -p $WORK/up +echo "[rebuild] pin=$PIN" +cd $ROOT/third_party/openpi && git archive "$PIN" | tar -x -C $WORK/up +cd $WORK/up +git init -q && git add -A && git -c user.email=rr@local -c user.name=rr commit -qm "upstream $PIN" +echo "[rebuild] ---- git apply --check of the SHIPPED patch onto pristine $PIN ----" +git apply --check "$PATCH" && echo "[rebuild] SHIPPED PATCH APPLIES CLEAN" +git apply "$PATCH" + +echo "[rebuild] ---- insert the _200k block ----" +python3 - "$ROOT" <<'PY' +import sys, pathlib +root = pathlib.Path(sys.argv[1]) +# take the block verbatim from the live rsm_rise config.py so the two can never drift +live = (root / "third_party/openpi/src/openpi/training/config.py").read_text() +start = live.index("# ---- rsm_rise (#263 follow-up, owner 2026-09-25): 200k continuations") +end = live.index("if len({config.name for config in _CONFIGS}) != len(_CONFIGS):", start) +block = live[start:end] +p = pathlib.Path("src/openpi/training/config.py") +src = p.read_text() +anchor = "if len({config.name for config in _CONFIGS}) != len(_CONFIGS):" +assert src.count(anchor) == 1, src.count(anchor) +assert "_cooking_200k" not in src +p.write_text(src.replace(anchor, block + anchor)) +print(f"[rebuild] inserted {len(block)} chars / {block.count(chr(10))} lines") +PY + +git add -A +git diff --cached HEAD > $WORK/rise_on_pi05.patch +echo "[rebuild] new patch: $(wc -l < $WORK/rise_on_pi05.patch) lines" + +echo "[rebuild] ---- verify the NEW patch applies clean to pristine upstream ----" +rm -rf $WORK/verify; mkdir -p $WORK/verify +cd $ROOT/third_party/openpi && git archive "$PIN" | tar -x -C $WORK/verify +cd $WORK/verify && git init -q && git add -A && git -c user.email=rr@local -c user.name=rr commit -qm base +git apply --check $WORK/rise_on_pi05.patch && echo "[rebuild] NEW PATCH APPLIES CLEAN" +git apply $WORK/rise_on_pi05.patch +$ROOT/third_party/openpi/.venv/bin/python -c "import ast;ast.parse(open('src/openpi/training/config.py').read());print('[rebuild] patched config.py parses')" + +echo "[rebuild] ---- diff-of-diffs: shipped vs new (should be ONLY the _200k block + line/hash shifts) ----" +{ diff "$PATCH" $WORK/rise_on_pi05.patch || true; } | grep -E "^[<>]" | grep -vE "^[<>] (index |@@ )" | head -60 || true +{ diff "$PATCH" $WORK/rise_on_pi05.patch || true; } | grep -E "^<" | grep -vE "^< (index |@@ )" > $WORK/removed.txt || true +echo "[rebuild] non-_200k content deltas (lines the new patch DROPS, must be 0): $(wc -l < $WORK/removed.txt)" +head -20 $WORK/removed.txt +test "$(wc -l < $WORK/removed.txt)" -eq 0 + +echo "[rebuild] ---- install into the worktree and re-number the docs ----" +cp $WORK/rise_on_pi05.patch "$PATCH" +cd $WT +export WT +python3 - <<'PY' +import os, re, pathlib +REPO = pathlib.Path(os.environ["WT"]) +patch = (REPO/"rise_stack/openpi/rise_on_pi05.patch").read_text() +stat, path, in_hunk, ins, dele = {}, None, False, 0, 0 +for line in patch.splitlines(): + m = re.match(r"^diff --git a/(\S+) b/(\S+)$", line) + if m: + if path is not None: stat[path] = (ins, dele) + path, in_hunk, ins, dele = m.group(2), False, 0, 0; continue + if path is None: continue + if line.startswith("@@"): in_hunk = True; continue + if not in_hunk: continue + if line.startswith("+"): ins += 1 + elif line.startswith("-"): dele += 1 +if path is not None: stat[path] = (ins, dele) +tot_i, tot_d, nf = sum(i for i,_ in stat.values()), sum(d for _,d in stat.values()), len(stat) +print("[renumber] numstat:", {k: v for k, v in sorted(stat.items())}) +print(f"[renumber] totals: {nf} files, +{tot_i} / -{tot_d}") + +def commas(n): return f"{n:,}" +# README per-file table rows +rp = REPO/"rise_stack/openpi/README.md"; r = rp.read_text() +for p_, (i_, d_) in stat.items(): + cell = f"+{commas(i_)}" + (f" / -{commas(d_)}" if d_ else "") + r, n = re.subn(rf"(^\|\s*`{re.escape(p_)}`\s*\|)[^|]*(\|)", lambda m: m.group(1)+f" {cell} "+m.group(2), r, flags=re.M) + assert n == 1, (p_, n) +# README totals row +r, n = re.subn(r"\|\s*\*\*\d+ files?, total\*\*\s*\|\s*\*\*\+[\d,]+\s*/\s*-[\d,]+\*\*", + f"| **{nf} files, total** | **+{commas(tot_i)} / -{commas(tot_d)}**", r); assert n == 1, n +# README headline +r, n = re.subn(r"\d+ files, [\d,]+ insertions and \d+ deletions", + f"{nf} files, {commas(tot_i)} insertions and {tot_d} deletions", r); assert n == 1, n +rp.write_text(r) +# SETUP.md headline +sp = REPO/"SETUP.md"; s = sp.read_text() +s, n = re.subn(r"\d+\s+files and [\d,]+ inserted lines", f"{nf} files and {commas(tot_i)} inserted lines", s) +assert n == 1, n +sp.write_text(s) +print("[renumber] README.md + SETUP.md updated") +PY +echo "[rebuild] done" diff --git a/rsm_rise/scripts/real/pi05_action_stats.sh b/rsm_rise/scripts/real/pi05_action_stats.sh new file mode 100644 index 0000000000000000000000000000000000000000..073149075ba02a11a74944ed95ff30b705260286 --- /dev/null +++ b/rsm_rise/scripts/real/pi05_action_stats.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +# CPU job: PI05_NORM deliverables 4 + 5 -- the action-target unit test over the whole split + the stats table. +# env: PI05_NORM_CONFIGS (default pi05_cooking_stock,pi05_cooking_rise), PI05_NORM_SPLITS, PI05_NORM_MAX_FRAMES +set -uo pipefail +ROOT=/proj/dmfexp/zwhong/rsm_rise +export JAX_PLATFORMS=cpu OPENPI_DATA_HOME=$ROOT/.openpi_assets HF_LEROBOT_HOME=$ROOT/data/real/lerobot_home +export HF_HUB_OFFLINE=1 PYTHONUNBUFFERED=1 TOKENIZERS_PARALLELISM=false +cd $ROOT/third_party/openpi +echo "[pi05_action_stats] host=$(hostname) job=${LSB_JOBID:-none} configs=${PI05_NORM_CONFIGS:-default} \ +splits=${PI05_NORM_SPLITS:-default} max_frames=${PI05_NORM_MAX_FRAMES:-all} $(date -u)" +$ROOT/third_party/openpi/.venv/bin/python -m pytest -q -s -p no:cacheprovider \ + $ROOT/tests/test_pi05_action_targets.py "$@" +rc=$?; echo "[pi05_action_stats] pytest exit=$rc $(date -u)"; exit $rc diff --git a/rsm_rise/scripts/real/pi05_candidates.py b/rsm_rise/scripts/real/pi05_candidates.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/rsm_rise/scripts/real/pi05_corner_watch.sh b/rsm_rise/scripts/real/pi05_corner_watch.sh new file mode 100644 index 0000000000000000000000000000000000000000..edb1655386e4c84c3649e1681445550185960edd --- /dev/null +++ b/rsm_rise/scripts/real/pi05_corner_watch.sh @@ -0,0 +1,23 @@ +#!/usr/bin/env bash +# gen_q #269 -- submit the planning screen for the last sweep corner (sn 1.0 / knn 0.05, LSF 1856693) the moment +# its 9999 checkpoint lands, instead of waiting for the next worker run. pi05_screen_sweep.sh is idempotent and +# carries its own duplicate guards, so calling it on a timer is safe. Exits once the screen is queued (or after +# MAXH hours). +set -uo pipefail +ROOT=/proj/dmfexp/zwhong/rsm_rise +CK=$ROOT/runs/openpi/checkpoints/pi05_cooking_sn1_knn0p05/ws_s0/9999 +MAXH=${MAXH:-5} +deadline=$(( $(date +%s) + MAXH*3600 )) +while [ "$(date +%s)" -lt "$deadline" ]; do + if [ -d "$CK" ]; then + echo "[corner-watch] $(date -u +%H:%M:%SZ) checkpoint exists -> pi05_screen_sweep.sh 0" + "$ROOT/scripts/real/pi05_screen_sweep.sh" 0 + if bjobs -o "job_name stat" -noheader 2>/dev/null | grep -qE "^rr_pi05scr_pi05sn1_knn0p05_ws9999 "; then + echo "[corner-watch] screen queued; exiting"; exit 0 + fi + else + echo "[corner-watch] $(date -u +%H:%M:%SZ) waiting (last step $(ls -d ${CK%/9999}/[0-9]* 2>/dev/null | sed 's|.*/||' | sort -n | tail -1))" + fi + sleep 300 +done +echo "[corner-watch] deadline reached without queueing a screen" diff --git a/rsm_rise/scripts/real/pi05_curve_audit.py b/rsm_rise/scripts/real/pi05_curve_audit.py new file mode 100644 index 0000000000000000000000000000000000000000..c86e83bc9a0037fe30084e009178b3ed0a4f7e6a --- /dev/null +++ b/rsm_rise/scripts/real/pi05_curve_audit.py @@ -0,0 +1,90 @@ +#!/usr/bin/env python +"""PI05_NORM deliverable 1: per-run val/train curve audit for every pi0.5 cooking run. + +Reads runs/openpi/checkpoints///eval_history.jsonl (one json per eval: {'val':{...},'train_eval':{...},'step':n}) +and reports, per metric: min step / min value / final value / the train_eval value at the same steps. +Pure json reading, no compute. +""" +import json, pathlib, sys + +ROOT = pathlib.Path("/proj/dmfexp/zwhong/rsm_rise") +CKPT = ROOT / "runs/openpi/checkpoints" +METRICS = ["loss", "mse_all10", "mse_x", "mse_y", "mse_z", "mse_r0", "mse_r1", "mse_r2", "mse_r3", "mse_r4", + "mse_r5", "mse_grip", "xyz_l2_first_cm", "xyz_l2_chunk_cm", "rot6d_l2_first", "grip_abs_first_mm", + "grip_bin_acc"] + +def load(p): + rows = [] + for ln in p.read_text().splitlines(): + ln = ln.strip() + if not ln: + continue + try: + rows.append(json.loads(ln)) + except json.JSONDecodeError: + pass + rows.sort(key=lambda r: r.get("step", -1)) + # de-duplicate steps (resumes re-log): keep the last occurrence + out = {} + for r in rows: + out[r.get("step")] = r + return [out[k] for k in sorted(out)] + +def main(): + result = {} + for p in sorted(CKPT.glob("*/*/eval_history.jsonl")): + cfg, exp = p.parent.parent.name, p.parent.name + rows = load(p) + if not rows: + continue + steps = [r["step"] for r in rows] + run = {"config": cfg, "exp": exp, "n_evals": len(rows), "first_step": steps[0], "last_step": steps[-1], + "steps": steps, "metrics": {}} + for m in METRICS: + v = [(r["step"], r["val"].get(m), r.get("train_eval", {}).get(m)) for r in rows if m in r.get("val", {})] + if not v: + continue + better = max if m.endswith("_acc") else min + # ignore step 0 (untrained) for the "best" search but keep it in the series + cand = [t for t in v if t[0] > 0] or v + best = better(cand, key=lambda t: t[1]) + run["metrics"][m] = { + "best_step": best[0], "best_val": best[1], "train_at_best": best[2], + "final_step": v[-1][0], "final_val": v[-1][1], "train_at_final": v[-1][2], + "step0_val": v[0][1] if v[0][0] == 0 else None, + "series": [[t[0], t[1], t[2]] for t in v], + } + result[f"{cfg}/{exp}"] = run + out = ROOT / "status/real/pi05_curve_audit.json" + out.write_text(json.dumps(result, indent=1)) + # markdown summary on val loss + key mse + print(f"wrote {out}\n") + hdr = ("| run | evals | steps | val loss @best | best step | train@best | val loss final | " + "train@final | gap final | val/train ratio final |") + print(hdr); print("|" + "---|" * 10) + for k, r in result.items(): + m = r["metrics"].get("loss") + if not m: + continue + gap = m["final_val"] - (m["train_at_final"] or float("nan")) + ratio = m["final_val"] / m["train_at_final"] if m["train_at_final"] else float("nan") + print(f"| {k} | {r['n_evals']} | {r['first_step']}-{r['last_step']} | {m['best_val']:.5f} | " + f"{m['best_step']} | {m['train_at_best']:.5f} | {m['final_val']:.5f} | {m['train_at_final']:.5f} | " + f"{gap:+.5f} | {ratio:.2f} |") + print("\n\n### per-dim val mse: best step / best / final (train at final in parens)\n") + dims = ["mse_all10", "mse_x", "mse_y", "mse_z", "mse_r0", "mse_r1", "mse_r2", "mse_r3", "mse_r4", "mse_r5", "mse_grip"] + for k, r in result.items(): + if not r["metrics"]: + continue + print(f"\n**{k}** (evals {r['n_evals']}, steps {r['first_step']}-{r['last_step']})\n") + print("| metric | best step | best val | final val | train @final | final/best |") + print("|---|---|---|---|---|---|") + for d in dims + ["xyz_l2_first_cm", "rot6d_l2_first", "grip_abs_first_mm", "grip_bin_acc"]: + m = r["metrics"].get(d) + if not m: + continue + rr = m["final_val"] / m["best_val"] if m["best_val"] else float("nan") + print(f"| {d} | {m['best_step']} | {m['best_val']:.6g} | {m['final_val']:.6g} | " + f"{(m['train_at_final'] if m['train_at_final'] is not None else float('nan')):.6g} | {rr:.3f} |") + +main() diff --git a/rsm_rise/scripts/real/pi05_export_keepers.sh b/rsm_rise/scripts/real/pi05_export_keepers.sh new file mode 100644 index 0000000000000000000000000000000000000000..9473598403a816312bf09eb610315c0b857c032f --- /dev/null +++ b/rsm_rise/scripts/real/pi05_export_keepers.sh @@ -0,0 +1,32 @@ +#!/usr/bin/env bash +# gen_q #269 -- params-only export of the pi0.5 RISE actors the PLANNING SCREEN keeps. +# Keep criterion (the owner's, step 4'): spread UP and oracle error DOWN vs stock, or a scorer below its +# permuted control. On the 10-episode screen (status/real/openloop_pi05*_e10/scorer_openloop.json) rise s0, +# rise s1 and riseadv s0 all pass on the first clause. +# The export hardlinks params/ + assets/ (no extra disk -- /proj/dmfexp is at 100%) and drops train_state. +set -uo pipefail +ROOT=/proj/dmfexp/zwhong/rsm_rise +CK=$ROOT/runs/openpi/checkpoints +EX=$ROOT/runs/openpi/export +# The list is a superset: a cell whose checkpoint does not exist yet is SKIPped, and a cell already exported is +# reported as "have" -- so this script is idempotent and can be called after every sweep cell lands (run 8). +# The sn x knn sweep cells are 10k-step WARM STARTS off pi05_cooking_rise/rise_s0/29999, hence ws_s0/9999; +# the destination names match PI05_DIRS in scripts/real/hf_upload.py one for one. +CELLS_DEFAULT="pi05_cooking_rise:$CK/pi05_cooking_rise/rise_s0/29999:$EX/pi05_rise_s0_29999 +pi05_cooking_rise:$CK/pi05_cooking_rise/rise_s1/29999:$EX/pi05_rise_s1_29999 +pi05_cooking_riseadv:$CK/pi05_cooking_riseadv/riseadv_s0/29999:$EX/pi05_riseadv_s0_29999 +pi05_cooking_risebn:$CK/pi05_cooking_risebn/risebn_s0/29999:$EX/pi05_risebn_s0_29999" +for c in wsctrl sn0p3_knn0p01 sn0p1_knn0p03 sn0p3_knn0p03 sn0p03_knn0p01 sn0p1_knn0p05 sn1_knn0p03 sn1_knn0p05 ; do + CELLS_DEFAULT="$CELLS_DEFAULT +pi05_cooking_$c:$CK/pi05_cooking_$c/ws_s0/9999:$EX/pi05_${c}_s0_ws9999" +done +for cell in ${CELLS:-$CELLS_DEFAULT} ; do + cfg=${cell%%:*}; rest=${cell#*:}; src=${rest%%:*}; dst=${rest#*:} + [ -d "$src" ] || { echo "[keepers] SKIP missing $src"; continue; } + [ -e "$dst/_CHECKPOINT_METADATA" ] && { echo "[keepers] have $dst"; continue; } + echo "=== [keepers] $cfg $src -> $dst" + $ROOT/scripts/real/openpi_export.sh $ROOT/scripts/real/openpi_export_params.py "$src" "$dst" --config "$cfg" \ + || echo "[keepers] FAILED $dst" +done +echo "[keepers] done $(date -u)" +du -sh $EX/* 2>/dev/null diff --git a/rsm_rise/scripts/real/pi05_export_keepers_cpu.sh b/rsm_rise/scripts/real/pi05_export_keepers_cpu.sh new file mode 100644 index 0000000000000000000000000000000000000000..cc245eb9f1a93e6b5f30ab8b0a0f993d4b6a0853 --- /dev/null +++ b/rsm_rise/scripts/real/pi05_export_keepers_cpu.sh @@ -0,0 +1,10 @@ +#!/usr/bin/env bash +# gen_q #269 -- CPU-only wrapper around pi05_export_keepers.sh. +# Why: the export itself is a hardlink pass (params/ + assets/, train_state dropped) and the verify step is ONE +# pi0.5 forward pass, so it needs no GPU -- and the GPU submission (1842203) starved in `normal` behind +# "ngpus_physical not satisfied: 132 hosts" while the whole HF upload chain waited on it. +# JAX_PLATFORMS=cpu keeps the jax cuda plugin from erroring on a job with no visible device. +set -uo pipefail +export JAX_PLATFORMS=cpu +export XLA_FLAGS="--xla_force_host_platform_device_count=1" +exec /proj/dmfexp/zwhong/rsm_rise/scripts/real/pi05_export_keepers.sh "$@" diff --git a/rsm_rise/scripts/real/pi05_ft50_chunk10_table.py b/rsm_rise/scripts/real/pi05_ft50_chunk10_table.py new file mode 100644 index 0000000000000000000000000000000000000000..6a237a53925487be8767c174fe34a06964a25622 --- /dev/null +++ b/rsm_rise/scripts/real/pi05_ft50_chunk10_table.py @@ -0,0 +1,90 @@ +#!/usr/bin/env python3 +"""PI05_FT req 6: build the CHUNK-10-COMPARABLE held-out table for the seven chunk-50 fine-tunes. + +Why this script exists. The stdout `EVAL` one-liner prints `xyz_chunk` over the config's FULL horizon, so a +chunk-50 run's 2.3 cm and a chunk-10 parent's 1.2 cm are not the same measurement. train.py emits +`*_chunk10_*` (the first-10 prefix) whenever horizon > 10 -- that is the metric the two generations share. +Everything here is read from `eval_history.jsonl` in each checkpoint dir; no compute, no GPU, no W&B. + +Selection metric per the brief: held-out `xyz_l2_first_cm` and the `*_chunk10_*` family -- NOT the +flow-matching loss (it rises from overfitting while the action error plateaus). +""" +import json, os, sys, statistics + +ROOT = "/proj/dmfexp/zwhong/rsm_rise" +# (label, ft50 config, ft50 exp, parent config, parent exp) +CELLS = [ + ("stock_s0", "pi05_cooking_stock_ft50_s0", "stock_s0_ft50", "pi05_cooking_stock", "stock_s0"), + ("stock_s1", "pi05_cooking_stock_ft50_s1", "stock_s1_ft50", "pi05_cooking_stock", "stock_s1"), + ("rise_s0", "pi05_cooking_rise_ft50_s0", "rise_s0_ft50", "pi05_cooking_rise", "rise_s0"), + ("rise_s1", "pi05_cooking_rise_ft50_s1", "rise_s1_ft50", "pi05_cooking_rise", "rise_s1"), + ("riseadv_s0", "pi05_cooking_riseadv_ft50_s0", "riseadv_s0_ft50", "pi05_cooking_riseadv", "riseadv_s0"), + ("sn1_knn0p03", "pi05_cooking_sn1_knn0p03_ft50_s0", "sn1_knn0p03_ft50", "pi05_cooking_sn1_knn0p03", "ws_s0"), + ("sn0p1_knn0p03", "pi05_cooking_sn0p1_knn0p03_ft50_s0","sn0p1_knn0p03_ft50", "pi05_cooking_sn0p1_knn0p03","ws_s0"), +] +CONTROL = ("stock_s0_h50 (from-base control)", "pi05_cooking_stock_h50", "stock_s0_h50", None, None) + + +def hist(cfg, exp): + p = f"{ROOT}/runs/openpi/checkpoints/{cfg}/{exp}/eval_history.jsonl" + if not os.path.exists(p): + return None + return [json.loads(l) for l in open(p) if l.strip()] + + +def at(H, step): + for h in H: + if h["step"] == step: + return h["val"] + return None + + +def tail(H, key, n=3): + """Mean of the last n evals -- the per-eval scatter on a fixed seeded val subset is ~0.01-0.02 cm, so a + single point must not be read as a trend.""" + vals = [h["val"][key] for h in H[-n:] if key in h["val"]] + return statistics.fmean(vals) if vals else float("nan") + + +def best(H, key): + vals = [(h["val"][key], h["step"]) for h in H if key in h["val"]] + return min(vals) if vals else (float("nan"), -1) + + +def main(): + out = [] + out.append("| model | parent chunk10 (final) | ft50 chunk10 @ step0 | ft50 chunk10 now (mean last 3) | step | recovered | ft50 first | ft50 chunk50 |") + out.append("|---|---|---|---|---|---|---|---|") + for label, cfg, exp, pcfg, pexp in CELLS + [CONTROL]: + H = hist(cfg, exp) + if not H: + out.append(f"| {label} | -- | MISSING eval_history.jsonl | | | | | |") + continue + step = H[-1]["step"] + c10_now = tail(H, "xyz_l2_chunk10_cm") + v0 = at(H, 0) or {} + c10_0 = v0.get("xyz_l2_chunk10_cm", float("nan")) + first_now = tail(H, "xyz_l2_first_cm") + c50_now = tail(H, "xyz_l2_chunk_cm") + if pcfg: + PH = hist(pcfg, pexp) + # the parent ran at horizon 10, so its own xyz_l2_chunk_cm IS the first-10 mean + p10 = PH[-1]["val"]["xyz_l2_chunk_cm"] if PH else float("nan") + gap0 = c10_0 - p10 + rec = (gap0 - (c10_now - p10)) / gap0 * 100.0 if gap0 and gap0 == gap0 and abs(gap0) > 1e-9 else float("nan") + out.append(f"| `{label}` | {p10:.3f} | {c10_0:.3f} (+{gap0:.3f}) | **{c10_now:.3f}** | {step} | {rec:+.0f}% | {first_now:.3f} | {c50_now:.3f} |") + else: + out.append(f"| `{label}` | n/a (from base) | {c10_0:.3f} | **{c10_now:.3f}** | {step} | n/a | {first_now:.3f} | {c50_now:.3f} |") + print("\n".join(out)) + print() + print("Columns. `parent chunk10 (final)` = the chunk-10 parent's own held-out `xyz_l2_chunk_cm` at its last") + print("eval (horizon 10, so it IS the first-10 mean). `ft50 chunk10 @ step0` = the same prefix measured on") + print("the IDENTICAL warm-started weights but denoised jointly over 50 tokens -- the gap in brackets is the") + print("pure cost of the horizon change, with no training in between. `recovered` = how much of that gap the") + print("fine-tune has clawed back so far (negative = currently further from the parent than at step 0, i.e. it") + print("is spending first-10 accuracy on the new 40-frame tail). `ft50 chunk50` is the full 1 s chunk and has") + print("NO chunk-10 counterpart by construction.") + + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/real/pi05_ft50_converse_ladder.sh b/rsm_rise/scripts/real/pi05_ft50_converse_ladder.sh new file mode 100644 index 0000000000000000000000000000000000000000..b605f716207e80042ae23f72cf53b4878a3a2e99 --- /dev/null +++ b/rsm_rise/scripts/real/pi05_ft50_converse_ladder.sh @@ -0,0 +1,202 @@ +#!/usr/bin/env bash +# rsm_real#14 / worker PI05_FT run 30 -- THE CONVERSE TEST (point prediction) + THE ALPHA LADDER. +# +# WHERE THIS COMES FROM. Run 28 measured that `oracle` (the planning CEILING) gets WORSE with more +# training and concluded "ship an early checkpoint for the planning deployment". Run 29 showed the +# degradation is PURE CANDIDATE-CLOUD NARROWING (headroom H = greedy-oracle tracks the candidate spread, +# rho in [1.015,1.070] on the last arm in 8/8 cells; E = H/spread has CV 7.7 % across 24 (cell,step) +# points) and launched the WIDENING test (LSF 1921943): re-screen 150k with --cand-shrink = each cell's +# own S(50k)/S(150k). +# +# Widening is a DIRECTIONAL test -- "oracle should get better". Almost any monotone story predicts that. +# The mechanism makes a much sharper claim, and this script tests it: +# +# (A) THE CONVERSE, WHICH IS A POINT PREDICTION. If the ONLY thing 100k extra steps did to planning is +# narrow the cloud by a factor r, then NARROWING THE EARLY CLOUD BY EXACTLY r MUST REPRODUCE THE +# LATE ORACLE -- not "be worse", but land ON it. So screen step 50000 with alpha = 1/r = +# S(150k)/S(50k) and compare oracle(50k, 1/r) against the ALREADY-MEASURED oracle(150k, 1.0). +# This can fail in a way widening cannot: if oracle(50k, 1/r) stays clearly BETTER than +# oracle(150k, 1.0), then the late checkpoint really did lose planning quality on top of losing +# width, and run 28's recommendation partly stands. A point prediction that survives is worth +# more than four directional ones, and one that dies kills the mechanism cleanly. +# It also runs in the SHRINKING direction, where candidates move TOWARD the cloud centroid and so +# stay on the action manifold -- widening can always be dismissed as "you invented candidates the +# policy would never emit", and this arm is immune to that objection. +# +# (B) THE LADDER, WHICH MAKES THE RECOMMENDATION DEPLOYABLE. Run 29's alpha is each cell's own +# S(50k)/S(150k) -- a number that needs the 50k checkpoint to compute. AT DEPLOYMENT THERE IS NO +# 50k CHECKPOINT. So a recommendation of the form "ship the late checkpoint with alpha>1" is not +# yet shippable. Two extra alphas (1.5 and 3.0) on two RISE actors bracket each cell's own ratio +# (sn1 1.772, riseadv 2.049) and, with the alpha=1.0 screens that already exist, give 4 points per +# cell. If argmin_alpha rsm lands in the same place for both cells, alpha ships as a CONSTANT and +# the 50k reference is not needed; if it does not, the knob is per-model and that is a real cost +# that has to be stated rather than discovered later. +# +# PREDICTIONS ARE REGISTERED IN status/real/ft50_converse_ladder.py BEFORE ANY OF THESE SCREENS EXIST +# (C1-C3, L1-L4), and that script was run once on CPU against zero data to timestamp the registration. +# +# HONESTY OF THE KNOB. scorer_openloop.py:569-576 rescales the candidates about THEIR OWN CENTROID +# (`cands = m + alpha*(c - m)`, m = candidates' mean), never the ground truth, so no arm of this can +# leak the target. It is applied BEFORE the --inject-logged block, and we inject nothing here. +# +# SHAPE. 4 converse + 4 ladder = 8 independent single-process screens = ONE FULL 8-GPU pack. An +# underfilled pack is a 1-GPU job wearing an 8-GPU request (CLAUDE.md), so this script HOLDS rather than +# submit a short pack unless RR_CL_FORCE=1. No replay eval in any payload: replay does not look at +# candidates at all, so alpha cannot change it and re-running it would be pure waste. +# +# TAGS CANNOT CONTAMINATE THE PUBLISHED TABLES. Every published table globs +# openloop_pi05*_/scorer_openloop.json, which requires the directory name to END in the step. +# These end in _cs / _lad. Verified with fnmatch below at submit time, not assumed. +set -uo pipefail +ROOT=/proj/dmfexp/zwhong/rsm_rise +CK=$ROOT/runs/openpi/checkpoints +GEN=$ROOT/scripts/real/_gen +PSDIR=$ROOT/status/real/pi05_pending_submits +LATE=150000 +EARLY=50000 +LADDER_ALPHAS="1.50 3.00" + +RSM=$ROOT/runs/real_cooking_v5/rsm/R_M/ckpt_s100000.pt +IDQL=$ROOT/runs/cooking_v5_expert_suboptimal/policy/S0Aidql_seed1/cooking_v5_expert_suboptimal_S0Aidql_s1/20260921235824/models/model_epoch_3000.pth +COMMON="--idql-ckpt $IDQL --rsm-ckpt $RSM --rsm-mode d1 --rsm-depth 1 --rsm-beta 0.99 \ + --rsm-score-kind prob --rsm-temperature 25 --n-cand 128 --horizon 8 --stride 25" +# n-cand MUST stay 128 everywhere: the order statistic c in oracle ~ mu - c*sigma depends on it, so a +# different n-cand would make every cross-arm comparison in this experiment meaningless (run 29's gate). + +# converse arm: all four cells run 29 measured a ratio for. ladder arm: the two RISE actors. +CONVERSE_CELLS=" +pi05_cooking_stock_ft50_s0:stock_s0_ft50 +pi05_cooking_sn1_knn0p03_ft50_s0:sn1_knn0p03_ft50 +pi05_cooking_riseadv_ft50_s0:riseadv_s0_ft50 +pi05_cooking_rise_ft50_s0:rise_s0_ft50 +" +LADDER_CELLS=" +pi05_cooking_sn1_knn0p03_ft50_s0:sn1_knn0p03_ft50 +pi05_cooking_riseadv_ft50_s0:riseadv_s0_ft50 +" +mkdir -p "$GEN" "$PSDIR" "$ROOT/logs/lsf" + +# ---------------------------------------------------------------- duplicate guard (run 29's shape) +JOBS=""; JOBS_OK=0 +for try in 1 2 3; do + out=$(bjobs -o "job_name stat" -noheader 2>&1); rc=$? + if [ $rc -eq 0 ] && [ -n "$out" ]; then JOBS="$out"; JOBS_OK=1; break; fi + case "$out" in *"No unfinished job found"*) JOBS=""; JOBS_OK=1; break;; esac + [ $try -lt 3 ] && sleep 5 +done +[ "$JOBS_OK" = 1 ] || { echo "[cl] ABORT: cannot read the LSF job table; refusing to submit"; exit 0; } +# MEASURED BUG (run 30, 01:43Z): the first version of this guard matched only "^rr_pi05cl +", but +# bsub_gpu_pack.sh:86-95 SPLITS an RR_GPUS=8 submission into two 4-GPU packs named _p4a / _p4b. +# The bare name therefore NEVER appears in the job table for an 8-GPU submission, the guard could not +# fire, and a second invocation two minutes later submitted duplicates 1922417/1922418 racing +# 1922400/1922401 on the same output directories. I killed 1922417/1922418 (my own jobs). The suffix +# must be part of the pattern -- the same way pi05_ft50_screen.sh:138 already writes it. +if printf '%s\n' "$JOBS" | grep -qE "^rr_pi05cl(_p4[ab])? +(PEND|RUN|PSUSP|USUSP|SSUSP)$"; then + echo "[cl] rr_pi05cl is already PEND/RUN -- refusing to submit a duplicate"; exit 0 +fi +[ -e "$PSDIR/ft50cl" ] && { echo "[cl] unconfirmed submission marker $PSDIR/ft50cl exists -- refusing"; exit 0; } + +emit_payload() { # $1 cfg $2 exp $3 step $4 alpha $5 tag + local cfg=$1 exp=$2 step=$3 alpha=$4 tag=$5 + local ckdir=$CK/$cfg/$exp/$step + local olout=$ROOT/status/real/openloop_$tag + local f=$GEN/rr_pi05cl_${tag}.sh + cat > "$f" < $olout/scorer_openloop.json" +else + $ROOT/scripts/real/run_env_openpi.sh $ROOT/scripts/real/scorer_openloop.py \\ + --policy "openpi:$cfg:$ckdir" $COMMON --cand-shrink $alpha \\ + --tag $tag --out "$olout" + echo "[cell $tag] screen rc=\$? \$(date -u)" +fi +PL + chmod +x "$f" + echo "$f" +} + +files=""; skipped=0; tags="" +# ---------------------------------------------------------------- (A) converse: EARLY at alpha = 1/r +for cell in $CONVERSE_CELLS; do + cfg=${cell%%:*}; exp=${cell##*:} + ck=$CK/$cfg/$exp/$EARLY + se=$ROOT/status/real/openloop_pi05${exp}_${EARLY}/scorer_openloop.json + sl=$ROOT/status/real/openloop_pi05${exp}_${LATE}/scorer_openloop.json + if [ ! -d "$ck/params" ]; then echo "[cl] $exp: no $EARLY checkpoint -- skip"; skipped=$((skipped+1)); continue; fi + if [ ! -e "$se" ] || [ ! -e "$sl" ]; then + echo "[cl] $exp: need BOTH $EARLY and $LATE screens to set 1/r -- skip"; skipped=$((skipped+1)); continue; fi + # alpha = S(LATE)/S(EARLY) < 1, from the measured json. Refuse a degenerate value. + alpha=$(python3 -c " +import json,sys +a=json.load(open('$se'))['candidate_spread_xyz_cm'] +b=json.load(open('$sl'))['candidate_spread_xyz_cm'] +r=b/a +sys.exit(1) if not (0.15 < r < 0.95) else print('%.3f'%r) +") || { echo "[cl] $exp: 1/r out of sane range -- skip"; skipped=$((skipped+1)); continue; } + cs=$(python3 -c "print('cs%03d'%round(float('$alpha')*100))") + tag=pi05${exp}_${EARLY}_${cs} + if [ -e "$ROOT/status/real/openloop_$tag/scorer_openloop.json" ]; then + echo "[cl] $tag: already measured"; skipped=$((skipped+1)); continue; fi + files="$files $(emit_payload $cfg $exp $EARLY $alpha $tag)"; tags="$tags $tag" + echo "[cl] queued CONVERSE $tag alpha=1/r=$alpha" +done +# ---------------------------------------------------------------- (B) ladder: LATE at fixed alphas +for cell in $LADDER_CELLS; do + cfg=${cell%%:*}; exp=${cell##*:} + ck=$CK/$cfg/$exp/$LATE + if [ ! -d "$ck/params" ]; then echo "[cl] $exp: no $LATE checkpoint -- skip"; skipped=$((skipped+1)); continue; fi + for alpha in $LADDER_ALPHAS; do + lad=$(python3 -c "print('lad%03d'%round(float('$alpha')*100))") + tag=pi05${exp}_${LATE}_${lad} + if [ -e "$ROOT/status/real/openloop_$tag/scorer_openloop.json" ]; then + echo "[cl] $tag: already measured"; skipped=$((skipped+1)); continue; fi + files="$files $(emit_payload $cfg $exp $LATE $alpha $tag)"; tags="$tags $tag" + echo "[cl] queued LADDER $tag alpha=$alpha" + done +done + +n=$(echo $files | wc -w) +if [ "$n" -eq 0 ]; then echo "[cl] nothing to submit ($skipped skipped)"; exit 0; fi + +# --------------- contamination gate: no new tag may be picked up by a published-table glob +python3 - "$tags" <<'PYG' || { echo "[cl] ABORT: contamination gate failed"; exit 4; } +import sys, fnmatch +tags = sys.argv[1].split() +pats = ['openloop_pi05*_%d' % s for s in (50000, 100000, 150000, 199999)] +bad = [(t, p) for t in tags for p in pats if fnmatch.fnmatch('openloop_' + t, p)] +for t, p in bad: + print('[cl] CONTAMINATION: openloop_%s matches %s' % (t, p)) +print('[cl] contamination gate: %d tags x %d globs, %d matches' % (len(tags), len(pats), len(bad))) +sys.exit(1 if bad else 0) +PYG + +# ---------------------------------------------------------------- pack size = the largest FULL pack +# This script is also the RESUME path: payloads skip any cell whose json exists, so after a preemption +# the remainder is whatever is left -- 5, or 3, or 1 -- and NOT 8. Two ways to get that wrong, both of +# which CLAUDE.md forbids and both of which the first draft of this tail would have done: +# * hold at "n != 8" forever, so a preempted sweep never finishes; or +# * hand a remainder of 5 to RR_GPUS=8, whose 8->4+4 splitter would make a 3-payload and a 2-payload +# pack -- two UNDERFILLED 4-GPU nodes, i.e. exactly the 1-GPU-job-in-disguise the rule is about. +# So round DOWN to a whole number of full packs and leave the tail for a later invocation; the tail is +# only submitted with RR_CL_FORCE=1, which is the deliberate "this really is the last 1-3 cells" call. +if [ "$n" -ge 8 ]; then G=8; take=8 +elif [ "$n" -ge 4 ]; then G=4; take=4 +else + echo "[cl] HOLDING: only $n payload(s) left; a $n-payload pack on a 4-GPU j_exclusive node wastes" + echo " $((4-n)) GPU(s), which is the 1-GPU-job-in-disguise CLAUDE.md forbids." + echo " Re-run when more cells are ready, or RR_CL_FORCE=1 to take the genuine tail deliberately." + [ "${RR_CL_FORCE:-0}" = 1 ] || exit 0 + G=4; take=$n + echo "[cl] RR_CL_FORCE=1 -- submitting the $n-payload tail anyway (waste documented above)" +fi +sub=$(echo $files | tr ' ' '\n' | head -n $take | tr '\n' ' ') +[ "$take" -lt "$n" ] && echo "[cl] $n ready, taking $take as full pack(s); $((n-take)) left for the next invocation" +touch "$PSDIR/ft50cl" +echo "[cl] submitting $take payload(s) on $G GPU(s) as rr_pi05cl" +RR_GPUS=$G RR_MEM=96G bash $ROOT/scripts/bsub_gpu_pack.sh rr_pi05cl $sub 2>&1 | tail -6 diff --git a/rsm_rise/scripts/real/pi05_ft50_gap_table.py b/rsm_rise/scripts/real/pi05_ft50_gap_table.py new file mode 100644 index 0000000000000000000000000000000000000000..26c3cf0d3b29dfd9c954f69474840f3944a0fb05 --- /dev/null +++ b/rsm_rise/scripts/real/pi05_ft50_gap_table.py @@ -0,0 +1,76 @@ +#!/usr/bin/env python3 +"""PI05_FT (rsm_real#14) -- the train/val GENERALISATION GAP over the fine-tune, read off disk. + +Why this exists. `pi05_ft50_chunk10_table.py` answers "is the fine-tune back to parent parity on the +metric the two generations share". It cannot answer "is the remaining budget buying anything", because a +single val number does not say whether a flat val curve is convergence or overfitting. train.py evaluates +BOTH a held-out `val` split and a `train_eval` split of the same size (256 chunks, same seeded draw), so +the ratio val/train_eval is a direct generalisation-gap read with no extra compute. + +Reads //eval_history.jsonl, whose records are {"val": {...}, "train_eval": {...}, "step": N}. +No GPU, no W&B, no re-eval. +""" +import json, glob, os, sys + +BASE = os.environ.get("RR_CKPT_BASE", "runs/openpi/checkpoints") + +def load(path): + evs = [] + with open(path) as fh: + for line in fh: + line = line.strip() + if not line: + continue + try: + d = json.loads(line) + except json.JSONDecodeError: + continue # a record torn by a concurrent write; the next run re-reads it + if "step" in d and "val" in d and "train_eval" in d: + evs.append(d) + return sorted(evs, key=lambda d: d["step"]) + +runs = {} +for p in sorted(glob.glob(os.path.join(BASE, "pi05_cooking_*", "*", "eval_history.jsonl"))): + exp = p.split(os.sep)[-2] + if "ft50" not in exp and "h50" not in exp: + continue + evs = load(p) + if evs: + runs[exp] = evs + +MARKS = (0, 1000, 5000, 10000, 15000, 20000, 50000, 100000, 150000, 199999) + +print("# PI05_FT -- train/val generalisation gap (val / train_eval, same 256-chunk draw)") +print() +print("`c10` = xyz_l2_chunk10_cm (the first-10 prefix, comparable to the chunk-10 parents).") +print("`c50` = xyz_l2_chunk_cm (the full 1 s chunk, this generation's real objective).") +print("`gap` = val/train_eval, so 1.0x = no overfitting. Built by scripts/real/pi05_ft50_gap_table.py.") +print() +print("| run | step | val c10 | tr c10 | val c50 | tr c50 | c50 gap | mse10 gap |") +print("|---|---|---|---|---|---|---|---|") +for exp, evs in runs.items(): + sel, seen = [], set() + for e in evs: + if e["step"] in MARKS: + sel.append(e); seen.add(e["step"]) + if evs[-1]["step"] not in seen: + sel.append(evs[-1]) + for e in sel: + v, t = e["val"], e["train_eval"] + cg = v["xyz_l2_chunk_cm"] / t["xyz_l2_chunk_cm"] if t["xyz_l2_chunk_cm"] else float("nan") + mg = v["mse_all10"] / t["mse_all10"] if t["mse_all10"] else float("nan") + print(f"| `{exp}` | {e['step']} | {v['xyz_l2_chunk10_cm']:.3f} | {t['xyz_l2_chunk10_cm']:.3f} " + f"| {v['xyz_l2_chunk_cm']:.3f} | {t['xyz_l2_chunk_cm']:.3f} | {cg:.2f}x | {mg:.1f}x |") + +print() +print("## Per-run best-so-far on each val metric (does the LATEST step win?)") +print() +print("| run | newest step | best val c10 (@step) | best val c50 (@step) | latest is best c50? |") +print("|---|---|---|---|---|") +for exp, evs in runs.items(): + b10 = min(evs, key=lambda e: e["val"]["xyz_l2_chunk10_cm"]) + b50 = min(evs, key=lambda e: e["val"]["xyz_l2_chunk_cm"]) + last = evs[-1] + print(f"| `{exp}` | {last['step']} | {b10['val']['xyz_l2_chunk10_cm']:.3f} (@{b10['step']}) " + f"| {b50['val']['xyz_l2_chunk_cm']:.3f} (@{b50['step']}) " + f"| {'YES' if b50['step'] == last['step'] else 'no -- best was @%d' % b50['step']} |") diff --git a/rsm_rise/scripts/real/pi05_ft50_horizon_probe.py b/rsm_rise/scripts/real/pi05_ft50_horizon_probe.py new file mode 100644 index 0000000000000000000000000000000000000000..08a0a9f38731e0fbd383a3997db73d6af2fc0409 --- /dev/null +++ b/rsm_rise/scripts/real/pi05_ft50_horizon_probe.py @@ -0,0 +1,174 @@ +#!/usr/bin/env python +"""rsm_real#14 / worker ft50scr TASK 1 -- what does `--horizon 8` MEAN for a policy whose action_horizon is 50? + +The 13 existing rows of the pi0.5 planning screen (status/real/pi05_screen_table_25.md) were all measured on +CHUNK-10 policies with `--horizon 8`. Before a single chunk-50 row is added to that table we have to know +whether `--horizon` truncates the policy's chunk (-> the new rows ARE comparable) or whether it is assumed +equal to action_horizon / padded / silently scored against a mismatched reference (-> NOT comparable). + +The code path (read first, then measured here): + * scorer_openloop.py:568 cands = pol.candidates(obs, a.n_cand, a.horizon) + * twin_rollout.py:207-216 OpenpiPolicy.candidates: the flow noise is drawn at (self.H, self.D) where + self.H = cfg.model.action_horizon -- i.e. MODEL-matched, 50 for an ft50 config -- + and the returned chunk is `np.asarray(a)[:horizon, :10]`, a PURE TRUNCATION. + * scorer_openloop.py:577 gt = A[i:i + a.horizon] (8 logged frames) + * scorer_openloop.py:545 grid = range(0, T - a.horizon, a.stride) (the same anchors as the chunk-10 runs) + * scorer_openloop.py:619 err_first = |cands[:, 0, :3] - gt[0, :3]| -> first action only + * scorer_openloop.py:620 err_chunk = |cands[..., :3] - gt[None, :, :3]|.mean(1) -> mean over 8 steps + * twin_rollout.py:307 IDQLScorer sees cands[:, 0, :] -> first action only + * twin_rollout.py:290-302 RSMScorer sees A[:, :rsm.chunk], PADDING with the last action if the chunk is + SHORTER than rsm.chunk -- and it is 8 steps here exactly as in the chunk-10 runs. + +So the prediction is: `--horizon 8` on a chunk-50 policy denoises a full 50-step chunk (the model's own +horizon, which is what its noise shape and attention mask are built for) and then keeps the FIRST 8 steps. +Every read-out downstream sees exactly the 8-step object it saw for the chunk-10 policies. + +This script MEASURES that instead of asserting it: + 1. cfg.model.action_horizon for a chunk-10 parent, an ft50 config and the _h50 control. + 2. candidates(obs, n, 8).shape == (n, 8, 10) and candidates(obs, n, 50).shape == (n, 50, 10). + 3. With the proposer RNG re-seeded identically (scorer_openloop.py:519 does exactly this, per episode), + candidates(...,8) is BIT-IDENTICAL to candidates(...,50)[:, :8]. That is the whole claim: --horizon + does not change the model call, the noise, or the sample -- only the slice that is returned. + 4. The failure mode at the other end: horizon > action_horizon returns a chunk SHORTER than requested + (the slice just runs out), which downstream is a broadcast error, not a silent wrong number. + 5. The realised spread of the first action, so the new rows' `spread` column has a sanity reference. + +usage: pi05_ft50_horizon_probe.py --ckpt [--config ...] [--n 8] [--ep 7] +""" +import argparse, json, sys, time +from pathlib import Path +import numpy as np + +ROOT = Path("/proj/dmfexp/zwhong/rsm_rise") +PROMPT = "Follow the displayed cooking state sequence" + + +def decode_frame(path, idx=0): + import av + with av.open(str(path)) as c: + st = c.streams.video[0]; st.thread_type = "AUTO" + for i, fr in enumerate(c.decode(st)): + if i == idx: + return fr.to_ndarray(format="rgb24") + raise RuntimeError(f"frame {idx} not in {path}") + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--ckpt", required=True, help="a CHUNK-50 checkpoint dir holding params/ and assets/") + ap.add_argument("--config", default="pi05_cooking_stock_ft50_s0") + ap.add_argument("--parent-config", default="pi05_cooking_stock", help="the chunk-10 parent, for the horizons") + ap.add_argument("--n", type=int, default=8, help="candidates per call (the real screen uses 128)") + ap.add_argument("--ep", type=int, default=7, help="held-out episode to take the probe observation from") + ap.add_argument("--frame", type=int, default=0) + ap.add_argument("--out", default=str(ROOT / "status/real/pi05_ft50_screen_horizon.json")) + a = ap.parse_args() + + sys.path.insert(0, str(ROOT / "scripts/real")) + from openpi.training import config as cfgmod + from twin_rollout import OpenpiPolicy + + rec = {"probe": "pi05_ft50_horizon_probe", "utc": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), + "ckpt": a.ckpt, "config": a.config, "n_cand": a.n, "episode": a.ep, "frame": a.frame} + + # ---- 1. the configured horizons ------------------------------------------------------------------ + hz = {} + for nm in (a.parent_config, a.config, "pi05_cooking_stock_h50"): + try: + c = cfgmod.get_config(nm) + hz[nm] = {"action_horizon": int(c.model.action_horizon), "action_dim": int(c.model.action_dim)} + except Exception as e: # a config that is not registered is a finding + hz[nm] = {"error": repr(e)} + rec["configured_horizons"] = hz + print("[probe] configured horizons:", json.dumps(hz), flush=True) + + # ---- the probe observation: a REAL held-out frame, exactly the objects scorer_openloop feeds ------- + import pyarrow.parquet as pq + t = pq.read_table(ROOT / f"data/real/rsm_cooking_v5/data/chunk-000/episode_{a.ep:06d}.parquet").to_pandas() + S = np.stack(t["observation.state"].values).astype(np.float32) + vr = ROOT / "data/real/rsm_cooking_v5/videos/chunk-000" + obs = {"state": S[a.frame], + "images": {"global": decode_frame(vr / f"observation.images.global/episode_{a.ep:06d}.mp4", a.frame), + "wrist": decode_frame(vr / f"observation.images.wrist/episode_{a.ep:06d}.mp4", a.frame)}} + rec["state_dim"] = int(S.shape[1]); rec["image_shape"] = list(obs["images"]["global"].shape) + + pol = OpenpiPolicy(a.config, a.ckpt, seed=0) + rec["policy_H"] = int(pol.H); rec["policy_D"] = int(pol.D) + rec["noise_shape_per_candidate"] = [int(pol.H), int(pol.D)] + print(f"[probe] OpenpiPolicy self.H={pol.H} self.D={pol.D} -> flow noise is drawn at " + f"({pol.H},{pol.D}), i.e. MODEL-matched", flush=True) + + # ---- 2/3. the same draw at two horizons, proposer RNG re-seeded exactly as scorer_openloop does ---- + seed, ep = 0, a.ep + pol.rng = np.random.default_rng([seed, ep]); t0 = time.time() + c8 = pol.candidates(obs, a.n, 8) + pol.rng = np.random.default_rng([seed, ep]) + c50 = pol.candidates(obs, a.n, int(pol.H)) + rec["secs_per_call"] = round((time.time() - t0) / 2, 2) + rec["shape_horizon_8"] = list(c8.shape) + rec["shape_horizon_H"] = list(c50.shape) + print(f"[probe] candidates(n={a.n}, horizon=8) -> {c8.shape} " + f"candidates(n={a.n}, horizon={pol.H}) -> {c50.shape}", flush=True) + + ok_shape = (tuple(c8.shape) == (a.n, 8, 10)) and (tuple(c50.shape) == (a.n, int(pol.H), 10)) + identical = bool(np.array_equal(c8, c50[:, :8])) + maxabs = float(np.abs(c8 - c50[:, :8]).max()) + rec["shapes_as_expected"] = bool(ok_shape) + rec["truncation_bit_identical"] = identical + rec["max_abs_diff_first8"] = maxabs + print(f"[probe] horizon-8 draw vs first 8 of the horizon-{pol.H} draw: " + f"bit-identical={identical} max|diff|={maxabs:.3e}", flush=True) + + # ---- 4. the other end: horizon > action_horizon silently returns a SHORTER chunk ------------------- + pol.rng = np.random.default_rng([seed, ep]) + over = pol.candidates(obs, 2, int(pol.H) + 10) + rec["shape_horizon_over"] = list(over.shape) + rec["over_horizon_is_truncated_to_H"] = bool(over.shape[1] == int(pol.H)) + print(f"[probe] candidates(horizon={pol.H + 10}) -> {over.shape}: the slice runs out, so asking for more " + f"than action_horizon yields action_horizon steps (downstream that is a BROADCAST ERROR in " + f"err_chunk, not a silent wrong number)", flush=True) + + # ---- 5. spread / first-action reference ----------------------------------------------------------- + f0 = c8[:, 0, :3] + rec["first_action_spread_xyz_cm"] = float(100 * np.linalg.norm(f0 - f0.mean(0), axis=1).mean()) + rec["chunk_span_xyz_cm_h8"] = float(100 * np.linalg.norm(c8[:, 7, :3] - c8[:, 0, :3], axis=1).mean()) + rec["chunk_span_xyz_cm_hH"] = float(100 * np.linalg.norm(c50[:, -1, :3] - c50[:, 0, :3], axis=1).mean()) + + # ---- the verdict ---------------------------------------------------------------------------------- + comparable = bool(ok_shape and identical and int(pol.H) == 50 and rec["configured_horizons"] + .get(a.parent_config, {}).get("action_horizon") == 10) + rec["verdict"] = "COMPARABLE" if comparable else "NOT_COMPARABLE_OR_INCONCLUSIVE" + rec["verdict_reason"] = ( + "--horizon is a pure post-hoc TRUNCATION of the policy's own chunk (twin_rollout.py:216 " + "`np.asarray(a)[:horizon, :10]`). The flow noise is drawn at the MODEL's (action_horizon, action_dim) " + "= (%d,%d), so the chunk-50 model is sampled exactly as it was trained; the returned object is its " + "first 8 steps. gt = A[i:i+8] and the anchor grid range(0, T-8, 25) depend only on --horizon, so a " + "chunk-50 row is measured at the SAME anchors against the SAME 8 logged frames as the 13 chunk-10 rows. " + "The IDQL read-out sees cands[:,0] and the RSM read-out sees an 8-step chunk padded to rsm.chunk -- " + "identical objects in both generations. Nothing is assumed equal to action_horizon, nothing is padded " + "to the reference, and the horizon-8 draw is bit-identical to the first 8 steps of the horizon-50 draw " + "under the same per-episode seed." + % (int(pol.H), int(pol.D)) + if comparable else + "one of the checks failed -- see shapes_as_expected / truncation_bit_identical / configured_horizons") + rec["caveats"] = [ + "NOT bit-comparable, only distributionally comparable: a chunk-50 candidate consumes H*D = %d*%d " + "standard normals from the per-episode stream np.random.default_rng([seed, ep]) where a chunk-10 one " + "consumed 10*%d, so candidate k gets a DIFFERENT (equally iid N(0,1)) noise draw. Means over 25 " + "episodes x ~28 anchors x 128 candidates are comparable; a per-candidate diff against a chunk-10 run " + "is not." % (int(pol.H), int(pol.D), int(pol.D)), + "The remaining difference is the MODEL, which is the point of the screen: the first 8 steps of a " + "chunk-50 policy come from a chunk that was jointly denoised over 50 steps. That is the property " + "being screened, not a measurement artefact.", + "--horizon must be <= action_horizon. At horizon 50 a chunk-10 policy returns 10 steps and " + "err_chunk raises a broadcast error; so the chunk-10 rows can never be re-measured at horizon 50, " + "only the chunk-50 rows can be re-measured at horizon 8 (which is what we do).", + ] + Path(a.out).write_text(json.dumps(rec, indent=1)) + print("[probe] wrote", a.out, flush=True) + print("[probe] VERDICT:", rec["verdict"], flush=True) + return 0 if comparable else 5 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/rsm_rise/scripts/real/pi05_ft50_hprobe.sh b/rsm_rise/scripts/real/pi05_ft50_hprobe.sh new file mode 100644 index 0000000000000000000000000000000000000000..7a62f7b29f89b35383bbf994252e6f1ad0dca834 --- /dev/null +++ b/rsm_rise/scripts/real/pi05_ft50_hprobe.sh @@ -0,0 +1,158 @@ +#!/usr/bin/env bash +# rsm_real#14 / worker ft50scr TASK 1 -- MEASURE what `--horizon 8` means for a chunk-50 pi0.5 policy, before +# any chunk-50 row is added to the 13-row pi0.5 planning screen table. +# +# Why a PINNED COPY of a checkpoint. `_cooking_ft50` and `_cooking_h50` both run with keep_period=50_000 and +# save_interval=500, so until step 50k there is exactly ONE step directory alive at a time and it is deleted +# ~4 min later (measured: 19500 at 05:47Z was already 20000 at 05:52Z). A probe that resolves the newest step +# at submit time races the trainer and dies on a vanished path. So a CPU job copies /params (12 G) + +# /assets (2 K) to runs/openpi/probe_ckpts/_/ -- OUTSIDE the live checkpoint tree, because +# adding a directory beside orbax's own step dirs in a RUNNING training is not worth the risk to a 28 h job -- +# and the GPU pack runs against the frozen copy under -w done(). +# +# Four payloads on 4 GPUs, no idle slot: +# slot0 the code-path probe (pi05_ft50_horizon_probe.py: shapes, truncation bit-identity, over-horizon +# behaviour) THEN a real 1-episode screen of the chunk-50 model at --horizon 8 with pi05_screen.sh's +# COMMON verbatim. +# slot1 the same 1-episode screen at --horizon 50 -- the 50-step read-out, which tells us what we would be +# measuring if the horizon were raised to match the chunk. +# slot2 the SAME 1-episode screen of the CHUNK-10 parent pi05_cooking_stock/stock_s1/29999. This is the +# control that makes the comparability claim empirical rather than code-reading: episode 7 is the +# first held-out episode, and status/real/openloop_pi05stock_s1/scorer_openloop.json already holds +# that episode's row from the full 25-episode chunk-10 screen, so slot2 must REPRODUCE it exactly. +# If it does, the 1-episode probe is a faithful slice of a real screen row and slot0's numbers can be +# read against the table. +# slot3 openpi_replay_eval.py on the chunk-50 checkpoint (TASK 3 smoke test): does the replay eval run at +# action_horizon=50 and does it emit xyz_l2_first_cm AND the *_chunk10_* prefixes that make chunk-50 +# comparable to the chunk-10 generation? +# +# usage: pi05_ft50_hprobe.sh (idempotent: nothing is submitted if the jsons exist or a job is queued) +set -uo pipefail +ROOT=/proj/dmfexp/zwhong/rsm_rise +CK=$ROOT/runs/openpi/checkpoints +GEN=$ROOT/scripts/real/_gen +PSDIR=$ROOT/status/real/pi05_pending_submits +NAME=rr_pi05scr_ft50_hprobe +PIN_NAME=rr_cpu_pi05scr_ft50_pin +PIN_CFG=${PIN_CFG:-pi05_cooking_stock_ft50_s0} +PIN_EXP=${PIN_EXP:-stock_s0_ft50} +PINROOT=$ROOT/runs/openpi/probe_ckpts +HZJSON=$ROOT/status/real/pi05_ft50_screen_horizon.json +C10CK=$CK/pi05_cooking_stock/stock_s1/29999 + +RSM=$ROOT/runs/real_cooking_v5/rsm/R_M/ckpt_s100000.pt +IDQL=$ROOT/runs/cooking_v5_expert_suboptimal/policy/S0Aidql_seed1/cooking_v5_expert_suboptimal_S0Aidql_s1/20260921235824/models/model_epoch_3000.pth +# COPIED VERBATIM from pi05_screen.sh's COMMON, minus --horizon (each slot sets its own) so the rows stay +# comparable to the existing 13. +COMMON_NOH="--idql-ckpt $IDQL --rsm-ckpt $RSM --rsm-mode d1 --rsm-depth 1 --rsm-beta 0.99 \ + --rsm-score-kind prob --rsm-temperature 25 --n-cand 128 --stride 25 --max-eps 1" + +mkdir -p "$GEN" "$PSDIR" "$PINROOT" + +if [ -e "$HZJSON" ]; then + echo "[hprobe] TASK 1 already answered -> $HZJSON" + python3 -c "import json;d=json.load(open('$HZJSON'));print('[hprobe] verdict:',d['verdict'])" 2>/dev/null + exit 0 +fi + +# ---------------------------------------------------------------- duplicate guard (pi05_screen_sweep.sh run 13/14) +JOBS=""; JOBS_OK=0 +for try in 1 2 3; do + out=$(bjobs -o "job_name stat" -noheader 2>&1); rc=$? + if [ $rc -eq 0 ] && [ -n "$out" ]; then JOBS="$out"; JOBS_OK=1; break; fi + case "$out" in *"No unfinished job found"*) JOBS=""; JOBS_OK=1; break;; esac + echo "[hprobe] bjobs attempt $try failed (rc=$rc): ${out:-}"; [ $try -lt 3 ] && sleep 5 +done +[ "$JOBS_OK" = 1 ] || { echo "[hprobe] ABORT: cannot read the LSF job table; refusing to submit"; exit 0; } +# clear a marker whose job we can now see in the table +for m in "$PSDIR"/hprobe "$PSDIR"/hprobe_pin; do + [ -e "$m" ] || continue + want=$NAME; [ "$(basename "$m")" = hprobe_pin ] && want=$PIN_NAME + printf '%s\n' "$JOBS" | grep -qE "^${want} +" && { rm -f "$m"; echo "[hprobe] cleared confirmed marker $(basename "$m")"; } +done +for p in "$NAME" "$PIN_NAME"; do + if printf '%s\n' "$JOBS" | grep -qE "^${p} +(PEND|RUN|PSUSP|USUSP|SSUSP)$"; then + echo "[hprobe] $p already queued/running -- nothing to do"; exit 0 + fi +done +if [ -e "$PSDIR/hprobe" ] || [ -e "$PSDIR/hprobe_pin" ]; then + echo "[hprobe] an UNCONFIRMED submission marker exists ($PSDIR/hprobe*) -- confirm with" + echo " 'bjobs -w | grep -E \"$NAME|$PIN_NAME\"' / 'bhist -n 2 -J $NAME' and delete it first"; exit 0 +fi + +# ---------------------------------------------------------------- the pin payload (CPU job, resolves at RUN time) +cat > "$GEN/${PIN_NAME}.sh" </dev/null | sed 's|.*/||' | sort -n | tail -1) + [ -n "\$st" ] || { echo "[pin] no step dir under \$SRC yet (attempt \$attempt)"; sleep 30; continue; } + dst=$PINROOT/${PIN_CFG}_\$st + if [ -e "\$dst/.complete" ]; then echo "[pin] already pinned: \$dst"; echo "\$dst" > $PINROOT/LATEST; exit 0; fi + echo "[pin] attempt \$attempt: copying \$SRC/\$st -> \$dst (\$(date -u))" + rm -rf "\$dst.tmp"; mkdir -p "\$dst.tmp" + if cp -r "\$SRC/\$st/params" "\$dst.tmp/params" && cp -r "\$SRC/\$st/assets" "\$dst.tmp/assets"; then + cp "\$SRC/\$st/_CHECKPOINT_METADATA" "\$dst.tmp/_CHECKPOINT_METADATA" 2>/dev/null + echo "step=\$st src=\$SRC/\$st pinned=\$(date -u)" > "\$dst.tmp/.complete" + rm -rf "\$dst"; mv "\$dst.tmp" "\$dst" + echo "\$dst" > $PINROOT/LATEST + echo "[pin] OK step \$st -> \$dst (\$(du -sh \$dst | cut -f1))"; exit 0 + fi + echo "[pin] copy of step \$st failed (the trainer probably rotated it) -- retrying with the new newest" + rm -rf "\$dst.tmp"; sleep 10 +done +echo "[pin] FAILED after 5 attempts"; exit 4 +PIN +chmod +x "$GEN/${PIN_NAME}.sh" + +printf '%s submitted %s; job id unconfirmed until a later run sees it\n' "$(date -u +'%F %H:%M UTC')" "$PIN_NAME" \ + > "$PSDIR/hprobe_pin" +mkdir -p "$ROOT/logs/lsf" +pin_out=$(bsub -G grp_runtime -q normal -n 8 -M 64G -J "$PIN_NAME" \ + -o "$ROOT/logs/lsf/$PIN_NAME.%J.out" -e "$ROOT/logs/lsf/$PIN_NAME.%J.err" \ + bash "$GEN/${PIN_NAME}.sh" 2>&1) +echo "[hprobe] pin: $pin_out" +PINJOB=$(printf '%s' "$pin_out" | sed -n 's/.*<\([0-9]\+\)>.*/\1/p' | head -1) +[ -n "$PINJOB" ] || { echo "[hprobe] pin submission gave no job id -- marker kept, aborting the pack"; exit 4; } + +# ---------------------------------------------------------------- the four GPU payloads +_slot () { # _slot + local i=$1; shift + { echo '#!/usr/bin/env bash'; echo "# ft50scr TASK 1 probe, slot $i"; echo 'set -uo pipefail' + echo "cd $ROOT"; echo "PIN=\$(cat $PINROOT/LATEST)"; echo 'echo "[slot'"$i"'] pinned ckpt=$PIN"' + printf '%s\n' "$@"; echo 'echo "[slot'"$i"'] done rc=$? $(date -u)"'; } > "$GEN/${NAME}_slot$i.sh" + chmod +x "$GEN/${NAME}_slot$i.sh" +} + +_slot 0 \ + "$ROOT/scripts/real/run_env_openpi.sh $ROOT/scripts/real/pi05_ft50_horizon_probe.py \\ + --ckpt \"\$PIN\" --config $PIN_CFG --parent-config pi05_cooking_stock \\ + --out $ROOT/status/real/pi05_ft50_screen_horizon.json" \ + "$ROOT/scripts/real/run_env_openpi.sh $ROOT/scripts/real/scorer_openloop.py \\ + --policy \"openpi:$PIN_CFG:\$PIN\" $COMMON_NOH --horizon 8 \\ + --tag pi05hprobe_ft50_h8_e1 --out $ROOT/status/real/openloop_pi05hprobe_ft50_h8_e1" + +_slot 1 \ + "$ROOT/scripts/real/run_env_openpi.sh $ROOT/scripts/real/scorer_openloop.py \\ + --policy \"openpi:$PIN_CFG:\$PIN\" $COMMON_NOH --horizon 50 \\ + --tag pi05hprobe_ft50_h50_e1 --out $ROOT/status/real/openloop_pi05hprobe_ft50_h50_e1" + +_slot 2 \ + "# the chunk-10 control: must REPRODUCE episode 7's row in openloop_pi05stock_s1/scorer_openloop.json" \ + "$ROOT/scripts/real/run_env_openpi.sh $ROOT/scripts/real/scorer_openloop.py \\ + --policy \"openpi:pi05_cooking_stock:$C10CK\" $COMMON_NOH --horizon 8 \\ + --tag pi05hprobe_c10stock_s1_h8_e1 --out $ROOT/status/real/openloop_pi05hprobe_c10stock_s1_h8_e1" + +_slot 3 \ + "# TASK 3 smoke test: openpi_replay_eval.py at action_horizon 50, does it emit the *_chunk10_* prefixes?" \ + "$ROOT/scripts/real/openpi_eval.sh $ROOT/scripts/real/openpi_replay_eval.py \\ + --config $PIN_CFG --ckpt \"\$PIN\" --max-eps 3 \\ + --out $ROOT/status/real/pi05_ft50_hprobe_replay" + +printf '%s submitted %s (4-GPU pack, dep on pin job %s); job id unconfirmed until a later run sees it\n' \ + "$(date -u +'%F %H:%M UTC')" "$NAME" "$PINJOB" > "$PSDIR/hprobe" +RR_GPUS=4 RR_MEM=96G RR_DEP="done($PINJOB)" \ + bash $ROOT/scripts/bsub_gpu_pack.sh $NAME \ + "$GEN/${NAME}_slot0.sh" "$GEN/${NAME}_slot1.sh" "$GEN/${NAME}_slot2.sh" "$GEN/${NAME}_slot3.sh" 2>&1 | tail -3 diff --git a/rsm_rise/scripts/real/pi05_ft50_keepperiod_fallback.sh b/rsm_rise/scripts/real/pi05_ft50_keepperiod_fallback.sh new file mode 100644 index 0000000000000000000000000000000000000000..413406ac2af4b58712b70fd9d60cc610559aa737 --- /dev/null +++ b/rsm_rise/scripts/real/pi05_ft50_keepperiod_fallback.sh @@ -0,0 +1,42 @@ +#!/usr/bin/env bash +# rsm_real#14 (stream PI05_FT) -- DISK FALLBACK, armed 2026-09-25 run 10, NOT fired automatically. +# +# WHY: the plan keeps checkpoints at every keep_period=50_000 -> 50k/100k/150k/199999 = 4 keeps x 42 GB x 8 runs +# = 1.34 TB by 200k. The brief's fallback is keep_period=100_000 (2 keeps -> 672 GB) "only if free < 800 G". +# +# GATE (measured, run 10): free on /proj/dmfexp is a SAWTOOTH, not a monotone fall -- 794 G ... 1050 G inside +# 90 s, because eight concurrent trainings each stage a 42 GB orbax tmp dir every 500 steps (~336 GB of +# self-inflicted oscillation) on top of other streams. So fire on the PEAK of several df samples, not on one +# trough: for i in 1 2 3 4 5 6; do df --output=avail -BG /proj/dmfexp | tail -1; sleep 15; done +# -> if the LARGEST of those is < 800 G, fire. A single trough below 800 G is not the signal. +# +# SEQUENCING: with keep_period=100_000 the EXISTING step-50000 checkpoints stop matching the keep rule and +# orbax garbage-collects them at the next save. Their metrics are already extracted (replay_50000/ +# replay_eval.json + status/real/openloop_pi05*_50000/scorer_openloop.json), but the 50k SCREENS read the +# weights, so do NOT fire while any rr_pi05scr_ft50_* job is RUN/PEND. My stream adds no NEW keep until +# ~16:15Z (100k), so there is no growth pressure from PI05_FT before then -- waiting costs nothing. +set -uo pipefail +ROOT=/proj/dmfexp/zwhong/rsm_rise +CFG=$ROOT/third_party/openpi/src/openpi/training/config.py + +if bjobs -o "job_name stat" -noheader 2>/dev/null | grep -q "rr_pi05scr_ft50"; then + echo "[fallback] REFUSING: a 50k screen is still RUN/PEND and would lose the weights it is reading."; exit 5 +fi + +n=$(grep -c "keep_period=50_000," "$CFG") +[ "$n" = "2" ] || { echo "[fallback] expected 2 keep_period=50_000 lines (h50 factory + ft50 factory), found $n"; exit 3; } +cp "$CFG" "$CFG.bak.keepperiod.$(date -u +%Y%m%d_%H%M%S)" +sed -i 's/keep_period=50_000,/keep_period=100_000, # DISK FALLBACK 2026-09-25: free < 800 G, see rsm_real#14/' "$CFG" +grep -n "keep_period=100_000, # DISK FALLBACK" "$CFG" || { echo "[fallback] edit did not apply"; exit 4; } + +echo "[fallback] killing the 7 fine-tunes + the from-base control so they restart under the new keep_period" +for jn in rr_ft50_stock_s0_ft50 rr_ft50_stock_s1_ft50 rr_ft50_rise_s0_ft50 rr_ft50_rise_s1_ft50 \ + rr_ft50_riseadv_s0_ft50 rr_ft50_sn1_knn0p03_ft50 rr_ft50_sn0p1_knn0p03_ft50 rr_h50_stock_s0_h50; do + bkill -J "$jn" 2>&1 | sed "s/^/[fallback] /" +done +sleep 30 +bash $ROOT/scripts/real/pi05_ft50_launch.sh # resumes every exp from its newest checkpoint +RR_GPUS=8 bash $ROOT/scripts/bsub_gpu_multi.sh rr_h50_stock_s0_h50 \ + $ROOT/scripts/real/openpi_train.sh pi05_cooking_stock_h50 stock_s0_h50 --seed 0 +echo "[fallback] done -- check: bjobs -o \"nreq_slot job_name\" (64 = correct 8-GPU training, 8 = the 1-GPU bug)" +echo "[fallback] and re-verify the vendored patch: bash $ROOT/scripts/real/pi05_ft50_rebuild_patch.sh" diff --git a/rsm_rise/scripts/real/pi05_ft50_launch.sh b/rsm_rise/scripts/real/pi05_ft50_launch.sh new file mode 100644 index 0000000000000000000000000000000000000000..42232540b025bdd135bb4deff46e0ca53c69bd22 --- /dev/null +++ b/rsm_rise/scripts/real/pi05_ft50_launch.sh @@ -0,0 +1,42 @@ +#!/usr/bin/env bash +# rsm_real#14 (stream PI05_FT): launch the pi0.5 flagship FINE-TUNES -- 200k steps, action chunk 50 (1.000 s +# @ 50 Hz), warm-started from the published flagship checkpoints. One 8-GPU node each (CLAUDE.md: never a +# 1-GPU job; `nreq_slot` must read 64, not 8). Idempotent: openpi_train.sh --resume's any exp that already +# has a checkpoint, so re-running this after a preemption is the correct recovery. +# +# cfg:exp:SEED -- the seed is an explicit tyro override, NOT a config field. TrainConfig.seed defaults to 42, +# so omitting it makes s0 and s1 bit-identical runs (that bug cost PI05_200K a relaunch, LSF 1909408-12). +# Each fine-tune inherits its PARENT's seed so the data order continues the run it warm-starts from. +set -uo pipefail +ROOT=/proj/dmfexp/zwhong/rsm_rise + +PAIRS="\ +pi05_cooking_stock_ft50_s0:stock_s0_ft50:0 \ +pi05_cooking_stock_ft50_s1:stock_s1_ft50:1 \ +pi05_cooking_rise_ft50_s0:rise_s0_ft50:0 \ +pi05_cooking_rise_ft50_s1:rise_s1_ft50:1 \ +pi05_cooking_riseadv_ft50_s0:riseadv_s0_ft50:0 \ +pi05_cooking_sn1_knn0p03_ft50_s0:sn1_knn0p03_ft50:0 \ +pi05_cooking_sn0p1_knn0p03_ft50_s0:sn0p1_knn0p03_ft50:0" + +# Preflight: the norm stats behind assets_dirs must be the PARENT's per-frame train-split file. A warm start +# under different normalisation silently moves the regression targets, so this is a hard gate, not a warning. +WANT_MD5=da20b66d4beb1dae800603b6745623c3 +for p in $PAIRS; do + cfg=${p%%:*} + f=$ROOT/runs/openpi/assets/$cfg/jmarangola/rsm_cooking_v5/norm_stats.json + [ -s "$f" ] || { echo "MISSING norm stats for $cfg ($f)"; exit 3; } + got=$(md5sum "$f" | awk '{print $1}') + [ "$got" = "$WANT_MD5" ] || { echo "WRONG norm stats for $cfg: $got != $WANT_MD5 (parent per-frame file)"; exit 4; } +done +echo "[launch] norm-stats preflight OK (all 7 resolve to the parent per-frame file $WANT_MD5)" + +for p in $PAIRS; do + cfg=${p%%:*}; rest=${p#*:}; exp=${rest%%:*}; sd=${rest##*:} + d=$ROOT/runs/openpi/checkpoints/$cfg/$exp + if ls -d "$d"/[0-9]* >/dev/null 2>&1; then + echo "[launch] $exp already has checkpoints -- the runner will RESUME (correct for a rerun/preemption)" + fi + echo "[launch] $cfg $exp --seed $sd" + RR_GPUS=8 bash $ROOT/scripts/bsub_gpu_multi.sh rr_ft50_$exp $ROOT/scripts/real/openpi_train.sh $cfg $exp --seed $sd +done diff --git a/rsm_rise/scripts/real/pi05_ft50_pin_early.sh b/rsm_rise/scripts/real/pi05_ft50_pin_early.sh new file mode 100644 index 0000000000000000000000000000000000000000..eba6e6ebadbccb31157ba7b903f2179d67c849ad --- /dev/null +++ b/rsm_rise/scripts/real/pi05_ft50_pin_early.sh @@ -0,0 +1,102 @@ +#!/bin/bash +# PI05_FT (rsm_real#14): pin a PARAMS-ONLY copy of the current rolling checkpoint for the fine-tunes +# whose held-out first-10 prefix is DEGRADING, so that selection at 200k has an early fallback. +# +# Why this exists. keep_period=50_000 means the earliest RETAINED checkpoint is 50k; save_interval=500 +# keeps only ONE rolling step dir, which is replaced every ~500 steps (~4 min at 2.15 steps/s). So today +# there is nothing retained between step 0 and step 50k. The run-4 curve shows riseadv_s0 / sn1_knn0p03 / +# sn0p1_knn0p03 losing first-10 accuracy monotonically (sn1: 1.657 @5k -> 1.818 @19k) while their full +# chunk-50 error is flat since ~5k -- i.e. their best checkpoint may well be EARLIER than the first keep. +# params is 12 G, train_state is 31 G; the screens load `params` only, so we copy params and skip the +# optimiser state. 3 x 12 G = 36 G, checked against df before writing. +# +# The source dir can be DELETED mid-copy by the trainer. Orbax step dirs are immutable once complete, so +# the only failure mode is deletion: we rsync, then re-assert the source still exists. If it vanished we +# retry with the new newest step. Nothing here ever writes into runs/openpi/checkpoints. +set -uo pipefail +cd /proj/dmfexp/zwhong/rsm_rise + +DEST=runs/openpi/probe_ckpts +MIN_FREE_GB=${MIN_FREE_GB:-500} + +RUNS=" +pi05_cooking_riseadv_ft50_s0/riseadv_s0_ft50 +pi05_cooking_sn1_knn0p03_ft50_s0/sn1_knn0p03_ft50 +pi05_cooking_sn0p1_knn0p03_ft50_s0/sn0p1_knn0p03_ft50 +" + +free_gb() { df -BG --output=avail /proj/dmfexp | tail -1 | tr -dc '0-9'; } + +echo "[pin] df free before: $(free_gb) G (floor ${MIN_FREE_GB} G)" +mkdir -p "$DEST" + +rc_all=0 +for rel in $RUNS; do + exp=$(basename "$rel") + cfg=$(dirname "$rel") + if [ "$(free_gb)" -lt "$MIN_FREE_GB" ]; then + echo "[pin] REFUSING $exp: only $(free_gb) G free, floor ${MIN_FREE_GB} G"; rc_all=4; continue + fi + # already pinned for this run? one early pin per run is the point; skip if present. + if compgen -G "$DEST/${cfg}_[0-9]*/.complete" >/dev/null 2>&1; then + echo "[pin] $exp: already has an early pin ($(ls -d $DEST/${cfg}_[0-9]* | tr '\n' ' ')), skipping"; continue + fi + ok=0 + for attempt in 1 2 3 4 5; do + src=$(ls -d runs/openpi/checkpoints/$rel/[0-9]* 2>/dev/null | awk -F/ '{print $NF, $0}' | sort -n | tail -1 | cut -d' ' -f2-) + if [ -z "${src:-}" ]; then echo "[pin] $exp attempt $attempt: no step dir yet"; sleep 20; continue; fi + step=$(basename "$src") + if [ ! -d "$src/params" ]; then echo "[pin] $exp attempt $attempt: $step has no params/ yet"; sleep 20; continue; fi + tgt="$DEST/${cfg}_${step}" + tmp="$tgt.partial.$$" + echo "[pin] $exp attempt $attempt: $src -> $tgt" + rm -rf "$tmp"; mkdir -p "$tmp" + # PARALLEL copy. A single-stream rsync of the 12 G params dir runs ~4.5 min, but the trainer replaces + # the rolling step dir every 500 steps = ~3.9 min at 2.15 steps/s -- so a serial copy LOSES THE RACE every + # time (observed: LSF 1910834 attempt 1 died with rsync rc=23, "failed to open ... Not a directory", which + # is what a mid-copy deletion looks like). Splitting the file list over 8 streams brings it to ~1 min, + # comfortably inside the window. -n 8 is what the job requests. + mkdir -p "$tmp/params" + ( cd "$src/params" && find . -type d -print0 ) | ( cd "$tmp/params" && xargs -0 -r mkdir -p ) 2>/dev/null + ( cd "$src/params" && find . -type f -printf '%f\t%s\t%p\n' ) 2>/dev/null \ + | sort -k2,2nr | awk -F'\t' '{print $3}' > "$tmp/.filelist" + nf=$(wc -l < "$tmp/.filelist") + # round-robin by descending size so every stream gets a mix of large and small files + awk -v n=8 'NR%n==0{print > "'"$tmp"'/.fl0"} NR%n==1{print > "'"$tmp"'/.fl1"} NR%n==2{print > "'"$tmp"'/.fl2"} NR%n==3{print > "'"$tmp"'/.fl3"} NR%n==4{print > "'"$tmp"'/.fl4"} NR%n==5{print > "'"$tmp"'/.fl5"} NR%n==6{print > "'"$tmp"'/.fl6"} NR%n==7{print > "'"$tmp"'/.fl7"}' "$tmp/.filelist" + echo "[pin] $exp attempt $attempt: $nf files over 8 streams" + r=0 + for k in 0 1 2 3 4 5 6 7; do + [ -s "$tmp/.fl$k" ] || continue + rsync -a --files-from="$tmp/.fl$k" "$src/params/" "$tmp/params/" > "$tmp/.rsync.$k.log" 2>&1 & + done + wait + for k in 0 1 2 3 4 5 6 7; do + [ -s "$tmp/.rsync.$k.log" ] && { r=1; tail -2 "$tmp/.rsync.$k.log"; } + done + [ -e "$src/_CHECKPOINT_METADATA" ] && rsync -a "$src/_CHECKPOINT_METADATA" "$tmp/" 2>/dev/null + [ -d "$src/assets" ] && rsync -a "$src/assets" "$tmp/" 2>/dev/null + # the ONLY failure mode for an immutable orbax dir is deletion mid-copy -- re-assert it. + if [ $r -ne 0 ] || [ ! -d "$src/params" ]; then + echo "[pin] $exp attempt $attempt: source rolled away (rsync rc=$r), retrying"; rm -rf "$tmp"; continue + fi + if [ ! -s "$tmp/params/_METADATA" ] || [ ! -e "$tmp/params/manifest.ocdbt" ]; then + echo "[pin] $exp attempt $attempt: copy incomplete (_METADATA/manifest.ocdbt missing), retrying"; rm -rf "$tmp"; continue + fi + sb=$(du -sb "$src/params" | cut -f1); tb=$(du -sb "$tmp/params" | cut -f1) + if [ "$sb" != "$tb" ]; then + echo "[pin] $exp attempt $attempt: size mismatch src=$sb copy=$tb, retrying"; rm -rf "$tmp"; continue + fi + rm -f "$tmp"/.rsync.*.log "$tmp"/.filelist "$tmp"/.fl[0-7] + date -u +%Y-%m-%dT%H:%M:%SZ > "$tmp/.complete" + echo "$src" >> "$tmp/.complete" + rm -rf "$tgt"; mv "$tmp" "$tgt" + echo "[pin] $exp OK: $tgt ($(du -sh $tgt/params | cut -f1), from step $step)" + ok=1; break + done + [ $ok -eq 1 ] || { echo "[pin] $exp FAILED after 5 attempts"; rc_all=5; } +done + +echo "[pin] df free after: $(free_gb) G" +echo "[pin] pins now:"; for d in $DEST/*/; do [ -e "$d/.complete" ] && echo " $d $(du -sh $d 2>/dev/null | cut -f1) <- $(sed -n 2p $d/.complete)"; done +ls -d $DEST/pi05_cooking_* 2>/dev/null | sed 's#.*/##' > $DEST/LATEST_PINS +exit $rc_all diff --git a/rsm_rise/scripts/real/pi05_ft50_pr12.sh b/rsm_rise/scripts/real/pi05_ft50_pr12.sh new file mode 100644 index 0000000000000000000000000000000000000000..4b2b3294a5ca1230a15cbf9a1d9b93ed2c85c3b1 --- /dev/null +++ b/rsm_rise/scripts/real/pi05_ft50_pr12.sh @@ -0,0 +1,12 @@ +#!/usr/bin/env bash +set -euo pipefail +ROOT=/proj/dmfexp/zwhong/rsm_rise +WT=/proj/dmfexp/zwhong/scratch_pi05_200k/rsm_real +PY=$ROOT/third_party/openpi/.venv/bin/python +$PY $ROOT/scripts/real/pi05_ft50_update_pr12.py "$WT" "$ROOT/status/real/pi05_ft50_section.md" +echo "=================== idempotence: run it twice ===================" +$PY $ROOT/scripts/real/pi05_ft50_update_pr12.py "$WT" "$ROOT/status/real/pi05_ft50_section.md" +cd $WT && git --no-pager diff --stat +echo "=================== headings after ===================" +grep -n "^## \|^### " rise_stack/CHECKPOINTS.md | sed -n '1,25p' +echo PR12_JOB_DONE diff --git a/rsm_rise/scripts/real/pi05_ft50_pr13.sh b/rsm_rise/scripts/real/pi05_ft50_pr13.sh new file mode 100644 index 0000000000000000000000000000000000000000..a8d9fd31bce885815678bac8ac0079ee61373f84 --- /dev/null +++ b/rsm_rise/scripts/real/pi05_ft50_pr13.sh @@ -0,0 +1,31 @@ +#!/usr/bin/env bash +# One CPU LSF job for the whole of PR #13's mechanical work: +# rebuild the patch (3 blocks) -> assert 0 lines dropped -> git apply --check -> py_compile +# -> install it in the worktree -> renumber README.md / SETUP.md FROM THE PATCH BYTES -> 20 guard tests. +# Leaves the worktree dirty but uncommitted; the main session reads this log and commits. +set -euo pipefail +ROOT=/proj/dmfexp/zwhong/rsm_rise +WT=/proj/dmfexp/zwhong/scratch_pi05_200k/rsm_real_scaffold +WORK=/proj/dmfexp/zwhong/scratch_pi05_200k/openpi_rebuild_ft50 +PY=$ROOT/third_party/openpi/.venv/bin/python + +bash $ROOT/scripts/real/pi05_ft50_rebuild_patch.sh "$WT" + +echo "=================== install into the worktree ===================" +cp $WORK/rise_on_pi05.patch $WT/rise_stack/openpi/rise_on_pi05.patch +cd $WT && git --no-pager diff --stat -- rise_stack/openpi/rise_on_pi05.patch + +echo "=================== renumber the docs from the patch bytes ===================" +$PY $ROOT/scripts/real/pi05_ft50_renumber_docs.py "$WT" + +echo "=================== guard tests ===================" +cd $WT && $PY -m pytest tests/test_rise_stack_openpi_patch_numbers.py -q 2>&1 | tail -30 + +echo "=================== worktree diff summary ===================" +cd $WT && git --no-pager diff --stat +echo "=================== doc numbers now in the tree ===================" +grep -n "insertions and" $WT/rise_stack/openpi/README.md || true +grep -n "files, total" $WT/rise_stack/openpi/README.md || true +grep -n "inserted lines on top of upstream commit" $WT/SETUP.md || true +grep -n "pi05_cooking_\*\` \`TrainConfig\|declares" $WT/rise_stack/openpi/README.md | head || true +echo "PR13_JOB_DONE" diff --git a/rsm_rise/scripts/real/pi05_ft50_pytest.sh b/rsm_rise/scripts/real/pi05_ft50_pytest.sh new file mode 100644 index 0000000000000000000000000000000000000000..27e963a589a1a3453239217af612e69fb7a4313e --- /dev/null +++ b/rsm_rise/scripts/real/pi05_ft50_pytest.sh @@ -0,0 +1,4 @@ +#!/usr/bin/env bash +cd /proj/dmfexp/zwhong/scratch_pi05_200k/rsm_real_scaffold +/proj/dmfexp/zwhong/rsm_rise/third_party/openpi/.venv/bin/python -m pytest tests/test_rise_stack_openpi_patch_numbers.py -q 2>&1 | tail -25 +echo FT50_PYTEST_DONE diff --git a/rsm_rise/scripts/real/pi05_ft50_rebuild_patch.sh b/rsm_rise/scripts/real/pi05_ft50_rebuild_patch.sh new file mode 100644 index 0000000000000000000000000000000000000000..cf5c7b36973b5553b110821eced8c8107eb30b7e --- /dev/null +++ b/rsm_rise/scripts/real/pi05_ft50_rebuild_patch.sh @@ -0,0 +1,129 @@ +#!/usr/bin/env bash +# Rebuild rsm_real's vendored openpi patch so it carries THREE of our blocks instead of two: +# 1. `_cooking_h50` -- the from-base chunk-50 configs (KEPT: LSF 1909448 stock_s0_h50 still trains on it) +# 2. `_cooking_ft50` -- NEW: the seven pi0.5 flagship FINE-TUNES at chunk 50 (rsm_real#14 / rsm_rise PI05_FT) +# 3. fit_metrics' `*_chunk10_*` variants in scripts/train.py +# +# Same discipline as scripts/real/pi05_h50_rebuild_patch.sh (do not "improve" it): the shipped patch is NOT a +# `git diff` of the rsm_rise openpi tree (that tree carries the run-54 factorial configs the patch has never +# shipped, and the patch carries the rsm_real#5 inference-split fix that was never back-ported). So: replay +# the shipped patch AS OF THE BRANCH POINT onto pristine upstream, apply ONLY our blocks on top, re-diff, and +# assert that the new patch drops nothing. +set -euo pipefail +ROOT=/proj/dmfexp/zwhong/rsm_rise +WT=${1:-/proj/dmfexp/zwhong/scratch_pi05_200k/rsm_real_scaffold} +BASE_REF=${2:-2dc85c8} # the branch point: the patch WITHOUT any chunk-50 block +WORK=/proj/dmfexp/zwhong/scratch_pi05_200k/openpi_rebuild_ft50 +PIN=$(head -1 $WT/rise_stack/openpi/UPSTREAM_COMMIT.txt) +rm -rf $WORK; mkdir -p $WORK/up +cd $WT && git show "$BASE_REF:rise_stack/openpi/rise_on_pi05.patch" > $WORK/base.patch +# the patch currently COMMITTED on the branch (h50 + chunk10), the one the 0-dropped-lines assertion must +# respect. Read it from HEAD, not from the working tree: on a re-run the working tree already holds the NEW +# patch, and comparing it against itself would silently turn the subset assertion into a tautology. +git show "HEAD:rise_stack/openpi/rise_on_pi05.patch" > $WORK/current.patch +echo "[rebuild] pin=$PIN base=$BASE_REF base.patch=$(wc -l < $WORK/base.patch) current.patch=$(wc -l < $WORK/current.patch) lines" +cd $ROOT/third_party/openpi && git archive "$PIN" | tar -x -C $WORK/up +cd $WORK/up +git init -q && git add -A && git -c user.email=rr@local -c user.name=rr commit -qm "upstream $PIN" +echo "[rebuild] ---- git apply --check of the BASE patch onto pristine $PIN ----" +git apply --check $WORK/base.patch && echo "[rebuild] BASE PATCH APPLIES CLEAN" +git apply $WORK/base.patch + +echo "[rebuild] ---- insert the _h50 block, the NEW _ft50 block, and the chunk10 fit metrics ----" +python3 - "$ROOT" <<'PY' +import sys, pathlib +root = pathlib.Path(sys.argv[1]) + +H50_MARK = "# ---- rsm_rise (#263 follow-up, owner 2026-09-25): CHUNK-50 200k cooking fine-tunes" +FT50_MARK = "# ---- rsm_rise / rsm_real#14: pi0.5 flagship FINE-TUNES to 200k steps at chunk 50" +ANCHOR = "if len({config.name for config in _CONFIGS}) != len(_CONFIGS):" + +# 1+2. the two TrainConfig blocks, verbatim from the live rsm_rise config.py so the two trees can never drift +live = (root / "third_party/openpi/src/openpi/training/config.py").read_text() +h50_s, ft50_s = live.index(H50_MARK), live.index(FT50_MARK) +assert h50_s < ft50_s, "expected the _h50 block to precede the _ft50 block" +end = live.index(ANCHOR, ft50_s) +h50 = live[h50_s:ft50_s] +ft50 = live[ft50_s:end] +p = pathlib.Path("src/openpi/training/config.py") +src = p.read_text() +assert src.count(ANCHOR) == 1, src.count(ANCHOR) +assert "_cooking_h50" not in src and "_cooking_ft50" not in src and "_cooking_200k" not in src, \ + "base patch already carries a chunk-50 / continuation block" +p.write_text(src.replace(ANCHOR, h50 + ft50 + ANCHOR)) +print(f"[rebuild] config.py: _h50 block {len(h50):6d} chars / {h50.count(chr(10)):4d} lines") +print(f"[rebuild] config.py: _ft50 block {len(ft50):6d} chars / {ft50.count(chr(10)):4d} lines (NEW)") + +# 3. the *_chunk10_* fit metrics, verbatim from the live rsm_rise train.py +livet = (root / "third_party/openpi/scripts/train.py").read_text() +s2 = livet.index(" # rsm_rise (owner 2026-09-25, chunk 50): the *_chunk_* means above run over") +e2 = livet.index(" return m", s2) +fit = livet[s2:e2] +q = pathlib.Path("scripts/train.py") +t = q.read_text() +a2 = ''' for i, n in enumerate(ACT_NAMES): + m[f"mse_{n}"] = float((d[..., i] ** 2).mean()) + return m''' +assert t.count(a2) == 1, t.count(a2) +q.write_text(t.replace(a2, a2[:-len(" return m")] + fit + " return m")) +print(f"[rebuild] train.py: inserted {len(fit)} chars / {fit.count(chr(10))} lines") +PY + +git add -A +git diff --cached HEAD > $WORK/rise_on_pi05.patch +echo "[rebuild] new patch: $(wc -l < $WORK/rise_on_pi05.patch) lines" + +echo "[rebuild] ---- verify the NEW patch applies clean to pristine upstream $PIN ----" +rm -rf $WORK/verify; mkdir -p $WORK/verify +cd $ROOT/third_party/openpi && git archive "$PIN" | tar -x -C $WORK/verify +cd $WORK/verify && git init -q && git add -A && git -c user.email=rr@local -c user.name=rr commit -qm base +git apply --check $WORK/rise_on_pi05.patch && echo "[rebuild] NEW PATCH APPLIES CLEAN" +git apply $WORK/rise_on_pi05.patch +PY=$ROOT/third_party/openpi/.venv/bin/python +$PY -c "import ast;ast.parse(open('src/openpi/training/config.py').read());print('[rebuild] patched config.py parses')" +$PY -c "import ast;ast.parse(open('scripts/train.py').read());print('[rebuild] patched train.py parses')" +$PY -m py_compile src/openpi/training/config.py scripts/train.py && echo "[rebuild] py_compile OK on both patched files" + +echo "[rebuild] ---- 0-lines-dropped: the CURRENT branch patch's line set must be a SUBSET of the new one ----" +$PY - "$WORK" <<'PY' +import collections, pathlib, sys +w = pathlib.Path(sys.argv[1]) +def bag(f): + c = collections.Counter() + for ln in (w / f).read_text().splitlines(): + if ln.startswith("index ") or ln.startswith("@@"): + continue # blob hashes and hunk headers legitimately shift + c[ln] += 1 + return c +for old in ("current.patch", "base.patch"): + o, n = bag(old), bag("rise_on_pi05.patch") + missing = o - n + tot = sum(missing.values()) + print(f"[rebuild] lines of {old} NOT in the new patch (must be 0): {tot}") + for ln, k in list(missing.items())[:20]: + print(f" x{k} {ln!r}") + assert tot == 0, f"{old}: the new patch DROPS {tot} lines" +PY + +echo "[rebuild] ---- +ins/-del, current vs new ----" +$PY - "$WORK" <<'PY' +import pathlib, sys +w = pathlib.Path(sys.argv[1]) +def numstat(f): + files, cur = {}, None + for ln in (w / f).read_text().splitlines(): + if ln.startswith("diff --git "): + cur = ln.split(" b/")[-1]; files.setdefault(cur, [0, 0]) + elif ln.startswith(("+++ ", "--- ", "@@")): + continue + elif cur and ln.startswith("+"): + files[cur][0] += 1 + elif cur and ln.startswith("-"): + files[cur][1] += 1 + return files +for f in ("current.patch", "rise_on_pi05.patch"): + fs = numstat(f) + ti, td = sum(v[0] for v in fs.values()), sum(v[1] for v in fs.values()) + print(f"[rebuild] {f:22s} {len(fs)} files +{ti} / -{td}") +PY +echo "[rebuild] OK -> $WORK/rise_on_pi05.patch" diff --git a/rsm_rise/scripts/real/pi05_ft50_reclaim_killed.sh b/rsm_rise/scripts/real/pi05_ft50_reclaim_killed.sh new file mode 100644 index 0000000000000000000000000000000000000000..86dcee8935ecc34cfc76e94248c12f88e297a578 --- /dev/null +++ b/rsm_rise/scripts/real/pi05_ft50_reclaim_killed.sh @@ -0,0 +1,34 @@ +#!/bin/bash +# PI05_FT req 4/req 8 (disk): the four from-base chunk-50 runs killed in run 1 (LSF 1909449-52) each still +# hold ONE 42 GB step dir from a run that is not the deliverable (from pi05_base, chunk-pooled norm stats, +# dead at step 7500-8000). The retained control stock_s0_h50 (1909448) is STILL RUNNING and is NOT touched. +# Deletes only the numeric step dirs; keeps eval_history.jsonl / fit_curves.png / wandb_id.txt as the record. +set -uo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +KEEP_ALIVE="stock_s0_h50" # the retained from-base control -- never touch +DIRS="runs/openpi/checkpoints/pi05_cooking_rise_h50/rise_s0_h50 +runs/openpi/checkpoints/pi05_cooking_rise_h50/rise_s1_h50 +runs/openpi/checkpoints/pi05_cooking_riseadv_h50/riseadv_s0_h50 +runs/openpi/checkpoints/pi05_cooking_stock_h50/stock_s1_h50" + +echo "[reclaim] df BEFORE:"; df -h /proj/dmfexp | tail -1 +# hard guard: refuse if any of these names is a live job +LIVE=$(bjobs -o "job_name" -noheader 2>/dev/null | tr -d ' ') +for d in $DIRS; do + exp=$(basename "$d") + if [[ "$exp" == "$KEEP_ALIVE" ]]; then echo "[reclaim] REFUSE: $exp is the retained control"; exit 3; fi + if echo "$LIVE" | grep -qx "rr_h50_${exp}"; then echo "[reclaim] REFUSE: rr_h50_${exp} is a LIVE job"; exit 4; fi +done +for d in $DIRS; do + [[ -d "$d" ]] || { echo "[reclaim] $d absent, skip"; continue; } + for s in "$d"/[0-9]*; do + [[ -d "$s" ]] || continue + base=$(basename "$s"); [[ "$base" =~ ^[0-9]+$ ]] || continue + sz=$(du -sh "$s" | cut -f1) + echo "[reclaim] rm -rf $s ($sz)" + rm -rf "$s" && echo "[reclaim] done" || echo "[reclaim] FAILED" + done + echo "[reclaim] $d now: $(ls "$d" | tr '\n' ' ')" +done +echo "[reclaim] df AFTER:"; df -h /proj/dmfexp | tail -1 +echo "[reclaim] OK" diff --git a/rsm_rise/scripts/real/pi05_ft50_renumber_docs.py b/rsm_rise/scripts/real/pi05_ft50_renumber_docs.py new file mode 100644 index 0000000000000000000000000000000000000000..168ca3b60ba7121454eb3fac34ce0d2a04790b55 --- /dev/null +++ b/rsm_rise/scripts/real/pi05_ft50_renumber_docs.py @@ -0,0 +1,83 @@ +"""Recompute rise_stack/openpi/README.md's per-file +ins/-del table, its totals row, the headline line and +SETUP.md's "N files and X inserted lines" from the SHIPPED patch bytes, after the patch is replaced. + +tests/test_rise_stack_openpi_patch_numbers.py recomputes the same numbers and fails on any drift, so this +script exists to keep the prose honest rather than to be believed. + +usage: pi05_ft50_renumber_docs.py +""" +import pathlib, re, sys + +wt = pathlib.Path(sys.argv[1]) +patch = (wt / "rise_stack/openpi/rise_on_pi05.patch").read_text().splitlines() + +# numstat straight from the hunk lines, exactly as the guard test does +files, cur = {}, None +for ln in patch: + if ln.startswith("diff --git "): + cur = ln.split(" b/")[-1] + files.setdefault(cur, [0, 0]) + elif ln.startswith("+++ ") or ln.startswith("--- ") or ln.startswith("@@"): + continue + elif cur and ln.startswith("+"): + files[cur][0] += 1 + elif cur and ln.startswith("-"): + files[cur][1] += 1 +ti = sum(v[0] for v in files.values()) +td = sum(v[1] for v in files.values()) +print(f"patch: {len(files)} files, +{ti} / -{td}") +for f, (a, d) in sorted(files.items(), key=lambda kv: -kv[1][0]): + print(f" {f}: +{a} / -{d}") + + +def fmt(a, d): + return f"+{a:,}" if d == 0 else f"+{a:,} / -{d:,}" + + +rp = wt / "rise_stack/openpi/README.md" +txt = rp.read_text() +n_before = txt + +# per-file rows +for f, (a, d) in files.items(): + pat = re.compile(r"^(\| `" + re.escape(f) + r"` \| )([^|]*?)( \|)", re.M) + if not pat.search(txt): + print(f" !! no README row for {f}") + continue + txt = pat.sub(lambda m: m.group(1) + fmt(a, d) + m.group(3), txt) + +# totals row +txt = re.sub(r"\| \*\*\d+ files, total\*\* \| \*\*[^*]*\*\* \|", + f"| **{len(files)} files, total** | **+{ti:,} / -{td:,}** |", txt) +# headline bullet +txt = re.sub(r"(\[`rise_on_pi05\.patch`\]\(rise_on_pi05\.patch\), )\d+ files, [\d,]+ insertions and [\d,]+ deletions", + rf"\g<1>{len(files)} files, {ti:,} insertions and {td:,} deletions", txt) +# the self-referential sentence that quotes the headline +txt = re.sub(r"(or the `)\d+ files,\n?([\d,]+) insertions` line above it", + lambda m: f"{m.group(1)}{len(files)} files,\n{ti:,} insertions` line above it", txt) +rp.write_text(txt) +print(f"README.md {'CHANGED' if txt != n_before else 'unchanged'}") + +sp = wt / "SETUP.md" +s = sp.read_text() +# NOTE (ft50): the h50 version of this script matched `is files and inserted lines` on ONE line. +# SETUP.md is hard-wrapped at ~110 cols and the sentence now breaks between "9" and "files", so that regex +# silently matched nothing and left SETUP.md at the old total -- which is exactly what +# test_headline_matches_the_patch[SETUP.md] and test_the_two_documents_agree_with_each_other caught. +# Tolerate any whitespace (including the newline) at both wrap points, and PRESERVE it so the wrap does not +# move. Then assert the substitution actually happened rather than trusting it. +pat = re.compile(r"(\d+)(\s+)files and ([\d,]+)(\s+)inserted lines on top of upstream commit") +assert pat.search(s), "SETUP.md: ' files and inserted lines on top of upstream commit' not found" +s2 = pat.sub(lambda m: f"{len(files)}{m.group(2)}files and {ti:,}{m.group(4)}inserted lines on top of upstream commit", s) +sp.write_text(s2) +print(f"SETUP.md {'CHANGED' if s2 != s else 'unchanged'}") + +# self-check: both documents' headlines must now read back out of the patch, the same way the guard test +# recomputes them (re.search over the whole text, so a hard wrap is invisible to it). +HEAD = re.compile(r"(\d+)\s+files?[^.\n]*?([\d,]+)\s+(?:inserted lines|insertions)") +for d in (rp, sp): + m = HEAD.search(d.read_text()) + assert m, f"{d.name}: no headline found" + got = (int(m.group(1)), int(m.group(2).replace(",", ""))) + assert got == (len(files), ti), f"{d.name} headline {got} != patch ({len(files)}, {ti})" + print(f"[selfcheck] {d.name} headline = {got} OK") diff --git a/rsm_rise/scripts/real/pi05_ft50_screen.sh b/rsm_rise/scripts/real/pi05_ft50_screen.sh new file mode 100644 index 0000000000000000000000000000000000000000..0a940eb33f02b45bf95edd20673e463dbf936997 --- /dev/null +++ b/rsm_rise/scripts/real/pi05_ft50_screen.sh @@ -0,0 +1,307 @@ +#!/usr/bin/env bash +# rsm_real#14 / worker ft50scr TASK 2+3 -- the PLANNING SCREEN and the HELD-OUT REPLAY EVAL of the pi0.5 +# chunk-50 fine-tunes, at every keep step. +# +# A RISE actor is judged by what planning can extract from its candidates, not by greedy fit (owner, PR +# jmarangola/rsm_real#1, 2026-09-22), so every keep-step checkpoint goes through scorer_openloop.py with the +# flagship RSM read-out. SETTINGS ARE COPIED VERBATIM from pi05_screen.sh's COMMON -- same IDQL critic +# (S0Aidql seed 1 epoch 3000), same RSM (R_M ckpt_s100000), d1 / depth 1 / beta 0.99 / prob / T=25, N=128, +# stride 25, --horizon 8, all 25 held-out episodes -- so the new rows drop straight into the 13-row table that +# status/real/pi05_screen_table_25.md and build_pi05_screen_table.py already hold. +# +# --horizon 8 ON A CHUNK-50 POLICY IS THE RIGHT SETTING, AND IT IS MEASURED, NOT ASSUMED. This script +# REFUSES to submit until status/real/pi05_ft50_screen_horizon.json says COMPARABLE. The finding +# (scripts/real/pi05_ft50_horizon_probe.py, TASK 1): --horizon is a pure post-hoc truncation of the policy's +# own chunk (twin_rollout.py:216 `np.asarray(a)[:horizon, :10]`); the flow noise is drawn at the MODEL's +# (action_horizon, action_dim), so a chunk-50 model is sampled exactly as trained and only its first 8 steps +# are returned. gt = A[i:i+8] and the anchor grid range(0, T-8, 25) depend on --horizon alone, so a chunk-50 +# row is measured at the SAME anchors against the SAME 8 logged frames as the chunk-10 rows. +# +# SHAPE (CLAUDE.md "many independent single-GPU tasks -> one job, one task per GPU"): the 8 cells are 8 +# independent single-process jobs, so they are PACKED, never submitted one per job (scripts/bsub_gpu.sh exits 3 +# by design since the admin banned 1-GPU jobs). Two things the pack wrapper forces, which is why this is not +# literally one 8-GPU pack per step: +# * bsub_gpu_pack.sh splits any RR_GPUS=8 pack with >= 2 payloads into two 4-GPU packs (_p4a/_p4b) because +# 8-GPU multi-payload packs measurably DO NOT PLACE on this cluster (ORCH run 75). So an 8-wide call +# becomes 4+4 by itself; we ask for 8 when we have 8 and let it split evenly. +# * an underfilled pack is a forbidden shape: 1 payload on a 4-GPU j_exclusive node IS a 1-GPU job wearing a +# 4-GPU request (jobs 1897367/1897368 wasted 6 GPUs for 70 min that way). The `_h50` control runs ~2 h +# AHEAD of the seven fine-tunes (it started at 02:30Z, they at 04:25Z), so at any given moment the ready +# cells are NOT one clean step's worth. Therefore this script POOLS every ready-and-unscreened cell +# ACROSS all four keep steps into one todo list and packs it in groups of 8 (then 4). A remainder of 1-3 +# is HELD, not submitted, and the script prints the RR_FT50SCR_FORCE=1 command that releases it -- by then +# it is the genuine tail of the work and the waste is bounded. +# +# TASK 3 -- the replay eval rides in the SAME payload as the screen, replay FIRST. openpi_replay_eval.py is +# 8 more independent single-GPU tasks, so it must be packed too; giving it its own packs would double the +# number of 4-GPU nodes this stream asks for on a cluster where packs already PEND for hours. A payload runs +# the ~20 min replay eval and then the ~1.5 h screen, so every replay number lands early in the pack's life +# and the screens finish later, on half the nodes. Each has its OWN json guard, so a payload that dies after +# the replay eval is resumed at the screen without re-running the replay. +# +# usage: +# pi05_ft50_screen.sh scan all four keep steps, submit what is ready, print what is pending +# pi05_ft50_screen.sh 50000 only that step +# RR_FT50SCR_FORCE=1 pi05_ft50_screen.sh also submit a remainder of 1-3 cells (documents the waste) +# Safe and useful to call every 30 min from now on; before 50k lands it submits nothing. +set -uo pipefail +ROOT=/proj/dmfexp/zwhong/rsm_rise +CK=$ROOT/runs/openpi/checkpoints +GEN=$ROOT/scripts/real/_gen +PSDIR=$ROOT/status/real/pi05_pending_submits +HZJSON=$ROOT/status/real/pi05_ft50_screen_horizon.json +STEPS=${*:-"50000 100000 150000 199999"} +FORCE=${RR_FT50SCR_FORCE:-0} + +# COPIED VERBATIM from pi05_screen.sh (do not edit one of these without re-measuring all 13 existing rows) +RSM=$ROOT/runs/real_cooking_v5/rsm/R_M/ckpt_s100000.pt +IDQL=$ROOT/runs/cooking_v5_expert_suboptimal/policy/S0Aidql_seed1/cooking_v5_expert_suboptimal_S0Aidql_s1/20260921235824/models/model_epoch_3000.pth +COMMON="--idql-ckpt $IDQL --rsm-ckpt $RSM --rsm-mode d1 --rsm-depth 1 --rsm-beta 0.99 \ + --rsm-score-kind prob --rsm-temperature 25 --n-cand 128 --horizon 8 --stride 25" + +# cfg:exp -- the 7 fine-tunes plus the retained from-base control, which is the init ablation against +# stock_s0_ft50 (same horizon, same 200k, same data; different init AND different norm stats). +CELLS=" +pi05_cooking_stock_ft50_s0:stock_s0_ft50 +pi05_cooking_stock_ft50_s1:stock_s1_ft50 +pi05_cooking_rise_ft50_s0:rise_s0_ft50 +pi05_cooking_rise_ft50_s1:rise_s1_ft50 +pi05_cooking_riseadv_ft50_s0:riseadv_s0_ft50 +pi05_cooking_sn1_knn0p03_ft50_s0:sn1_knn0p03_ft50 +pi05_cooking_sn0p1_knn0p03_ft50_s0:sn0p1_knn0p03_ft50 +pi05_cooking_stock_h50:stock_s0_h50 +" + +mkdir -p "$GEN" "$PSDIR" "$ROOT/logs/lsf" + +# ---------------------------------------------------------------- TASK 1 gate +if [ ! -e "$HZJSON" ]; then + echo "[ft50-screen] BLOCKED on TASK 1: $HZJSON does not exist yet." + echo "[ft50-screen] --horizon 8 against an action_horizon-50 policy has not been MEASURED, so a screen" + echo "[ft50-screen] fired now could produce rows that are not comparable to the existing 13." + echo "[ft50-screen] Run: bash scripts/real/pi05_ft50_hprobe.sh (then re-run this script)" + exit 0 +fi +HZV=$(python3 -c "import json;print(json.load(open('$HZJSON')).get('verdict','?'))" 2>/dev/null) +if [ "$HZV" != COMPARABLE ]; then + echo "[ft50-screen] REFUSING TO SUBMIT: $HZJSON verdict=$HZV (expected COMPARABLE)." + echo "[ft50-screen] A screen whose rows are not comparable to the table's other 13 would MISLEAD." + echo "[ft50-screen] Read the json, fix the one setting it names, and document the change here." + exit 5 +fi + +# ---------------------------------------------------------------- duplicate guard (pi05_screen_sweep.sh run 13/14) +# A pack that is PEND/RUN has no json yet, so the json guard alone would re-submit it; and a stalled mbatchd can +# hide a bsub that WILL still appear, so every submission also drops an unconfirmed-submission marker. A +# duplicate screen corrupts a cell's parts/ cache, so when the job table cannot be trusted we submit NOTHING. +JOBS=""; JOBS_OK=0 +for try in 1 2 3; do + out=$(bjobs -o "job_name stat" -noheader 2>&1); rc=$? + if [ $rc -eq 0 ] && [ -n "$out" ]; then JOBS="$out"; JOBS_OK=1; break; fi + case "$out" in *"No unfinished job found"*) JOBS=""; JOBS_OK=1; break;; esac + echo "[ft50-screen] bjobs attempt $try failed (rc=$rc): ${out:-}"; [ $try -lt 3 ] && sleep 5 +done +[ "$JOBS_OK" = 1 ] || { echo "[ft50-screen] ABORT: cannot read the LSF job table; refusing to submit (duplicate risk)"; exit 0; } + +# clear markers whose job we can now see in the table (any state), or whose screen has produced its json. +# +# PI05_FT run 30 BUGFIX. Only the first half of that sentence was implemented. A marker is a promise +# "a pack was bsub'd but I have not yet seen its id", and the job-table check can only ever clear it +# WHILE THE JOB IS STILL LIVE. If the pack finishes before any later run looks -- which is the normal +# case for a 4-cell screen pack that takes ~1.5 h against a ~30 min run cadence -- the job is gone from +# the table forever and the marker becomes PERMANENT. Its only effect from then on is the `live=2` +# branch below, which reports every cell in that pack as "in flight" and therefore NEVER RESUBMITS IT: +# a silent, unrecoverable deadlock that looks like healthy "in flight" output. +# Measured: status/real/pi05_pending_submits/ft50scr_rr_pi05scr_ft50_g1_09251204 (Sep 25 12:04) was still +# present 13.5 h later with its job long finished and all four of its cells screened. +# So implement the second, work-based condition the comment already promised: if every `--tag` in the +# pack's payload files has a scorer_openloop.json, the pack's work is DONE and the marker is meaningless +# regardless of what the job table says. This is strictly safer than a time-based expiry -- it cannot +# clear a marker for a pack that still has unfinished work, so the duplicate-submission protection the +# marker exists for is fully preserved. +for m in "$PSDIR"/ft50scr_*; do + [ -e "$m" ] || continue + mt=$(basename "$m" | sed 's/^ft50scr_//') # mt = the pack name stem + if printf '%s\n' "$JOBS" | grep -qE "^${mt}(_p4[ab])? +"; then + rm -f "$m"; echo "[ft50-screen] cleared confirmed submission marker $mt (job visible in the table)" + continue + fi + # not in the table: either never submitted, or finished. Distinguish by whether the work exists. + ntag=0; njson=0 + for p in "$GEN"/${mt}_slot*.sh; do + [ -e "$p" ] || continue + for t in $(grep -oE -- '--tag [A-Za-z0-9_]+' "$p" | awk '{print $2}' | sort -u); do + ntag=$((ntag+1)) + [ -e "$ROOT/status/real/openloop_$t/scorer_openloop.json" ] && njson=$((njson+1)) + done + done + if [ "$ntag" -gt 0 ] && [ "$ntag" = "$njson" ]; then + rm -f "$m" + echo "[ft50-screen] cleared STALE submission marker $mt: job not in the table and all $ntag cell(s) screened" + elif [ "$ntag" -gt 0 ]; then + # Job not in the table AND work incomplete => the pack died (preemption is routine on this queue). + # Keeping the marker here would be the SAME deadlock, just with a warning printed: the cells would + # never be resubmitted. But clearing it unconditionally would reopen the exact race the marker + # exists for -- a marker is written immediately after `bsub`, and LSF can take a few seconds to + # publish the job, so a run that fires in that window would see "not in the table" and double-submit. + # Age is the correct discriminator: that publication window is seconds, so a marker older than + # RR_MARKER_STALE_MIN (default 30 min, one run cadence) cannot still be waiting to appear. + age_min=$(( ( $(date +%s) - $(stat -c %Y "$m" 2>/dev/null || date +%s) ) / 60 )) + if [ "$age_min" -ge "${RR_MARKER_STALE_MIN:-30}" ]; then + rm -f "$m" + echo "[ft50-screen] cleared DEAD-PACK marker $mt: not in the table, ${age_min} min old," + echo " only $njson/$ntag cell(s) screened -- its unscreened cells are now resubmittable" + else + echo "[ft50-screen] marker $mt kept: not in the table but only ${age_min} min old ($njson/$ntag screened)" + echo " -- inside the bsub publication window, so this may be a job LSF has not listed yet" + fi + fi +done + +# A cell whose training is permanently STOPPED can never produce a later keep. Expecting one is not merely +# cosmetic: it keeps $waiting non-empty forever, which silently DISABLES the terminal-release branch in the +# packing tail and so leaves the final-step remainder held for good. The from-base control was stopped by the +# owner at 154 000 on 2026-09-25 ~20:15 UTC (LSF 1913561, TERM_OWNER) when GPUs were freed for the DINO/WM +# top-ups; its last keep -- and its last word in every table -- is 150 000. +CELL_LAST_STEP="stock_s0_h50:150000" + +# ---------------------------------------------------------------- build the todo list +todo=""; waiting=""; stopped=""; done_n=0; queued=0 +for st in $STEPS; do + for cell in $CELLS; do + cfg=${cell%%:*}; exp=${cell##*:} + ckdir=$CK/$cfg/$exp/$st + tag=pi05${exp}_${st} + lim=$(printf '%s\n' $CELL_LAST_STEP | sed -n "s/^$exp://p") + if [ -n "$lim" ] && [ "$st" -gt "$lim" ] && [ ! -d "$ckdir/params" ]; then + stopped="$stopped\n $tag -> that training was STOPPED at step $lim; this keep will never exist, so it is" + stopped="$stopped\n NOT counted as waiting (counting it would hold the final remainder forever)" + continue + fi + if [ ! -d "$ckdir/params" ]; then + last=$(ls -d $CK/$cfg/$exp/[0-9]* 2>/dev/null | sed 's|.*/||' | sort -n | tail -1) + waiting="$waiting\n $tag -> $ckdir/params (that run's newest step is ${last:-none})" + continue + fi + if [ -e "$ROOT/status/real/openloop_$tag/scorer_openloop.json" ]; then + done_n=$((done_n+1)); continue + fi + # is this cell already inside a queued/running pack? The pack name carries the cell list's hash-free + # stem, so we look the cell up in the payload files of every live pack instead of guessing the name. + live=0 + for p in "$GEN"/rr_pi05scr_ft50_g*_slot*.sh; do + [ -e "$p" ] || continue + grep -q -- "--tag $tag " "$p" || continue + pk=$(basename "$p" | sed 's/_slot[0-9]*\.sh$//') + if printf '%s\n' "$JOBS" | grep -qE "^${pk}(_p4[ab])? +(PEND|RUN|PSUSP|USUSP|SSUSP)$"; then live=1; break; fi + [ -e "$PSDIR/ft50scr_$pk" ] && { live=2; break; } + done + if [ "$live" = 1 ]; then echo "[ft50-screen] $tag: already in a queued/running pack"; queued=$((queued+1)); continue; fi + if [ "$live" = 2 ]; then + echo "[ft50-screen] $tag: in a pack whose submission is UNCONFIRMED (marker $PSDIR/ft50scr_*) --" + echo " confirm the job id with 'bjobs -w | grep rr_pi05scr_ft50_g' and delete the marker" + queued=$((queued+1)); continue + fi + todo="$todo $cfg:$exp:$st" + done +done + +echo "[ft50-screen] cells: $(echo $todo | wc -w) ready-and-unscreened, $done_n already screened, $queued in flight" +[ -n "$waiting" ] && { echo "[ft50-screen] WAITING FOR CHECKPOINTS:"; printf "$waiting\n"; } +[ -n "$stopped" ] && { echo "[ft50-screen] STOPPED TRAININGS (steps that will never arrive):"; printf "$stopped\n"; } +[ -z "$todo" ] && { echo "[ft50-screen] nothing to submit"; exit 0; } + +# ---------------------------------------------------------------- payload writer +_payload () { # _payload + local f=$1 cfg=$2 exp=$3 st=$4 + local tag=pi05${exp}_${st} + local ckdir=$CK/$cfg/$exp/$st + local olout=$ROOT/status/real/openloop_$tag + local rpout=$CK/$cfg/$exp/replay_$st + cat > "$f" < 10) the *_chunk10_* +# prefixes that make a chunk-50 run comparable to the chunk-10 generation. +if [ -e "$rpout/replay_eval.json" ]; then + echo "[cell $tag] replay eval already done -> $rpout/replay_eval.json" +else + mkdir -p "$rpout" + $ROOT/scripts/real/openpi_eval.sh $ROOT/scripts/real/openpi_replay_eval.py \\ + --config $cfg --ckpt "$ckdir" --out "$rpout" + echo "[cell $tag] replay eval rc=\$? \$(date -u)" +fi + +# --- TASK 2: the planning screen, settings verbatim from pi05_screen.sh's COMMON, all 25 held-out episodes. +if [ -e "$olout/scorer_openloop.json" ]; then + echo "[cell $tag] screen already done -> $olout/scorer_openloop.json" +else + $ROOT/scripts/real/run_env_openpi.sh $ROOT/scripts/real/scorer_openloop.py \\ + --policy "openpi:$cfg:$ckdir" $COMMON \\ + --tag $tag --out "$olout" + echo "[cell $tag] screen rc=\$? \$(date -u)" +fi +echo "[cell $tag] finished \$(date -u)" +PL + chmod +x "$f" +} + +# ---------------------------------------------------------------- pack the todo list +set -- $todo +g=0 +while [ $# -gt 0 ]; do + if [ $# -ge 8 ]; then n=8; G=8 + elif [ $# -ge 4 ]; then n=4; G=4 + elif [ "$FORCE" = 1 ]; then n=$#; G=4 + elif [ -z "$waiting" ] && [ $# -ge 2 ]; then + # TERMINAL REMAINDER. The hold below rests entirely on "the other cells' checkpoints are still coming", + # which is exactly FALSE once $waiting is empty: every cell of the CELLS x STEPS grid then either has its + # json or is in this remainder, so NO later call can ever add a payload and the hold is permanent. At the + # final keep that is the normal case, not an edge case: 7 fine-tunes pack as 4 + 3, and the trailing 3 -- + # three of the seven 200k deliverable cells -- would be held forever while the log kept promising a later + # pack that cannot exist. So release them, on a 4-GPU node, and say what it costs. A remainder of 1 is + # still held: ONE payload on a 4-GPU j_exclusive node is the forbidden 1-GPU job in disguise, and that one + # needs a human's RR_FT50SCR_FORCE=1 with a reason. + n=$#; G=4 + echo "[ft50-screen] TERMINAL REMAINDER: releasing the last $# cell(s) on a 4-GPU node ($((4 - $#)) GPU(s) idle)." + echo " Nothing is waiting for a checkpoint, so no later call could ever fill this pack and" + echo " holding it would stall these cells permanently." + else + echo "[ft50-screen] HOLDING the last $# cell(s): a pack with $# payload(s) on a 4-GPU j_exclusive node is" + echo " the forbidden 1-GPU-wearing-a-4-GPU-request shape (see 1897367/1897368). The other" + echo " cells' checkpoints are still coming, so these will join a full pack on a later call." + echo " To release them anyway (accepting $((4 - $#)) idle GPU(s)):" + echo " RR_FT50SCR_FORCE=1 bash scripts/real/pi05_ft50_screen.sh $STEPS" + for c in "$@"; do echo " held: pi05$(echo $c | cut -d: -f2)_$(echo $c | cut -d: -f3)"; done + break + fi + # TERMINAL BALANCE. Symmetric to the terminal release above, for the one split it cannot save: at terminal + # state a 4-pack that leaves exactly 1 cell behind ORPHANS it, because a lone payload on a 4-GPU j_exclusive + # node is the forbidden shape and is therefore the one remainder that is never auto-released. 5 unscreened + # terminal cells (a preemption away on this queue) would do exactly that. Shrink this pack to 2 so the tail + # is a releasable 3. Only the n=4 branch is adjusted -- shrinking the 8-wide branch would leave n > G. + if [ -z "$waiting" ] && [ "$FORCE" != 1 ] && [ "$n" = 4 ] && [ $(( $# - n )) -eq 1 ]; then + n=2 + echo "[ft50-screen] TERMINAL BALANCE: packing $n (not 4) so the tail is 3, not an orphaned 1." + fi + g=$((g+1)); PK=rr_pi05scr_ft50_g${g}_$(date -u +%m%d%H%M) + # a pack name must be unique per submission or the duplicate guard above cannot tell two packs apart + while printf '%s\n' "$JOBS" | grep -qE "^${PK}(_p4[ab])? +"; do PK=${PK}x; done + files=""; i=0 + for c in $(echo "$@" | cut -d' ' -f1-$n); do + cfg=$(echo $c | cut -d: -f1); exp=$(echo $c | cut -d: -f2); st=$(echo $c | cut -d: -f3) + f=$GEN/${PK}_slot$i.sh; _payload "$f" "$cfg" "$exp" "$st"; files="$files $f"; i=$((i+1)) + echo "[ft50-screen] $PK slot$i -> pi05${exp}_${st}" + done + printf '%s submitted %s (%d payloads, RR_GPUS=%d; the wrapper may split it into %s_p4a/_p4b); job id unconfirmed until a later run sees it\n' \ + "$(date -u +'%F %H:%M UTC')" "$PK" "$n" "$G" "$PK" > "$PSDIR/ft50scr_$PK" + RR_GPUS=$G RR_MEM=96G bash $ROOT/scripts/bsub_gpu_pack.sh $PK $files 2>&1 | tail -4 + shift $n +done diff --git a/rsm_rise/scripts/real/pi05_ft50_shrink_sweep.sh b/rsm_rise/scripts/real/pi05_ft50_shrink_sweep.sh new file mode 100644 index 0000000000000000000000000000000000000000..aaa6bb43e1fbdec0c97d72dbbc752038c261eaa0 --- /dev/null +++ b/rsm_rise/scripts/real/pi05_ft50_shrink_sweep.sh @@ -0,0 +1,127 @@ +#!/usr/bin/env bash +# rsm_real#14 / worker PI05_FT run 29 -- THE INFERENCE-TIME DIVERSITY TEST. +# +# WHY. status/real/ft50_oracle_mechanism_50k_150k.md (LSF 1921907) showed that the `oracle` +# degradation run 28 found is PURE DIVERSITY COLLAPSE: headroom H = greedy-oracle tracks the +# candidate spread with rho in [1.015, 1.070] on the last arm in 8 of 8 cells, so the fine-tuned +# checkpoint is not worse at planning -- its candidate cloud is narrower. Run 28's recommendation +# (ship an EARLY checkpoint for the planning deployment) therefore buys planning headroom by ALSO +# surrendering the greedy gains of the extra 100k steps. If the mechanism is right, the SAME +# headroom is recoverable at the LATE checkpoint for free, by widening the cloud at INFERENCE. +# +# scorer_openloop.py already has the exact knob, and it is honest: --cand-shrink ALPHA rescales the +# candidates about THEIR OWN CENTROID (scorer_openloop.py:569-576, `cands = m + alpha*(c - m)`, the +# centroid is the candidates' mean and never the ground truth, so it cannot leak the target). +# +# THE TEST. At step 150000, run each cell a second time with ALPHA set to that cell's OWN measured +# spread ratio S(50000)/S(150000) -- i.e. widen the 150k cloud back to exactly its 50k width -- and +# compare against two screens that ALREADY EXIST (no new control is measured): +# oracle(150k, alpha*) vs oracle(50k, 1.0) does the planning CEILING come back? +# rsm (150k, alpha*) vs rsm (150k, 1.0) does the DEPLOYED planning policy gain? +# greedy(150k, alpha*) vs greedy(150k, 1.0) what does the greedy deployment pay? +# greedy is candidate 0 -- a plain sample (scorer_openloop.py docstring) -- NOT the centroid, so +# widening pushes it off-centre and greedy is EXPECTED to degrade. That is the cost side of the +# trade and the reason this is a sweep and not a free lunch: the planning deployment ships `rsm`, +# the greedy deployment ships candidate 0, and they do not want the same alpha. +# +# ALPHA IS COMPUTED FROM THE JSON AT RUN TIME, never hardcoded, so it cannot drift from the table. +# +# SHAPE. 4 cells = 4 independent single-process screens = ONE FULL 4-GPU pack (CLAUDE.md: many +# independent single-GPU tasks -> one job, one task per GPU; a 1-GPU job is banned and an +# underfilled 4-GPU pack is a 1-GPU job wearing a 4-GPU request). No replay eval in the payload -- +# replay does not depend on alpha, so re-running it would be pure waste. +# +# TAGS CANNOT CONTAMINATE THE EXISTING TABLES -- verified, not assumed: every published table globs +# openloop_pi05*_/scorer_openloop.json, which requires the directory name to END in the step; +# these end in _sh, so fnmatch is False against _50000/_100000/_150000/_199999 alike. +set -uo pipefail +ROOT=/proj/dmfexp/zwhong/rsm_rise +CK=$ROOT/runs/openpi/checkpoints +GEN=$ROOT/scripts/real/_gen +PSDIR=$ROOT/status/real/pi05_pending_submits +STEP=150000 +REF=50000 + +RSM=$ROOT/runs/real_cooking_v5/rsm/R_M/ckpt_s100000.pt +IDQL=$ROOT/runs/cooking_v5_expert_suboptimal/policy/S0Aidql_seed1/cooking_v5_expert_suboptimal_S0Aidql_s1/20260921235824/models/model_epoch_3000.pth +COMMON="--idql-ckpt $IDQL --rsm-ckpt $RSM --rsm-mode d1 --rsm-depth 1 --rsm-beta 0.99 \ + --rsm-score-kind prob --rsm-temperature 25 --n-cand 128 --horizon 8 --stride 25" + +# the BC reference, the keep/best actor, the actor whose advantage vanished by 150k, and one plain RISE +CELLS=" +pi05_cooking_stock_ft50_s0:stock_s0_ft50 +pi05_cooking_sn1_knn0p03_ft50_s0:sn1_knn0p03_ft50 +pi05_cooking_riseadv_ft50_s0:riseadv_s0_ft50 +pi05_cooking_rise_ft50_s0:rise_s0_ft50 +" +mkdir -p "$GEN" "$PSDIR" "$ROOT/logs/lsf" + +# ---------------------------------------------------------------- duplicate guard +JOBS=""; JOBS_OK=0 +for try in 1 2 3; do + out=$(bjobs -o "job_name stat" -noheader 2>&1); rc=$? + if [ $rc -eq 0 ] && [ -n "$out" ]; then JOBS="$out"; JOBS_OK=1; break; fi + case "$out" in *"No unfinished job found"*) JOBS=""; JOBS_OK=1; break;; esac + [ $try -lt 3 ] && sleep 5 +done +[ "$JOBS_OK" = 1 ] || { echo "[shrink] ABORT: cannot read the LSF job table; refusing to submit"; exit 0; } + +files=""; skipped=0 +for cell in $CELLS; do + cfg=${cell%%:*}; exp=${cell##*:} + ckdir=$CK/$cfg/$exp/$STEP + ref=$ROOT/status/real/openloop_pi05${exp}_${REF}/scorer_openloop.json + cur=$ROOT/status/real/openloop_pi05${exp}_${STEP}/scorer_openloop.json + if [ ! -d "$ckdir/params" ]; then echo "[shrink] $exp: no $STEP checkpoint -- skip"; skipped=$((skipped+1)); continue; fi + if [ ! -e "$ref" ] || [ ! -e "$cur" ]; then + echo "[shrink] $exp: need BOTH $REF and $STEP screens to set alpha -- skip"; skipped=$((skipped+1)); continue + fi + # alpha = S(REF)/S(STEP), from the measured json. Refuse a degenerate or absurd alpha. + alpha=$(python3 -c " +import json,sys +a=json.load(open('$ref'))['candidate_spread_xyz_cm'] +b=json.load(open('$cur'))['candidate_spread_xyz_cm'] +r=a/b +sys.exit(1) if not (1.05 < r < 6.0) else print('%.3f'%r) +") || { echo "[shrink] $exp: alpha out of sane range -- skip"; skipped=$((skipped+1)); continue; } + sh=$(python3 -c "print('sh%03d'%round(float('$alpha')*100))") + tag=pi05${exp}_${STEP}_${sh} + olout=$ROOT/status/real/openloop_$tag + if [ -e "$olout/scorer_openloop.json" ]; then echo "[shrink] $tag: already measured"; skipped=$((skipped+1)); continue; fi + if printf '%s\n' "$JOBS" | grep -qE "^rr_pi05shrink(_p4[ab])? +(PEND|RUN|PSUSP|USUSP|SSUSP)$"; then + echo "[shrink] a shrink pack is already PEND/RUN -- refusing to submit a duplicate"; exit 0 + fi + [ -e "$PSDIR/ft50shrink" ] && { echo "[shrink] unconfirmed submission marker $PSDIR/ft50shrink exists -- refusing"; exit 0; } + f=$GEN/rr_pi05shrink_${exp}.sh + cat > "$f" < $olout/scorer_openloop.json" +else + $ROOT/scripts/real/run_env_openpi.sh $ROOT/scripts/real/scorer_openloop.py \\ + --policy "openpi:$cfg:$ckdir" $COMMON --cand-shrink $alpha \\ + --tag $tag --out "$olout" + echo "[cell $tag] screen rc=\$? \$(date -u)" +fi +PL + chmod +x "$f" + files="$files $f" + echo "[shrink] queued $tag alpha=$alpha" +done + +n=$(echo $files | wc -w) +if [ "$n" -eq 0 ]; then echo "[shrink] nothing to submit ($skipped skipped)"; exit 0; fi +if [ "$n" -lt 4 ]; then + echo "[shrink] HOLDING: only $n payload(s); a $n-payload pack on a 4-GPU j_exclusive node wastes" + echo " $((4-n)) GPU(s). Re-run when the missing cells' screens exist, or force deliberately." + [ "${RR_SHRINK_FORCE:-0}" = 1 ] || exit 0 + echo "[shrink] RR_SHRINK_FORCE=1 -- submitting the underfilled pack anyway (waste documented above)" +fi +touch "$PSDIR/ft50shrink" +echo "[shrink] submitting $n payloads as one ${n}-GPU pack rr_pi05shrink" +RR_GPUS=$n RR_MEM=96G bash $ROOT/scripts/bsub_gpu_pack.sh rr_pi05shrink $files 2>&1 | tail -6 diff --git a/rsm_rise/scripts/real/pi05_ft50_tag_killed_frombase.sh b/rsm_rise/scripts/real/pi05_ft50_tag_killed_frombase.sh new file mode 100644 index 0000000000000000000000000000000000000000..ea3792929f7b4ca14e6f2c7ec0cef01bfbb09571 --- /dev/null +++ b/rsm_rise/scripts/real/pi05_ft50_tag_killed_frombase.sh @@ -0,0 +1,34 @@ +#!/usr/bin/env bash +# The owner asked for FINE-TUNES of the previous flagship models, not from-base runs, so four of the five +# from-base `_h50` runs (LSF 1909449-52) were killed on 2026-09-25 ~04:3xZ and replaced by the seven `_ft50` +# warm starts. `stock_s0_h50` (1909448) was deliberately KEPT as the from-base init control and is NOT tagged. +# Template: scripts/real/pi05_h50_tag_aborted.sh. Prints the tags it found first, so the report can say +# whether they were already tagged. +set -uo pipefail +ROOT=/proj/dmfexp/zwhong/rsm_rise +source $ROOT/wandb_env.sh +$ROOT/third_party/openpi/.venv/bin/python - <<'PYEOF' +from wandb import Api +api = Api() +IDS = {"stock_s1_h50": "6tgzfqno", "rise_s0_h50": "72oqvymt", + "rise_s1_h50": "sm423uvs", "riseadv_s0_h50": "b2i4k33z"} +TAG = "killed_frombase_h50" +NOTE = ("KILLED 2026-09-25 ~04:3xZ (LSF 1909449-52). These were chunk-50 200k runs initialised FROM " + "pi05_base on chunk-pooled norm stats; the owner asked instead for fine-tunes of the previous " + "flagship checkpoints, so they were superseded by the seven _ft50 warm starts (rsm_real#14). " + "The fifth sibling, stock_s0_h50 (72wjnv03, LSF 1909448), was deliberately kept as the from-base " + "init control and is still training.") +for name, rid in IDS.items(): + try: + r = api.run(f"richardrl/rsm_rise/{rid}") + print(f"[tag] {name} {rid}: tags BEFORE = {list(r.tags)} state={r.state}", flush=True) + if TAG not in r.tags: + r.tags = list(r.tags) + [TAG] + if NOTE not in (r.notes or ""): + r.notes = ((r.notes or "") + "\n" + NOTE).strip() + r.update() + print(f"[tag] {name} {rid}: tags AFTER = {list(r.tags)}", flush=True) + except Exception as e: + print(f"[tag] FAILED {name} {rid}: {e}", flush=True) +PYEOF +echo TAG_JOB_DONE diff --git a/rsm_rise/scripts/real/pi05_ft50_update_pr12.py b/rsm_rise/scripts/real/pi05_ft50_update_pr12.py new file mode 100644 index 0000000000000000000000000000000000000000..9a444ea31f827a174b86f980d2216dda11c796cd --- /dev/null +++ b/rsm_rise/scripts/real/pi05_ft50_update_pr12.py @@ -0,0 +1,115 @@ +"""Rewrite rsm_real's rise_stack/CHECKPOINTS.md for the pi0.5 chunk-50 FINE-TUNES (rsm_real#14): + + 1. replace the whole chunk-50 H2 section (which describes the five from-base `_h50` runs, four of which + were killed) with the drafted fine-tune section; + 2. swap the five `_h50` rows of the W&B index for the seven `_ft50` runs PLUS the one retained from-base + control `stock_s0_h50`, keeping the index's two-column shape; + 3. fix the sentence under the index that counts those rows; + 4. add a `killed_frombase_h50` table next to the existing `killed_chunk10` one so that tag stays findable. + +Adapted from scripts/real/pi05_h50_update_pr12.py. Differences that matter: the section text is drafted in +full (status/real/pi05_ft50_section.md) rather than templated with __WB_*__ placeholders -- the seven runs plus +a control plus two killed tables have too much per-run prose for placeholders to stay readable -- so this +script only splices and rewires the index, and it is IDEMPOTENT: re-running it on an already-updated document +is a no-op (it detects the new heading / rows and says so). + +usage: pi05_ft50_update_pr12.py +""" +import pathlib +import re +import sys + +wt, section_path = sys.argv[1], sys.argv[2] +section = pathlib.Path(section_path).read_text() +assert not re.search(r"__[A-Z_]+__", section), re.findall(r"__[A-Z_]+__", section) +p = pathlib.Path(wt) / "rise_stack/CHECKPOINTS.md" +doc = p.read_text() +before = doc + +H2 = "## The chunk-50 200k pi0.5 fine-tunes (started 2026-09-25)" +INDEX_H3 = "\n### Every pi0.5 training run in this document, with its W&B run" + +# ---- 1. the section ------------------------------------------------------------------------------------- +start = doc.index(H2) +nxt = doc.index(INDEX_H3, start) +doc = doc[:start] + section.rstrip("\n") + "\n" + doc[nxt:] +print("[pr12] section spliced") + +# ---- 2. the W&B index rows ---------------------------------------------------------------------------- +# the seven fine-tunes, then the retained from-base control last (so it reads as the odd one out) +FT50 = [ + ("pi05_cooking_stock_ft50_s0/stock_s0_ft50", "4sls4xv4"), + ("pi05_cooking_stock_ft50_s1/stock_s1_ft50", "sa309a54"), + ("pi05_cooking_rise_ft50_s0/rise_s0_ft50", "ffc3e5o0"), + ("pi05_cooking_rise_ft50_s1/rise_s1_ft50", "k22pmyen"), + ("pi05_cooking_riseadv_ft50_s0/riseadv_s0_ft50", "3ipijvt3"), + ("pi05_cooking_sn1_knn0p03_ft50_s0/sn1_knn0p03_ft50", "8zxd9bti"), + ("pi05_cooking_sn0p1_knn0p03_ft50_s0/sn0p1_knn0p03_ft50", "0cjoeuwz"), + ("pi05_cooking_stock_h50/stock_s0_h50", "72wjnv03"), # the retained from-base control +] +KILLED_FROMBASE = [ + ("pi05_cooking_stock_h50/stock_s1_h50", "6tgzfqno"), + ("pi05_cooking_rise_h50/rise_s0_h50", "72oqvymt"), + ("pi05_cooking_rise_h50/rise_s1_h50", "sm423uvs"), + ("pi05_cooking_riseadv_h50/riseadv_s0_h50", "b2i4k33z"), +] + + +def row(path, rid): + return f"| `{path}` | [{rid}](https://wandb.ai/richardrl/rsm_rise/runs/{rid}) |" + + +# Detect the NEW state first. A `_h50` row regex is NOT a usable "not yet done" test after the first run: +# the retained control row stays in the index and the four killed rows appear in the killed table below, so +# the regex keeps finding five `_h50` rows -- just no longer contiguous. +if all(row(a, b) in doc for a, b in FT50): + print("[pr12] index: already the _ft50 rows + the kept control, nothing to do") +else: + old_rows = re.findall(r"^\| `pi05_cooking_\w+_h50/\w+_h50` \| \[.*$", doc, re.M) + assert len(old_rows) == 5, old_rows + block = "\n".join(old_rows) + assert doc.count(block) == 1, "the five _h50 index rows are not contiguous" + doc = doc.replace(block, "\n".join(row(a, b) for a, b in FT50)) + print(f"[pr12] index: {len(old_rows)} `_h50` rows -> {len(FT50)} rows (7 fine-tunes + the kept control)") + +# ---- 3. the sentence that counts the index's odd rows --------------------------------------------------- +old_note = ("The four `_s0` rows above are from-scratch attempts of swept cells that the sweep replaced " + "with warm\nstarts, and the five `_h50` rows are the chunk-50 runs of the section above; they are " + "listed for\ncompleteness, not because a checkpoint of theirs ships yet.") +new_note = ("The four `_s0` rows above are from-scratch attempts of swept cells that the sweep replaced " + "with warm\nstarts; the seven `_ft50` rows are the chunk-50 fine-tunes of the section above and " + "`stock_s0_h50` is the\nretained from-base control. They are listed for completeness, not because " + "a checkpoint of theirs ships yet.") +if old_note in doc: + doc = doc.replace(old_note, new_note) + print("[pr12] index footnote rewritten") +else: + assert new_note in doc, "index footnote is neither the old wording nor the new one" + print("[pr12] index footnote already rewritten") + +# ---- 4. the killed_frombase_h50 table, next to the killed_chunk10 one ----------------------------------- +MARK = ("The five **killed chunk-10 200k continuations** are tagged `killed_chunk10` in W&B and their " + "checkpoints were deleted; they are listed here only so the tag is findable:") +assert MARK in doc, "the killed_chunk10 paragraph moved" +NEW_TBL = ("The four **killed from-base chunk-50 runs** are tagged `killed_frombase_h50` in W&B and their " + "checkpoints were deleted. They were killed because the owner asked for **fine-tunes of the " + "previous flagship models**, not runs from `pi05_base`; the fifth sibling, `stock_s0_h50`, was kept " + "as the from-base control. Listed here only so the tag is findable:\n\n" + "| killed from-base run | W&B |\n|---|---|\n" + + "\n".join(row(a, b) for a, b in KILLED_FROMBASE) + "\n\n") +if "killed_frombase_h50` in W&B" not in doc: + doc = doc.replace(MARK, NEW_TBL + MARK) + print("[pr12] killed_frombase_h50 table added") +else: + print("[pr12] killed_frombase_h50 table already present") + +p.write_text(doc) +print(f"[pr12] wrote {p} ({len(doc)} chars, {'CHANGED' if doc != before else 'unchanged'})") + +# ---- cheap consistency checks -------------------------------------------------------------------------- +for rid in [b for _, b in FT50] + [b for _, b in KILLED_FROMBASE]: + assert doc.count(rid) >= 1, rid +assert doc.count("killed_chunk10") >= 1 and doc.count("killed_frombase_h50") >= 1 +assert "pi05_cooking_rise_h50/rise_s0_h50" in doc, "the killed runs must stay findable" +assert doc.count(H2) == 1, doc.count(H2) +print("[pr12] consistency checks OK") diff --git a/rsm_rise/scripts/real/pi05_ft50_verify.py b/rsm_rise/scripts/real/pi05_ft50_verify.py new file mode 100644 index 0000000000000000000000000000000000000000..a1350af34e5503bbd3f9ad145913acb3aac76f40 --- /dev/null +++ b/rsm_rise/scripts/real/pi05_ft50_verify.py @@ -0,0 +1,179 @@ +"""rsm_real#14 (stream PI05_FT): verify the pi0.5 flagship fine-tune configs before launch. + +Three questions, in order of how badly a wrong answer would hurt: + + 1. Is ANY model parameter horizon-shaped? Built as a direct diff: make the params SHAPE tree at + action_horizon=10 (what the parents were trained at) and at 50 (what we fine-tune at) and compare + leaf by leaf. Any leaf whose shape moves is horizon-shaped and the warm start would be invalid + for it. Needs no checkpoint and no accelerator -- it is pure jax.eval_shape. + 2. Do the published parent params ACTUALLY load into the horizon-50 model? Runs openpi's own + `_load_weights_and_validate` (check_shapes=True, check_dtypes=True), i.e. the exact call train.py + makes at init. This is the real gate. + 3. Is each config what we think it is? action_horizon / steps / LR schedule / keep_period / + save_interval / batch / workers, the norm_stats.json md5 behind assets_dirs, and the full + augmentation picture (image_aug + kNN + spectral norm + advantage weighting). + +Usage: pi05_ft50_verify.py [config ...] (default: all *_ft50_* configs) +""" + +import dataclasses +import hashlib +import json +import pathlib +import sys +import traceback + +import jax +import numpy as np +from flax import nnx + +sys.path.insert(0, "/proj/dmfexp/zwhong/rsm_rise/third_party/openpi/src") +sys.path.insert(0, "/proj/dmfexp/zwhong/rsm_rise/third_party/openpi") + +import openpi.shared.array_typing as at # noqa: E402 +import openpi.training.config as _config # noqa: E402 + +sys.path.insert(0, "/proj/dmfexp/zwhong/rsm_rise/third_party/openpi/scripts") +from train import _load_weights_and_validate # noqa: E402 + + +def params_shape(cfg, horizon): + """The params SHAPE tree of cfg's model at the given action horizon (no weights materialised).""" + model_cfg = dataclasses.replace(cfg.model, action_horizon=horizon) + rng = jax.random.key(0) + model = nnx.eval_shape(lambda: model_cfg.create(rng)) + graphdef, state = nnx.split(model) + return state.to_pure_dict() + + +def flat(tree): + out = {} + + def rec(prefix, node): + if isinstance(node, dict): + for k, v in node.items(): + rec((*prefix, str(k)), v) + else: + out["/".join(prefix)] = tuple(getattr(node, "shape", ())) + + rec((), tree) + return out + + +def md5(path): + return hashlib.md5(pathlib.Path(path).read_bytes()).hexdigest() + + +def main(): + names = sys.argv[1:] or [n for n in _config._CONFIGS_DICT if "_ft50_" in n] + report = {} + for name in names: + print("=" * 100, flush=True) + print(f"CONFIG {name}", flush=True) + print("=" * 100, flush=True) + r = {} + try: + cfg = _config.get_config(name) + + # ---- (3) what the config says ----------------------------------------------------- + lr = cfg.lr_schedule.create() + r["action_horizon"] = int(cfg.model.action_horizon) + r["action_horizon_seconds_at_50hz"] = cfg.model.action_horizon / 50.0 + r["num_train_steps"] = cfg.num_train_steps + r["keep_period"] = cfg.keep_period + r["save_interval"] = cfg.save_interval + r["batch_size"] = cfg.batch_size + r["num_workers"] = cfg.num_workers + r["ema_decay"] = cfg.ema_decay + r["encoder_lr_scale"] = cfg.encoder_lr_scale + r["seed_default"] = cfg.seed + r["lr"] = {str(s): float(lr(s)) for s in (0, 1, 1000, 2000, 50_000, 100_000, 150_000, 199_999)} + r["weight_loader"] = getattr(cfg.weight_loader, "params_path", str(cfg.weight_loader)) + r["weight_loader_exists"] = pathlib.Path(r["weight_loader"]).exists() + + # augmentation picture (owner req 3) + d = cfg.data + r["aug"] = { + "image_aug": cfg.image_aug, + "knn_pairs": getattr(d, "knn_pairs", None), + "knn_distance_threshold": getattr(d, "knn_distance_threshold", None), + "knn_augment_play": getattr(d, "knn_augment_play", None), + "spectral_norm_policy": getattr(cfg.model, "spectral_norm_policy", None), + "policy_bottleneck_beta": getattr(cfg.model, "policy_bottleneck_beta", None), + "bottleneck_policy": getattr(cfg.model, "bottleneck_policy", None), + "adv_path": getattr(d, "adv_path", None), + "adv_beta": getattr(d, "adv_beta", None), + } + + # norm stats actually behind assets_dirs + ns = pathlib.Path(cfg.assets_base_dir) / cfg.name / "jmarangola/rsm_cooking_v5/norm_stats.json" + r["norm_stats_path"] = str(ns) + r["norm_stats_resolved"] = str(ns.resolve()) + r["norm_stats_md5"] = md5(ns) if ns.exists() else None + r["norm_stats_is_parent_per_frame_file"] = r["norm_stats_md5"] == "da20b66d4beb1dae800603b6745623c3" + + print(json.dumps({k: v for k, v in r.items()}, indent=2, default=str), flush=True) + + # ---- (1) is anything horizon-shaped? ---------------------------------------------- + s10, s50 = flat(params_shape(cfg, 10)), flat(params_shape(cfg, 50)) + only10 = sorted(set(s10) - set(s50)) + only50 = sorted(set(s50) - set(s10)) + moved = sorted(k for k in set(s10) & set(s50) if s10[k] != s50[k]) + r["n_params_leaves"] = len(s50) + r["leaves_only_at_h10"] = only10 + r["leaves_only_at_h50"] = only50 + r["leaves_whose_shape_moved"] = {k: [s10[k], s50[k]] for k in moved} + r["horizon_shaped_params"] = bool(only10 or only50 or moved) + print( + f"[shape-diff] {len(s50)} param leaves; only@h10={len(only10)} only@h50={len(only50)} " + f"moved={len(moved)} -> horizon_shaped_params={r['horizon_shaped_params']}", + flush=True, + ) + for k in moved: + print(f" MOVED {k}: {s10[k]} -> {s50[k]}", flush=True) + # the projections and time embedding the brief calls out by name + for probe in ("action_in_proj", "action_out_proj", "action_time_mlp_in", "action_time_mlp_out", + "time_mlp_in", "time_mlp_out", "state_proj"): + hits = {k: s50[k] for k in s50 if probe in k} + for k, v in sorted(hits.items()): + print(f" [h50] {k}: {v} (h10: {s10.get(k)})", flush=True) + + # ---- (2) do the parent's params really load at h50? ------------------------------- + ps = params_shape(cfg, 50) + loaded = _load_weights_and_validate(cfg.weight_loader, ps) + nleaf = len(flat(loaded)) + r["weights_loaded_ok"] = True + r["n_loaded_leaves"] = nleaf + print(f"[load] OK -- {nleaf} leaves loaded and validated at action_horizon=50", flush=True) + del loaded + + except Exception as e: # noqa: BLE001 + r["error"] = f"{type(e).__name__}: {e}" + r["weights_loaded_ok"] = False + traceback.print_exc() + print(f"[load] FAILED: {e}", flush=True) + report[name] = r + + out = pathlib.Path("/proj/dmfexp/zwhong/rsm_rise/status/real/pi05_ft50_verify.json") + out.write_text(json.dumps(report, indent=2, default=str)) + print(f"\nwrote {out}", flush=True) + + # ---- summary table ------------------------------------------------------------------- + print("\n" + "=" * 100) + print(f"{'config':<38} {'H':>3} {'steps':>7} {'md5 ok':>7} {'hshaped':>8} {'load':>6}") + print("=" * 100) + bad = 0 + for n, r in report.items(): + ok = r.get("weights_loaded_ok") and r.get("norm_stats_is_parent_per_frame_file") \ + and not r.get("horizon_shaped_params", True) and r.get("action_horizon") == 50 + bad += 0 if ok else 1 + print(f"{n:<38} {r.get('action_horizon','?'):>3} {r.get('num_train_steps','?'):>7} " + f"{str(r.get('norm_stats_is_parent_per_frame_file')):>7} " + f"{str(r.get('horizon_shaped_params')):>8} {str(r.get('weights_loaded_ok')):>6}") + print("=" * 100) + print("ALL GOOD" if bad == 0 else f"{bad} CONFIG(S) NOT READY") + return 1 if bad else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/rsm_rise/scripts/real/pi05_ft50_verify.sh b/rsm_rise/scripts/real/pi05_ft50_verify.sh new file mode 100644 index 0000000000000000000000000000000000000000..2decc944770179a16b81109131e10219c1d77a86 --- /dev/null +++ b/rsm_rise/scripts/real/pi05_ft50_verify.sh @@ -0,0 +1,14 @@ +#!/usr/bin/env bash +# CPU runner for pi05_ft50_verify.py (rsm_real#14). No GPU: jax runs on cpu for eval_shape + the param load. +set -uo pipefail +ROOT=/proj/dmfexp/zwhong/rsm_rise +export OPENPI_DATA_HOME=$ROOT/.openpi_assets +export HF_LEROBOT_HOME=$ROOT/data/real/lerobot_home +export UV_CACHE_DIR=$ROOT/.uv_cache +export HF_HUB_OFFLINE=1 TOKENIZERS_PARALLELISM=false PYTHONUNBUFFERED=1 +export JAX_PLATFORMS=cpu +export WANDB_MODE=disabled +cd $ROOT/third_party/openpi +echo "[ft50-verify] host=$(hostname) job=${LSB_JOBID:-none} $(date -u)" +$ROOT/third_party/openpi/.venv/bin/python $ROOT/scripts/real/pi05_ft50_verify.py "$@" +rc=$?; echo "[ft50-verify] exit=$rc $(date -u)"; exit $rc diff --git a/rsm_rise/scripts/real/pi05_h50_cleanup.sh b/rsm_rise/scripts/real/pi05_h50_cleanup.sh new file mode 100644 index 0000000000000000000000000000000000000000..346450191cb9018ea7f52d1b96e840abb34591df --- /dev/null +++ b/rsm_rise/scripts/real/pi05_h50_cleanup.sh @@ -0,0 +1,40 @@ +#!/usr/bin/env bash +# rsm_rise PI05_200K, owner change 2026-09-25 ~03:20Z: the chunk-10 200k continuations (LSF 1908485-89) were +# bkilled; delete their exp dirs (210 GB of 42 GB train states) after archiving the small artefacts, and +# re-verify the five HF-published 29999 parents are intact. +set -uo pipefail +ROOT=/proj/dmfexp/zwhong/rsm_rise +ARC=$ROOT/runs/openpi/archive/killed_chunk10_200k +echo "[cleanup] start $(date -u)"; df -h /proj/dmfexp | tail -1 +echo "[cleanup] refusing to delete anything if a matching job still runs:" +bjobs -o "jobid stat job_name" 2>/dev/null | grep -E "p200k" && { echo "[cleanup] ABORT: a p200k job is still listed"; exit 4; } +mkdir -p $ARC +for d in $ROOT/runs/openpi/checkpoints/pi05_cooking_*_200k/*; do + [ -d "$d" ] || continue + n=$(basename $(dirname $d))/$(basename $d) + mkdir -p "$ARC/$n" + for f in eval_history.jsonl wandb_id.txt fit_curves.png augmentation_raw_vs_aug.png; do + [ -e "$d/$f" ] && cp -a "$d/$f" "$ARC/$n/$f" + done + echo "[cleanup] archived small artefacts of $n -> $ARC/$n ($(ls $ARC/$n | tr '\n' ' '))" + echo "[cleanup] step dirs present: $(ls -d $d/[0-9]* 2>/dev/null | xargs -n1 basename 2>/dev/null | tr '\n' ' ')" +done +echo "[cleanup] parent 29999 BEFORE:" +for p in pi05_cooking_stock/stock_s0 pi05_cooking_stock/stock_s1 pi05_cooking_rise/rise_s0 \ + pi05_cooking_rise/rise_s1 pi05_cooking_riseadv/riseadv_s0; do + echo " $p 29999: $(find $ROOT/runs/openpi/checkpoints/$p/29999 -type f | wc -l) files, $(du -sh $ROOT/runs/openpi/checkpoints/$p/29999 | cut -f1)" +done +for d in $ROOT/runs/openpi/checkpoints/pi05_cooking_stock_200k $ROOT/runs/openpi/checkpoints/pi05_cooking_rise_200k \ + $ROOT/runs/openpi/checkpoints/pi05_cooking_riseadv_200k; do + [ -d "$d" ] || continue + case "$d" in *_200k) ;; *) echo "[cleanup] SAFETY: $d is not a _200k dir, skipping"; continue;; esac + echo "[cleanup] rm -rf $d ($(du -sh $d | cut -f1))"; rm -rf "$d" +done +echo "[cleanup] parent 29999 AFTER:" +for p in pi05_cooking_stock/stock_s0 pi05_cooking_stock/stock_s1 pi05_cooking_rise/rise_s0 \ + pi05_cooking_rise/rise_s1 pi05_cooking_riseadv/riseadv_s0; do + echo " $p 29999: $(find $ROOT/runs/openpi/checkpoints/$p/29999 -type f | wc -l) files, $(du -sh $ROOT/runs/openpi/checkpoints/$p/29999 | cut -f1)" +done +# the stale assets symlinks of the killed configs +for s in $ROOT/runs/openpi/assets/pi05_cooking_*_200k; do [ -L "$s" ] && { echo "[cleanup] rm symlink $s"; rm -f "$s"; }; done +echo "[cleanup] done $(date -u)"; df -h /proj/dmfexp | tail -1 diff --git a/rsm_rise/scripts/real/pi05_h50_computenorm.sh b/rsm_rise/scripts/real/pi05_h50_computenorm.sh new file mode 100644 index 0000000000000000000000000000000000000000..9a5e8cd673fb384d6f1dcdce272bba075f5286dc --- /dev/null +++ b/rsm_rise/scripts/real/pi05_h50_computenorm.sh @@ -0,0 +1,36 @@ +#!/usr/bin/env bash +# rsm_rise PI05_200K chunk-50: the cooking norm stats are horizon-dependent (scripts/real/pi05_h50_normstats.py +# measured up to 18.6 % of a std on the action quantiles between H=10 and H=50, and pi05 normalises with +# q01/q99). Recompute them with openpi's OWN compute_norm_stats.py so the h50 files are produced by exactly +# the code that produced the parents' -- the horizon is then the only difference. +# The three shipped parent files are byte-identical and match a TRAIN-split, NO-augmentation pooling, i.e. +# they were computed once for stock and copied; do the same here. +set -uo pipefail +ROOT=/proj/dmfexp/zwhong/rsm_rise +export OPENPI_DATA_HOME=$ROOT/.openpi_assets HF_LEROBOT_HOME=$ROOT/data/real/lerobot_home +export HF_HUB_OFFLINE=1 TOKENIZERS_PARALLELISM=false PYTHONUNBUFFERED=1 JAX_PLATFORMS=cpu +cd $ROOT/third_party/openpi +echo "[norm] start $(date -u) host=$(hostname)" +$ROOT/third_party/openpi/.venv/bin/python scripts/compute_norm_stats.py --config-name pi05_cooking_stock_h50 +rc=$?; echo "[norm] compute rc=$rc $(date -u)" +[ $rc -ne 0 ] && exit $rc +SRC=$ROOT/runs/openpi/assets/pi05_cooking_stock_h50/jmarangola/rsm_cooking_v5/norm_stats.json +for cfg in pi05_cooking_rise_h50 pi05_cooking_riseadv_h50; do + d=$ROOT/runs/openpi/assets/$cfg/jmarangola/rsm_cooking_v5 + mkdir -p $d && cp -a $SRC $d/norm_stats.json && echo "[norm] copied -> $d/norm_stats.json" +done +$ROOT/third_party/openpi/.venv/bin/python - <<'PYEOF' +import json, numpy as np +R="/proj/dmfexp/zwhong/rsm_rise/runs/openpi/assets" +a=json.load(open(f"{R}/pi05_cooking_stock/jmarangola/rsm_cooking_v5/norm_stats.json"))["norm_stats"] +b=json.load(open(f"{R}/pi05_cooking_stock_h50/jmarangola/rsm_cooking_v5/norm_stats.json"))["norm_stats"] +print("[norm] h10 (parent, shipped) vs h50 (just computed), per field max |d| as a fraction of the h10 std:") +for k in ("state","actions"): + sd=np.asarray(a[k]["std"],float) + for f in ("mean","std","q01","q99"): + x=np.asarray(a[k][f],float); y=np.asarray(b[k][f],float) + print(f" {k}.{f}: max|d|={np.abs(x-y).max():.6g} = {(np.abs(x-y)/np.maximum(sd,1e-6)).max():.4%} of std") +print("[norm] h50 actions q01:", [round(v,4) for v in b["actions"]["q01"]]) +print("[norm] h50 actions q99:", [round(v,4) for v in b["actions"]["q99"]]) +PYEOF +echo "[norm] done $(date -u)" diff --git a/rsm_rise/scripts/real/pi05_h50_launch.sh b/rsm_rise/scripts/real/pi05_h50_launch.sh new file mode 100644 index 0000000000000000000000000000000000000000..6b3e7f7265d877c7cb633c469d91d83dcab79865 --- /dev/null +++ b/rsm_rise/scripts/real/pi05_h50_launch.sh @@ -0,0 +1,24 @@ +#!/usr/bin/env bash +# Launch the five CHUNK-50 pi0.5 cooking 200k fine-tunes, one 8-GPU node each (CLAUDE.md: never a 1-GPU job). +# Fresh from pi05_base, so no exp dir may exist beforehand (openpi_train.sh would then --resume a stale state). +set -uo pipefail +ROOT=/proj/dmfexp/zwhong/rsm_rise +# cfg:exp:SEED. The seed is NOT a config field for these runs -- the chunk-10 parents were launched with an +# explicit `--seed 0` / `--seed 1` tyro override (see logs/lsf/rr_openpi_stock_s1.1841430.out and the spec list +# in scripts/real/replay_watcher.sh), and TrainConfig.seed defaults to 42. Omitting it makes s0 and s1 the +# SAME run (caught on the first launch, LSF 1909408-12, killed at ~step 500 and relaunched). +PAIRS="pi05_cooking_stock_h50:stock_s0_h50:0 pi05_cooking_stock_h50:stock_s1_h50:1 \ +pi05_cooking_rise_h50:rise_s0_h50:0 pi05_cooking_rise_h50:rise_s1_h50:1 pi05_cooking_riseadv_h50:riseadv_s0_h50:0" +for cfg in pi05_cooking_stock_h50 pi05_cooking_rise_h50 pi05_cooking_riseadv_h50; do + f=$ROOT/runs/openpi/assets/$cfg/jmarangola/rsm_cooking_v5/norm_stats.json + [ -s "$f" ] || { echo "MISSING norm stats for $cfg ($f) -- run scripts/real/pi05_h50_computenorm.sh first"; exit 3; } +done +for p in $PAIRS; do + cfg=${p%%:*}; rest=${p#*:}; exp=${rest%%:*}; sd=${rest##*:} + d=$ROOT/runs/openpi/checkpoints/$cfg/$exp + if ls -d "$d"/[0-9]* >/dev/null 2>&1; then + echo "[launch] $exp already has checkpoints ($d) -- the runner will RESUME, which is what we want for a rerun" + fi + echo "[launch] $cfg $exp --seed $sd" + RR_GPUS=8 bash $ROOT/scripts/bsub_gpu_multi.sh rr_h50_$exp $ROOT/scripts/real/openpi_train.sh $cfg $exp --seed $sd +done diff --git a/rsm_rise/scripts/real/pi05_h50_normstats.py b/rsm_rise/scripts/real/pi05_h50_normstats.py new file mode 100644 index 0000000000000000000000000000000000000000..1e957540a7f09a52b97189865633cfefae6b6dc1 --- /dev/null +++ b/rsm_rise/scripts/real/pi05_h50_normstats.py @@ -0,0 +1,148 @@ +"""rsm_rise PI05_200K (chunk-50 change, owner 2026-09-25): does the action-chunk horizon change the norm stats? + +openpi's compute_norm_stats.py streams the TRAIN dataset through the repack + CookingInputs transforms and +feeds `state` [10] and `actions` [H, 10] into shared.normalize.RunningStats. With use_quantile_norm=True +(pi05) the numbers that matter are q01/q99, estimated from 5000-bin histograms. The chunk is built by +LeRobot's delta_indices with indices CLAMPED to the episode bounds, so H changes which (frame, offset) pairs +are pooled -- at H=50 3.35 % of chunk steps are end-of-episode repeats vs 0.61 % at H=10. + +This reproduces that pooling from the parquet action/state columns alone (no video decode, so it is a few +minutes on CPU instead of an hour), for H=10 and H=50, with and without the RISE kNN augmented rows. +Validation: the H=10 / no-aug reproduction must match the shipped norm_stats.json. Output tells us whether +the h50 configs need their own norm_stats.json or can share the parents'. +""" +import glob, json, sys +import numpy as np +import pyarrow.parquet as pq + +sys.path.insert(0, "/proj/dmfexp/zwhong/rsm_rise/third_party/openpi/src") +from openpi.shared import normalize as _norm # noqa: E402 + +ROOT = "/proj/dmfexp/zwhong/rsm_rise" +DATA = f"{ROOT}/data/real/lerobot_home/jmarangola/rsm_cooking_v5" +BATCH = 32 + + +def load_frames(): + """Global LeRobot frame order = episodes ascending. Returns actions [N,10], state [N,10], ep_from/ep_len.""" + acts, states, lens = [], [], [] + for f in sorted(glob.glob(f"{DATA}/data/chunk-*/episode_*.parquet")): + t = pq.read_table(f, columns=["action", "observation.state"]).to_pandas() + a = np.stack(t["action"].to_numpy()).astype(np.float32) + s = np.stack(t["observation.state"].to_numpy()).astype(np.float32) + acts.append(a); states.append(s); lens.append(len(a)) + lens = np.asarray(lens) + ep_from = np.concatenate([[0], lens.cumsum()[:-1]]) + return np.concatenate(acts), np.concatenate(states), ep_from, lens + + +def chunk_rows(A, ep_from, ep_len, rows, H): + """actions[rows] as [n, H, 10] with LeRobot's clamping (max(start, min(end-1, i+dt))).""" + ep_of = np.repeat(np.arange(len(ep_len)), ep_len) + e = ep_of[rows] + lo = ep_from[e][:, None] + hi = (ep_from[e] + ep_len[e] - 1)[:, None] + q = np.clip(rows[:, None] + np.arange(H)[None, :], lo, hi) + return A[q] + + +def knn_pairs(path, thr, augment_play, gripper_ok=True): + z = np.load(path, allow_pickle=False) + play, gripper, demo = z["play_gidx"], z["gripper"], z["demo"] + ok_e = (z["p2e_dist"] <= thr) & (gripper[z["p2e_gidx"]] == gripper[play][:, None]) + src = [np.repeat(play, ok_e.sum(1))]; nbr = [z["p2e_gidx"][ok_e]] + if augment_play: + ok_p = (z["p2p_dist"] <= thr) & (z["p2p_gidx"] != play[:, None]) & (demo[z["p2p_gidx"]] != demo[play][:, None]) + src.append(np.repeat(play, ok_p.sum(1))); nbr.append(z["p2p_gidx"][ok_p]) + return np.concatenate(src), np.concatenate(nbr) + + +def run(name, rows_base, A, S, ep_from, ep_len, H, aug=None): + """aug = (src, nbr) global rows; augmented sample = state of src, action chunk of nbr.""" + st = {"state": _norm.RunningStats(), "actions": _norm.RunningStats()} + order_state = [S[rows_base]] + order_act = [chunk_rows(A, ep_from, ep_len, rows_base, H)] + if aug is not None: + src, nbr = aug + order_state.append(S[src]) + order_act.append(chunk_rows(A, ep_from, ep_len, nbr, H)) + Sx = np.concatenate(order_state); Ax = np.concatenate(order_act) + n = (len(Sx) // BATCH) * BATCH # TorchDataLoader(num_batches=len//batch) drops the tail + for i in range(0, n, BATCH): + st["state"].update(Sx[i:i + BATCH]) + st["actions"].update(Ax[i:i + BATCH]) + out = {k: v.get_statistics() for k, v in st.items()} + print(f"[{name}] H={H} rows={len(Sx)} used={n}", flush=True) + return out + + +def cmp(tag, a, b): + """a, b: dict key -> NormStats.""" + worst = 0.0 + for k in ("state", "actions"): + for f in ("mean", "std", "q01", "q99"): + x = np.asarray(getattr(a[k], f), float); y = np.asarray(getattr(b[k], f), float) + scale = np.maximum(np.abs(np.asarray(getattr(a[k], "std"), float)), 1e-6) + rel = np.abs(x - y) / scale + worst = max(worst, float(rel.max())) + print(f" {tag} {k}.{f}: max |d| = {np.abs(x-y).max():.6g} (={rel.max():.4%} of std)") + print(f" {tag} WORST relative-to-std deviation over all fields: {worst:.4%}") + return worst + + +def main(): + A, S, ep_from, ep_len = load_frames() + print(f"frames {len(A)} episodes {len(ep_len)}", flush=True) + split = json.load(open(f"{ROOT}/data/derived/cooking_v5_split.json"))["episodes"] + train_eps = sorted(int(k) for k, v in split.items() if v["split"] == "train") + rows = np.concatenate([np.arange(ep_from[e], ep_from[e] + ep_len[e]) for e in train_eps]) + all_rows = np.arange(len(A)) + print(f"train episodes {len(train_eps)} rows {len(rows)}; all rows {len(all_rows)}", flush=True) + + shipped = {} + for cfg in ("pi05_cooking_stock", "pi05_cooking_rise", "pi05_cooking_riseadv"): + d = json.load(open(f"{ROOT}/runs/openpi/assets/{cfg}/jmarangola/rsm_cooking_v5/norm_stats.json"))["norm_stats"] + shipped[cfg] = {k: _norm.NormStats(**{f: np.asarray(v[f]) for f in ("mean", "std", "q01", "q99")}) for k, v in d.items()} + same = all(np.allclose(np.asarray(shipped["pi05_cooking_stock"][k].q01, float), + np.asarray(shipped[c][k].q01, float)) for c in shipped for k in ("state", "actions")) + print(f"shipped norm_stats identical across the three parent configs: {same}", flush=True) + + res = {} + # which pooling reproduces the shipped file? try train-split and all-episodes, with and without kNN aug + pairs = knn_pairs(f"{ROOT}/data/derived/cooking_v5_knn_pairs_ee.npz", 0.01, True) + print(f"kNN pairs at thr=0.01 augment_play=True: {len(pairs[0])}", flush=True) + cands = { + "train_noaug": (rows, None), + "all_noaug": (all_rows, None), + "train_aug": (rows, pairs), + } + best = None + for nm, (r, ag) in cands.items(): + res[(nm, 10)] = run(nm, r, A, S, ep_from, ep_len, 10, ag) + print(f"--- shipped vs {nm} H=10 ---") + w = cmp(nm, shipped["pi05_cooking_stock"], res[(nm, 10)]) + if best is None or w < best[1]: + best = (nm, w) + print(f"\n==> shipped norm_stats were produced by pooling `{best[0]}` (worst dev {best[1]:.4%})\n", flush=True) + + nm = best[0] + r, ag = cands[nm] + res[(nm, 50)] = run(nm, r, A, S, ep_from, ep_len, 50, ag) + print("--- H=10 vs H=50 (same pooling) ---") + w50 = cmp("h10-vs-h50", res[(nm, 10)], res[(nm, 50)]) + print("--- shipped vs H=50 ---") + ws = cmp("shipped-vs-h50", shipped["pi05_cooking_stock"], res[(nm, 50)]) + + out = {"pooling": nm, "worst_h10_repro": best[1], "worst_h10_vs_h50": w50, "worst_shipped_vs_h50": ws, + "h50": {k: {f: np.asarray(getattr(v, f), float).tolist() for f in ("mean", "std", "q01", "q99")} + for k, v in res[(nm, 50)].items()}, + "h10_repro": {k: {f: np.asarray(getattr(v, f), float).tolist() for f in ("mean", "std", "q01", "q99")} + for k, v in res[(nm, 10)].items()}} + p = f"{ROOT}/status/real/_pi05_h50_normstats.json" + json.dump(out, open(p, "w"), indent=1) + print(f"wrote {p}") + print(f"VERDICT: h10 reproduction error {best[1]:.4%} of std; h50 differs from h10 by {w50:.4%} of std.") + + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/real/pi05_h50_normstats.sh b/rsm_rise/scripts/real/pi05_h50_normstats.sh new file mode 100644 index 0000000000000000000000000000000000000000..8fbc62854e0ec7f1e19adc799831cf473559de82 --- /dev/null +++ b/rsm_rise/scripts/real/pi05_h50_normstats.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +set -uo pipefail +ROOT=/proj/dmfexp/zwhong/rsm_rise +$ROOT/third_party/openpi/.venv/bin/python $ROOT/scripts/real/pi05_h50_normstats.py +echo "[normstats] exit=$? $(date -u)" diff --git a/rsm_rise/scripts/real/pi05_h50_prep.sh b/rsm_rise/scripts/real/pi05_h50_prep.sh new file mode 100644 index 0000000000000000000000000000000000000000..e4325ff69bdb755a54aea2b8e177246fdbd63c34 --- /dev/null +++ b/rsm_rise/scripts/real/pi05_h50_prep.sh @@ -0,0 +1,73 @@ +#!/usr/bin/env bash +# One-shot prep for the CHUNK-50 pi0.5 cooking runs (owner 2026-09-25: "expand the action chunk length to be +# 50 steps ... 50 Hz -> 1 second wall clock"). Idempotent. +# 1. tag the five KILLED chunk-10 200k continuation W&B runs with `killed_chunk10` +# 2. (no W&B pre-creation: these start FRESH, and train.py's init_wandb(resuming=False) creates the run +# itself with name=exp_name=_h50 and the FULL TrainConfig as its config, then writes +# wandb_id.txt. Pre-creating would be worse -- --overwrite rmtree's the dir, id file included.) +# 3. print the resolved _h50 TrainConfigs, their LR curve, and the dataset fps sanity check +set -uo pipefail +ROOT=/proj/dmfexp/zwhong/rsm_rise +CK=$ROOT/runs/openpi/checkpoints +source $ROOT/wandb_env.sh +export HF_HUB_OFFLINE=1 TOKENIZERS_PARALLELISM=false PYTHONUNBUFFERED=1 JAX_PLATFORMS=cpu +export OPENPI_DATA_HOME=$ROOT/.openpi_assets HF_LEROBOT_HOME=$ROOT/data/real/lerobot_home +PY=$ROOT/third_party/openpi/.venv/bin/python + +echo "[prep] ==== 1. tag the five KILLED chunk-10 200k continuations in W&B ====" +$PY - <<'PYEOF' +import pathlib +from wandb import Api +ARC = pathlib.Path("/proj/dmfexp/zwhong/rsm_rise/runs/openpi/archive/killed_chunk10_200k") +PAIRS = [("pi05_cooking_stock","stock_s0"),("pi05_cooking_stock","stock_s1"), + ("pi05_cooking_rise","rise_s0"),("pi05_cooking_rise","rise_s1"), + ("pi05_cooking_riseadv","riseadv_s0")] +api = Api() +for cfg, exp in PAIRS: + idf = ARC / f"{cfg}_200k" / f"{exp}_200k" / "wandb_id.txt" + if not idf.exists(): + print(f"[tag] no archived id for {exp}_200k ({idf})", flush=True); continue + rid = idf.read_text().strip() + try: + r = api.run(f"richardrl/rsm_rise/{rid}") + if "killed_chunk10" not in r.tags: + r.tags = list(r.tags) + ["killed_chunk10"] + note = ("KILLED 2026-09-25 ~03:20 UTC (bkill): superseded by the chunk-50 run " + exp + "_h50 " + "(action_horizon 10 -> 50 = 1.0 s at the dataset 50 Hz). Checkpoints deleted.") + if note not in (r.notes or ""): + r.notes = ((r.notes or "") + "\n" + note).strip() + r.update() + print(f"[tag] {exp}_200k {rid}: tags={r.tags} url=https://wandb.ai/richardrl/rsm_rise/runs/{rid}", flush=True) + except Exception as e: + print(f"[tag] FAILED {exp}_200k {rid}: {e}", flush=True) +PYEOF + +echo "[prep] ==== 3. resolved _h50 configs ====" +cd $ROOT/third_party/openpi +$PY - <<'PYEOF' +import json +from openpi.training import config as _c +info = json.load(open("/proj/dmfexp/zwhong/rsm_rise/data/real/lerobot_home/jmarangola/rsm_cooking_v5/meta/info.json")) +fps = info["fps"] +print(f"dataset fps = {fps} -> action_horizon 50 = {50/fps:.3f} s (chunk 10 was {10/fps:.3f} s)") +assert fps == 50, f"dataset fps is {fps}, NOT 50 -- stop and report (owner assumed 50 Hz)" +for name in ("pi05_cooking_stock_h50","pi05_cooking_rise_h50","pi05_cooking_riseadv_h50"): + cfg = _c.get_config(name) + m = cfg.model + print(f"--- {name}: action_horizon={m.action_horizon} action_dim={m.action_dim} pi05={m.pi05} " + f"spectral_norm={getattr(m,'spectral_norm_policy',None)} beta={getattr(m,'policy_bottleneck_beta',None)}") + print(f" steps={cfg.num_train_steps} keep_period={cfg.keep_period} save_interval={cfg.save_interval} " + f"batch={cfg.batch_size} workers={cfg.num_workers} fsdp={cfg.fsdp_devices} ema={cfg.ema_decay} " + f"enc_lr_scale={cfg.encoder_lr_scale} img_aug={cfg.image_aug}") + print(f" weight_loader={cfg.weight_loader}") + print(f" knn={cfg.data.knn_pairs} thr={cfg.data.knn_distance_threshold} aug_play={cfg.data.knn_augment_play} adv={cfg.data.adv_path}") + print(f" assets_dirs={cfg.assets_dirs} exists={cfg.assets_dirs.exists()} " + f"norm_stats={(cfg.assets_dirs/'jmarangola/rsm_cooking_v5/norm_stats.json').exists()}") + sch = cfg.lr_schedule.create() + print(" lr:", " ".join(f"{s}={float(sch(s)):.3e}" for s in (0, 1000, 50000, 100000, 150000, 199999))) + # the chunk-50 delta_timestamps the loader will build + dc = cfg.data.create(cfg.assets_dirs, cfg.model) + print(f" action_sequence_keys={dc.action_sequence_keys} -> delta t = " + f"[0 .. {(m.action_horizon-1)/fps:.2f}] s in {m.action_horizon} steps; episodes={len(dc.episodes or [])}") +PYEOF +echo "[prep] done rc=$?" diff --git a/rsm_rise/scripts/real/pi05_h50_rebuild_patch.sh b/rsm_rise/scripts/real/pi05_h50_rebuild_patch.sh new file mode 100644 index 0000000000000000000000000000000000000000..6c18489cac31b250ce5469c64e2596210dd61859 --- /dev/null +++ b/rsm_rise/scripts/real/pi05_h50_rebuild_patch.sh @@ -0,0 +1,79 @@ +#!/usr/bin/env bash +# Rebuild rsm_real's vendored openpi patch so it carries the CHUNK-50 work instead of the killed `_200k` +# continuations: the three `pi05_cooking_*_h50` TrainConfigs, and fit_metrics' `*_chunk10_*` variants. +# +# Same discipline as scripts/real/pi05_200k_rebuild_patch.sh: the shipped patch is NOT a `git diff` of the +# rsm_rise openpi tree (it carries the rsm_real#5 inference-split fix that was never back-ported, and the +# rsm_rise tree carries run-54 factorial configs the patch has never shipped). So: replay the shipped patch +# AS OF THE BRANCH POINT onto pristine upstream, apply ONLY our two blocks on top, re-diff, and assert that +# the new patch drops nothing. +set -euo pipefail +ROOT=/proj/dmfexp/zwhong/rsm_rise +WT=${1:-/proj/dmfexp/zwhong/scratch_pi05_200k/rsm_real_scaffold} +BASE_REF=${2:-2dc85c8} # the branch point: the patch WITHOUT the _200k block +WORK=/proj/dmfexp/zwhong/scratch_pi05_200k/openpi_rebuild_h50 +PIN=$(head -1 $WT/rise_stack/openpi/UPSTREAM_COMMIT.txt) +rm -rf $WORK; mkdir -p $WORK/up +cd $WT && git show "$BASE_REF:rise_stack/openpi/rise_on_pi05.patch" > $WORK/base.patch +echo "[rebuild] pin=$PIN base=$BASE_REF base.patch=$(wc -l < $WORK/base.patch) lines" +cd $ROOT/third_party/openpi && git archive "$PIN" | tar -x -C $WORK/up +cd $WORK/up +git init -q && git add -A && git -c user.email=rr@local -c user.name=rr commit -qm "upstream $PIN" +echo "[rebuild] ---- git apply --check of the BASE patch onto pristine $PIN ----" +git apply --check $WORK/base.patch && echo "[rebuild] BASE PATCH APPLIES CLEAN" +git apply $WORK/base.patch + +echo "[rebuild] ---- insert the _h50 config block and the chunk10 fit metrics ----" +python3 - "$ROOT" <<'PY' +import sys, pathlib +root = pathlib.Path(sys.argv[1]) + +# 1. the _h50 TrainConfig block, verbatim from the live rsm_rise config.py so the two can never drift +live = (root / "third_party/openpi/src/openpi/training/config.py").read_text() +start = live.index("# ---- rsm_rise (#263 follow-up, owner 2026-09-25): CHUNK-50 200k cooking fine-tunes") +end = live.index("if len({config.name for config in _CONFIGS}) != len(_CONFIGS):", start) +block = live[start:end] +p = pathlib.Path("src/openpi/training/config.py") +src = p.read_text() +anchor = "if len({config.name for config in _CONFIGS}) != len(_CONFIGS):" +assert src.count(anchor) == 1, src.count(anchor) +assert "_cooking_h50" not in src and "_cooking_200k" not in src, "base patch already carries a continuation block" +p.write_text(src.replace(anchor, block + anchor)) +print(f"[rebuild] config.py: inserted {len(block)} chars / {block.count(chr(10))} lines") + +# 2. the *_chunk10_* fit metrics, verbatim from the live rsm_rise train.py +livet = (root / "third_party/openpi/scripts/train.py").read_text() +s2 = livet.index(" # rsm_rise (owner 2026-09-25, chunk 50): the *_chunk_* means above run over") +e2 = livet.index(" return m", s2) +fit = livet[s2:e2] +q = pathlib.Path("scripts/train.py") +t = q.read_text() +a2 = ''' for i, n in enumerate(ACT_NAMES): + m[f"mse_{n}"] = float((d[..., i] ** 2).mean()) + return m''' +assert t.count(a2) == 1, t.count(a2) +q.write_text(t.replace(a2, a2[:-len(" return m")] + fit + " return m")) +print(f"[rebuild] train.py: inserted {len(fit)} chars / {fit.count(chr(10))} lines") +PY + +git add -A +git diff --cached HEAD > $WORK/rise_on_pi05.patch +echo "[rebuild] new patch: $(wc -l < $WORK/rise_on_pi05.patch) lines" + +echo "[rebuild] ---- verify the NEW patch applies clean to pristine upstream ----" +rm -rf $WORK/verify; mkdir -p $WORK/verify +cd $ROOT/third_party/openpi && git archive "$PIN" | tar -x -C $WORK/verify +cd $WORK/verify && git init -q && git add -A && git -c user.email=rr@local -c user.name=rr commit -qm base +git apply --check $WORK/rise_on_pi05.patch && echo "[rebuild] NEW PATCH APPLIES CLEAN" +git apply $WORK/rise_on_pi05.patch +PY=$ROOT/third_party/openpi/.venv/bin/python +$PY -c "import ast;ast.parse(open('src/openpi/training/config.py').read());print('[rebuild] patched config.py parses')" +$PY -c "import ast;ast.parse(open('scripts/train.py').read());print('[rebuild] patched train.py parses')" + +echo "[rebuild] ---- diff-of-diffs: base vs new (should be ONLY our two blocks + line/hash shifts) ----" +{ diff $WORK/base.patch $WORK/rise_on_pi05.patch || true; } | grep -E "^>" | grep -vE "^> (index |@@ )" | head -40 || true +{ diff $WORK/base.patch $WORK/rise_on_pi05.patch || true; } | grep -E "^<" | grep -vE "^< (index |@@ )" > $WORK/removed.txt || true +echo "[rebuild] lines the new patch DROPS vs the base patch (must be 0): $(wc -l < $WORK/removed.txt)" +head -20 $WORK/removed.txt +test "$(wc -l < $WORK/removed.txt)" -eq 0 +echo "[rebuild] OK -> $WORK/rise_on_pi05.patch" diff --git a/rsm_rise/scripts/real/pi05_h50_renumber_docs.py b/rsm_rise/scripts/real/pi05_h50_renumber_docs.py new file mode 100644 index 0000000000000000000000000000000000000000..a8720234d88a0675e0c77601dc9a65bdfb32b323 --- /dev/null +++ b/rsm_rise/scripts/real/pi05_h50_renumber_docs.py @@ -0,0 +1,66 @@ +"""Recompute rise_stack/openpi/README.md's per-file +ins/-del table, its totals row, the headline line and +SETUP.md's "N files and X inserted lines" from the SHIPPED patch bytes, after the patch is replaced. + +tests/test_rise_stack_openpi_patch_numbers.py recomputes the same numbers and fails on any drift, so this +script exists to keep the prose honest rather than to be believed. + +usage: pi05_h50_renumber_docs.py +""" +import pathlib, re, sys + +wt = pathlib.Path(sys.argv[1]) +patch = (wt / "rise_stack/openpi/rise_on_pi05.patch").read_text().splitlines() + +# numstat straight from the hunk lines, exactly as the guard test does +files, cur = {}, None +for ln in patch: + if ln.startswith("diff --git "): + cur = ln.split(" b/")[-1] + files.setdefault(cur, [0, 0]) + elif ln.startswith("+++ ") or ln.startswith("--- ") or ln.startswith("@@"): + continue + elif cur and ln.startswith("+"): + files[cur][0] += 1 + elif cur and ln.startswith("-"): + files[cur][1] += 1 +ti = sum(v[0] for v in files.values()) +td = sum(v[1] for v in files.values()) +print(f"patch: {len(files)} files, +{ti} / -{td}") +for f, (a, d) in sorted(files.items(), key=lambda kv: -kv[1][0]): + print(f" {f}: +{a} / -{d}") + + +def fmt(a, d): + return f"+{a:,}" if d == 0 else f"+{a:,} / -{d:,}" + + +rp = wt / "rise_stack/openpi/README.md" +txt = rp.read_text() +n_before = txt + +# per-file rows +for f, (a, d) in files.items(): + pat = re.compile(r"^(\| `" + re.escape(f) + r"` \| )([^|]*?)( \|)", re.M) + if not pat.search(txt): + print(f" !! no README row for {f}") + continue + txt = pat.sub(lambda m: m.group(1) + fmt(a, d) + m.group(3), txt) + +# totals row +txt = re.sub(r"\| \*\*\d+ files, total\*\* \| \*\*[^*]*\*\* \|", + f"| **{len(files)} files, total** | **+{ti:,} / -{td:,}** |", txt) +# headline bullet +txt = re.sub(r"(\[`rise_on_pi05\.patch`\]\(rise_on_pi05\.patch\), )\d+ files, [\d,]+ insertions and [\d,]+ deletions", + rf"\g<1>{len(files)} files, {ti:,} insertions and {td:,} deletions", txt) +# the self-referential sentence that quotes the headline +txt = re.sub(r"(or the `)\d+ files,\n?([\d,]+) insertions` line above it", + lambda m: f"{m.group(1)}{len(files)} files,\n{ti:,} insertions` line above it", txt) +rp.write_text(txt) +print(f"README.md {'CHANGED' if txt != n_before else 'unchanged'}") + +sp = wt / "SETUP.md" +s = sp.read_text() +s2 = re.sub(r"is \d+ files and [\d,]+ inserted lines on top of upstream commit", + f"is {len(files)} files and {ti:,} inserted lines on top of upstream commit", s) +sp.write_text(s2) +print(f"SETUP.md {'CHANGED' if s2 != s else 'unchanged'}") diff --git a/rsm_rise/scripts/real/pi05_h50_tag_aborted.sh b/rsm_rise/scripts/real/pi05_h50_tag_aborted.sh new file mode 100644 index 0000000000000000000000000000000000000000..6a919f6ba0e2496d5bb4949953e4f83a41fee77a --- /dev/null +++ b/rsm_rise/scripts/real/pi05_h50_tag_aborted.sh @@ -0,0 +1,27 @@ +#!/usr/bin/env bash +# The first h50 launch (LSF 1909408-12) omitted the `--seed 0/1` tyro override the chunk-10 parents used, so +# TrainConfig.seed fell back to 42 and s0/s1 were the SAME run. Killed at ~step 500 (no checkpoint written) +# and relaunched as 1909448-52 with the seeds. Tag the five stray W&B runs so nobody mistakes them. +set -uo pipefail +ROOT=/proj/dmfexp/zwhong/rsm_rise +source $ROOT/wandb_env.sh +$ROOT/third_party/openpi/.venv/bin/python - <<'PYEOF' +from wandb import Api +api = Api() +IDS = {"stock_s0_h50": "ni4uad09", "stock_s1_h50": "uewb6syk", "rise_s0_h50": "t0r57dsa", + "rise_s1_h50": "9yuvx5op", "riseadv_s0_h50": "18y9r6wl"} +for name, rid in IDS.items(): + try: + r = api.run(f"richardrl/rsm_rise/{rid}") + if "aborted_seed42" not in r.tags: + r.tags = list(r.tags) + ["aborted_seed42"] + note = ("ABORTED at ~step 500 on 2026-09-25 (LSF 1909408-12): launched without the --seed 0/1 override " + "the chunk-10 parents used, so every run fell back to TrainConfig.seed=42 and s0/s1 were " + "identical. No checkpoint was written. Relaunched as LSF 1909448-52 with the seeds.") + if note not in (r.notes or ""): + r.notes = ((r.notes or "") + "\n" + note).strip() + r.update() + print(f"[tag] {name} {rid}: tags={r.tags}", flush=True) + except Exception as e: + print(f"[tag] FAILED {name} {rid}: {e}", flush=True) +PYEOF diff --git a/rsm_rise/scripts/real/pi05_h50_update_pr12.py b/rsm_rise/scripts/real/pi05_h50_update_pr12.py new file mode 100644 index 0000000000000000000000000000000000000000..f70233ee7baed059646c95e08eb54741a3ae0d50 --- /dev/null +++ b/rsm_rise/scripts/real/pi05_h50_update_pr12.py @@ -0,0 +1,53 @@ +"""Rewrite rsm_real's rise_stack/CHECKPOINTS.md: replace the (now killed) chunk-10 `_200k` continuation +section with the chunk-50 section, and swap the five `_200k` rows of the W&B index for the `_h50` runs. + +usage: pi05_h50_update_pr12.py + ids.json: {"stock_s0_h50": {"wandb": "", "job": "", "status": "running"}, ..., + "_status_block": "free text for the Status subsection"} +""" +import json, pathlib, re, sys + +wt, section_path, ids_path = sys.argv[1], sys.argv[2], sys.argv[3] +ids = json.load(open(ids_path)) +section = pathlib.Path(section_path).read_text() +p = pathlib.Path(wt) / "rise_stack/CHECKPOINTS.md" +doc = p.read_text() + +KEYS = ["stock_s0_h50", "stock_s1_h50", "rise_s0_h50", "rise_s1_h50", "riseadv_s0_h50"] +for k in KEYS: + e = ids[k] + url = f"https://wandb.ai/richardrl/rsm_rise/runs/{e['wandb']}" + section = section.replace(f"__WB_{k[:-4].upper()}__", f"**[{k}]({url})**") + section = section.replace(f"__ST_{k[:-4].upper()}__", f"{e['status']} (LSF {e['job']})") +section = section.replace("__STATUS_BLOCK__", ids["_status_block"]) +assert "__" not in section.replace("__", "", 0) or not re.search(r"__[A-Z_]+__", section), \ + re.findall(r"__[A-Z_]+__", section) + +# 1. replace the whole old section (from its H2 up to the next H2) +start = doc.index("## The 200k continuations of the five 30k pi0.5 fine-tunes") +nxt = doc.index("\n### Every pi0.5 training run in this document, with its W&B run", start) +doc = doc[:start] + section.rstrip("\n") + "\n" + doc[nxt:] + +# 2. the W&B index: the five `_200k` rows become the `_h50` runs +old_rows = re.findall(r"^\| `pi05_cooking_\w+_200k/\w+_200k` \| \[.*$", doc, re.M) +assert len(old_rows) == 5, old_rows +cfg_of = {"stock_s0_h50": "pi05_cooking_stock_h50", "stock_s1_h50": "pi05_cooking_stock_h50", + "rise_s0_h50": "pi05_cooking_rise_h50", "rise_s1_h50": "pi05_cooking_rise_h50", + "riseadv_s0_h50": "pi05_cooking_riseadv_h50"} +new_rows = [f"| `{cfg_of[k]}/{k}` | [{ids[k]['wandb']}](https://wandb.ai/richardrl/rsm_rise/runs/{ids[k]['wandb']}) |" + for k in KEYS] +for o, n in zip(old_rows, new_rows): + doc = doc.replace(o + "\n", n + "\n") + +# 3. a line under the index explaining what happened to the killed runs +marker = "The last four `_s0` rows are from-scratch attempts" +killed = json.load(open(ids_path)).get("_killed", {}) +if killed and marker in doc: + tbl = "\n".join(f"| `{c}` | [{i}](https://wandb.ai/richardrl/rsm_rise/runs/{i}) |" for c, i in killed.items()) + doc = doc.replace(marker, + "The five **killed chunk-10 200k continuations** are tagged `killed_chunk10` in W&B and their " + "checkpoints were deleted; they are listed here only so the tag is findable:\n\n" + "| killed continuation | W&B |\n|---|---|\n" + tbl + "\n\n" + marker) + +p.write_text(doc) +print(f"wrote {p} ({len(doc)} chars)") diff --git a/rsm_rise/scripts/real/pi05_hub_verify.py b/rsm_rise/scripts/real/pi05_hub_verify.py new file mode 100644 index 0000000000000000000000000000000000000000..54271c36694319e20b9f4d45e02f7751e8d784cd --- /dev/null +++ b/rsm_rise/scripts/real/pi05_hub_verify.py @@ -0,0 +1,21 @@ +#!/usr/bin/env python +"""gen_q #269 -- list the pi0.5 RISE-actor folders that actually resolve on the hub. +Writes status/real/pi05_hub_files_.txt : one line per pi05_* folder with its file count.""" +import os, sys, collections, json +from huggingface_hub import HfApi +repo = os.environ.get("RR_HF_REPO", "rli14/rsm_cooking_v5_checkpoints") +tag = os.environ.get("RR_TAG", "run18") +api = HfApi(token=os.environ.get("HF_TOKEN") or os.environ.get("HUGGINGFACE_HUB_TOKEN")) +files = api.list_repo_files(repo_id=repo, repo_type="model") +cnt = collections.Counter() +for f in files: + if "/" in f: + top = f.split("/", 1)[0] + if top.startswith("pi05_"): + cnt[top] += 1 +out = "/proj/dmfexp/zwhong/rsm_rise/status/real/pi05_hub_files_%s.txt" % tag +with open(out, "w") as fh: + fh.write("repo=%s total_files=%d\n" % (repo, len(files))) + for k in sorted(cnt): + fh.write("%s\t%d\n" % (k, cnt[k])) +print(open(out).read()) diff --git a/rsm_rise/scripts/real/pi05_optstate_audit.py b/rsm_rise/scripts/real/pi05_optstate_audit.py new file mode 100644 index 0000000000000000000000000000000000000000..8083f5cb5deb33ec9835579da8ce52e9a0648d66 --- /dev/null +++ b/rsm_rise/scripts/real/pi05_optstate_audit.py @@ -0,0 +1,134 @@ +#!/usr/bin/env python +"""PI05_NORM deliverable 2: does a saved openpi train_state contain the optimizer state, and is it restored? + +Evidence, not code-reading: + A. Open the orbax checkpoint of a *parent* run (pi05_cooking_stock/stock_s0/29999) and report the TREE of + `train_state`: is there an `opt_state` with AdamW mu/nu, is there `ema_params`, what is `step`, and what is + the optax `count` inside opt_state. Report per-leaf norms and zero-fraction for a sample of leaves so + "mu/nu are non-zero" is a measured statement. + B. Report what the `params` item contains (that is what CheckpointWeightLoader reads on a warm start) -- i.e. + show that a warm start via weight_loader gets params ONLY and therefore RESETS the optimizer, while a + `--resume` restores the whole train_state. +JAX on CPU; reads leaves lazily so the 31 GB checkpoint is never fully materialised. +""" +import json, os, re, sys, pathlib + +os.environ.setdefault("JAX_PLATFORMS", "cpu") +import numpy as np +import jax +import orbax.checkpoint as ocp + +ROOT = pathlib.Path("/proj/dmfexp/zwhong/rsm_rise") +ckpt = pathlib.Path(sys.argv[1] if len(sys.argv) > 1 + else ROOT / "runs/openpi/checkpoints/pi05_cooking_stock/stock_s0/29999") +out_path = pathlib.Path(sys.argv[2] if len(sys.argv) > 2 else ROOT / "status/real/pi05_optstate_audit.json") + +report = {"checkpoint": str(ckpt), "items": sorted(p.name for p in ckpt.iterdir())} +print(f"[optstate] checkpoint {ckpt}") +print(f"[optstate] items: {report['items']}") + +def tree_meta(sub: pathlib.Path): + """Orbax metadata for one item: path -> (shape, dtype) without loading the arrays.""" + with ocp.PyTreeCheckpointer() as ckptr: + md = ckptr.metadata(sub) + flat, _ = jax.tree_util.tree_flatten_with_path(md) + return [(jax.tree_util.keystr(k), getattr(v, "shape", None), str(getattr(v, "dtype", type(v).__name__))) + for k, v in flat] + +for item in ("train_state", "params"): + sub = ckpt / item + if not sub.exists(): + continue + meta = tree_meta(sub) + report[f"{item}_n_leaves"] = len(meta) + # top-level structure: the first two path components + tops = {} + for k, shp, dt in meta: + parts = [p for p in k.replace("']", "").split("['") if p] + top = parts[0] if parts else k + tops.setdefault(top, 0) + tops[top] += 1 + report[f"{item}_top_level"] = tops + print(f"\n[optstate] --- item '{item}': {len(meta)} leaves, top-level groups: {tops}") + for k, shp, dt in meta[:6]: + print(f" e.g. {k}: {shp}@{dt}") + +# ---- load the SMALL leaves of train_state (step, opt_state count) and a sample of mu/nu ------------------- +with ocp.PyTreeCheckpointer() as ckptr: + md = ckptr.metadata(ckpt / "train_state") + flat, treedef = jax.tree_util.tree_flatten_with_path(md) + keys = [jax.tree_util.keystr(k) for k, _ in flat] + +scalars = [i for i, (k, v) in enumerate(zip(keys, [v for _, v in flat])) + if getattr(v, "shape", None) in ((), None) or (getattr(v, "shape", None) == ())] +print(f"\n[optstate] scalar-shaped leaves ({len(scalars)}):") +for i in scalars[:40]: + print(f" {keys[i]}") + +# restore with a restore_args that only materialises the leaves we care about would need a matching tree; +# simplest robust route: restore the whole train_state item but ask orbax for float32 -> too big. +# Instead: pick leaves by name and read them one at a time through the ocdbt store via ocp.tree metadata. +sel_scalar = [k for k in keys if k.rstrip("']").endswith("step") or "count" in k] +# a representative small 2-D weight and its mu/nu +cands = [k for k in keys if "opt_state" in k] +report["opt_state_leaf_count"] = len(cands) +report["opt_state_sample_keys"] = cands[:12] +report["scalar_keys"] = [keys[i] for i in scalars] +report["keys_with_step_or_count"] = sel_scalar +print(f"\n[optstate] opt_state leaves: {len(cands)}") +print(f"[optstate] step/count-like keys: {sel_scalar}") + +# Full restore of only the scalar + a few sampled leaves, using ocp.args.PyTreeRestore with a transform tree. +# Easiest supported path: restore the item and immediately reduce. To bound memory we restore with +# `ocp.args.PyTreeRestore(restore_args=...)` where non-selected leaves are replaced by ocp.RestoreArgs(dtype=...) +# -- orbax has no "skip leaf" API, so instead we read the raw tensorstore for the selected leaves. +import tensorstore as ts + +def _ocdbt_path(keystr: str) -> str: + """orbax key path -> the dot-joined ocdbt key ( ['a'][1]['b'] -> a.1.b ).""" + parts = re.findall(r"\['([^']*)'\]|\[(\d+)\]", keystr) + return ".".join(a or b for a, b in parts) + + +def read_leaf(item_dir: pathlib.Path, keystr: str): + """Read one leaf array out of the ocdbt store (zarr v2 chunks, dot-joined keys).""" + key = _ocdbt_path(keystr) + spec = {"driver": "zarr", "kvstore": {"driver": "ocdbt", "base": f"file://{item_dir}", "path": key}} + try: + return ts.open(spec).result().read().result() + except Exception as e: # noqa: BLE001 + return f"ERR {type(e).__name__}: {e}" + + +ts_dir = ckpt / "train_state" +probe = {} +for k in sel_scalar[:20]: + v = read_leaf(ts_dir, k) + probe[k] = (v.tolist() if isinstance(v, np.ndarray) else v) + print(f"[optstate] {k} = {probe[k]}") +report["scalar_values"] = probe + +# sample a handful of opt_state leaves with real shapes and report norm / zero-fraction +big = [(k, v) for (k, _), v in zip(flat, [v for _, v in flat])] +shapes = {keys[i]: getattr(v, "shape", None) for i, (_, v) in enumerate(flat)} +picks = [k for k in cands if ("action_in_proj" in k or "action_out_proj" in k or "encoder_norm" in k + or k.endswith("['count']"))] +sample = picks + [k for k in cands if k not in picks and shapes.get(k) + and 0 < int(np.prod(shapes[k])) <= 2_000_000][:8] +stats = {} +for k in sample: + a = read_leaf(ts_dir, k) + if isinstance(a, str): + stats[k] = a + print(f"[optstate] {k}: {a}") + continue + a = np.asarray(a, dtype=np.float64) + stats[k] = {"shape": list(a.shape), "l2": float(np.linalg.norm(a)), + "rms": float(np.sqrt((a ** 2).mean())), "absmax": float(np.abs(a).max()), + "zero_frac": float((a == 0).mean()), "mean": float(a.mean())} + print(f"[optstate] {k}: shape={a.shape} rms={stats[k]['rms']:.4g} absmax={stats[k]['absmax']:.4g} " + f"zero_frac={stats[k]['zero_frac']:.4f}") +report["opt_state_leaf_stats"] = stats + +out_path.write_text(json.dumps(report, indent=1, default=str)) +print(f"\n[optstate] wrote {out_path}") diff --git a/rsm_rise/scripts/real/pi05_optstate_audit.sh b/rsm_rise/scripts/real/pi05_optstate_audit.sh new file mode 100644 index 0000000000000000000000000000000000000000..be87e8cd0febe692f392d81333aa6916d4f22d25 --- /dev/null +++ b/rsm_rise/scripts/real/pi05_optstate_audit.sh @@ -0,0 +1,8 @@ +#!/usr/bin/env bash +# CPU job wrapper: PI05_NORM deliverable 2. JAX on CPU, openpi venv. +set -uo pipefail +ROOT=/proj/dmfexp/zwhong/rsm_rise +export JAX_PLATFORMS=cpu OPENPI_DATA_HOME=$ROOT/.openpi_assets HF_LEROBOT_HOME=$ROOT/data/real/lerobot_home +export HF_HUB_OFFLINE=1 PYTHONUNBUFFERED=1 +cd $ROOT/third_party/openpi +$ROOT/third_party/openpi/.venv/bin/python $ROOT/scripts/real/pi05_optstate_audit.py "$@" diff --git a/rsm_rise/scripts/real/pi05_partial_screen.py b/rsm_rise/scripts/real/pi05_partial_screen.py new file mode 100644 index 0000000000000000000000000000000000000000..31a890a5251214f50a3cda09800f97897d085ce8 --- /dev/null +++ b/rsm_rise/scripts/real/pi05_partial_screen.py @@ -0,0 +1,69 @@ +#!/usr/bin/env python3 +"""gen_q #269 -- partial read-out of a planning screen that is still running. + +`scorer_openloop.py` writes its summary only after the last episode, but since run 5 it caches every finished +episode to `/parts/ep.npz` (aggregates in float64 on purpose). This rebuilds exactly the summary +quantities `build_pi05_screen_table.py` prints -- candidate spread, per-scorer first-step error, oracle, +headroom and oracle-rank percentile -- from whatever parts exist, so a 13-of-25 screen can be read without +waiting or re-running anything. Aggregation matches scorer_openloop.py's summary block: an unweighted mean +over DECISIONS (parts are concatenated), not a mean of per-episode means. + +usage: pi05_partial_screen.py [ ...] +""" +import glob +import json +import os +import sys + +import numpy as np + +MODES = ["greedy", "idql", "permuted__idql", "rsm", "permuted__rsm", "oracle"] +LABEL = {"permuted__idql": "perm:idql", "permuted__rsm": "perm:rsm"} + + +def read(d): + parts = sorted(glob.glob(os.path.join(d, "parts", "ep*.npz"))) + if not parts: + return None + spread, rows, ranks = [], {m: [] for m in MODES}, {m: [] for m in MODES} + for p in parts: + z = np.load(p, allow_pickle=True) + spread.append(np.asarray(z["spread"], np.float64)) + for m in MODES: + rows[m].append(np.asarray(z["rows_" + m], np.float64)) + ranks[m].append(np.asarray(z["rank_" + m], np.float64)) + out = {"dir": d, "n_episodes": len(parts), "final": os.path.exists(os.path.join(d, "scorer_openloop.json")), + "spread": float(np.concatenate(spread).mean())} + for m in MODES: + f1 = np.concatenate(rows[m])[:, 0] + out[m] = {"first_mean_cm": float(f1.mean()), "rank": float(np.concatenate(ranks[m]).mean())} + out["n_decisions"] = int(sum(len(r) for r in rows["greedy"])) + out["head"] = out["greedy"]["first_mean_cm"] - out["oracle"]["first_mean_cm"] + return out + + +def main(dirs): + got = [r for r in (read(d) for d in dirs) if r] + if not got: + print("[partial] no parts/ found in " + " ".join(dirs)) + return 1 + hdr = ["screen", "ep", "dec", "spread", "greedy", "oracle", "head"] + \ + [LABEL.get(m, m) for m in ("idql", "permuted__idql", "rsm", "permuted__rsm")] + \ + ["rank idql", "rank rsm"] + print("| " + " | ".join(hdr) + " |") + print("|" + "---|" * len(hdr)) + for r in got: + name = os.path.basename(r["dir"].rstrip("/")) + ("" if r["final"] else " *(partial)*") + cells = [name, f"{r['n_episodes']}", f"{r['n_decisions']}", f"{r['spread']:.3f}", + f"{r['greedy']['first_mean_cm']:.3f}", f"{r['oracle']['first_mean_cm']:.3f}", f"{r['head']:.3f}"] + cells += [f"{r[m]['first_mean_cm']:.3f}" for m in ("idql", "permuted__idql", "rsm", "permuted__rsm")] + cells += [f"{r['idql']['rank']:.3f}", f"{r['rsm']['rank']:.3f}"] + print("| " + " | ".join(cells) + " |") + return 0 + + +if __name__ == "__main__": + if len(sys.argv) < 2: + print(__doc__) + sys.exit(2) + sys.exit(main(sys.argv[1:])) diff --git a/rsm_rise/scripts/real/pi05_risebn_watch.sh b/rsm_rise/scripts/real/pi05_risebn_watch.sh new file mode 100644 index 0000000000000000000000000000000000000000..09323733d1c53d95a0c3a25b7996b3d6aaddc54e --- /dev/null +++ b/rsm_rise/scripts/real/pi05_risebn_watch.sh @@ -0,0 +1,23 @@ +#!/usr/bin/env bash +# gen_q #269 (closed) follow-on -- submit risebn's planning screen the moment its 9999 checkpoint lands, +# instead of waiting for the next worker run. Same pattern as pi05_corner_watch.sh: pi05_screen_risebn.sh +# is idempotent and carries its own duplicate guards (json / bjobs / unconfirmed-submission marker), so +# calling it on a timer is safe. Exits once the pack is queued (or after MAXH hours). +set -uo pipefail +ROOT=/proj/dmfexp/zwhong/rsm_rise +CK=$ROOT/runs/openpi/checkpoints/pi05_cooking_risebn/ws_s0/9999 +MAXH=${MAXH:-4} +deadline=$(( $(date +%s) + MAXH*3600 )) +while [ "$(date +%s)" -lt "$deadline" ]; do + if [ -d "$CK" ]; then + echo "[risebn-watch] $(date -u +%H:%M:%SZ) checkpoint exists -> pi05_screen_risebn.sh" + "$ROOT/scripts/real/pi05_screen_risebn.sh" + if bjobs -o "job_name stat" -noheader 2>/dev/null | grep -qE "^rr_pi05scr_risebn_pack "; then + echo "[risebn-watch] pack queued; exiting"; exit 0 + fi + else + echo "[risebn-watch] $(date -u +%H:%M:%SZ) waiting (last step $(ls -d ${CK%/9999}/[0-9]* 2>/dev/null | sed 's|.*/||' | sort -n | tail -1))" + fi + sleep 300 +done +echo "[risebn-watch] deadline reached without queueing a screen" diff --git a/rsm_rise/scripts/real/pi05_screen.sh b/rsm_rise/scripts/real/pi05_screen.sh new file mode 100644 index 0000000000000000000000000000000000000000..ccdd5e8b159b3438707ef52cc7a94d27fc7f82c4 --- /dev/null +++ b/rsm_rise/scripts/real/pi05_screen.sh @@ -0,0 +1,46 @@ +#!/usr/bin/env bash +# rsm_rise #269 -- PLANNING SCREEN of the pi0.5 proposers. +# +# The owner's point (PR jmarangola/rsm_real#1, 2026-09-22): the RISE actor should be built on pi0.5, and a RISE +# actor is judged by WHAT PLANNING CAN EXTRACT FROM ITS CANDIDATES, not by greedy fit. So every pi0.5 checkpoint +# is run through scorer_openloop.py with the flagship RSM read-out (the settings of +# status/real/openloop_S0Aidql_*/scorer_openloop.json: N=128, d1 depth 1, beta 0.99, prob read-out, T=25, +# stride 25, horizon 8, the 25 held-out episodes) and we read four things per proposer: +# candidate_spread_xyz_cm -- did the RISE regularisers WIDEN the proposal distribution? +# oracle first_mean_cm -- the headroom: the best candidate in the set (lower = a better set to plan over) +# greedy first_mean_cm -- the old, WRONG criterion (candidate 0 = a plain sample) +# rsm / idql vs their permuted control on the IDENTICAL candidates -- does any scorer harvest the spread? +# The IDQL column is the S0Aidql critic: it scores 84 px images + a 10-d absolute action, and pi0.5's candidates +# are the same 10-d absolute actions, so it can rank them (rise_stack/scorers.py IDQLScorer / rm_obs_single). +# +# usage: pi05_screen.sh [MAXEPS] (MAXEPS=10 for the first pass, 0 = all 25 held-out episodes) +set -uo pipefail +ROOT=/proj/dmfexp/zwhong/rsm_rise +MAXEPS=${1:-10} +CK=$ROOT/runs/openpi/checkpoints +RSM=$ROOT/runs/real_cooking_v5/rsm/R_M/ckpt_s100000.pt +# the S0Aidql critic that provides the IDQL column for every proposer (seed 1, epoch 3000) +IDQL=$ROOT/runs/cooking_v5_expert_suboptimal/policy/S0Aidql_seed1/cooking_v5_expert_suboptimal_S0Aidql_s1/20260921235824/models/model_epoch_3000.pth +SUF=""; [ "$MAXEPS" != 0 ] && SUF="_e${MAXEPS}" +COMMON=(--idql-ckpt "$IDQL" --rsm-ckpt "$RSM" --rsm-mode d1 --rsm-depth 1 --rsm-beta 0.99 + --rsm-score-kind prob --rsm-temperature 25 --n-cand 128 --horizon 8 --stride 25) +[ "$MAXEPS" != 0 ] && COMMON+=(--max-eps "$MAXEPS") + +# name:config:checkpoint (CELLS can be overridden to screen one new sweep proposer) +DEFAULT_CELLS=" +pi05stock_s1:pi05_cooking_stock:$CK/pi05_cooking_stock/stock_s1/29999 +pi05rise_s0:pi05_cooking_rise:$CK/pi05_cooking_rise/rise_s0/29999 +pi05rise_s1:pi05_cooking_rise:$CK/pi05_cooking_rise/rise_s1/29999 +pi05riseadv_s0:pi05_cooking_riseadv:$CK/pi05_cooking_riseadv/riseadv_s0/29999 +" +for cell in ${CELLS:-$DEFAULT_CELLS}; do + nm=${cell%%:*}; rest=${cell#*:}; cfg=${rest%%:*}; ck=${rest#*:} + [ -d "$ck" ] || { echo "[screen] SKIP $nm: no checkpoint at $ck"; continue; } + TAG=${nm}${SUF} + OUT=$ROOT/status/real/openloop_$TAG + [ -e "$OUT/scorer_openloop.json" ] && { echo "[screen] have $TAG"; continue; } + RR_QUEUE=${RR_QUEUE:-preemptable} RR_GROUP=${RR_GROUP:-grp_preemptable} RR_MEM=${RR_MEM:-96G} \ + $ROOT/scripts/bsub_gpu.sh rr_pi05scr_$TAG $ROOT/scripts/real/run_env_openpi.sh \ + $ROOT/scripts/real/scorer_openloop.py --policy "openpi:$cfg:$ck" "${COMMON[@]}" \ + --tag "$TAG" --out "$OUT" 2>&1 | tail -1 +done diff --git a/rsm_rise/scripts/real/pi05_screen_risebn.sh b/rsm_rise/scripts/real/pi05_screen_risebn.sh new file mode 100644 index 0000000000000000000000000000000000000000..871dcd8cd9d3027a1a9fa411af97a8c712fa4b8c --- /dev/null +++ b/rsm_rise/scripts/real/pi05_screen_risebn.sh @@ -0,0 +1,105 @@ +#!/usr/bin/env bash +# gen_q #269 (closed) -- the one follow-on: the 25-episode planning screen of the `risebn` diagnostic arm. +# +# Why this is not just another call to pi05_screen_sweep.sh: the admin banned 1-GPU jobs on 2026-09-22 20:30 +# UTC and scripts/bsub_gpu.sh now exits 3, so a screen has to go through bsub_gpu_pack.sh (one 4-GPU node, +# one payload per GPU). A single screen would waste 3 GPUs for ~1.5 h, so the 25 held-out episodes are split +# over the four GPUs with scorer_openloop.py's --ep-shard I/K. +# +# The shards are EXACTLY equivalent to an unsharded run: every episode's proposer noise and permuted-control +# shuffle are seeded per episode from [seed, ep] (scorer_openloop.py's per-episode RNG block, added in run 5 +# and covered by test_screen_resume.sh), so an episode's candidates do not depend on which episodes ran +# beside it. Each shard writes into its own openloop__s/ whose parts/ is a symlink to the shared +# openloop_/parts/, so the four cooperate on one per-episode cache without any of them overwriting the +# real summary; slot 0 then waits for all 25 parts and runs one final unsharded pass, which resumes every +# episode from parts (no candidate recomputed) and writes the scorer_openloop.json that +# build_pi05_screen_table.py reads. +# +# Settings are copied verbatim from pi05_screen.sh so the row is comparable to the other 13. +# +# usage: pi05_screen_risebn.sh (idempotent: does nothing if the json exists or the job is queued) +set -uo pipefail +ROOT=/proj/dmfexp/zwhong/rsm_rise +CK=$ROOT/runs/openpi/checkpoints/pi05_cooking_risebn/ws_s0/9999 +TAG=pi05risebn_ws9999 +OUT=$ROOT/status/real/openloop_$TAG +GEN=$ROOT/scripts/real/_gen +NAME=rr_pi05scr_risebn_pack +K=4 + +RSM=$ROOT/runs/real_cooking_v5/rsm/R_M/ckpt_s100000.pt +IDQL=$ROOT/runs/cooking_v5_expert_suboptimal/policy/S0Aidql_seed1/cooking_v5_expert_suboptimal_S0Aidql_s1/20260921235824/models/model_epoch_3000.pth +COMMON="--idql-ckpt $IDQL --rsm-ckpt $RSM --rsm-mode d1 --rsm-depth 1 --rsm-beta 0.99 \ + --rsm-score-kind prob --rsm-temperature 25 --n-cand 128 --horizon 8 --stride 25" + +if [ ! -d "$CK" ]; then + last=$(ls -d $ROOT/runs/openpi/checkpoints/pi05_cooking_risebn/ws_s0/[0-9]* 2>/dev/null | sed 's|.*/||' | sort -n | tail -1) + echo "[risebn-screen] not finished yet (last step ${last:-none}); nothing submitted"; exit 0 +fi +if [ -e "$OUT/scorer_openloop.json" ]; then + echo "[risebn-screen] already screened -> $OUT/scorer_openloop.json"; exit 0 +fi + +# Duplicate guard, same shape as pi05_screen_sweep.sh: a queued/running pack has no json yet, and a stalled +# mbatchd can hide a submission that will still appear, so we also keep an unconfirmed-submission marker. +JOBS=""; JOBS_OK=0 +for try in 1 2 3; do + out=$(bjobs -o "job_name stat" -noheader 2>&1); rc=$? + if [ $rc -eq 0 ] && [ -n "$out" ]; then JOBS="$out"; JOBS_OK=1; break; fi + case "$out" in *"No unfinished job found"*) JOBS=""; JOBS_OK=1; break;; esac + echo "[risebn-screen] bjobs attempt $try failed (rc=$rc)"; [ $try -lt 3 ] && sleep 5 +done +[ "$JOBS_OK" = 1 ] || { echo "[risebn-screen] ABORT: cannot read the LSF job table; refusing to submit"; exit 0; } +if printf '%s\n' "$JOBS" | grep -qE "^$NAME +(PEND|RUN|PSUSP|USUSP|SSUSP)$"; then + echo "[risebn-screen] pack already queued/running ($NAME)"; exit 0 +fi +PS=$ROOT/status/real/pi05_pending_submits/$TAG +if [ -e "$PS" ]; then + echo "[risebn-screen] an UNCONFIRMED submission exists ($PS) -- confirm with 'bjobs -w | grep $NAME'" + echo " and delete the marker before submitting again"; exit 0 +fi + +mkdir -p "$GEN" "$OUT/parts" "$(dirname "$PS")" +# Each shard gets its OWN --out dir whose parts/ is a symlink to the shared one: the shards then cooperate on +# one cache of per-episode npz files (atomic tmp->rename writes, keyed only by episode number) while their +# own partial summaries land in openloop__s/ and never overwrite the real +# openloop_/scorer_openloop.json, which only the final unsharded pass writes. +for i in $(seq 0 $((K-1))); do + sd=$ROOT/status/real/openloop_${TAG}_s$i + mkdir -p "$sd" + [ -e "$sd/parts" ] || ln -s "$OUT/parts" "$sd/parts" + cat > "$GEN/${NAME}_slot$i.sh" <> "$GEN/${NAME}_slot0.sh" </dev/null | wc -l) + echo "[slot0] waiting for all shards: \$n/25 parts (poll \$w)" + [ "\$n" -ge 25 ] && break + sleep 60 +done +$ROOT/scripts/real/run_env_openpi.sh $ROOT/scripts/real/scorer_openloop.py \\ + --policy "openpi:pi05_cooking_risebn:$CK" $COMMON --tag $TAG --out $OUT +echo "[slot0] final pass rc=\$? \$(date -u)" +EOF + +printf '%s submitted %s (4-GPU pack, 4 episode shards); job id unconfirmed until a later run sees it\n' \ + "$(date -u +'%F %H:%M UTC')" "$NAME" > "$PS" +RR_GPUS=4 RR_MEM=96G RR_QUEUE=preemptable RR_GROUP=grp_preemptable \ + bash $ROOT/scripts/bsub_gpu_pack.sh $NAME \ + "$GEN/${NAME}_slot0.sh" "$GEN/${NAME}_slot1.sh" "$GEN/${NAME}_slot2.sh" "$GEN/${NAME}_slot3.sh" 2>&1 | tail -2 diff --git a/rsm_rise/scripts/real/pi05_screen_sweep.sh b/rsm_rise/scripts/real/pi05_screen_sweep.sh new file mode 100644 index 0000000000000000000000000000000000000000..e28fbf92d42a4ef42ab5ff58a67198c52fdf2c89 --- /dev/null +++ b/rsm_rise/scripts/real/pi05_screen_sweep.sh @@ -0,0 +1,87 @@ +#!/usr/bin/env bash +# rsm_rise #269 -- screen every WARM-START SWEEP cell that has reached its final (9999) checkpoint. +# +# The sweep (spectral-norm weight x kNN augmentation radius, warm-started from pi05_cooking_rise/rise_s0/29999, +# 10k steps) is judged by the SAME planning screen as the four original proposers -- candidate spread, oracle +# headroom, RSM / IDQL against their permuted controls on identical candidates -- never by greedy fit. +# This script is idempotent: it submits a screen only for cells whose 9999 checkpoint exists and whose +# status/real/openloop_/scorer_openloop.json is not already there, so it can be re-run every worker run. +# +# usage: pi05_screen_sweep.sh [MAXEPS] (default 0 = all 25 held-out episodes; 10 for a fast first pass) +set -uo pipefail +ROOT=/proj/dmfexp/zwhong/rsm_rise +CK=$ROOT/runs/openpi/checkpoints +MAXEPS=${1:-0} +SUF=""; [ "$MAXEPS" != 0 ] && SUF="_e${MAXEPS}" + +# cell name (= config suffix and tag stem used by build_pi05_screen_table.py) +CELLS_LIST="wsctrl sn0p03_knn0p01 sn0p3_knn0p01 sn0p1_knn0p03 sn0p3_knn0p03 sn1_knn0p03 sn0p1_knn0p05 sn1_knn0p05" + +# run 13: snapshot the job table ONCE, fail-safe. The per-cell guard below used to call `bjobs ... 2>/dev/null` +# inline; when mbatchd hiccups, bjobs prints nothing to stdout, the grep finds no running screen and the script +# submits a DUPLICATE screen (it did at 11:48 UTC for sn1_knn0p03 -> 1855610, killed). So: try a few times, and +# if we cannot get a trustworthy listing, submit NOTHING this run (the next worker run will retry). +JOBS=""; JOBS_OK=0 +for try in 1 2 3; do + out=$(bjobs -o "job_name stat" -noheader 2>&1); rc=$? + if [ $rc -eq 0 ] && [ -n "$out" ]; then JOBS="$out"; JOBS_OK=1; break; fi + case "$out" in *"No unfinished job found"*) JOBS=""; JOBS_OK=1; break;; esac + echo "[sweep-screen] bjobs attempt $try failed (rc=$rc): ${out:-}" + [ $try -lt 3 ] && sleep 5 +done +if [ "$JOBS_OK" != 1 ]; then + echo "[sweep-screen] ABORT: cannot read the LSF job table; refusing to submit (would risk duplicates)"; exit 0 +fi + +# run 14: clear any UNCONFIRMED-submission marker whose job we can now see in the table (any state) or whose +# screen has since produced its json. Only markers for submissions that truly vanished survive this pass. +PSDIR=$ROOT/status/real/pi05_pending_submits +mkdir -p "$PSDIR" +for m in "$PSDIR"/*; do + [ -e "$m" ] || continue + mt=$(basename "$m") + if [ -e "$ROOT/status/real/openloop_$mt/scorer_openloop.json" ] \ + || printf '%s\n' "$JOBS" | grep -qE "^rr_pi05scr_${mt} +"; then + rm -f "$m"; echo "[sweep-screen] cleared confirmed submission marker $mt" + fi +done + +todo="" +for c in $CELLS_LIST; do + ck=$CK/pi05_cooking_$c/ws_s0/9999 + tag=pi05${c}_ws9999${SUF} + if [ ! -d "$ck" ]; then + last=$(ls -d $CK/pi05_cooking_$c/ws_s0/[0-9]* 2>/dev/null | sed 's|.*/||' | sort -n | tail -1) + echo "[sweep-screen] $c: not finished (last step ${last:-none})"; continue + fi + if [ -e "$ROOT/status/real/openloop_$tag/scorer_openloop.json" ]; then + echo "[sweep-screen] $c: already screened -> status/real/openloop_$tag/scorer_openloop.json"; continue + fi + # A screen that is PEND/RUN has no scorer_openloop.json yet, so the json guard alone would re-submit it + # (run 9: a background watcher and the next worker run can both call this script). Job name is the one + # pi05_screen.sh builds: rr_pi05scr_. + if printf '%s\n' "$JOBS" | grep -qE "^rr_pi05scr_${tag} +(PEND|RUN|PSUSP|USUSP|SSUSP)$"; then + echo "[sweep-screen] $c: screen already queued/running (rr_pi05scr_${tag})"; continue + fi + # run 14: mbatchd can stall so long that a bsub issued by an earlier run is STILL hung when the next run + # starts -- the job is not in the table yet but will appear later, so the guard above cannot see it and we + # would submit a duplicate. Each submission drops a marker under status/real/pi05_pending_submits/; + # the marker is only cleared by a run that has confirmed the job's id (bjobs/bhist by name). + if [ -e "$ROOT/status/real/pi05_pending_submits/$tag" ]; then + echo "[sweep-screen] $c: a submission for rr_pi05scr_${tag} is UNCONFIRMED (marker" + echo " status/real/pi05_pending_submits/$tag) -- confirm its job id with" + echo " 'bjobs -w | grep rr_pi05scr_${tag}' / 'bhist -n 2 -J rr_pi05scr_${tag}' and delete" + echo " the marker before this cell is screened again."; continue + fi + todo="$todo pi05${c}_ws9999:pi05_cooking_$c:$ck" +done + +[ -z "$todo" ] && { echo "[sweep-screen] nothing to submit"; exit 0; } +echo "[sweep-screen] submitting:$todo" +for t in $todo; do + mtag=${t%%:*} + printf '%s submitted rr_pi05scr_%s via pi05_screen.sh; job id unconfirmed until a later run sees it\n' \ + "$(date -u +'%F %H:%M UTC')" "$mtag" > "$PSDIR/$mtag" +done + +CELLS="$todo" "$ROOT/scripts/real/pi05_screen.sh" "$MAXEPS" diff --git a/rsm_rise/scripts/real/plot_proposal_curves.py b/rsm_rise/scripts/real/plot_proposal_curves.py new file mode 100644 index 0000000000000000000000000000000000000000..9ff76db1ae07121663a06b4452a488656d75083d --- /dev/null +++ b/rsm_rise/scripts/real/plot_proposal_curves.py @@ -0,0 +1,50 @@ +"""Training curves of the real-data PROPOSAL policies (#263). +Panel 1: openpi pi0.5 fine-tunes -- stock (plain BC), rise (kNN-augmented), riseadv (advantage-weighted) -- held-out + xyz L2 of the first action and of the chunk mean vs step, from the `EVAL step N:` lines of their LSF logs, + with the 1 cm fit gate. Panel 2: robomimic-stack policies on the same data (S0B = BC-unified, S0Aidql = + IDQL actor) -- training loss vs epoch from W&B (richardrl/rsm_rise), since those runs log nothing per-epoch + to disk. Writes docs/figs/real_proposal_curves.png and prints a compact table.""" +import glob, os, re, sys, collections +import matplotlib; matplotlib.use("Agg"); import matplotlib.pyplot as plt +ROOT = "/proj/dmfexp/zwhong/rsm_rise" +pat = re.compile(r"EVAL step (\d+): val: xyz_first=([0-9.]+)cm xyz_chunk=([0-9.]+)cm loss=([0-9.e-]+) grip_acc=([0-9.]+), train_eval: xyz_first=([0-9.]+)cm xyz_chunk=([0-9.]+)cm") +runs = {} +for j in ("stock_s0", "stock_s1", "rise_s0", "rise_s1", "riseadv_s0", "riseadv_s1"): + pts = {} + for f in glob.glob(f"{ROOT}/logs/lsf/rr_openpi_{j}.*.out"): + for m in pat.finditer(open(f, errors="ignore").read()): + s = int(m.group(1)); s -= s % 500 # the resume re-logs at N+1 + pts[s] = tuple(float(x) for x in m.groups()[1:]) + if pts: runs[j] = sorted(pts.items()) +fig, axes = plt.subplots(1, 2, figsize=(13, 4.6)) +ax = axes[0]; cols = {"stock": "C0", "rise": "C1", "riseadv": "C3"} +for j, pts in runs.items(): + fam, seed = j.rsplit("_s", 1); c = cols[fam]; ls = "-" if seed == "0" else "--" + x = [s for s, _ in pts] + ax.plot(x, [v[0] for _, v in pts], color=c, ls=ls, lw=1.8, label=f"{fam} s{seed} val first") + ax.plot(x, [v[1] for _, v in pts], color=c, ls=ls, lw=0.9, alpha=0.6, label=f"{fam} s{seed} val chunk") +ax.axhline(1.0, color="k", lw=0.8, ls=":", label="1 cm gate"); ax.set_ylim(0, 3.2); ax.set_xlim(0, 32000) +ax.set_xlabel("fine-tune step"); ax.set_ylabel("held-out xyz L2 (cm)"); ax.set_title("pi0.5 proposal policies (real cooking data)") +ax.legend(fontsize=6.5, ncol=2) +print("| run | last step | val first (cm) | val chunk (cm) | train first | train chunk | gate |") +print("|---|---|---|---|---|---|---|") +for j, pts in runs.items(): + s, v = pts[-1]; print(f"| {j} | {s} | {v[0]:.2f} | {v[1]:.2f} | {v[4]:.2f} | {v[5]:.2f} | {'first<1' if v[0]<1 else 'no'}{' & chunk<1' if v[1]<1 else ''} |") +# panel 2: W&B histories of the robomimic-stack runs +ax = axes[1]; ok = False +try: + import wandb + api = wandb.Api(timeout=60) + for r in api.runs("richardrl/rsm_rise", filters={"display_name": {"$regex": "cooking_v5_expert_suboptimal/(S0B|S0Aidql)_seed"}}): + h = r.history(samples=400, pandas=False) + keys = [k for k in (h[0].keys() if h else []) if "loss" in k.lower() and "policy" in k.lower()] or [k for k in (h[0].keys() if h else []) if "loss" in k.lower()] + if not keys: continue + k = sorted(keys)[0]; xs = [row.get("epoch", row.get("_step")) for row in h if row.get(k) is not None]; ys = [row[k] for row in h if row.get(k) is not None] + fam = re.search(r"/(S0B|S0Aidql)_seed(\d)", r.display_name); lab = f"{fam.group(1)} s{fam.group(2)}" if fam else r.display_name + ax.plot(xs, ys, lw=1.4, label=f"{lab}: {k}"); ok = True + print(f"| wandb {lab} | {len(ys)} pts | last {k}={ys[-1]:.4g} |") +except Exception as e: + print("wandb panel skipped:", str(e)[:120], file=sys.stderr) +ax.set_title("robomimic-stack proposal policies (W&B)" + ("" if ok else " -- unavailable")); ax.set_xlabel("epoch"); ax.set_ylabel("training loss") +if ok: ax.legend(fontsize=7); ax.set_yscale("log") +plt.tight_layout(); out = f"{ROOT}/docs/figs/real_proposal_curves.png"; plt.savefig(out, dpi=130); print("wrote", out) diff --git a/rsm_rise/scripts/real/plot_reward_timelines.py b/rsm_rise/scripts/real/plot_reward_timelines.py new file mode 100644 index 0000000000000000000000000000000000000000..2c64e39a5679033b2898febf5f48c814f99ba920 --- /dev/null +++ b/rsm_rise/scripts/real/plot_reward_timelines.py @@ -0,0 +1,85 @@ +#!/usr/bin/env python +"""Per-episode stage-vs-frame timelines with the positive reward frames shaded, for every reward +version of the #261 reward-head study. Reads only cache/real_cooking_v5 (meta.npz, edge_to.i16.npy, +reward_v*.f32.npy) -- every number in the figure is traceable to those files.""" +import json +from pathlib import Path +import numpy as np +import matplotlib +matplotlib.use("Agg") +import matplotlib.pyplot as plt + +CACHE = Path("/proj/dmfexp/zwhong/rsm_rise/cache/real_cooking_v5") +OUT = Path("/proj/dmfexp/zwhong/rsm_rise/docs/figs/real_stages"); OUT.mkdir(parents=True, exist_ok=True) +m = np.load(CACHE / "meta.npz", allow_pickle=True) +ep_from, ep_to = m["ep_from"].astype(int), m["ep_to"].astype(int) +succ = np.asarray(m["ep_success"], bool); path = np.asarray(m["ep_path"]) +et = np.load(CACHE / "edge_to.i16.npy").astype(int) +ef = np.load(CACHE / "edge_from.i16.npy").astype(int) +V = {k: np.load(CACHE / f"reward_{k}.f32.npy") + for k in ["v0_provenance", "v1_goaltrans", "v2_arrival", "v3_finalseg"]} +LBL = {"v0_provenance": "v0 provenance (dense)", "v1_goaltrans": "v1 goal transition", + "v2_arrival": "v2 arrival only", "v3_finalseg": "v3 final segment (all episodes)"} +COL = {"v0_provenance": "#8a8a8a", "v1_goaltrans": "#1f77b4", + "v2_arrival": "#d62728", "v3_finalseg": "#2ca02c"} + +# 3 expert (rewarded) + 3 suboptimal, one per distinct route where possible +exp = [i for i in range(len(ep_from)) if succ[i]][:3] +sub, seen = [], set() +for i in range(len(ep_from)): + if not succ[i] and str(path[i]) not in seen: + sub.append(i); seen.add(str(path[i])) + if len(sub) == 3: + break +eps = exp + sub + +fig, axes = plt.subplots(len(eps), 1, figsize=(10, 1.9 * len(eps)), sharex=False) +for ax, i in zip(axes, eps): + a, b = ep_from[i], ep_to[i] + n = b - a + t = np.arange(n) + # the state the episode is IN: edge_from, stepping up to edge_to at the very last frame + st = ef[a:b].astype(float) + ax.step(t, st, where="post", color="k", lw=1.3, label="stage (edge_from)") + ax.step(t, et[a:b].astype(float), where="post", color="k", lw=0.7, ls=":", + label="edge_to (target stage)") + for j, (k, v) in enumerate(V.items()): + p = v[a:b] > 0 + if p.any(): + ax.fill_between(t, -0.4 - 0.32 * j, -0.08 - 0.32 * j, where=p, + color=COL[k], step="post", lw=0) + ax.text(1.005, 0.78 - 0.21 * j, LBL[k], transform=ax.transAxes, fontsize=6, + color=COL[k], va="center") + ax.set_ylim(-1.7, 7) + ax.set_yticks([0, 1, 2, 3, 4, 5, 6]) + ax.set_ylabel("stage", fontsize=7) + ax.tick_params(labelsize=6) + ax.set_title(f"episode {i} route path {str(path[i])} " + f"{'EXPERT (rewarded)' if succ[i] else 'SUBOPTIMAL (never rewarded)'} " + f"{n} frames", fontsize=7.5, loc="left") +axes[-1].set_xlabel("frame within episode", fontsize=7) +fig.suptitle("rsm_cooking_v5: stage vs frame, with the positive reward frames of each label version " + "shaded\n(cache/real_cooking_v5: meta.npz, edge_from/edge_to.i16.npy, reward_v*.f32.npy)", + fontsize=8.5) +fig.tight_layout(rect=[0, 0, 0.84, 0.95]) +fig.savefig(OUT / "reward_timelines.png", dpi=170) +print("[tl] wrote", OUT / "reward_timelines.png", "episodes", eps) + +# bar chart of positive-frame counts per version, split expert / suboptimal +fig2, ax = plt.subplots(figsize=(6.4, 2.8)) +ks = list(V) +xe = [sum(int((V[k][ep_from[i]:ep_to[i]] > 0).sum()) for i in np.nonzero(succ)[0]) for k in ks] +xs = [sum(int((V[k][ep_from[i]:ep_to[i]] > 0).sum()) for i in np.nonzero(~succ)[0]) for k in ks] +x = np.arange(len(ks)) +ax.bar(x - 0.18, xe, 0.36, label="expert (rewarded) episodes", color="#1f77b4") +ax.bar(x + 0.18, xs, 0.36, label="suboptimal episodes", color="#d62728") +ax.set_yscale("symlog", linthresh=10) +ax.set_xticks(x); ax.set_xticklabels([LBL[k] for k in ks], fontsize=7, rotation=12) +ax.set_ylabel("positive frames (symlog)", fontsize=8) +for xi, (a_, b_) in zip(x, zip(xe, xs)): + ax.text(xi - 0.18, a_, str(a_), ha="center", va="bottom", fontsize=6.5) + ax.text(xi + 0.18, b_, str(b_), ha="center", va="bottom", fontsize=6.5) +ax.legend(fontsize=7); ax.tick_params(labelsize=7) +ax.set_title("positive frames per reward version (status/real/GOAL_REWARD.json)", fontsize=8) +fig2.tight_layout(); fig2.savefig(OUT / "reward_counts.png", dpi=170) +print("[tl] wrote", OUT / "reward_counts.png") diff --git a/rsm_rise/scripts/real/post_issue.sh b/rsm_rise/scripts/real/post_issue.sh new file mode 100644 index 0000000000000000000000000000000000000000..d689b469346a41de6df380077ac23a00fff66c33 --- /dev/null +++ b/rsm_rise/scripts/real/post_issue.sh @@ -0,0 +1,24 @@ +#!/usr/bin/env bash +# gen_q#280 / rsm_real#2 -- post ONE markdown file as a comment to BOTH issues, exactly once each. +# usage: scripts/real/post_issue.sh status/real/comment_foo.md +# Written after run 5 posted the TASK A table twice per issue (a shell loop that ran the POST in both the +# -w probe and the real call; the duplicates 5799347879 / 5799348936 had to be deleted). One curl per +# issue, the response id printed, the token never echoed. +set -euo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +MD=${1:?usage: post_issue.sh } +[ -f "$MD" ] || { echo "no such file: $MD"; exit 2; } +J=$(mktemp -p status/real body_post.XXXXXX.json) +venv_rsm/bin/python -c " +import json,sys; json.dump({'body': open(sys.argv[1]).read()}, open(sys.argv[2],'w')) +" "$MD" "$J" +TOK=$(grep -m1 'https://richardrl:' ~/.git-credentials | sed -E 's|https://richardrl:([^@]*)@.*|\1|') +# PT_ISSUES overrides the target pair (the metric spec of record lives in #281 / rsm_real#3, +# so a correction to a DEFINITION goes there rather than to the measurement issues). +for spec in ${PT_ISSUES:-williamd4112/gen_q:280 jmarangola/rsm_real:2}; do + repo=${spec%:*}; n=${spec#*:} + r=$(curl -sS -X POST -H "Authorization: token $TOK" -d @"$J" \ + "https://api.github.com/repos/$repo/issues/$n/comments") + echo "$repo#$n -> $(printf '%s' "$r" | venv_rsm/bin/python -c 'import json,sys; d=json.load(sys.stdin); print(d.get("id", d))')" +done +rm -f "$J" diff --git a/rsm_rise/scripts/real/pp_d1_timing.sh b/rsm_rise/scripts/real/pp_d1_timing.sh new file mode 100644 index 0000000000000000000000000000000000000000..088697980dd354836c165d698449ab24c09b717c --- /dev/null +++ b/rsm_rise/scripts/real/pp_d1_timing.sh @@ -0,0 +1,24 @@ +#!/usr/bin/env bash +# gen_q#280 / rsm_real#2 -- TIMING PROBE ONLY, throwaway dir, produces no measured cell. +# +# WHY. The 16-cell RSM pairs wave has been PEND on GPU capacity for >1 h and the `chain` read-out is not +# CPU-viable: smoke 1888569 took 445 s for ONE anchor at bank=2/particles=2 because the coin chain runs +# cap=67 levels per particle. But gen_q#280's read-out axis explicitly includes "chain against depth 1", +# and rsm_scorer.py:792 has a `d1` mode that runs ONE level and needs no hop head (pt_pairs_score.py:135 +# only passes --rsm-hop-ckpt when the mode starts with "chain"). If d1 at FULL settings (bank 16, +# particles 16) is cheap enough on CPU, the whole reward-head axis -- the brief's first sweep axis, and the +# one that has never been varied in any ranking test -- can be measured without waiting for a GPU. +# This probe changes NOTHING but the mode and the anchor count, and exists to produce one number: s/anchor. +set -uo pipefail +ROOT=/proj/dmfexp/zwhong/rsm_rise +export OPENPI_DATA_HOME=$ROOT/.openpi_assets HF_LEROBOT_HOME=$ROOT/data/real/lerobot_home UV_CACHE_DIR=$ROOT/.uv_cache +export HF_HUB_OFFLINE=1 TOKENIZERS_PARALLELISM=false PYTHONUNBUFFERED=1 +export MUJOCO_GL=disable CUDA_VISIBLE_DEVICES="" JAX_PLATFORMS=cpu +export PYTHONPATH=$ROOT/code/rise_robomimic:$ROOT/code/diffusion_policy:$ROOT/code/robosuite:$ROOT/code/mimicgen_environments:$ROOT/code/rise_code:$ROOT/scripts/real:${PYTHONPATH:-} +cd $ROOT/third_party/openpi +echo "[pp_d1_timing] host=$(hostname) job=${LSB_JOBID:-none} $(date -u)" +rm -rf $ROOT/status/real/pp_D1TIME +exec $ROOT/third_party/openpi/.venv/bin/python $ROOT/scripts/real/pt_pairs_score.py \ + --out $ROOT/status/real/pp_D1TIME --tag D1TIME --bank 16 --stride 5 --ep-shard 0/49 \ + --rsm-mode d1 --rsm-depth 1 --rsm-particles 16 \ + --rsm-ckpt "$ROOT/runs/real_cooking_v5/rsm/R_M/ckpt_s100000.pt" --rsm-beta 0.99 diff --git a/rsm_rise/scripts/real/pp_idql_cpu.sh b/rsm_rise/scripts/real/pp_idql_cpu.sh new file mode 100644 index 0000000000000000000000000000000000000000..73b80c7ba766e37b71502feffccba11bb32c559d --- /dev/null +++ b/rsm_rise/scripts/real/pp_idql_cpu.sh @@ -0,0 +1,25 @@ +#!/usr/bin/env bash +# gen_q#280 / rsm_real#2 -- the IDQL baseline COLUMN of the caliper-matched pairs test, run on CPU. +# Why CPU and why now: the 16-cell GPU wave (1888551/1888552 + drain) is PEND behind a saturated +# cluster (191 hosts cannot reserve 4 GPUs). Passing an EMPTY --rsm-ckpt makes pt_pairs_score.py build +# modes = ["idql","permuted:idql"] ONLY (line 118) and skip the DINO cache entirely, so this cell needs +# no GPU. It is NOT a duplicate of the GPU cells: it lands the baseline column, the measured permuted +# zero line, and -- the reason it is worth a run -- the raw-vs-centered gap at FULL anchor count, which +# says whether this pairs metric is anchor-driven BEFORE any RSM cell is read. +# Anchors/bank/stride/window/L are byte-identical to the GPU cells, so the reduce can table them together. +# usage: pp_idql_cpu.sh +set -uo pipefail +ROOT=/proj/dmfexp/zwhong/rsm_rise +I=${1:?shard i}; K=${2:?shard n} +export OPENPI_DATA_HOME=$ROOT/.openpi_assets HF_LEROBOT_HOME=$ROOT/data/real/lerobot_home UV_CACHE_DIR=$ROOT/.uv_cache +export HF_HUB_OFFLINE=1 TOKENIZERS_PARALLELISM=false PYTHONUNBUFFERED=1 +export MUJOCO_GL=disable CUDA_VISIBLE_DEVICES="" JAX_PLATFORMS=cpu +export OMP_NUM_THREADS=8 MKL_NUM_THREADS=8 +export PYTHONPATH=$ROOT/code/rise_robomimic:$ROOT/code/diffusion_policy:$ROOT/code/robosuite:$ROOT/code/mimicgen_environments:$ROOT/code/rise_code:$ROOT/scripts/real:${PYTHONPATH:-} +cd $ROOT/third_party/openpi +echo "[pp_idql_cpu] host=$(hostname) job=${LSB_JOBID:-none} shard=$I/$K $(date -u)" +exec $ROOT/third_party/openpi/.venv/bin/python $ROOT/scripts/real/pt_pairs_score.py \ + --out $ROOT/status/real/pp_IDQLCPU --tag IDQLCPU \ + --bank 16 --stride 5 --entry-window 100 --lengths 8 --ep-shard "$I/$K" \ + --idql-ckpt "$ROOT/runs/cooking_v5_expert_suboptimal/policy/S0Aidql_seed1/cooking_v5_expert_suboptimal_S0Aidql_s1/20260921235824/models/model_epoch_3000.pth" \ + --rsm-ckpt "" diff --git a/rsm_rise/scripts/real/pp_reduce_idql.sh b/rsm_rise/scripts/real/pp_reduce_idql.sh new file mode 100644 index 0000000000000000000000000000000000000000..e74cba158b012b2ab068c715deb96987a87695ab --- /dev/null +++ b/rsm_rise/scripts/real/pp_reduce_idql.sh @@ -0,0 +1,10 @@ +#!/usr/bin/env bash +# Reduce the IDQL-only CPU cell of the caliper-matched pairs test (gen_q#280 / rsm_real#2). +# CPU only: the reduce reads npz parts and refits the supervised ceiling/guard, no GPU. +set -uo pipefail +ROOT=/proj/dmfexp/zwhong/rsm_rise +export MUJOCO_GL=disable CUDA_VISIBLE_DEVICES="" OMP_NUM_THREADS=8 MKL_NUM_THREADS=8 +echo "[pp_reduce_idql] host=$(hostname) job=${LSB_JOBID:-none} $(date -u)" +exec $ROOT/venv_rsm/bin/python $ROOT/scripts/real/pt_pairs_reduce.py \ + --cells pp_IDQLCPU \ + --out $ROOT/status/real/PT_PAIRS_IDQL.md "$@" diff --git a/rsm_rise/scripts/real/pp_reduce_ladder.sh b/rsm_rise/scripts/real/pp_reduce_ladder.sh new file mode 100644 index 0000000000000000000000000000000000000000..bd0b341cc5972b2732e7bb8a277282bf3fbcc84b --- /dev/null +++ b/rsm_rise/scripts/real/pp_reduce_ladder.sh @@ -0,0 +1,18 @@ +#!/usr/bin/env bash +# gen_q#280 / rsm_real#2 -- the BASELINE LADDER on the caliper-matched S2 pairs. +# +# WHY: run 16 reported CEILING chunk:logreg 0.983 vs GUARD anchor:logreg 0.509 vs idql:centered 0.559 (ns). +# The obvious question against that table is whether 0.983 is a rich read of the chunk or a single trivial +# statistic -- and #280's own legitimate-baseline list (pose continuity, random, greedy) had no row at all. +# This reduce adds both, computed from arrays ALREADY stored in the npz parts, so it needs no scoring job +# and no GPU: nine out-of-fold logreg arms (sign learned on training episodes, never fished) plus random, +# each carried through the same caliper ladder, 200-draw rematch permuted null and episode bootstrap as the +# ceiling. `greedy index` is printed UNDEFINED, not omitted: it ranks within a candidate set and this test +# scores one logged chunk per anchor. +set -uo pipefail +ROOT=/proj/dmfexp/zwhong/rsm_rise +export MUJOCO_GL=disable CUDA_VISIBLE_DEVICES="" OMP_NUM_THREADS=8 MKL_NUM_THREADS=8 +echo "[pp_reduce_ladder] host=$(hostname) job=${LSB_JOBID:-none} $(date -u)" +exec $ROOT/venv_rsm/bin/python $ROOT/scripts/real/pt_pairs_reduce.py \ + --cells pp_IDQLCPU \ + --out $ROOT/status/real/PT_PAIRS_LADDER.md "$@" diff --git a/rsm_rise/scripts/real/pp_smoke.sh b/rsm_rise/scripts/real/pp_smoke.sh new file mode 100644 index 0000000000000000000000000000000000000000..cf81b33b680717cf78849b70d8eb0fabbdf92da3 --- /dev/null +++ b/rsm_rise/scripts/real/pp_smoke.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# CPU smoke for pt_pairs_score.py: ONE episode, tiny bank, no GPU. Exists because the real wave is an +# 8-GPU packed job and an API slip in a brand-new script would burn a whole node; this validates the +# Scorer construction, the rsm_feat cache lookup, the IQL obs path and the npz writer on 8 CPU cores. +# It writes to a THROWAWAY out dir so it can never be mistaken for a measured cell. +set -uo pipefail +ROOT=/proj/dmfexp/zwhong/rsm_rise +export OPENPI_DATA_HOME=$ROOT/.openpi_assets HF_LEROBOT_HOME=$ROOT/data/real/lerobot_home UV_CACHE_DIR=$ROOT/.uv_cache +export HF_HUB_OFFLINE=1 TOKENIZERS_PARALLELISM=false PYTHONUNBUFFERED=1 +export MUJOCO_GL=disable CUDA_VISIBLE_DEVICES="" +export JAX_PLATFORMS=cpu +export PYTHONPATH=$ROOT/code/rise_robomimic:$ROOT/code/diffusion_policy:$ROOT/code/robosuite:$ROOT/code/mimicgen_environments:$ROOT/code/rise_code:$ROOT/scripts/real:${PYTHONPATH:-} +cd $ROOT/third_party/openpi +echo "[pp_smoke] host=$(hostname) job=${LSB_JOBID:-none} $(date -u)" +rm -rf $ROOT/status/real/pp_SMOKE +exec $ROOT/third_party/openpi/.venv/bin/python $ROOT/scripts/real/pt_pairs_score.py \ + --out $ROOT/status/real/pp_SMOKE --tag SMOKE --bank 4 --ep-shard 0/98 \ + --idql-ckpt "$ROOT/runs/cooking_v5_expert_suboptimal/policy/S0Aidql_seed1/cooking_v5_expert_suboptimal_S0Aidql_s1/20260921235824/models/model_epoch_3000.pth" \ + --rsm-ckpt "$ROOT/runs/real_cooking_v5/rsm/R_M/ckpt_s100000.pt" --rsm-beta 0.99 diff --git a/rsm_rise/scripts/real/pp_smoke_fast.sh b/rsm_rise/scripts/real/pp_smoke_fast.sh new file mode 100644 index 0000000000000000000000000000000000000000..f1615146ea9b68548b6c38db717b58c9abcc0fd1 --- /dev/null +++ b/rsm_rise/scripts/real/pp_smoke_fast.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# FAST CPU smoke: 1 episode, stride 400 (~1 anchor), bank 2, particles 2 -- exists ONLY to confirm the +# npz WRITER path, which the slow smoke 1888121 has not reached in 45 min of CPU scoring. Throwaway dir. +# 8-GPU packed job and an API slip in a brand-new script would burn a whole node; this validates the +# Scorer construction, the rsm_feat cache lookup, the IQL obs path and the npz writer on 8 CPU cores. +# It writes to a THROWAWAY out dir so it can never be mistaken for a measured cell. +set -uo pipefail +ROOT=/proj/dmfexp/zwhong/rsm_rise +export OPENPI_DATA_HOME=$ROOT/.openpi_assets HF_LEROBOT_HOME=$ROOT/data/real/lerobot_home UV_CACHE_DIR=$ROOT/.uv_cache +export HF_HUB_OFFLINE=1 TOKENIZERS_PARALLELISM=false PYTHONUNBUFFERED=1 +export MUJOCO_GL=disable CUDA_VISIBLE_DEVICES="" +export JAX_PLATFORMS=cpu +export PYTHONPATH=$ROOT/code/rise_robomimic:$ROOT/code/diffusion_policy:$ROOT/code/robosuite:$ROOT/code/mimicgen_environments:$ROOT/code/rise_code:$ROOT/scripts/real:${PYTHONPATH:-} +cd $ROOT/third_party/openpi +echo "[pp_smoke_fast] host=$(hostname) job=${LSB_JOBID:-none} $(date -u)" +rm -rf $ROOT/status/real/pp_SMOKE2 +exec $ROOT/third_party/openpi/.venv/bin/python $ROOT/scripts/real/pt_pairs_score.py \ + --out $ROOT/status/real/pp_SMOKE2 --tag SMOKE2 --bank 2 --stride 400 --rsm-particles 2 --ep-shard 0/98 \ + --idql-ckpt "$ROOT/runs/cooking_v5_expert_suboptimal/policy/S0Aidql_seed1/cooking_v5_expert_suboptimal_S0Aidql_s1/20260921235824/models/model_epoch_3000.pth" \ + --rsm-ckpt "$ROOT/runs/real_cooking_v5/rsm/R_M/ckpt_s100000.pt" --rsm-beta 0.99 diff --git a/rsm_rise/scripts/real/probe_fr3_backend.sh b/rsm_rise/scripts/real/probe_fr3_backend.sh new file mode 100644 index 0000000000000000000000000000000000000000..18df2eca3f8a000c5062c4e3857e4c0ded6e8cfe --- /dev/null +++ b/rsm_rise/scripts/real/probe_fr3_backend.sh @@ -0,0 +1,29 @@ +#!/usr/bin/env bash +# Captures, on a COMPUTE NODE, exactly what the real-rig backend cannot do here (#263 gate evidence). +set -uo pipefail +ROOT=/proj/dmfexp/zwhong/rsm_rise; source $ROOT/scripts/env.sh +echo "[probe] host=$(hostname) $(date -u)" +echo "--- 1. is the rsm_real package importable?" +$ROOT/env/bin/python -c "import real.env" 2>&1 | tail -2 +echo "--- 2. is the repo obtainable? (unauthenticated clone, as in LSF 1818497)" +git ls-remote https://github.com/jmarangola/rsm_real.git 2>&1 | tail -2 +echo "--- 3. RealSense cameras on this node?" +$ROOT/env/bin/python -c "import pyrealsense2" 2>&1 | tail -1 +ls /dev/video* 2>&1 | head -3 +echo "--- 4. CAN interfaces (AgileX gripper)?" +ip link show type can 2>&1 | head -3; ls /sys/class/net | tr '\n' ' '; echo +echo "--- 5. aiofranka / OSC server reachable? (default cfg.zmq.url)" +$ROOT/env/bin/python - <<'PY' 2>&1 | tail -3 +import socket +for hp in [("localhost", 5555), ("localhost", 5556)]: + s = socket.socket(); s.settimeout(1.0) + try: + s.connect(hp); print("connected", hp) + except Exception as e: + print(f"no server at {hp}: {type(e).__name__}: {e}") + finally: + s.close() +PY +echo "--- 6. does the harness itself construct the fr3 backend?" +$ROOT/env/bin/python $ROOT/scripts/real/twin_rollout.py --backend fr3 --policy random --out $ROOT/status/real/twin_fr3_probe 2>&1 | tail -6 +echo "[probe] done $(date -u)" diff --git a/rsm_rise/scripts/real/probe_hf.sh b/rsm_rise/scripts/real/probe_hf.sh new file mode 100644 index 0000000000000000000000000000000000000000..c179fc8602a394fad73ba59c0a7198a62715f77b --- /dev/null +++ b/rsm_rise/scripts/real/probe_hf.sh @@ -0,0 +1,39 @@ +#!/usr/bin/env bash +# Diagnose HF access for jmarangola/rsm_cooking_v5. CPU job only. +set -uo pipefail +ROOT=/proj/dmfexp/zwhong/rsm_rise +export HF_HOME="$ROOT/.hf_cache" +echo "[probe] host=$(hostname) $(date -u)" +"$ROOT/venv_rsm/bin/python" - <<'PY' +import os, json, urllib.request, urllib.error +tok = os.environ.get("HF_TOKEN", "") +print("[probe] HF_TOKEN present:", bool(tok), "len:", len(tok), "prefix:", tok[:4] if tok else "-") + +def get(url, token=None): + req = urllib.request.Request(url) + if token: + req.add_header("Authorization", "Bearer " + token) + try: + with urllib.request.urlopen(req, timeout=30) as r: + return r.status, r.read(4000).decode("utf-8", "replace") + except urllib.error.HTTPError as e: + return e.code, e.read(600).decode("utf-8", "replace") + except Exception as e: + return -1, repr(e) + +print("\n[probe] whoami WITH token:") +print(get("https://huggingface.co/api/whoami-v2", tok)) + +print("\n[probe] dataset info ANONYMOUS:") +s, b = get("https://huggingface.co/api/datasets/jmarangola/rsm_cooking_v5") +print(s, b[:600]) + +print("\n[probe] dataset info WITH token:") +s, b = get("https://huggingface.co/api/datasets/jmarangola/rsm_cooking_v5", tok) +print(s, b[:600]) + +print("\n[probe] control: public dataset ANONYMOUS (network sanity):") +s, b = get("https://huggingface.co/api/datasets/lerobot/pusht") +print(s, b[:200]) +PY +echo "[probe] done $(date -u)" diff --git a/rsm_rise/scripts/real/proposal_ceiling.py b/rsm_rise/scripts/real/proposal_ceiling.py new file mode 100644 index 0000000000000000000000000000000000000000..777c94eaa77737b44dc8c72322babea57be68503 --- /dev/null +++ b/rsm_rise/scripts/real/proposal_ceiling.py @@ -0,0 +1,420 @@ +#!/usr/bin/env python +"""gen_q#280 / rsm_real#2 TASK A -- the CEILING of the proposal test, measured supervised on logged data. + +THE QUESTION. The proposal test asks a value to rank an 8-frame action chunk by the ROUTE it belongs to. +An 8-frame chunk moves the end effector ~14 mm; the branch unfolds over hundreds of frames. If the chunk +is not informative about the route IN PRINCIPLE then every value scores ~0.5 and the sweep is measuring a +ceiling, not a defect. So: train a direct supervised classifier on (anchor feature, logged chunk) -> route +label, at S2 anchors only, with episodes split so no episode appears in both train and validation. + +THREE ARMS, which is the whole point: + both (anchor feature + chunk) -- what a perfect value could know + anchor (anchor feature only) -- what the state alone already says; the chunk's INFORMATION is the gap + chunk (chunk only) -- the ceiling for a purely direction-based scorer + +NB on the label. Here the label is the episode's ROUTE ([2,3,4] reaches the goal, [0,2,6] reaches the +failure), NOT sign(signed margin). So the meta-direction heuristic IS a legitimate row in this table -- +it is not the ruler here. It is nonetheless refit from the FOLD'S TRAINING EPISODES ONLY, so it cannot +read the validation episodes' own directions back out. + +THE CONFOUND, measured before any number was reported (data/derived/cooking_v5_split.json): + route [2,3,4] "reaches goal" = 50 episodes, 100% provenance EXPERT, median length 1051 + route [0,2,6] "reaches failure" = 50 episodes, 100% provenance SUBOPTIMAL, median length 392 +The route label as specified is therefore PERFECTLY confounded with which demonstrator generated the +episode. A classifier that separates them may be reading the generator, not the destiny. So this script +runs THREE contrasts at S2 and the confound-free one is the answer: + C1 goal_vs_fail [2,3,4] vs [0,2,6] -- as specified; expert vs suboptimal, CONFOUNDED + C2 goal_vs_cook [2,3,4] vs [0,2,3] -- both EXPERT; reaches the goal vs cooks and never pours. + This is the destiny question with the generator held fixed. + C3 cook_vs_fail [0,2,3] vs [0,2,6] -- both NON-goal; expert vs suboptimal. Any AUC here is pure + generator identity, so it is the size of C1's confound. +and every contrast carries an EPISODE-LEVEL LABEL PERMUTATION as its measured zero line, because a +grouped-CV bug would also produce a high AUC and 0.5 is only a nominal expectation. + +FEATURE HYGIENE, stated because each of these would have manufactured a number: + * the chunk is taken RELATIVE to its first action (`chunk - chunk[0]`). Absolute action values are the + pose, which is already the anchor feature, so an absolute chunk would let the `chunk` arm smuggle in + the anchor arm and the gap would be unreadable. + * NO time index, normalised or raw. Failure episodes end sooner after the junction, so t or t/T is a + near-perfect route label that has nothing to do with the chunk. + * the anchor set is held FIXED across the chunk-length sweep (every --stride-th S2 frame with + t + max(L) <= T), so the L axis varies the temporal SPAN and nothing else. Dropped anchors counted. + * `waypoints` chunk featurisation takes 8 equally spaced frames of the chunk whatever L is, so the + feature DIMENSION is constant across L too. `full` is reported beside it as the unconstrained variant. +""" +from __future__ import annotations +import argparse, json, sys, time, warnings +from pathlib import Path +import numpy as np + +ROOT = "/proj/dmfexp/zwhong/rsm_rise" +warnings.filterwarnings("ignore") + + +def unit(v, axis=-1, eps=1e-12): + n = np.linalg.norm(v, axis=axis, keepdims=True) + return v / np.maximum(n, eps) + + +def auc(y, s): + y = np.asarray(y); s = np.asarray(s, np.float64) + p, n = int((y == 1).sum()), int((y == 0).sum()) + if p == 0 or n == 0: return float("nan") + r = np.empty(len(s)); o = np.argsort(s, kind="mergesort"); ss = s[o] + i = 0 + while i < len(ss): # average ranks over ties + j = i + while j + 1 < len(ss) and ss[j + 1] == ss[i]: j += 1 + r[o[i:j + 1]] = 0.5 * (i + j) + 1.0 + i = j + 1 + return float((r[y == 1].sum() - p * (p + 1) / 2.0) / (p * n)) + + +def ep_bootstrap(y, s, ep, B=2000, seed=0): + """Episode-level bootstrap: resample EPISODES with replacement, recompute the anchor-level AUC.""" + rng = np.random.default_rng(seed) + ue = np.unique(ep); idx = {e: np.where(ep == e)[0] for e in ue} + out = [] + for _ in range(B): + pick = rng.choice(ue, len(ue), replace=True) + ii = np.concatenate([idx[e] for e in pick]) + a = auc(y[ii], s[ii]) + if not np.isnan(a): out.append(a) + if not out: return float("nan"), float("nan"), float("nan") + out = np.sort(np.asarray(out)) + return float(out.std(ddof=1)), float(out[int(0.025 * len(out))]), float(out[int(0.975 * len(out))]) + + +def ep_bootstrap_diff(y, sa, sb, ep, B=2000, seed=0): + """PAIRED episode bootstrap of AUC(sa) - AUC(sb): one resample of EPISODES, both AUCs on it. + + The unpaired SEs of two arms do not give an interval on their difference, because the two arms are + scored on the SAME anchors and are strongly correlated. This is the interval that licenses a claim + about the MARGINAL information the chunk carries over the anchor (TASK A's quantity). + """ + rng = np.random.default_rng(seed) + ue = np.unique(ep); idx = {e: np.where(ep == e)[0] for e in ue} + out = [] + for _ in range(B): + pick = rng.choice(ue, len(ue), replace=True) + ii = np.concatenate([idx[e] for e in pick]) + d = auc(y[ii], sa[ii]) - auc(y[ii], sb[ii]) + if not np.isnan(d): out.append(d) + if not out: return (float("nan"),) * 4 + out = np.sort(np.asarray(out)) + return (float(out.mean()), float(out.std(ddof=1)), + float(out[int(0.025 * len(out))]), float(out[int(0.975 * len(out))])) + + +def build(a): + """S2 anchors on the two ROUTE-labelled episode groups, with the fixed anchor set.""" + import h5py + split = json.load(open(a.split))["episodes"] + goal, fail = json.loads(a.route_pos), json.loads(a.route_neg) + lab = {} + for k, v in split.items(): + if v["path"] == goal: lab[int(k)] = 1 + elif v["path"] == fail: lab[int(k)] = 0 + Lmax = max(a.lengths) + rows = [] + n_drop = 0 + n_drop_entry = [0] + with h5py.File(a.hdf5, "r") as f: + for ep in sorted(lab): + g = f["data"][f"demo_{ep}"] + ef = g["annot"]["edge_from"][()].astype(int) + T = len(ef) + allS = [t for t in range(T) if ef[t] == a.state][::a.stride] + idx = [t for t in allS if t + Lmax <= T] + n_drop += len(allS) - len(idx) + # 18:15Z gate: keep only anchors within --entry-window frames of meta-state ENTRY. Identical + # definition to proposal_report.restrict_to_entry_window -- the smallest S2 frame IS the entry + # frame, and the t+Lmax filter above only removes LATE anchors so the minimum is preserved. + if a.entry_window is not None and a.entry_window >= 0 and allS: + t0 = min(allS) + kept = [t for t in idx if t - t0 <= a.entry_window] + n_drop_entry[0] += len(idx) - len(kept) + idx = kept + if not idx: continue + S = g["obs"]["ee_state"][()].astype(np.float32) + P = g["obs"]["robot0_eef_pos"][()].astype(np.float32) + A = (g["actions_raw"] if "actions_raw" in g else g["actions"])[()].astype(np.float32) + for t in idx: + rows.append(dict(ep=ep, t=t, y=lab[ep], + anchor=np.concatenate([S[t], P[t]]).astype(np.float32), + chunk=A[t:t + Lmax].astype(np.float32))) + if a.entry_window is not None and a.entry_window >= 0: + print(f"[ceil] entry window {a.entry_window}: dropped {n_drop_entry[0]} anchors beyond it", flush=True) + return rows, n_drop, len(lab) + + +def chunk_feat(CH, L, mode): + """[n, Lmax, 10] -> features for chunk length L. Relative to the chunk's first action, in mm.""" + c = CH[:, :L, :] - CH[:, :1, :] + if mode == "waypoints": + k = np.unique(np.linspace(0, L - 1, min(8, L)).round().astype(int)) + c = c[:, k, :] + v = CH[:, L - 1, :3] - CH[:, 0, :3] + mag = np.linalg.norm(v, axis=1, keepdims=True) + return np.concatenate([1000.0 * c.reshape(len(c), -1), 1000.0 * v, 1000.0 * mag, unit(v)], 1) + + +def fit_arm(X, y, ep, folds, seed, model): + """Out-of-fold predictions under StratifiedGroupKFold over EPISODES (no episode in both sides).""" + from sklearn.model_selection import StratifiedGroupKFold + from sklearn.pipeline import make_pipeline + from sklearn.preprocessing import StandardScaler + from sklearn.linear_model import LogisticRegression + from sklearn.neural_network import MLPClassifier + oof = np.full(len(y), np.nan) + skf = StratifiedGroupKFold(n_splits=folds, shuffle=True, random_state=seed) + for tr, va in skf.split(X, y, groups=ep): + if model == "logreg": + m = make_pipeline(StandardScaler(), + LogisticRegression(max_iter=4000, C=1.0, class_weight="balanced", + random_state=seed)) + else: + m = make_pipeline(StandardScaler(), + MLPClassifier(hidden_layer_sizes=(64, 64), max_iter=600, early_stopping=True, + n_iter_no_change=15, random_state=seed)) + m.fit(X[tr], y[tr]) + oof[va] = m.predict_proba(X[va])[:, 1] + return oof + + +def metaheur_oof(CH, y, ep, L, folds, seed): + """The meta-direction heuristic, ruler REFIT ON TRAINING EPISODES ONLY in every fold.""" + from sklearn.model_selection import StratifiedGroupKFold + oof = np.full(len(y), np.nan) + d = unit((CH[:, L - 1, :3] - CH[:, 0, :3]).astype(np.float64)) + skf = StratifiedGroupKFold(n_splits=folds, shuffle=True, random_state=seed) + for tr, va in skf.split(d, y, groups=ep): + # the entry chunk of each training episode defines that route's mean unit direction + uS, uF = [], [] + for e in np.unique(ep[tr]): + m = (ep == e) + first = np.argmin(np.where(m, np.arange(len(m)), 10 ** 9)) + (uS if y[first] == 1 else uF).append(d[first]) + if not uS or not uF: continue + uS, uF = unit(np.mean(np.stack(uS), 0)), unit(np.mean(np.stack(uF), 0)) + oof[va] = d[va] @ uS - d[va] @ uF + return oof + + +# ---- THE GATE'S OWN GEOMETRY BASIS, lifted byte-for-byte from the statistic it belongs to. +# FT_EVAL's S2 gate reports `gatexf`, which residualises every score against `basis(disp, mag, "quad")` +# (scripts/tmp/edge_gate_power.py) under a 5-fold cross-fit. That file calls main() at module level so it +# cannot be imported; instead its `basis` FunctionDef is extracted by ast and exec'd here, and its source +# sha256 is printed, so this is the same definition and not a retyped copy of it. +GATE_SRC = f"{ROOT}/scripts/tmp/edge_gate_power.py" + + +def _load_gate_basis(): + import ast, hashlib + text = open(GATE_SRC).read() + for node in ast.parse(text).body: + if isinstance(node, ast.FunctionDef) and node.name == "basis": + seg = ast.get_source_segment(text, node) + ns = {"np": np} + exec(seg, ns) + return ns["basis"], hashlib.sha256(seg.encode()).hexdigest()[:16], seg.count("\n") + 1 + raise SystemExit(f"no def basis in {GATE_SRC}") + + +GATE_BASIS, GATE_BASIS_SHA, GATE_BASIS_LINES = _load_gate_basis() + + +def geom_feat(CH, L): + """The chunk reduced to exactly what `gatexf` removes: displacement, magnitude, unit direction and the + quadratic cross terms. Column 0 of `basis` is the constant, dropped because the models carry an + intercept and StandardScaler would divide it by a zero sd.""" + v = (CH[:, L - 1, :3] - CH[:, 0, :3]).astype(np.float64) + mag = np.linalg.norm(v, axis=1) + X = GATE_BASIS(1000.0 * v, 1000.0 * mag, "quad")[:, 1:] + return np.ascontiguousarray(X.astype(np.float32)) + + +def dir_feat(CH, L, kind): + v = CH[:, L - 1, :3] - CH[:, 0, :3] + if kind == "dir": return unit(v.astype(np.float64)).astype(np.float32) + if kind == "mag": return (1000.0 * np.linalg.norm(v, axis=1, keepdims=True)).astype(np.float32) + raise ValueError(kind) + + +def perm_labels(y, ep, seed): + """Permute the label ACROSS EPISODES (every anchor of an episode keeps one label). The measured zero + line: a grouped-CV leak would show up here as an AUC above 0.5 and 0.5 is only nominal.""" + rng = np.random.default_rng([seed, 77]) + ue = np.unique(ep) + yl = np.array([y[ep == e][0] for e in ue]) + rng.shuffle(yl) + m = dict(zip(ue.tolist(), yl.tolist())) + return np.array([m[e] for e in ep]) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--out", required=True) + ap.add_argument("--hdf5", default=f"{ROOT}/data/raw/cooking_v5_expert_suboptimal.hdf5") + ap.add_argument("--split", default=f"{ROOT}/data/derived/cooking_v5_split.json") + ap.add_argument("--state", type=int, default=2) + ap.add_argument("--route-pos", default="[2, 3, 4]", help="episodes labelled 1") + ap.add_argument("--route-neg", default="[0, 2, 6]", help="episodes labelled 0") + ap.add_argument("--contrast", default="goal_vs_fail", help="name of this contrast, for the table") + ap.add_argument("--stride", type=int, default=5) + ap.add_argument("--entry-window", type=int, default=None, + help="keep only anchors within this many frames of meta-state ENTRY (18:15Z gate: 100)") + ap.add_argument("--lengths", type=int, nargs="+", default=[8, 16, 32, 64]) + ap.add_argument("--folds", type=int, default=5) + ap.add_argument("--seeds", type=int, nargs="+", default=[0, 1, 2]) + ap.add_argument("--boot", type=int, default=2000) + ap.add_argument("--perm-null", type=int, default=0, + help="N episode-level label permutations; each is refit end to end and its PAIRED " + "marginal AUC(both)-AUC(anchor) recorded, giving the null DISTRIBUTION of the " + "marginal. A single permuted draw (the ZEROLINE row) has an episode-bootstrap " + "SE of ~0.026 and therefore cannot calibrate a +0.034 effect; this can.") + ap.add_argument("--perm-null-models", nargs="+", default=["logreg"]) + ap.add_argument("--perm-null-lengths", type=int, nargs="+", default=None, + help="lengths for the permutation null (default: --lengths)") + a = ap.parse_args() + t0 = time.time() + out = Path(a.out); out.mkdir(parents=True, exist_ok=True) + + rows, n_drop, n_ep = build(a) + if not rows: raise SystemExit("no S2 anchors on the two routes") + ep = np.array([r["ep"] for r in rows]); y = np.array([r["y"] for r in rows]) + AN = np.stack([r["anchor"] for r in rows]); CH = np.stack([r["chunk"] for r in rows]) + print(f"[ceil] contrast={a.contrast} pos={a.route_pos} neg={a.route_neg}", flush=True) + print(f"[ceil] anchors={len(rows)} episodes={len(np.unique(ep))}/{n_ep} " + f"goal={int((y==1).sum())} fail={int((y==0).sum())} dropped_by_Lmax={n_drop} " + f"anchor_dim={AN.shape[1]} chunk={CH.shape}", flush=True) + + res = [] + SC = {} # (arm, L, fm, seed) -> out-of-fold score vector, for pairing + def add(name, L, fm, s, seed): + SC[(name, int(L), fm, int(seed))] = np.asarray(s, float) + ok = ~np.isnan(s) + se, lo, hi = ep_bootstrap(y[ok], s[ok], ep[ok], a.boot, seed) + A = auc(y[ok], s[ok]) + # episode-level: mean score per episode against that episode's label + ue = np.unique(ep[ok]); es = np.array([s[ok][ep[ok] == e].mean() for e in ue]) + ey = np.array([y[ok][ep[ok] == e][0] for e in ue]) + r = dict(arm=name, L=int(L), chunk_feat=fm, seed=int(seed), auc=A, se=se, ci_lo=lo, ci_hi=hi, + auc_episode=auc(ey, es), n=int(ok.sum()), n_eps=int(len(ue))) + res.append(r) + print(f"[ceil] L={L:3d} {fm:9s} seed{seed} {name:18s} AUC={A:.4f} +-{se:.4f} " + f"[{lo:.3f},{hi:.3f}] ep-level={r['auc_episode']:.3f} n={r['n']}", flush=True) + + for seed in a.seeds: + for L in a.lengths: + for fm in ("waypoints", "full"): + CF = chunk_feat(CH, L, fm) + for model in ("logreg", "mlp"): + add(f"both:{model}", L, fm, fit_arm(np.concatenate([AN, CF], 1), y, ep, a.folds, seed, model), seed) + add(f"chunk:{model}", L, fm, fit_arm(CF, y, ep, a.folds, seed, model), seed) + for model in ("logreg", "mlp"): # anchor-only does not depend on L or fm + add(f"anchor:{model}", L, "-", fit_arm(AN, y, ep, a.folds, seed, model), seed) + # what inside the chunk carries it: 3-d unit direction alone, and speed alone + # THE GEOMETRY-RESIDUALISED CEILING: what the chunk carries BEYOND the channel `gatexf` + # removes. `anchorgeom` is the anchor plus the chunk's own geometry basis, so the paired + # marginal `both - anchorgeom` is the route information left in the chunk once direction and + # magnitude are already known. That marginal is the ceiling for any geometry-residualised gate. + GF = geom_feat(CH, L) + for model in ("logreg", "mlp"): + add(f"anchorgeom:{model}", L, "geom", fit_arm(np.concatenate([AN, GF], 1), y, ep, a.folds, seed, model), seed) + add("chunkgeom:logreg", L, "geom", fit_arm(GF, y, ep, a.folds, seed, "logreg"), seed) + add("chunkdir:logreg", L, "dir3", fit_arm(dir_feat(CH, L, "dir"), y, ep, a.folds, seed, "logreg"), seed) + add("chunkmag:logreg", L, "mag1", fit_arm(dir_feat(CH, L, "mag"), y, ep, a.folds, seed, "logreg"), seed) + add("metaheur", L, "dir", metaheur_oof(CH, y, ep, L, a.folds, seed), seed) + # THE MEASURED ZERO LINE: same features, same CV, labels permuted across episodes + yp = perm_labels(y, ep, seed) + CFw = chunk_feat(CH, L, "waypoints") + for nm, X in (("labelperm_both", np.concatenate([AN, CFw], 1)), + ("labelperm_anchor", AN), ("labelperm_chunk", CFw), + ("labelperm_anchorgeom", np.concatenate([AN, geom_feat(CH, L)], 1))): + s_ = fit_arm(X, yp, ep, a.folds, seed, "logreg") + SC[(nm, int(L), "waypoints", int(seed))] = np.asarray(s_, float) + SC[("_yperm", int(L), "waypoints", int(seed))] = np.asarray(yp, float) + ok = ~np.isnan(s_) + se, lo, hi = ep_bootstrap(yp[ok], s_[ok], ep[ok], a.boot, seed) + A_ = auc(yp[ok], s_[ok]) + res.append(dict(arm=nm, L=int(L), chunk_feat="waypoints", seed=int(seed), auc=A_, se=se, + ci_lo=lo, ci_hi=hi, auc_episode=float("nan"), n=int(ok.sum()), + n_eps=int(len(np.unique(ep[ok]))))) + print(f"[ceil] L={L:3d} waypoints seed{seed} {nm:18s} AUC={A_:.4f} +-{se:.4f} " + f"[{lo:.3f},{hi:.3f}] (zero line)", flush=True) + rng = np.random.default_rng([seed, L]) + add("random", L, "-", rng.random(len(y)), seed) + + # ---- PAIRED marginals: the chunk's information over the anchor, with an interval on the DIFFERENCE, + # each beside its own permuted-label zero line (a permuted marginal need not be 0). + dres = [] + for seed in a.seeds: + for L in a.lengths: + def P(nm_a, nm_b, fm_a, fm_b, yy, tag): + ka = (nm_a, int(L), fm_a, int(seed)); kb = (nm_b, int(L), fm_b, int(seed)) + if ka not in SC or kb not in SC: return + sa, sb = SC[ka], SC[kb] + ok = ~(np.isnan(sa) | np.isnan(sb)) + m, se, lo, hi = ep_bootstrap_diff(yy[ok], sa[ok], sb[ok], ep[ok], a.boot, seed) + d0 = auc(yy[ok], sa[ok]) - auc(yy[ok], sb[ok]) + dres.append(dict(pair=f"{nm_a} - {nm_b}", tag=tag, L=int(L), seed=int(seed), + diff=d0, boot_mean=m, se=se, ci_lo=lo, ci_hi=hi, n=int(ok.sum()), + n_eps=int(len(np.unique(ep[ok]))))) + flag = "SIG" if (lo > 0 or hi < 0) else "n.s." + print(f"[ceil] L={L:3d} seed{seed} PAIRED {tag:9s} {nm_a} - {nm_b}: " + f"d={d0:+.4f} +-{se:.4f} [{lo:+.4f},{hi:+.4f}] {flag} n={ok.sum()}", flush=True) + P("both:mlp", "anchor:mlp", "waypoints", "-", y, "real") + P("both:logreg", "anchor:logreg", "waypoints", "-", y, "real") + P("chunkdir:logreg", "anchor:logreg", "dir3", "-", y, "real") + P("both:mlp", "anchorgeom:mlp", "waypoints", "geom", y, "resid") + P("both:logreg", "anchorgeom:logreg", "waypoints", "geom", y, "resid") + yp = SC.get(("_yperm", int(L), "waypoints", int(seed))) + if yp is not None: + P("labelperm_both", "labelperm_anchor", "waypoints", "waypoints", yp, "ZEROLINE") + P("labelperm_both", "labelperm_anchorgeom", "waypoints", "waypoints", yp, "ZEROLINE") + + # ---- PERMUTATION NULL of the paired marginal. ONE CHANGE from the single ZEROLINE row: N draws + # instead of 1, so the marginal has a calibrated bar (the null's q95) and not just an interval on 0. + pnull = [] + if a.perm_null > 0: + pl = a.perm_null_lengths or a.lengths + fseed = int(a.seeds[0]) + for model in a.perm_null_models: + for L in pl: + CFw = chunk_feat(CH, L, "waypoints") + XB = np.concatenate([AN, CFw], 1) + # run 33 ONE CHANGE: the RESIDUALISED pair gets the same N-draw null as the raw pair. + # `both - anchorgeom` was calibrated only by a SINGLE permuted draw, whose episode + # bootstrap CI [-0.044,+0.036] overlaps the +0.038 effect, so (B) could not be declared. + XG = np.concatenate([AN, geom_feat(CH, L)], 1) + for rep in range(a.perm_null): + rng = np.random.default_rng([7919, rep]) + ue = np.unique(ep) + yl = np.array([y[ep == e][0] for e in ue]); rng.shuffle(yl) + mp = dict(zip(ue.tolist(), yl.tolist())) + yp = np.array([mp[e] for e in ep]) + sb_ = fit_arm(XB, yp, ep, a.folds, fseed, model) + sa_ = fit_arm(AN, yp, ep, a.folds, fseed, model) + sg_ = fit_arm(XG, yp, ep, a.folds, fseed, model) + ok = ~(np.isnan(sa_) | np.isnan(sb_)) + okg = ~(np.isnan(sg_) | np.isnan(sb_)) + d = auc(yp[ok], sb_[ok]) - auc(yp[ok], sa_[ok]) + dg = auc(yp[okg], sb_[okg]) - auc(yp[okg], sg_[okg]) + pnull.append(dict(model=model, L=int(L), rep=int(rep), + diff=float(d), diff_resid=float(dg))) + sel = [r for r in pnull if r["model"] == model and r["L"] == L] + for key, tag in (("diff", "raw "), ("diff_resid", "RESID")): + dd = np.sort(np.array([r[key] for r in sel])) + print(f"[ceil] PERMNULL {tag} {model} L={L} n={len(dd)} mean={dd.mean():+.4f} " + f"sd={dd.std(ddof=1):+.4f} q95={dd[int(0.95*len(dd))]:+.4f} " + f"q99={dd[min(len(dd)-1,int(0.99*len(dd)))]:+.4f}", flush=True) + + json.dump(dict(contrast=a.contrast, entry_window=a.entry_window, perm_null=pnull, + results=res, paired=dres, n_anchors=len(rows), n_episodes=int(len(np.unique(ep))), + dropped_by_Lmax=n_drop, config=vars(a)), open(out / "ceiling.json", "w"), indent=1) + print(f"[ceil] done {time.time()-t0:.0f}s -> {out}/ceiling.json", flush=True) + + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/real/proposal_report.py b/rsm_rise/scripts/real/proposal_report.py new file mode 100644 index 0000000000000000000000000000000000000000..e7e413a9914f60266ce97ea05254775c41d0e2f5 --- /dev/null +++ b/rsm_rise/scripts/real/proposal_report.py @@ -0,0 +1,384 @@ +#!/usr/bin/env python +"""gen_q#280 / rsm_real#2 -- reduce one or more proposal-test cells to the pre-registered table. + +Phase 1 (coverage) columns: anchors, episodes, the per-anchor label split, anchors passing the >=16/side +gate, anchors dropped and why, candidate direction spread. NO value is read here, because the gate is the +first measurement: if the proposer's draws all land on one side of the branch there is nothing to rank. + +Phase 2 columns, per scorer, on the GATED anchors only, every one computed WITHIN an anchor and then +averaged over anchors (scores from different states are not comparable, so a pooled AUC would be a +between-state statistic wearing a within-state label): + AUC Mann-Whitney of the score against the binary label (ties count 0.5), mean over anchors + SE episode bootstrap (resample EPISODES with replacement, 2000 draws) of that mean + permuted the same for the scorer's permutation -- the MEASURED zero line, never the nominal 0.5 + rho per-anchor Spearman between the score and the signed margin, mean over anchors + lift mean m of the top N/4 candidates by score, minus the mean m over all N, mean over anchors + ties@max mean number of candidates tied at the maximum score + CV median over anchors of std(score)/|mean(score)| +The signed margin is the RULER and never appears as a scorer column. +Usage: proposal_report.py [ ...] [--json OUT.json] [--md OUT.md] +""" +from __future__ import annotations +import argparse, json, sys +from pathlib import Path +import numpy as np + +BOOT = 2000 + + +H5 = "/proj/dmfexp/zwhong/rsm_rise/data/raw/cooking_v5_expert_suboptimal.hdf5" +# gen_q#281 STOP-AND-REREAD 2026-09-23 18:15Z. The direction proxy that generates the label was measured +# (jobs 1884691/1884695) to be BELOW chance when anchors are spread over the whole meta state (S2 47.7% +# assignment accuracy, oracle AUC 0.467), and sound only near meta-state ENTRY (S2 within 100 frames, +# 50-frame chunks: 92.2%, oracle 0.917; at the 8-frame chunk this proposer can actually draw, 68.0% / +# 0.616 at window 100 and 81.6% / 0.822 at window 25). So the anchor set is now a restricted one and +# every row prints the oracle ceiling OF ITS OWN ANCHOR SET. +EDGE_AT = {"0->5": {0: "0->5"}, "0->1->3": {0: "0->1"}, "0->2->3": {0: "0->2", 2: "2->3"}, + "0->2->6": {0: "0->2", 2: "2->6"}, "2->3->4": {2: "2->3", 3: "3->4"}} +GOOD_BAD = {0: ("0->1", "0->5"), 2: ("2->3", "2->6")} + + +def restrict_to_entry_window(recs, window): + """Keep only anchors within `window` frames of meta-state ENTRY. + + The harness lays anchors down as `[t for t in range(0, T-H) if edge_from[t] == state][::stride]` + (`proposal_test.py:251`), so the smallest anchor frame in an episode IS the entry frame and the offset + needs no second pass over the hdf5.""" + if window is None or window < 0: + return recs + entry = {} + for r in recs: + e = r["episode"] + entry[e] = min(entry.get(e, 10 ** 9), int(r["frame"])) + return [r for r in recs if int(r["frame"]) - entry[r["episode"]] <= window] + + +_H5CACHE = {} + + +def _h5_actions(h5=H5): + """Load {episode: (ee target xyz, edge_from, route)} once per process. The ceiling is evaluated for + several anchor sets and several windows in one job, and re-reading the hdf5 per call dominated the + runtime.""" + if h5 in _H5CACHE: + return _H5CACHE[h5] + import h5py + out = {} + with h5py.File(h5, "r") as f: + d = f["data"] + for k in d: + g = d[k] + A = (g["actions_raw"] if "actions_raw" in g else g["actions"])[:, :3].astype(np.float64) + out[int(str(k).split("_")[1])] = (A, g["annot"]["edge_from"][()].astype(int), + str(g.attrs.get("path", ""))) + _H5CACHE[h5] = out + return out + + +def oracle_ceiling(anchors, chunk, state, h5=H5): + """The ORACLE CEILING for exactly this anchor set: how much route truth the direction label can carry. + + Assign each anchor's LOGGED chunk direction to the nearest edge-direction centroid, then ask how often + that assignment agrees with the edge the anchor's episode actually took, and what AUC the true edge + gets for predicting the assigned edge. This is `scripts/real/proxy_fidelity_window.py` evaluated on + the kept (episode, frame) pairs instead of on a swept window, so a scorer can be read against the + ceiling of the very anchors it was scored on. A scorer AT OR ABOVE its ceiling is exploiting the + label, not tracking the route. + """ + if state not in GOOD_BAD or not anchors: + return dict(n=0, acc=float("nan"), auc=float("nan"), chunk=chunk) + good, bad = GOOD_BAD[state] + want = {} + for ep, fr in anchors: + want.setdefault(int(ep), []).append(int(fr)) + tab = _h5_actions(h5) # {ep: (actions[:, :3], edge_from)} loaded once per process + cent = {} + for ep, (A, ef, rt) in tab.items(): + e = EDGE_AT.get(rt, {}).get(state) + if e is None: + continue + idx = np.where(ef == state)[0] + if len(idx) < chunk + 1: + continue + t = int(idx[0]) + v = A[t + chunk - 1] - A[t] + cent.setdefault(e, []).append(v / max(np.linalg.norm(v), 1e-12)) + edges = sorted(cent) + C = {} + for e in edges: + m = np.mean(np.stack(cent[e]), 0) + C[e] = m / max(np.linalg.norm(m), 1e-12) + rows = [] + for ep, frames in want.items(): + if ep not in tab: + continue + A, ef, rt = tab[ep] + e = EDGE_AT.get(rt, {}).get(state) + if e is None: + continue + for t in frames: + if t + chunk - 1 >= len(A): + continue + v = A[t + chunk - 1] - A[t] + v = v / max(np.linalg.norm(v), 1e-12) + j = int(np.argmax([float(np.dot(v, C[x])) for x in edges])) + rows.append((e, edges[j])) + sel = [(t, p) for t, p in rows if p in (good, bad)] + if len(sel) < 20: + return dict(n=len(sel), acc=float("nan"), auc=float("nan"), chunk=chunk) + lab = np.array([p == good for _, p in sel]) + sc = np.array([1.0 if t == good else 0.0 for t, _ in sel]) + sc = sc + 1e-6 * np.random.default_rng(0).random(len(sc)) + return dict(n=len(sel), acc=float(np.mean([t == p for t, p in sel])), + auc=auc(sc, lab), chunk=chunk) + + +def load_cell(d: Path, entry_window=None): + d = Path(d) + recs = [] + for f in sorted((d / "parts").glob("ep*.npz")): + if f.name.endswith(".tmp.npz"): + continue + z = np.load(f, allow_pickle=True) + meta = json.loads(bytes(z["__meta__"]).decode()) + if not meta.get("n_anchors"): + continue + n = meta["n_anchors"] + sc = {k[6:].replace("__", ":").replace("_AT_", "@"): z[k] for k in z.files if k.startswith("score_")} + for i in range(n): + recs.append(dict(episode=meta["episode"], path=meta["path"], frame=meta["frames"][i], + margin=z["margin"][i], gate=bool(z["gate"][i]), + dir_mm=z["cand_dir_mm"][i], pose_cont_mm=z["pose_cont_mm"][i], + logged_margin=meta["logged_margin"][i], + beta_cap=(float(z["beta_cap"][i]) if "beta_cap" in z.files else np.nan), + beta_used=(float(z["beta_used"][i]) if "beta_used" in z.files else np.nan), + frames_left=(int(z["frames_left"][i]) if "frames_left" in z.files else -1), + beta_mode=meta.get("beta_mode", "fixed"), + scores={k: v[i] for k, v in sc.items()})) + cfg = json.load(open(d / "config.json")) if (d / "config.json").exists() else {} + return restrict_to_entry_window(recs, entry_window), cfg + + +def auc(score, label): + """Mann-Whitney AUC with ties at 0.5. label True = success-side.""" + pos, neg = score[label], score[~label] + if len(pos) == 0 or len(neg) == 0: + return np.nan + # proper tie handling: average ranks + allv = np.concatenate([pos, neg]); order = np.argsort(allv, kind="mergesort") + ranks = np.empty(len(allv), float); s = allv[order] + i = 0 + while i < len(s): + j = i + while j + 1 < len(s) and s[j + 1] == s[i]: + j += 1 + ranks[order[i:j + 1]] = 0.5 * (i + j) + 1.0 + i = j + 1 + return float((ranks[:len(pos)].sum() - len(pos) * (len(pos) + 1) / 2.0) / (len(pos) * len(neg))) + + +def spearman(a, b): + ra = np.argsort(np.argsort(a)).astype(float); rb = np.argsort(np.argsort(b)).astype(float) + ra -= ra.mean(); rb -= rb.mean() + den = np.sqrt((ra * ra).sum() * (rb * rb).sum()) + return float((ra * rb).sum() / den) if den > 0 else np.nan + + +def perm_auc(score, label, rng, reps=200): + """The MEASURED zero line for this scorer at this anchor: the same score vector against the same + label, shuffled. Done here rather than in the harness because the score array is already on disk, + so 200 shuffles cost nothing and the null is measured instead of assumed. Its expectation is 0.5; + the point of measuring it is that a saturated score (mass ties) drags BOTH the real and the shuffled + AUC toward 0.5, and only the pair tells you which.""" + v = np.array([auc(rng.permutation(score), label) for _ in range(reps)]) + return float(np.nanmean(v)) + + +def ep_bootstrap(per_anchor, episodes, rng): + """SE of the mean of a per-anchor statistic, resampling EPISODES (the unit of independence).""" + v = np.asarray(per_anchor, float); e = np.asarray(episodes) + ok = np.isfinite(v); v, e = v[ok], e[ok] + if len(v) == 0: + return np.nan, (np.nan, np.nan) + ue = np.unique(e); byep = {x: v[e == x] for x in ue} + draws = np.empty(BOOT) + for b in range(BOOT): + pick = rng.choice(ue, len(ue), replace=True) + draws[b] = np.concatenate([byep[x] for x in pick]).mean() + return float(draws.std(ddof=1)), (float(np.percentile(draws, 2.5)), float(np.percentile(draws, 97.5))) + + +def model_free_scores(r): + """Reference columns that need no checkpoint. greedy_index reproduces the proposer's own sampling + order (candidate 0 first), random is a fresh uniform draw, pose_cont prefers the chunk whose first + target sits closest to the current pose.""" + n = len(r["margin"]) + return {"greedy_index": -np.arange(n, dtype=float), + "pose_cont": -np.asarray(r["pose_cont_mm"], float), + "random": np.random.default_rng([int(r["episode"]), int(r["frame"])]).standard_normal(n)} + + +def summarise(recs, cell, gate_min=16, entry_window=None, oracle_chunk=0, state=2): + eps = sorted({r["episode"] for r in recs}) + gated = [r for r in recs if r["gate"]] + ns = np.array([int((r["margin"] > 0).sum()) for r in recs]) + N = len(recs[0]["margin"]) if recs else 0 + spread = float(np.mean([np.linalg.norm(r["dir_mm"] - r["dir_mm"].mean(0), axis=1).mean() for r in recs])) if recs else np.nan + mag = float(np.mean([np.linalg.norm(r["dir_mm"], axis=1).mean() for r in recs])) if recs else np.nan + cov = dict(cell=cell, anchors=len(recs), episodes=len(eps), + n_cand=N, gated_anchors=len(gated), + gated_episodes=len({r["episode"] for r in gated}), + dropped_all_success=int(((N - ns) < gate_min).sum()), + dropped_all_failure=int((ns < gate_min).sum()), + succ_side_min=int(ns.min()) if len(ns) else 0, + succ_side_med=float(np.median(ns)) if len(ns) else np.nan, + succ_side_max=int(ns.max()) if len(ns) else 0, + dir_spread_mm=spread, dir_mag_mm=mag, + logged_margin_mean=float(np.mean([r["logged_margin"] for r in recs])) if recs else np.nan, + gate_pass=bool(len(gated) >= 30 and len({r["episode"] for r in gated}) >= 4), + # gen_q#280 TASK B: the truncation cap is route-dependent, so the realised beta belongs on + # every row rather than in the caller's head. + beta_mode=(recs[0].get("beta_mode", "fixed") if recs else "fixed"), + beta_cap_med=float(np.nanmedian([r.get("beta_cap", np.nan) for r in recs])) if recs else np.nan, + beta_used_med=float(np.nanmedian([r.get("beta_used", np.nan) for r in recs])) if recs else np.nan, + frames_left_med=float(np.median([r.get("frames_left", -1) for r in recs])) if recs else np.nan, + entry_window=(-1 if entry_window is None else int(entry_window)), + entry_offset_max=int(max([r["frame"] - min(x["frame"] for x in recs if x["episode"] == r["episode"]) + for r in recs])) if recs else -1) + # gen_q#281 item 4: the ceiling of THIS anchor set, on the gated anchors the rows are computed on. + if oracle_chunk: + cov["oracle"] = oracle_ceiling([(r["episode"], r["frame"]) for r in gated], oracle_chunk, state) + cov["oracle_all"] = oracle_ceiling([(r["episode"], r["frame"]) for r in recs], oracle_chunk, state) + rows = [] + if gated: + names = sorted(set().union(*[set(r["scores"]) for r in gated])) + ["greedy_index", "pose_cont", "random"] + rng = np.random.default_rng(0) + for m in names: + A, S, L, TI, CV, P = [], [], [], [], [], [] + epi = [] + prng = np.random.default_rng(12345) + for r in gated: + sc = r["scores"].get(m) + if sc is None: + sc = model_free_scores(r).get(m) + if sc is None: + continue + sc = np.asarray(sc, float); mg = np.asarray(r["margin"], float) + lab = mg > 0 + A.append(auc(sc, lab)); S.append(spearman(sc, mg)) + P.append(perm_auc(sc, lab, prng)) + k = max(1, len(sc) // 4) + L.append(float(np.sort(mg[np.argsort(-sc)[:k]]).mean() - mg.mean())) + TI.append(float((sc == sc.max()).sum())) + CV.append(float(sc.std() / abs(sc.mean())) if sc.mean() != 0 else np.inf) + epi.append(r["episode"]) + if not A: + continue + se, ci = ep_bootstrap(A, epi, rng) + se_p, _ = ep_bootstrap(P, epi, rng) + se_r, _ = ep_bootstrap(S, epi, rng) + se_l, _ = ep_bootstrap(L, epi, rng) + rows.append(dict(scorer=m, auc=float(np.nanmean(A)), auc_se=se, auc_ci=ci, + auc_permuted=float(np.nanmean(P)), auc_permuted_se=se_p, + delta_vs_permuted=float(np.nanmean(A) - np.nanmean(P)), + # The pre-registered bar is BOTH margins AND the coverage gate (>=30 gated + # anchors across >=4 episodes). Without the episode clause a 1-episode + # bootstrap has se == 0.000 exactly, so ANY auc != 0.5 "passes": the prelim + # run marked `random` PASS at auc 0.503 / se 0.000 on one episode. se > 0 is + # required for the same reason. + passes=bool(se > 0 and (np.nanmean(A) - 0.5) > se + and (np.nanmean(A) - np.nanmean(P)) > se + and len(A) >= 30 and len(set(epi)) >= 4), + rho=float(np.nanmean(S)), rho_se=se_r, + lift=float(np.nanmean(L)), lift_se=se_l, + ties_at_max=float(np.mean(TI)), cv=float(np.median(CV)), + anchors=len(A), episodes=len(set(epi)), + oracle_auc=(cov.get("oracle", {}) or {}).get("auc", float("nan")), + oracle_acc=(cov.get("oracle", {}) or {}).get("acc", float("nan")), + oracle_n=(cov.get("oracle", {}) or {}).get("n", 0), + entry_window=cov["entry_window"], + at_or_above_ceiling=bool(np.isfinite((cov.get("oracle", {}) or {}).get("auc", np.nan)) + and np.nanmean(A) >= (cov.get("oracle", {}) or {})["auc"]))) + return cov, rows + + +def md_table(cov_rows, score_rows): + o = ["### Coverage gate at S2 (first measurement; no value is read to produce this)", "", + "| proposer cell | entry window | anchors | eps | N | succ-side/anchor min/med/max | gated anchors | " + "gated eps | dropped all-succ | dropped all-fail | dir spread mm | dir mag mm | beta mode | " + "beta cap med | beta used med | frames left med | ORACLE acc | **ORACLE AUC** | GATE |", + "|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|"] + for c in cov_rows: + orc = c.get("oracle") or {} + o.append(f"| {c['cell']} | {'all' if c.get('entry_window', -1) < 0 else c['entry_window']} | " + f"{c['anchors']} | {c['episodes']} | {c['n_cand']} | " + f"{c['succ_side_min']}/{c['succ_side_med']:.0f}/{c['succ_side_max']} | " + f"**{c['gated_anchors']}** | {c['gated_episodes']} | {c['dropped_all_success']} | " + f"{c['dropped_all_failure']} | {c['dir_spread_mm']:.1f} | {c['dir_mag_mm']:.1f} | " + f"{c.get('beta_mode','fixed')} | {c.get('beta_cap_med', float('nan')):.4f} | " + f"{c.get('beta_used_med', float('nan')):.4f} | {c.get('frames_left_med', float('nan')):.0f} | " + f"{(('%.1f%%' % (100*orc['acc'])) if np.isfinite(orc.get('acc', np.nan)) else '--')} | " + f"**{(('%.3f' % orc['auc']) if np.isfinite(orc.get('auc', np.nan)) else '--')}** | " + f"{'PASS' if c['gate_pass'] else 'FAIL'} |") + if score_rows: + o += ["", "### Ranking on the GATED anchors (the signed margin is the ruler and is NOT a column)", "", + "| cell | scorer | AUC | SE | 95% CI | permuted AUC | AUC-perm | **ORACLE ceiling** | " + "rho | lift | ties@max | score CV | anchors | eps | PASS |", + "|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|"] + for cell, r in score_rows: + o.append(f"| {cell} | {r['scorer']} | {r['auc']:.3f} | {r['auc_se']:.3f} | " + f"[{r['auc_ci'][0]:.3f},{r['auc_ci'][1]:.3f}] | {r['auc_permuted']:.3f} | " + f"{r['delta_vs_permuted']:+.3f} | " + f"{(('%.3f' % r['oracle_auc']) if np.isfinite(r.get('oracle_auc', np.nan)) else '--')}" + f"{' **AT/ABOVE CEILING**' if r.get('at_or_above_ceiling') else ''} | " + f"{r['rho']:+.3f} | {r['lift']:+.4f} | " + f"{r['ties_at_max']:.1f} | {r['cv']:.2e} | {r['anchors']} | {r['episodes']} | " + f"{'PASS' if r['passes'] else '--'} |") + return "\n".join(o) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("cells", nargs="+") + ap.add_argument("--json", default="") + ap.add_argument("--md", default="") + ap.add_argument("--gate-min", type=int, default=16) + ap.add_argument("--entry-window", type=int, default=None, + help="gen_q#281 18:15Z: keep only anchors within this many frames of meta-state ENTRY. " + "The direction label is below chance over the whole meta state (S2 oracle AUC " + "0.467) and sound only near entry (0.822 at window 25, 0.616 at window 100, both " + "at the 8-frame chunk this proposer can draw).") + ap.add_argument("--oracle-chunk", type=int, default=8, + help="chunk length for the oracle ceiling of each anchor set; 0 disables it. The " + "proposer's action_horizon is 10, so 8 is what the candidates actually are.") + ap.add_argument("--state", type=int, default=2) + ap.add_argument("--by-route", action="store_true", + help="gen_q#280 TASK B: emit a separate row per episode route (`2->3->4`, `0->2->6`, " + "`0->2->3`) as well as the pooled one. The truncation cap is route-dependent, so a " + "pooled route-comparing number mixes an in-distribution arm with an " + "out-of-distribution one; the per-route rows are the reportable ones.") + a = ap.parse_args() + cov_rows, score_rows, out = [], [], {} + for c in a.cells: + d = Path(c) + recs, cfg = load_cell(d, entry_window=a.entry_window) + if not recs: + print(f"[rep] {d.name}: no anchors yet", file=sys.stderr); continue + groups = [(d.name.replace("pt_", ""), recs)] + if a.by_route: + for rt in sorted({r["path"] for r in recs}): + groups.append((f"{d.name.replace('pt_', '')} | {rt}", [r for r in recs if r["path"] == rt])) + for gname, grecs in groups: + cov, rows = summarise(grecs, gname, a.gate_min, entry_window=a.entry_window, + oracle_chunk=a.oracle_chunk, state=a.state) + cov["policy"] = cfg.get("config", {}).get("policy", "?") + cov_rows.append(cov); score_rows += [(cov["cell"], r) for r in rows] + out[cov["cell"]] = dict(coverage=cov, scorers=rows, ruler=cfg.get("ruler")) + md = md_table(cov_rows, score_rows) + print(md) + if a.json: json.dump(out, open(a.json, "w"), indent=1) + if a.md: open(a.md, "w").write(md + "\n") + + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/real/proposal_screen.sh b/rsm_rise/scripts/real/proposal_screen.sh new file mode 100644 index 0000000000000000000000000000000000000000..b2972ef6bf8530f454772d4d3c1f9b1ad15b6cee --- /dev/null +++ b/rsm_rise/scripts/real/proposal_screen.sh @@ -0,0 +1,37 @@ +#!/usr/bin/env bash +# gen_q#280 / rsm_real#2 -- one cell of the owner's proposal test at S2. +# usage: PT_NAME= PT_POLICY= [PT_COVERAGE=1] proposal_screen.sh [shard-i shard-n] +# Phase 1 (PT_COVERAGE=1) draws candidates and labels them against the measured meta directions; no value +# is loaded, so it fails fast if the proposer cannot put candidates on both sides of the branch. +set -uo pipefail +ROOT=/proj/dmfexp/zwhong/rsm_rise +I=${1:-0}; K=${2:-1} +NAME=${PT_NAME:?set PT_NAME} +CK=$ROOT/runs/openpi/checkpoints +POLICY=${PT_POLICY:-openpi:pi05_cooking_sn1_knn0p03:$CK/pi05_cooking_sn1_knn0p03/ws_s0/9999} +NCAND=${PT_NCAND:-128} +STRIDE=${PT_STRIDE:-5} +OUT=$ROOT/status/real/pt_$NAME +mkdir -p "$OUT" +ARGS=(--policy "$POLICY" --n-cand "$NCAND" --horizon 8 --state "${PT_STATE:-2}" + --anchor-stride "$STRIDE" --gate-min "${PT_GATEMIN:-16}" + --ep-shard "$I/$K" --tag "pt_$NAME" --out "$OUT" --seed "${PT_SEED:-0}") +# Re-score the CACHED draws of an already-measured cell: two rows then differ ONLY by the knob varied, +# and the proposer is never re-run (measured 6 s/anchor to draw, so this is the whole cost of a sweep row). +if [ -n "${PT_CANDS_FROM:-}" ]; then ARGS+=(--cands-from "$ROOT/status/real/pt_${PT_CANDS_FROM}" --no-save-cands); fi +if [ "${PT_COVERAGE:-0}" = 1 ]; then + ARGS+=(--coverage-only) +else + ARGS+=(--idql-ckpt "${PT_IDQL:-$ROOT/runs/cooking_v5_expert_suboptimal/policy/S0Aidql_seed1/cooking_v5_expert_suboptimal_S0Aidql_s1/20260921235824/models/model_epoch_3000.pth}" + --rsm-ckpt "${PT_RSM:-$ROOT/runs/real_cooking_v5/rsm/R_M/ckpt_s100000.pt}" + --rsm-mode "${PT_MODE:-chain}" --rsm-depth "${PT_DEPTH:-1}" + --rsm-beta "${PT_BETA:-0.99}" --rsm-gamma "${PT_GAMMA:-0.999}" + --rsm-particles "${PT_PARTICLES:-16}" --rsm-score-kind "${PT_SCOREKIND:-prob}" + --rsm-temperature "${PT_TEMP:-25}" + --rsm-beta-mode "${PT_BETAMODE:-fixed}" --beta-trunc-eps "${PT_BETAEPS:-0.02}") + case "${PT_MODE:-chain}" in + chain|chain_rb) ARGS+=(--rsm-hop-ckpt "${PT_HOP:-$ROOT/runs/real_cooking_v5/hop/flow/policy_r1.pt}") ;; + esac + for e in ${PT_EXTRA:-}; do ARGS+=(--rsm-ckpt-extra "$e"); done +fi +exec $ROOT/scripts/real/run_env_openpi.sh $ROOT/scripts/real/proposal_test.py "${ARGS[@]}" diff --git a/rsm_rise/scripts/real/proposal_test.py b/rsm_rise/scripts/real/proposal_test.py new file mode 100644 index 0000000000000000000000000000000000000000..66863824981745e12a08f7ee186ab4f6cfbbfed6 --- /dev/null +++ b/rsm_rise/scripts/real/proposal_test.py @@ -0,0 +1,354 @@ +#!/usr/bin/env python +"""gen_q#280 / rsm_real#2 -- THE OWNER'S PROPOSAL TEST at the S2 branch. + +At the one meta state that branches to both success and failure (S2: pan on stove, tomato at start), draw +N chunks FROM THE PROPOSAL ACTOR and ask whether the value ranks the ones aligned with the success meta +direction above the ones aligned with the failure meta direction. + +THE RULER (not a scorer). Per route, take the FIRST horizon-frame chunk from the frame where the meta +state is entered, take its end-effector translation `chunk[-1,:3] - chunk[0,:3]`, normalise, and average +those unit vectors over the route's episodes. Measured at S2: + 2->3->4 success (0.196,-0.479, 0.855) conc 0.738 n=50 + 0->2->6 failure (0.107,-0.055,-0.993) conc 0.458 n=50 + 143.3 deg apart, dominated by z. +A candidate's signed margin is m(v) = cos(v,u_S) - cos(v,u_F); its label is sign(m). m GENERATES the +label, so m scores AUC 1.0 by construction and MUST NOT appear as a scorer column. + +THE ACTION CONVENTION, settled by measurement (scripts/tmp/meta_action_dirs.py, job 1881603): the 10-d +action is an ABSOLUTE ee target ~4 mm ahead of the current pose (|a-p_t|=0.0053, |a-p_t+1|=0.0039, +|a-(p_t+1-p_t)|=0.3034). A chunk's direction is therefore `chunk[-1,:3] - chunk[0,:3]`. Averaging raw +action VALUES instead makes every route agree to 7-10 deg -- that measures where the workspace is. +NB the existing edge harness (scorer_openloop.py --edge-test) uses `a[H-1,:3] - p_t` instead; the two +differ by the first action's 4-5 mm lead, so its coverage numbers are NOT interchangeable with these. +Both are recorded here (`cand_dir_mm` and `cand_disp_mm`) so the two conventions can be compared. + +THE COVERAGE GATE, which fails loudly: an anchor is scoreable only if at least --gate-min of the N +candidates lie on EACH side of the label. Anchors that fail are counted and excluded, never scored. + +Two phases, so the cheap one can fail fast: + * --coverage-only : draw candidates, label them, write the per-anchor split. No value is loaded. + * default : additionally score every candidate with each requested scorer. +One npz per episode under /parts/, so a preempted cell resumes and a sharded cell reduces identically. +""" +from __future__ import annotations +import argparse, json, sys, time +from pathlib import Path +import numpy as np + +ROOT = "/proj/dmfexp/zwhong/rsm_rise" +sys.path.insert(0, f"{ROOT}/scripts/real") + +# the spec's measured ruler, re-derived at run time from the hdf5 and asserted against these +SPEC_US = np.array([0.196, -0.479, 0.855]) +SPEC_UF = np.array([0.107, -0.055, -0.993]) + + +def unit(v, axis=-1, eps=1e-12): + n = np.linalg.norm(v, axis=axis, keepdims=True) + return v / np.maximum(n, eps) + + +def meta_dirs(hdf5, horizon, state, route_success, route_failure): + """Re-derive u_success / u_failure exactly as scripts/tmp/meta_action_dirs.py did. + + Averaged over EVERY logged episode of the route (the ruler is a property of the task, not of a split). + A train-only copy is returned beside it so the leakage question has a number instead of an argument. + """ + import h5py, collections + per = collections.defaultdict(list) + split = json.load(open(f"{ROOT}/data/derived/cooking_v5_split.json"))["episodes"] + with h5py.File(hdf5, "r") as f: + d = f["data"] + for k in d: + g = d[k] + A = (g["actions_raw"] if "actions_raw" in g else g["actions"])[()].astype(np.float64) + st = g["annot"]["edge_from"][()] + ep = int(k.split("_")[1]) + sp = split.get(str(ep), {}).get("split", "?") + seen = set() + for t in range(len(A) - horizon): + s = int(st[t]) + if s in seen: + continue + seen.add(s) # first frame of this meta state = the entry + ch = A[t:t + horizon, :3] + per[(str(g.attrs.get("path", "")), s)].append((unit(ch[-1] - ch[0]), sp)) + def summarise(route, only_train=False): + V = [u for u, sp in per[(route, state)] if (sp == "train" or not only_train)] + if not V: + raise SystemExit(f"no episodes on route {route} at state {state}") + M = np.mean(np.stack(V), 0) + return unit(M), float(np.linalg.norm(M)), len(V) + uS, cS, nS = summarise(route_success) + uF, cF, nF = summarise(route_failure) + tS, _, tnS = summarise(route_success, True) + tF, _, tnF = summarise(route_failure, True) + ang = lambda a, b: float(np.degrees(np.arccos(np.clip(float(a @ b), -1, 1)))) + return dict(u_success=uS.tolist(), conc_success=cS, n_success=nS, + u_failure=uF.tolist(), conc_failure=cF, n_failure=nF, + angle_success_failure_deg=ang(uS, uF), + u_success_trainonly=tS.tolist(), n_success_trainonly=tnS, + u_failure_trainonly=tF.tolist(), n_failure_trainonly=tnF, + angle_ruler_vs_trainonly_success_deg=ang(uS, tS), + angle_ruler_vs_trainonly_failure_deg=ang(uF, tF), + angle_vs_spec_success_deg=ang(uS, unit(SPEC_US)), + angle_vs_spec_failure_deg=ang(uF, unit(SPEC_UF))) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--policy", required=True, help="openpi:: | robomimic: | random") + ap.add_argument("--out", required=True) + ap.add_argument("--tag", default="") + ap.add_argument("--coverage-only", action="store_true", help="phase 1: draws + labels, no value loaded") + ap.add_argument("--hdf5", default=f"{ROOT}/data/raw/cooking_v5_expert_suboptimal.hdf5") + ap.add_argument("--split", default=f"{ROOT}/data/derived/cooking_v5_split.json") + ap.add_argument("--lerobot-root", default=f"{ROOT}/data/real/rsm_cooking_v5") + ap.add_argument("--n-cand", type=int, default=128) + ap.add_argument("--horizon", type=int, default=8) + ap.add_argument("--state", type=int, default=2, help="the meta state; S2 is the ONLY eligible one") + ap.add_argument("--route-success", default="2->3->4") + ap.add_argument("--route-failure", default="0->2->6") + ap.add_argument("--anchor-stride", type=int, default=5) + ap.add_argument("--gate-min", type=int, default=16, help="candidates required on EACH side of the label") + ap.add_argument("--max-eps", type=int, default=0) + ap.add_argument("--ep-shard", default="") + ap.add_argument("--seed", type=int, default=0) + ap.add_argument("--no-resume", action="store_true") + ap.add_argument("--save-cands", action="store_true", default=True, + help="persist the drawn [N,H,10] chunks in the part. 1143 S2 anchors x 128 x 8 x 10 " + "float32 is ~47 MB per proposer, and it turns every later cell of the value sweep " + "into re-scoring: the state features, the images and the ruler all live on disk " + "and are indexed by (episode, frame), so only the draws were irreproducible.") + ap.add_argument("--no-save-cands", dest="save_cands", action="store_false") + ap.add_argument("--cands-from", default="", + help="score the candidates ALREADY drawn by that cell instead of running the proposer. " + "The draws, the anchors and the labels are then bit-identical across every setting " + "in the sweep, so two rows differ only by the knob being varied.") + # ---- phase 2 scorers (ignored under --coverage-only) + ap.add_argument("--idql-ckpt", default=None) + ap.add_argument("--rsm-ckpt", default=None) + ap.add_argument("--rsm-ckpt-extra", action="append", default=[], metavar="NAME=PATH") + ap.add_argument("--rsm-cache", default=f"{ROOT}/cache/real_cooking_v5") + ap.add_argument("--rsm-backend", default="mlp") + ap.add_argument("--rsm-mode", default="chain") + ap.add_argument("--rsm-depth", type=int, default=1) + ap.add_argument("--rsm-beta", type=float, default=0.99) + ap.add_argument("--rsm-gamma", type=float, default=0.999) + ap.add_argument("--rsm-particles", type=int, default=16) + ap.add_argument("--rsm-score-kind", default="prob", choices=["prob", "logit"]) + ap.add_argument("--rsm-temperature", type=float, default=25.0) + ap.add_argument("--rsm-hop-ckpt", default="") + # ---- gen_q#280 TASK B: the beta truncation cap confounds route with training beta. Measured by the + # audit in logs/lsf/rr_cpu_betacap.1883723.out: beta 0.99 needs ln(eps)/ln(beta) = 389 frames of episode + # remaining at eps=0.02, and at S2 100.0% of `2->3->4` anchors support it (median cap 0.9953) against + # 0.0% of `0->2->6` anchors (median cap 0.9545) and 10.9% of `0->2->3` (0.9814). Scoring both routes at + # beta 0.99 therefore compares an in-distribution arm against an out-of-distribution one. + ap.add_argument("--rsm-beta-mode", default="fixed", choices=["fixed", "per_anchor"], + help="per_anchor: score each anchor at min(--rsm-beta, its own cap), so both sides of " + "the route comparison are in distribution. The cap and the realised beta are " + "written into the part as `beta_cap` / `beta_used` and go on every reported row.") + ap.add_argument("--beta-trunc-eps", type=float, default=0.02, + help="the training truncation tail; cap(anchor) = eps ** (1/(T-t)). 0.02 is the shipped " + "R_M value (R_M_notrunc trained at 0.99, i.e. cap effectively off).") + a = ap.parse_args() + + import h5py + t0 = time.time() + out = Path(a.out); out.mkdir(parents=True, exist_ok=True) + parts = out / "parts"; parts.mkdir(exist_ok=True) + + R = meta_dirs(a.hdf5, a.horizon, a.state, a.route_success, a.route_failure) + uS = np.array(R["u_success"]); uF = np.array(R["u_failure"]) + print(f"[ruler] u_success {np.round(uS,3).tolist()} conc {R['conc_success']:.3f} n={R['n_success']}\n" + f"[ruler] u_failure {np.round(uF,3).tolist()} conc {R['conc_failure']:.3f} n={R['n_failure']}\n" + f"[ruler] success-vs-failure {R['angle_success_failure_deg']:.1f} deg | " + f"vs the spec's published vectors {R['angle_vs_spec_success_deg']:.2f} / " + f"{R['angle_vs_spec_failure_deg']:.2f} deg | " + f"vs a train-only ruler {R['angle_ruler_vs_trainonly_success_deg']:.2f} / " + f"{R['angle_ruler_vs_trainonly_failure_deg']:.2f} deg", flush=True) + if max(R["angle_vs_spec_success_deg"], R["angle_vs_spec_failure_deg"]) > 1.0: + raise SystemExit("the re-derived ruler disagrees with the spec's published vectors by >1 deg -- " + "the convention or the annotation changed; refusing to label anything.") + + from twin_rollout import RandomPolicy, RobomimicPolicy, OpenpiPolicy, Scorer # noqa: F401 + with h5py.File(a.hdf5, "r") as f: + lo = np.array(json.loads(f["data"].attrs["action_min"]), np.float32) + hi = np.array(json.loads(f["data"].attrs["action_max"]), np.float32) + grip_thresh = float(f["data"].attrs["gripper_thresh"]) + kind = a.policy.split(":")[0] + if a.cands_from: + # the draws come off disk, so the proposer is never built: no pi0.5 on the GPU, and no full-res + # mp4 decode either (only an openpi proposer needs those frames; the IQL critic reads the hdf5's + # 84 px obs and the RSM reads the DINO cache). + pol, kind = None, "cached" + elif kind == "random": + pol = RandomPolicy(lo, hi, a.seed) + elif kind == "robomimic": + pol = RobomimicPolicy(a.policy.split(":", 1)[1], lo, hi) + elif kind == "openpi": + _, cfgname, ck = a.policy.split(":", 2); pol = OpenpiPolicy(cfgname, ck, a.seed) + else: + raise ValueError(a.policy) + need_frames = kind == "openpi" + if need_frames: + import av # noqa: F401 + + def decode_mp4(path): + import av + with av.open(str(path)) as c: + st = c.streams.video[0]; st.thread_type = "AUTO" + return np.stack([fr.to_ndarray(format="rgb24") for fr in c.decode(st)]) + + # ---- scorers. The legitimate comparison columns only: the value under test, its permutation (the + # MEASURED zero line, never the nominal 0.5), the IQL critic, and three model-free references that need + # no checkpoint. The signed margin is NOT here and must never be. + extra_ck = dict(kv.split("=", 1) for kv in a.rsm_ckpt_extra) + modes, scorers = [], {} + zfeat = pfeat = mu = sd = zclip = ep_from = None + d_in = 1546 + if not a.coverage_only: + modes = (["idql", "permuted:idql"] if a.idql_ckpt else []) \ + + (["rsm", "permuted:rsm"] if a.rsm_ckpt else []) + [f"rsm@{n}" for n in extra_ck] + if a.rsm_ckpt or extra_ck: + cache = Path(a.rsm_cache) + zfeat = np.load(cache / "z.f16.npy", mmap_mode="r") + pfeat = np.load(cache / "proprio.f32.npy", mmap_mode="r") + st = np.load(cache / "feat_stats.npz"); m = np.load(cache / "meta.npz", allow_pickle=True) + d_in = zfeat.shape[1] + pfeat.shape[1] + mu, sd = st["mu"][:d_in].astype(np.float32), st["sd"][:d_in].astype(np.float32) + zclip = float(st["z_clip"]) if "z_clip" in st else 10.0 + ep_from = {int(e): int(v) for e, v in enumerate(m["ep_from"])} + kw = dict(rsm_backend=a.rsm_backend, rsm_mode=a.rsm_mode, rsm_depth=a.rsm_depth, + rsm_beta=a.rsm_beta, rsm_gamma=a.rsm_gamma, rsm_particles=a.rsm_particles, + rsm_hop_ckpt=a.rsm_hop_ckpt, rsm_score_kind=a.rsm_score_kind, + rsm_temperature=a.rsm_temperature, rsm_dim=d_in) + for mm in modes: + if mm.startswith("rsm@"): + scorers[mm] = Scorer("rsm", lo, hi, idql_ckpt=None, rsm_ckpt=extra_ck[mm[4:]], seed=a.seed, **kw) + else: + scorers[mm] = Scorer(mm, lo, hi, idql_ckpt=a.idql_ckpt, rsm_ckpt=a.rsm_ckpt, seed=a.seed, **kw) + print(f"[pt] policy={a.policy} scorers={modes or '(coverage only)'} N={a.n_cand} " + f"horizon={a.horizon} state=S{a.state} stride={a.anchor_stride}", flush=True) + + def _k(s): return s.replace(":", "__").replace("@", "_AT_") + + eps = sorted(int(k) for k, v in json.load(open(a.split))["episodes"].items() if v["split"] == "valid") + if a.max_eps: eps = eps[:a.max_eps] + if a.ep_shard: + si, sn = (int(x) for x in a.ep_shard.split("/")) + eps = eps[si::sn] + print(f"[pt] shard {si}/{sn}: {len(eps)} held-out episodes -> {eps}", flush=True) + + with h5py.File(a.hdf5, "r") as f: + for ep in eps: + dst = parts / f"ep{ep:06d}.npz" + if dst.exists() and not a.no_resume: + print(f"[pt] ep {ep} RESUMED from {dst.name}", flush=True); continue + g = f["data"][f"demo_{ep}"] + ef = g["annot"]["edge_from"][()].astype(int) + T = len(ef) + idx = [t for t in range(0, T - a.horizon) if ef[t] == a.state][::a.anchor_stride] + if not idx: + np.savez_compressed(parts / f"ep{ep:06d}.tmp.npz", + __meta__=np.frombuffer(json.dumps( + {"episode": ep, "path": str(g.attrs["path"]), "n_anchors": 0} + ).encode(), np.uint8)) + (parts / f"ep{ep:06d}.tmp.npz").rename(dst) + print(f"[pt] ep {ep} {g.attrs['path']} no S{a.state} frames", flush=True); continue + S = g["obs"]["ee_state"][()].astype(np.float32) + P = g["obs"]["robot0_eef_pos"][()].astype(np.float64) + A = (g["actions_raw"] if "actions_raw" in g else g["actions"])[()].astype(np.float32) + im = {"global": g["obs"]["agentview_image"], "wrist": g["obs"]["robot0_eye_in_hand_image"]} + hi_g = hi_w = None + if need_frames: + vr = Path(a.lerobot_root) / "videos/chunk-000" + hi_g = decode_mp4(vr / f"observation.images.global/episode_{ep:06d}.mp4") + hi_w = decode_mp4(vr / f"observation.images.wrist/episode_{ep:06d}.mp4") + assert len(hi_g) == T and len(hi_w) == T, (ep, len(hi_g), len(hi_w), T) + mk_obs = lambda t: {"state": S[t], "grip_thresh": grip_thresh, + "images84": {c: im[c][t] for c in im}, + "images": ({"global": hi_g[t], "wrist": hi_w[t]} if need_frames else None)} + To = int(getattr(pol, "To", 1)) if pol is not None else 1 + # per-episode RNG so a sharded / resumed cell draws the SAME candidates (scorer_openloop.py's rule) + if pol is not None and hasattr(pol, "rng"): pol.rng = np.random.default_rng([a.seed, ep]) + for i_, mm in enumerate(sorted(scorers)): + if hasattr(scorers[mm], "rng"): scorers[mm].rng = np.random.default_rng([a.seed, ep, 1000 + i_]) + CACHE = None + if a.cands_from: + cf = Path(a.cands_from) / "parts" / f"ep{ep:06d}.npz" + if not cf.exists(): + print(f"[pt] ep {ep} SKIPPED: {cf} has no cached draws", flush=True); continue + zc = np.load(cf, allow_pickle=True) + if "cands" not in zc.files: + raise SystemExit(f"{cf} was written without --save-cands; re-draw that cell") + mc = json.loads(bytes(zc["__meta__"]).decode()) + if mc["frames"] != [int(x) for x in idx]: + raise SystemExit(f"{cf}: cached anchors {len(mc['frames'])} != this run's {len(idx)} -- " + "the anchor definition changed, so the draws are not comparable") + CACHE = {int(fr): zc["cands"][j] for j, fr in enumerate(mc["frames"])} + CAND = [] + D, DISP, MARG, CONT, LOG = [], [], [], [], [] + # TASK B: the per-anchor truncation cap. T is this episode's length, so an anchor late in a + # short (failure-route) episode simply cannot support a long beta horizon. + BCAP = np.clip(a.beta_trunc_eps ** (1.0 / np.maximum(T - np.asarray(idx, np.float64), 1.0)), + 0.0, 0.999999) + BUSED = (np.minimum(a.rsm_beta, BCAP) if a.rsm_beta_mode == "per_anchor" + else np.full(len(idx), float(a.rsm_beta))) + SC = {mm: [] for mm in modes} + for i_t, t in enumerate(idx): + obs = mk_obs(t) + obs["history"] = [mk_obs(max(0, t - k)) for k in range(To - 1, 0, -1)] + if zfeat is not None: + gi = ep_from[ep] + t + z = np.concatenate([np.asarray(zfeat[gi], np.float32), np.asarray(pfeat[gi], np.float32)]) + obs["rsm_feat"] = np.clip((z - mu) / sd, -zclip, zclip) + cands = (CACHE[t] if CACHE is not None else pol.candidates(obs, a.n_cand, a.horizon)) + v = cands[:, -1, :3] - cands[:, 0, :3] # THE convention (metres) + uv = unit(v.astype(np.float64)) + if a.save_cands: CAND.append(np.asarray(cands, np.float32)) + D.append((1000.0 * v).astype(np.float32)) + DISP.append((1000.0 * (cands[:, a.horizon - 1, :3] - P[t][None, :])).astype(np.float32)) + MARG.append((uv @ uS - uv @ uF).astype(np.float32)) + # pose continuity: how far the chunk's FIRST target sits from the current pose (mm). A + # model-free reference that needs no checkpoint; scored as its negative (closer = better). + CONT.append((1000.0 * np.linalg.norm(cands[:, 0, :3] - P[t][None, :], axis=1)).astype(np.float32)) + lv = unit((A[t + a.horizon - 1, :3] - A[t, :3]).astype(np.float64)) + LOG.append(np.float32(float(lv @ uS - lv @ uF))) + for mm in modes: + b_ = float(BUSED[i_t]) if a.rsm_beta_mode == "per_anchor" else None + _, sc = scorers[mm].pick(cands, obs, beta=b_) + SC[mm].append(np.asarray(sc, np.float32) if sc is not None else np.zeros(len(cands), np.float32)) + marg = np.stack(MARG) + ns = (marg > 0).sum(1) + gate = (ns >= a.gate_min) & ((marg.shape[1] - ns) >= a.gate_min) + meta = {"episode": ep, "path": str(g.attrs["path"]), "state": a.state, + "frames": [int(x) for x in idx], "n_anchors": len(idx), + "n_cand": int(marg.shape[1]), "n_gated": int(gate.sum()), + "logged_margin": [float(x) for x in LOG], + "beta_mode": a.rsm_beta_mode, "beta_nominal": float(a.rsm_beta), + "beta_trunc_eps": float(a.beta_trunc_eps), "episode_length": int(T)} + d = {"__meta__": np.frombuffer(json.dumps(meta).encode(), np.uint8), + "cand_dir_mm": np.stack(D), "cand_disp_mm": np.stack(DISP), + "margin": marg, "gate": gate, "pose_cont_mm": np.stack(CONT), + "ee_xyz_mm": (1000.0 * P[idx]).astype(np.float32), + "beta_cap": BCAP.astype(np.float32), "beta_used": BUSED.astype(np.float32), + "frames_left": (T - np.asarray(idx, np.int32)).astype(np.int32)} + if a.save_cands: d["cands"] = np.stack(CAND) + for mm in modes: + d["score_" + _k(mm)] = np.stack(SC[mm]).astype(np.float32) + tmp = parts / f"ep{ep:06d}.tmp.npz" + np.savez_compressed(tmp, **d); tmp.rename(dst) + print(f"[pt] ep {ep} {g.attrs['path']} beta={a.rsm_beta_mode} " + f"cap med={float(np.median(BCAP)):.4f} used med={float(np.median(BUSED)):.4f} " + f"anchors={len(idx)} gated={int(gate.sum())} " + f"succ-side/anchor min={int(ns.min())} med={int(np.median(ns))} max={int(ns.max())} " + f"of {marg.shape[1]} {time.time()-t0:.0f}s", flush=True) + + json.dump({"ruler": R, "config": {k: v for k, v in vars(a).items()}}, + open(out / "config.json", "w"), indent=1) + print(f"[pt] done {time.time()-t0:.0f}s -> {out}", flush=True) + + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/real/proxy_fidelity.py b/rsm_rise/scripts/real/proxy_fidelity.py new file mode 100644 index 0000000000000000000000000000000000000000..b21806840d010041ed1709cd15128d429b31c245 --- /dev/null +++ b/rsm_rise/scripts/real/proxy_fidelity.py @@ -0,0 +1,79 @@ +"""Is direction-clustering a sound proxy for "which meta transition does this action lead to"? + +The rank metrics label a candidate by the nearest edge-direction cluster. That is a HEURISTIC. If the +clusters are not separated relative to their own spread, the label is noise and the metric measures +agreement with a bad ruler rather than with the truth. + +Validate the ruler on data whose answer we know: LOGGED chunks, whose episode's route is recorded. + * confusion matrix true edge vs assigned cluster + * between-centroid angles against within-route angular spread + * ORACLE AUC: give a scorer the TRUE route (a perfect value) and score it against the ASSIGNED label. + That is the ceiling this labelling permits. If the oracle cannot reach much above 0.5, then no value + function can, and the measured 0.611 / 0.490 must be read against that ceiling, not against 1.0. +""" +import numpy as np, h5py, collections, json +ROOT="/proj/dmfexp/zwhong/rsm_rise"; H=f"{ROOT}/data/raw/cooking_v5_expert_suboptimal.hdf5" +HZ=8; STRIDE=5 +def unit(v): + n=np.linalg.norm(v,axis=-1,keepdims=True); return v/np.maximum(n,1e-12) +def ang(a,b): return np.degrees(np.arccos(np.clip(np.sum(unit(a)*unit(b),-1),-1,1))) +def auc(s,y): + s=np.asarray(s,float); y=np.asarray(y,bool) + if y.all() or (~y).all(): return np.nan + r=np.argsort(np.argsort(s))+1.0; n1=y.sum(); n0=(~y).sum() + return float((r[y].sum()-n1*(n1+1)/2)/(n1*n0)) + +with h5py.File(H,"r") as f: + d=f["data"]; route=lambda k: str(d[k].attrs.get("path","")) + # edge taken out of a state, per route + EDGE={"0->5":{0:"0->5"}, "0->1->3":{0:"0->1"}, "0->2->3":{0:"0->2",2:"2->3"}, + "0->2->6":{0:"0->2",2:"2->6"}, "2->3->4":{2:"2->3",3:"3->4"}} + for STATE,GOOD,BAD in ((0,"0->1","0->5"),(2,"2->3","2->6")): + print("="*95); print(f"META STATE S{STATE} good edge {GOOD} bad edge {BAD}") + # 1) centroids from the FIRST chunk at state entry, exactly as the metric builds them + cent=collections.defaultdict(list) + for k in d: + r=route(k); e=EDGE.get(r,{}).get(STATE) + if e is None: continue + A=(d[k]["actions_raw"] if "actions_raw" in d[k] else d[k]["actions"])[()].astype(np.float64) + st=d[k]["annot"]["edge_from"][()]; idx=np.where(st==STATE)[0] + if len(idx)10}" for e in edges) + f"{'acc':>9}") + for e in edges: + tot=sum(conf[(e,x)] for x in edges) or 1 + print(f" {e:<8}" + "".join(f"{100*conf[(e,x)]/tot:>9.1f}%" for x in edges) + + f"{100*conf[(e,e)]/tot:>8.1f}%") + # 3) the ceiling: a PERFECT scorer (knows the true edge) judged against the ASSIGNED label + sel=[(te,asg) for te,asg in rows if asg in (GOOD,BAD)] + if sel: + y=np.array([a==GOOD for _,a in sel]) # the label the metric uses + s=np.array([1.0 if t==GOOD else 0.0 for t,_ in sel]) # a perfect value function + rng=np.random.default_rng(0); s=s+1e-6*rng.random(len(s)) + print(f"\n ORACLE AUC under this labelling (perfect value vs assigned label): {auc(s,y):.3f}" + f" [n={len(sel)}]") + acc=np.mean([t==a for t,a in sel]) + print(f" assignment accuracy on the {GOOD}/{BAD} pair: {100*acc:.1f}% (chance {100/len(edges):.0f}%)") + print(" -> every measured AUC must be read against this ceiling, not against 1.0.") diff --git a/rsm_rise/scripts/real/proxy_fidelity_window.py b/rsm_rise/scripts/real/proxy_fidelity_window.py new file mode 100644 index 0000000000000000000000000000000000000000..385199a102324f7e6b7719579e4f96ff09bb5175 --- /dev/null +++ b/rsm_rise/scripts/real/proxy_fidelity_window.py @@ -0,0 +1,54 @@ +"""The first fidelity run assigned chunks from the WHOLE meta state against centroids built from the +FIRST chunk at entry. The owner's design was explicitly near-entry ("episodes always start at similar +initialization in the meta state"). So sweep the window: does the proxy become sound if we only score +anchors within W frames of entry, as designed, and does it degrade with distance from entry? +""" +import numpy as np, h5py, collections +ROOT="/proj/dmfexp/zwhong/rsm_rise"; H=f"{ROOT}/data/raw/cooking_v5_expert_suboptimal.hdf5" +HZ=8 +def unit(v): + n=np.linalg.norm(v,axis=-1,keepdims=True); return v/np.maximum(n,1e-12) +def auc(s,y): + s=np.asarray(s,float); y=np.asarray(y,bool) + if y.all() or (~y).all(): return np.nan + r=np.argsort(np.argsort(s))+1.0; n1=y.sum(); n0=(~y).sum() + return float((r[y].sum()-n1*(n1+1)/2)/(n1*n0)) +EDGE={"0->5":{0:"0->5"},"0->1->3":{0:"0->1"},"0->2->3":{0:"0->2",2:"2->3"}, + "0->2->6":{0:"0->2",2:"2->6"},"2->3->4":{2:"2->3",3:"3->4"}} +with h5py.File(H,"r") as f: + d=f["data"]; route=lambda k: str(d[k].attrs.get("path","")) + for STATE,GOOD,BAD in ((0,"0->1","0->5"),(2,"2->3","2->6")): + print("="*92); print(f"S{STATE}: {GOOD} (good) vs {BAD} (bad) -- proxy fidelity as a function of") + print(" how far past meta-state ENTRY the anchor sits, and of the chunk length used") + for CH in (8, 25, 50): + cent=collections.defaultdict(list) + for k in d: + e=EDGE.get(route(k),{}).get(STATE) + if e is None: continue + A=(d[k]["actions_raw"] if "actions_raw" in d[k] else d[k]["actions"])[()].astype(np.float64) + st=d[k]["annot"]["edge_from"][()]; idx=np.where(st==STATE)[0] + if len(idx)8}{'assign acc':>12}{'oracle AUC':>12}") + for W in (25, 50, 100, 200, 400, 10**9): + rows=[] + for k in d: + e=EDGE.get(route(k),{}).get(STATE) + if e is None: continue + A=(d[k]["actions_raw"] if "actions_raw" in d[k] else d[k]["actions"])[()].astype(np.float64) + st=d[k]["annot"]["edge_from"][()]; idx=np.where(st==STATE)[0] + if len(idx)10**8 else W)):<22}{len(sel):>8} too few"); continue + y=np.array([a==GOOD for _,a in sel]); s=np.array([1.0 if t==GOOD else 0.0 for t,_ in sel]) + rng=np.random.default_rng(0); s=s+1e-6*rng.random(len(s)) + acc=np.mean([t==a for t,a in sel]) + lab = "all" if W>10**8 else str(W) + print(f" {('<= '+lab):<22}{len(sel):>8}{100*acc:>11.1f}%{auc(s,y):>12.3f}") diff --git a/rsm_rise/scripts/real/pt_betaB_reduce.sh b/rsm_rise/scripts/real/pt_betaB_reduce.sh new file mode 100644 index 0000000000000000000000000000000000000000..59a261c86e3b305694d75d4686ee81f5cc71bf17 --- /dev/null +++ b/rsm_rise/scripts/real/pt_betaB_reduce.sh @@ -0,0 +1,63 @@ +#!/bin/bash +# gen_q#280 / rsm_real#2 TASK B -- reduce ALL FOUR beta arms TOGETHER. +# A single beta arm is not a comparison: the whole point of TASK B is that beta 0.99 compares an +# in-distribution goal-route arm against an out-of-distribution failure-route arm (100% vs 0.0% of anchors +# support 0.99; median caps 0.9953 vs 0.9545). So the four arms are only reportable side by side: +# arm 1 matched beta 0.99 : b099_RM vs b099_notrunc vs b099_notruncs1 (cap isolation at 0.99) +# arm 2 PER-ANCHOR beta : peranchor (each anchor scored at a beta its own cap supports) +# arm 3 matched beta 0.95 : b095_RM vs b095_notrunc (both routes support it; 20-frame horizon) +# arm 4 beta 0.97 : b097_RM vs b097_notrunc (action-sensitivity optimum, 21% of mass) +# Anchor gate is the 18:15Z one: S2, within 100 frames of meta-state ENTRY, BY ROUTE, never pooled, with +# the gated oracle ceiling on every row and the permutation-calibrated family-wise q95 bar recomputed on +# the SAME restricted anchors. Eval-free: reads saved npz parts + hdf5 actions, loads no checkpoint. +set -uo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +export MUJOCO_GL=disable +PY=venv_rsm/bin/python + +# Run 18 (2026-09-24): jobs 1888534/1888535 add the SECOND SUCCESSOR SEED to every arm and the +# per-anchor arm at both cap settings and at the second proposer, so each arm is a seed pair and +# arm 2 is no longer a single cell. Names added here so the reduce reads them the moment they land. +CELLS="b099_RM b099_RMs1 b099_notrunc b099_notruncs1 \ + peranchor peranchor_RMs1 peranchor_notrunc peranchor_notruncs1 peranchor_ws \ + b095_RM b095_notrunc b095_notruncs1 b097_RM b097_RMs1 b097_notrunc b097_notruncs1" + +echo "=============== part counts at reduce time ===============" +for C in $CELLS; do echo " $C $(ls status/real/pt_betaB_${C}/parts 2>/dev/null | wc -l) parts"; done + +INCOMPLETE=0 +for C in $CELLS; do + N=$(ls status/real/pt_betaB_${C}/parts 2>/dev/null | wc -l) + [ "$N" -ge 25 ] || { echo "[betaB] WARNING ${C} only ${N}/25 parts -- arm is INCOMPLETE"; INCOMPLETE=1; } +done +echo "[betaB] incomplete=${INCOMPLETE}" + +# Run 20: a cell under 25 parts sits on FEWER EPISODES than its arm-mates, so printing its row beside +# them would be exactly the cross-anchor-set non-comparison this stream keeps catching elsewhere. Such a +# cell is skipped and named PENDING, never reported partial. +for C in $CELLS; do + DD="status/real/pt_betaB_${C}" + [ -d "$DD/parts" ] || { echo "[betaB] $DD missing"; continue; } + N=$(ls "$DD/parts" 2>/dev/null | wc -l) + [ "$N" -ge 25 ] || { echo "[betaB] PENDING ${C} ${N}/25 parts -- SKIPPED, not reported partial"; continue; } + echo "=============== beta ${C} entry window 100, by route ===============" + $PY scripts/real/proposal_report.py "$DD" --entry-window 100 --oracle-chunk 8 --by-route \ + --md "status/real/PT_BETAB_${C}_w100.md" \ + --json "status/real/PT_BETAB_${C}_w100.json" || { echo "[betaB] report FAILED $C"; continue; } + $PY scripts/real/pt_nullcal.py "$DD" --entry-window 100 --by-route --reps 3000 --boot 300 \ + --reflag "status/real/PT_BETAB_${C}_w100.json" \ + --md "status/real/PT_BETABCAL_${C}_w100.md" \ + --json "status/real/PT_BETABCAL_${C}_w100.json" || echo "[betaB] nullcal FAILED $C" +done +# Run 18: the dz-coupling statistic comes free with the same parts (job 1889567, gen_q#280). +# It is a property of the value, not an AUC, and it is what showed no head reads the channel the +# label is made of; running it on the seed-pair cells says whether that is seed-stable. +DZCELLS="" +for C in $CELLS; do + N=$(ls "status/real/pt_betaB_${C}/parts" 2>/dev/null | wc -l) + [ "$N" -ge 25 ] && DZCELLS="$DZCELLS pt_betaB_${C}" +done +$PY scripts/real/pt_score_dz.py $DZCELLS --entry-window 100 \ + --md status/real/PT_SCORE_DZ_betaB.md --json status/real/PT_SCORE_DZ_betaB.json \ + || echo "[betaB] score_dz FAILED" +echo "[betaB] done" diff --git a/rsm_rise/scripts/real/pt_capmatch.sh b/rsm_rise/scripts/real/pt_capmatch.sh new file mode 100644 index 0000000000000000000000000000000000000000..6601364bcf757e2ec40dba40f9c5ff73febefe52 --- /dev/null +++ b/rsm_rise/scripts/real/pt_capmatch.sh @@ -0,0 +1,9 @@ +#!/bin/bash +# PROPOSAL_TEST run 38b -- artefact magnitude of the CAPACITY-MATCHED statistic under the gb H0 DGP. +set -euo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +export MUJOCO_GL=disable OMP_NUM_THREADS=1 MKL_NUM_THREADS=1 OPENBLAS_NUM_THREADS=1 +exec venv_rsm/bin/python scripts/real/pt_capmatch_artefact.py \ + --out status/real/pt_capmatch_w100_goal_vs_cook \ + --entry-window 100 --lengths 8 --seeds 0 \ + --stat-models logreg mlp --dgp gb --m 40 --jobs 16 diff --git a/rsm_rise/scripts/real/pt_capmatch_artefact.py b/rsm_rise/scripts/real/pt_capmatch_artefact.py new file mode 100644 index 0000000000000000000000000000000000000000..3d8ba35c0edf5cc256dc9c335e82e2de26222b71 --- /dev/null +++ b/rsm_rise/scripts/real/pt_capmatch_artefact.py @@ -0,0 +1,214 @@ +#!/usr/bin/env python +"""gen_q#280 / jmarangola/rsm_real#2 -- PROPOSAL_TEST run 38b. + +THE CAPACITY-MATCHED STATISTIC'S ARTEFACT. +------------------------------------------ +Run 38 (job 1900982) measured, on H0 datasets where the chunk carries ZERO route information by +construction, that the published statistic `both:logreg - anchor:logreg` still reads +0.0250 raw / ++0.0216 resid -- 32-63 % of its published value. The stated mechanism is that the chunk is a +near-deterministic function of its own anchor (this stream's measured action convention: the action is an +ABSOLUTE end-effector target ~4 mm ahead of the current pose), so appending it hands a LINEAR model a +richer ANCHOR basis. The artefact is therefore predicted to scale with how much richer the true +anchor->label relation is than the STATISTIC's own anchor arm -- not with anything about the chunk. + +That prediction is falsifiable and this script tests it. `both:mlp - anchor:mlp` is the SAME statistic +with a capacity-matched anchor arm: its anchor arm reaches OOF AUC 0.9529 on the real y against logreg's +0.9102, so under the gb DGP (credential 0.9609) its credential GAP is 0.0080 instead of 0.0507. + +PRE-REGISTERED PREDICTION AND KILL CONDITION (fixed before any number here exists): + * If the mechanism is right, the mlp statistic's artefact must be MATERIALLY SMALLER than the logreg + statistic's +0.0250 raw / +0.0216 resid, measured on the SAME H0 datasets. Strict proportionality to + the credential gap would put it near +0.0039 raw; the prediction being tested is only the ORDERING. + * KILL: if the mlp artefact is NOT smaller than the logreg artefact (CIs overlapping or reversed), the + "better anchor basis" mechanism is WRONG and run 38's interpretation -- including the 32-63 % bound + and the retro-justification of run 36 item 5 -- must be revisited in public, not quietly dropped. + +WHAT THIS DOES AND DOES NOT MEASURE. This measures ARTEFACT MAGNITUDE only. It draws no null +distribution and computes no p-value, so it inherits none of the validity failures that voided the +chunk-permutation null (run 36, 18/20) and the y-resample null (run 37 and run 38, 37/40). H0 datasets +are valid for this one purpose precisely because the true marginal on them is ZERO BY CONSTRUCTION: any +positive reading IS the artefact. Nothing here declares the published marginal significant or not. + +Definitions are IMPORTED from proposal_ceiling.py and pt_yresample_null.py rather than retyped, so +nothing published moves and the generator is bit-identical to run 38's gb rung. +""" +import argparse, importlib.util, json, time +from pathlib import Path +from types import SimpleNamespace + +import numpy as np + +ROOT = "/proj/dmfexp/zwhong/rsm_rise" + + +def _load(name, path): + spec = importlib.util.spec_from_file_location(name, path) + m = importlib.util.module_from_spec(spec) + spec.loader.exec_module(m) + return m + + +YR = _load("yr", f"{ROOT}/scripts/real/pt_yresample_null.py") # episode_logits, draw_y, fit_arm_ext +PC = YR.PC # the SAME proposal_ceiling module + + +def stat_model(AN, CFw, GF, yy, ep, folds, seed, model): + """(raw, resid, auc_both, auc_anchor, auc_anchorgeom) with ALL THREE arms fit by `model`. + + This is PC's statistic with the arm model lifted to a parameter; at model='logreg' it is exactly + pt_yresample_null.stat, which the guard below checks against the published table.""" + s_a = PC.fit_arm(AN, yy, ep, folds, seed, model) + s_b = PC.fit_arm(np.concatenate([AN, CFw], 1), yy, ep, folds, seed, model) + s_g = PC.fit_arm(np.concatenate([AN, GF], 1), yy, ep, folds, seed, model) + ok = ~(np.isnan(s_a) | np.isnan(s_b) | np.isnan(s_g)) + aa, ab, ag = PC.auc(yy[ok], s_a[ok]), PC.auc(yy[ok], s_b[ok]), PC.auc(yy[ok], s_g[ok]) + return float(ab - aa), float(ab - ag), float(ab), float(aa), float(ag) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--out", required=True) + ap.add_argument("--hdf5", default=f"{ROOT}/data/raw/cooking_v5_expert_suboptimal.hdf5") + ap.add_argument("--split", default=f"{ROOT}/data/derived/cooking_v5_split.json") + ap.add_argument("--state", type=int, default=2) + ap.add_argument("--route-pos", default="[2, 3, 4]") + ap.add_argument("--route-neg", default="[0, 2, 3]") + ap.add_argument("--contrast", default="goal_vs_cook") + ap.add_argument("--stride", type=int, default=5) + ap.add_argument("--entry-window", type=int, default=100) + ap.add_argument("--lengths", type=int, nargs="+", default=[8]) + ap.add_argument("--folds", type=int, default=5) + ap.add_argument("--seeds", type=int, nargs="+", default=[0]) + ap.add_argument("--stat-models", nargs="+", default=["logreg", "mlp"]) + ap.add_argument("--dgp", default="gb") + ap.add_argument("--m", type=int, default=40) + ap.add_argument("--min-per-class", type=int, default=8) + ap.add_argument("--boot", type=int, default=2000) + ap.add_argument("--jobs", type=int, default=16) + ap.add_argument("--published", default=f"{ROOT}/status/real/pt_ceilresid_w100_goal_vs_cook/ceiling.json") + a = ap.parse_args() + t0 = time.time() + out = Path(a.out); out.mkdir(parents=True, exist_ok=True) + from joblib import Parallel, delayed + + rows, n_drop, n_ep = PC.build(SimpleNamespace( + hdf5=a.hdf5, split=a.split, state=a.state, route_pos=a.route_pos, route_neg=a.route_neg, + stride=a.stride, entry_window=a.entry_window, lengths=a.lengths)) + if not rows: + raise SystemExit("no anchors") + ep = np.array([r["ep"] for r in rows]); y = np.array([r["y"] for r in rows]) + AN = np.stack([r["anchor"] for r in rows]); CH = np.stack([r["chunk"] for r in rows]) + FEAT = {L: (PC.chunk_feat(CH, L, "waypoints"), PC.geom_feat(CH, L)) for L in a.lengths} + print(f"[cap] contrast={a.contrast} anchors={len(rows)} episodes={len(np.unique(ep))}/{n_ep} " + f"goal={int((y==1).sum())} fail={int((y==0).sum())} window={a.entry_window} dropped={n_drop}", + flush=True) + + # ---- OBSERVED statistic per arm model + REGRESSION GUARD against the published table. + pub = json.load(open(a.published)) + pubmap = {(p["pair"], p["L"], p["seed"]): p["diff"] for p in pub["paired"]} + obs, guard = {}, [] + for model in a.stat_models: + for seed in a.seeds: + for L in a.lengths: + CFw, GF = FEAT[L] + raw, rsd, ab, aa, ag = stat_model(AN, CFw, GF, y, ep, a.folds, seed, model) + obs[f"{model}|{seed}|{L}"] = dict(raw=raw, resid=rsd, auc_both=ab, auc_anchor=aa, + auc_anchorgeom=ag) + for key, val in ((f"both:{model} - anchor:{model}", raw), + (f"both:{model} - anchorgeom:{model}", rsd)): + if (key, L, seed) in pubmap: + guard.append(dict(pair=key, L=L, seed=seed, mine=float(val), + published=pubmap[(key, L, seed)], + delta=abs(float(val) - pubmap[(key, L, seed)]))) + print(f"[cap] OBSERVED stat={model:6s} L={L:3d} seed{seed} raw={raw:+.6f} " + f"resid={rsd:+.6f} both={ab:.4f} anchor={aa:.4f} anchorgeom={ag:.4f}", flush=True) + worst = max([g["delta"] for g in guard], default=float("nan")) + print(f"[cap] [GUARD] {len(guard)} published rows reproduced, worst |delta| = {worst:.3e}", flush=True) + if not (worst < 1e-9): + print("[cap] [GUARD] FAIL -- observed statistic does not reproduce the published table; every " + "number below is void.", flush=True) + + # ---- the H0 generator: identical to run 38's gb rung (same module, same seeds). + gseed = int(a.seeds[0]) + p_d = YR.fit_arm_ext(AN, y, ep, a.folds, gseed, a.dgp) + ok_d = ~np.isnan(p_d) + cred = float(PC.auc(y[ok_d], p_d[ok_d])) + ue, l_d, _, base = YR.episode_logits(p_d, y, ep) + print(f"[cap] DGP={a.dgp} credential (anchor-only OOF AUC on the REAL y) = {cred:.4f} base={base:.4f}", + flush=True) + for model in a.stat_models: + bar = obs[f"{model}|{gseed}|{a.lengths[0]}"]["auc_anchor"] + print(f"[cap] ADMISSIBILITY stat={model:6s}: its own anchor arm = {bar:.4f} -> DGP admissible = " + f"{cred >= bar} (credential gap {cred-bar:+.4f})", flush=True) + + # ---- artefact: the SAME H0 dataset scored by every statistic, so the comparison is paired. + Lt, seed = a.lengths[0], gseed + CFw, GF = FEAT[Lt] + + def one(m): + rngm = np.random.default_rng([90210, 0, m]) # run 38's gb rung used dgp_ix=0 for gb + ystar, _ = YR.draw_y(ue, l_d, 1.0, ep, rngm, a.min_per_class) + rec = dict(m=m) + for model in a.stat_models: + raw, rsd, ab, aa, ag = stat_model(AN, CFw, GF, ystar, ep, a.folds, seed, model) + rec[model] = dict(raw=raw, resid=rsd, auc_both=ab, auc_anchor=aa, auc_anchorgeom=ag) + return rec + + recs = Parallel(n_jobs=a.jobs, verbose=5)(delayed(one)(m) for m in range(a.m)) + recs.sort(key=lambda r: r["m"]) + for r in recs: + print("[cap] H0 m=%2d " % r["m"] + " ".join( + f"{k}: raw={r[k]['raw']:+.4f} resid={r[k]['resid']:+.4f} anchor={r[k]['auc_anchor']:.3f}" + for k in a.stat_models), flush=True) + + summ = {} + for model in a.stat_models: + raws = np.array([r[model]["raw"] for r in recs]) + rsds = np.array([r[model]["resid"] for r in recs]) + o = obs[f"{model}|{seed}|{Lt}"] + summ[model] = dict( + n=len(raws), observed_raw=o["raw"], observed_resid=o["resid"], + anchor_auc=o["auc_anchor"], credential_gap=cred - o["auc_anchor"], + artefact_raw_mean=float(raws.mean()), artefact_raw_se=float(raws.std(ddof=1) / len(raws) ** .5), + artefact_raw_med=float(np.median(raws)), artefact_raw_min=float(raws.min()), + artefact_raw_max=float(raws.max()), + artefact_resid_mean=float(rsds.mean()), artefact_resid_se=float(rsds.std(ddof=1) / len(rsds) ** .5), + artefact_resid_med=float(np.median(rsds)), artefact_resid_min=float(rsds.min()), + artefact_resid_max=float(rsds.max()), + frac_raw=float(raws.mean() / o["raw"]) if o["raw"] else None, + frac_resid=float(rsds.mean() / o["resid"]) if o["resid"] else None, + n_ge_observed_raw=int((raws >= o["raw"]).sum()), + n_ge_observed_resid=int((rsds >= o["resid"]).sum())) + s = summ[model] + print(f"[cap] ARTEFACT stat={model:6s} gap={s['credential_gap']:+.4f} " + f"raw={s['artefact_raw_mean']:+.4f}+-{s['artefact_raw_se']:.4f} " + f"({100*s['frac_raw']:.0f}% of observed {s['observed_raw']:+.4f}) " + f"resid={s['artefact_resid_mean']:+.4f}+-{s['artefact_resid_se']:.4f} " + f"({100*s['frac_resid']:.0f}% of observed {s['observed_resid']:+.4f}) " + f"n>=obs: {s['n_ge_observed_raw']}/{s['n']} raw, {s['n_ge_observed_resid']}/{s['n']} resid", + flush=True) + + # ---- the pre-registered ORDERING test, paired over the SAME H0 datasets. + verdict = None + if "logreg" in a.stat_models and "mlp" in a.stat_models: + for arm in ("raw", "resid"): + d = np.array([r["mlp"][arm] - r["logreg"][arm] for r in recs]) + se = d.std(ddof=1) / len(d) ** .5 + print(f"[cap] PAIRED mlp-minus-logreg artefact {arm}: {d.mean():+.4f} +- {se:.4f} " + f"(n={len(d)}; negative => capacity matching SHRINKS the artefact, as predicted)", + flush=True) + if arm == "raw": + verdict = "PREDICTION HELD (mlp artefact smaller)" if d.mean() + 2 * se < 0 else ( + "KILL CONDITION MET (mlp artefact not smaller) -- run 38's mechanism must be revisited") + print(f"[cap] VERDICT (raw arm, pre-registered): {verdict}", flush=True) + + json.dump(dict(contrast=a.contrast, entry_window=a.entry_window, n_anchors=len(rows), + n_episodes=int(len(np.unique(ep))), base_rate=base, dgp=a.dgp, credential=cred, + guard=guard, guard_worst=worst, observed=obs, summary=summ, + per_dataset=recs, verdict=verdict, config=vars(a)), + open(out / "capmatch.json", "w"), indent=1) + print(f"[cap] done {time.time()-t0:.0f}s -> {out}/capmatch.json", flush=True) + + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/real/pt_capmatch_declare.py b/rsm_rise/scripts/real/pt_capmatch_declare.py new file mode 100644 index 0000000000000000000000000000000000000000..0ab5f10c285e750737fb7f8b2bae182fdc704d6d --- /dev/null +++ b/rsm_rise/scripts/real/pt_capmatch_declare.py @@ -0,0 +1,211 @@ +#!/usr/bin/env python +"""gen_q#280 / jmarangola/rsm_real#2 -- PROPOSAL_TEST run 39. + +THE DECLARATION TEST: does the capacity-matched marginal survive its own null ON THE REAL DATA? +----------------------------------------------------------------------------------------------- +This is the last step of a four-run chain and it changes exactly ONE thing from run 38c +(`pt_capmatch_typei.py`): the dataset is the REAL `y` instead of an H0-by-construction resample of it. +Statistic, null generator, shrinkage and protocol are bit-for-bit the same code path. + + run 38 y-resample null, `both:logreg - anchor:logreg` statistic: type-I 37/40 = 0.925 -> INVALID. + run 38b WHY: the artefact is the chunk acting as a better ANCHOR basis for an under-capacity anchor + arm. Artefact +0.0250 +- 0.0014 (logreg, credential gap +0.0506) against -0.0020 +- 0.0024 + (mlp, gap +0.0080); paired difference -0.0271 +- 0.0017 on the SAME 40 H0 datasets. + run 38c therefore the null should be VALID for the capacity-matched statistic. Pre-registered + prediction <= 0.10 on the raw arm; exact-reproduction guard on the logreg rung (37/40, 34/40). + run 39 THIS: given a valid null, is the observed +0.0341 raw significant? + +PRE-REGISTERED DECISION RULE (fixed before any number here exists, and before run 38c's mlp rung +finished -- at submission time its raw arm stood at 3/24 with 16 draws outstanding, so the validity +verdict was NOT known when this rule was written): + + * DECLARE TASK A POSITIVE only if BOTH hold: + (i) run 38c's mlp raw type-I rate is <= 0.10 (its own pre-registered bar), AND + (ii) p_raw <= 0.05 at ALL THREE statistic seeds {0, 1, 2}, no pooling, no best-of. + The declaration is then: the 8-frame chunk carries a SMALL BUT REAL increment of route information + beyond the anchor, of magnitude +0.031..+0.040 AUC on top of an anchor arm already at 0.953. + * If (ii) fails at ANY seed, TASK A is NOT declared positive; every per-seed p is reported anyway. + * If (i) fails, every p-value in this file is VOID and TASK A stays UNDECLARED, as run 38b + pre-registered. Say so in public; do not quietly report the p. + * MAGNITUDE HONESTY, pre-registered because it is the tempting overclaim: a positive here is an + increment of ~0.034 AUC over an anchor arm at 0.953. It does NOT mean the chunk is informative + enough for the proposal test to be winnable, and it does NOT rehabilitate any retracted RSM number. + +The `logreg` statistic is computed alongside as a REFERENCE COLUMN ONLY. Its null is KNOWN INVALID +(37/40) and its p-value is printed with that label attached; it is not evidence for anything and must +never be quoted without it. + +REGRESSION GUARD. All four observed statistics at seed 0 must reproduce run 38b's published values to +zero delta, or every number here is void. + +Definitions imported from proposal_ceiling.py, pt_yresample_null.py and pt_capmatch_artefact.py; none of +the three is edited. +""" +import argparse, json, time +from pathlib import Path +from types import SimpleNamespace + +import numpy as np + +ROOT = "/proj/dmfexp/zwhong/rsm_rise" + +import importlib.util + + +def _load(name, path): + spec = importlib.util.spec_from_file_location(name, path) + m = importlib.util.module_from_spec(spec) + spec.loader.exec_module(m) + return m + + +YR = _load("yr", f"{ROOT}/scripts/real/pt_yresample_null.py") +CAP = _load("cap", f"{ROOT}/scripts/real/pt_capmatch_artefact.py") +PC = YR.PC +stat_model = CAP.stat_model +q95, qq = YR.q95, YR.qq + +# run 38b's published observed statistics, seed 0, L=8, window 100, goal_vs_cook. +PUBLISHED = { + ("logreg", "raw"): 0.06703325774754343, + ("logreg", "resid"): 0.0398800075585789, + ("mlp", "raw"): 0.034095332577475435, + ("mlp", "resid"): 0.02873866213151932, +} + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--out", required=True) + ap.add_argument("--hdf5", default=f"{ROOT}/data/raw/cooking_v5_expert_suboptimal.hdf5") + ap.add_argument("--split", default=f"{ROOT}/data/derived/cooking_v5_split.json") + ap.add_argument("--state", type=int, default=2) + ap.add_argument("--route-pos", default="[2, 3, 4]") + ap.add_argument("--route-neg", default="[0, 2, 3]") + ap.add_argument("--contrast", default="goal_vs_cook") + ap.add_argument("--stride", type=int, default=5) + ap.add_argument("--entry-window", type=int, default=100) + ap.add_argument("--lengths", type=int, nargs="+", default=[8]) + ap.add_argument("--folds", type=int, default=5) + # the statistic's own seed (fold split + model init). ALL of these must clear for a declaration. + ap.add_argument("--seeds", type=int, nargs="+", default=[0, 1, 2]) + # cheap reference rung first, so a guard break is caught before the expensive rung is paid for. + ap.add_argument("--stat-models", nargs="+", default=["logreg", "mlp"]) + ap.add_argument("--draws", type=int, default=1000) + ap.add_argument("--declare-lam", type=float, default=1.0) + ap.add_argument("--min-per-class", type=int, default=8) + ap.add_argument("--alpha", type=float, default=0.05) + ap.add_argument("--jobs", type=int, default=16) + a = ap.parse_args() + t0 = time.time() + out = Path(a.out); out.mkdir(parents=True, exist_ok=True) + from joblib import Parallel, delayed + + rows, n_drop, n_ep = PC.build(SimpleNamespace( + hdf5=a.hdf5, split=a.split, state=a.state, route_pos=a.route_pos, route_neg=a.route_neg, + stride=a.stride, entry_window=a.entry_window, lengths=a.lengths)) + ep = np.array([r["ep"] for r in rows]); y = np.array([r["y"] for r in rows]) + AN = np.stack([r["anchor"] for r in rows]); CH = np.stack([r["chunk"] for r in rows]) + Lt = a.lengths[0] + CFw, GF = PC.chunk_feat(CH, Lt, "waypoints"), PC.geom_feat(CH, Lt) + n_kept_ep = int(len(np.unique(ep))) + print(f"[dec] contrast={a.contrast} anchors={len(rows)} episodes={n_kept_ep}/{n_ep} " + f"window={a.entry_window} L={Lt} dropped={n_drop} draws={a.draws} lam={a.declare_lam}", + flush=True) + + # ---------------- observed statistics + the regression guard (seed 0 only, where PUBLISHED applies) + observed, guard = {}, [] + for model in a.stat_models: + for seed in a.seeds: + raw, rsd, ab, aa, ag = stat_model(AN, CFw, GF, y, ep, a.folds, seed, model) + observed[(model, seed)] = dict(raw=raw, resid=rsd, auc_both=ab, auc_anchor=aa, + auc_anchorgeom=ag) + print(f"[dec] OBSERVED stat={model:6s} seed={seed} both={ab:.4f} anchor={aa:.4f} " + f"anchorgeom={ag:.4f} raw={raw:+.4f} resid={rsd:+.4f}", flush=True) + if seed == 0: + for arm, val in (("raw", raw), ("resid", rsd)): + pub = PUBLISHED[(model, arm)] + guard.append(dict(stat=model, arm=arm, mine=val, published=pub, + delta=abs(val - pub))) + worst = max(g["delta"] for g in guard) + print(f"[dec] [GUARD] {len(guard)} published rows reproduced, worst |delta| = {worst:.3e}", flush=True) + if worst > 1e-12: + print("[dec] [GUARD] FAIL -- observed statistics do not reproduce run 38b's published table; " + "every number below is VOID.", flush=True) + + # ---------------- the null, per (statistic, seed): generator MATCHED to the statistic, fit on REAL y + results, verdict_rows = [], [] + for model in a.stat_models: + for seed in a.seeds: + p_a = PC.fit_arm(AN, y, ep, a.folds, seed, model) + ok = ~np.isnan(p_a) + cred = float(PC.auc(y[ok], p_a[ok])) + ue, l_e, _, base = YR.episode_logits(p_a, y, ep) + print(f"[dec] NULL GEN stat={model} seed={seed} arm-credential-on-real-y={cred:.4f} " + f"base={base:.4f} episodes={len(ue)}", flush=True) + + def one(rep): + rng = np.random.default_rng([31337, seed, rep]) + yy, _ = YR.draw_y(ue, l_e, a.declare_lam, ep, rng, a.min_per_class) + r, d, _, _, _ = stat_model(AN, CFw, GF, yy, ep, a.folds, seed, model) + return r, d + + res = Parallel(n_jobs=a.jobs, prefer="processes")(delayed(one)(r) for r in range(a.draws)) + nr = np.array([r[0] for r in res]); nd = np.array([r[1] for r in res]) + rec = dict(stat=model, seed=seed, n_draws=int(a.draws), + reference_only=(model == "logreg")) + for arm, obs, nul in (("raw", observed[(model, seed)]["raw"], nr), + ("resid", observed[(model, seed)]["resid"], nd)): + # one-sided, +1/+1 so p is never 0 and the resolution is explicit. + p = float((1 + int((nul >= obs).sum())) / (1 + len(nul))) + rec[arm] = dict(obs=float(obs), p=p, n_ge=int((nul >= obs).sum()), + null_mean=float(nul.mean()), null_sd=float(nul.std(ddof=1)), + null_q95=q95(nul), null_q99=qq(nul, 0.99), + clears_q95=bool(obs > q95(nul)), clears_alpha=bool(p <= a.alpha)) + tag = "REFERENCE-ONLY, null KNOWN INVALID 37/40" if model == "logreg" else "" + print(f"[dec] P stat={model:6s} seed={seed} {arm:5s}: obs={obs:+.4f} " + f"null mean={nul.mean():+.4f} sd={nul.std(ddof=1):.4f} q95={q95(nul):+.4f} " + f"-> p={p:.4f} (n>=obs {int((nul >= obs).sum())}/{len(nul)}) " + f"{'CLEARS' if p <= a.alpha else 'does not clear'} alpha={a.alpha} {tag} " + f"[{time.time()-t0:.0f}s]", flush=True) + rec["arm_credential_on_real_y"] = cred + results.append(rec) + + # ---------------- the pre-registered rule, applied to condition (ii) only. (i) lives in run 38c. + summary = {} + for model in a.stat_models: + rr = [r for r in results if r["stat"] == model] + for arm in ("raw", "resid"): + ps = {r["seed"]: r[arm]["p"] for r in rr} + allclear = all(p <= a.alpha for p in ps.values()) + summary[f"{model}_{arm}"] = dict(p_by_seed=ps, all_seeds_clear=bool(allclear), + n_seeds=len(ps)) + note = ("" if model == "mlp" else + " [REFERENCE ONLY -- this statistic's null is INVALID at 37/40; not evidence]") + print(f"[dec] RULE(ii) stat={model} {arm}: p by seed " + f"{ {k: round(v, 4) for k, v in ps.items()} } -> all {len(ps)} seeds clear " + f"alpha={a.alpha}: {allclear}{note}", flush=True) + + mlp_raw = summary.get("mlp_raw", {}) + print("[dec] ---------------------------------------------------------------", flush=True) + print(f"[dec] CONDITION (ii) on the capacity-matched raw arm: " + f"{'SATISFIED' if mlp_raw.get('all_seeds_clear') else 'NOT satisfied'}", flush=True) + print("[dec] CONDITION (i) is run 38c's mlp raw type-I rate <= 0.10 and is NOT decided here. " + "Read it from logs/slurm/rr_cpu_ptcaptypei.41854.out before declaring anything.", flush=True) + print("[dec] A declaration requires BOTH. If (i) failed, every p above is VOID.", flush=True) + + json.dump(dict(contrast=a.contrast, entry_window=a.entry_window, n_anchors=len(rows), + n_episodes=n_kept_ep, n_episodes_total=n_ep, dropped=n_drop, + guard=guard, guard_worst=worst, observed={f"{k[0]}_s{k[1]}": v + for k, v in observed.items()}, + results=results, summary=summary, + prereg=dict(alpha=a.alpha, seeds=a.seeds, draws=a.draws, + condition_i="run 38c mlp raw type-I <= 0.10 (decided elsewhere)", + condition_ii="p_raw <= alpha at ALL seeds for stat=mlp"), + config=vars(a)), + open(out / "capmatch_declare.json", "w"), indent=1) + print(f"[dec] done {time.time()-t0:.0f}s -> {out}/capmatch_declare.json", flush=True) + + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/real/pt_capmatch_declare.sh b/rsm_rise/scripts/real/pt_capmatch_declare.sh new file mode 100644 index 0000000000000000000000000000000000000000..0ab09cf3b8462f5d67a6be927bb02540fd91288e --- /dev/null +++ b/rsm_rise/scripts/real/pt_capmatch_declare.sh @@ -0,0 +1,10 @@ +#!/bin/bash +# PROPOSAL_TEST run 39 -- the DECLARATION test: capacity-matched marginal against its own null, REAL data. +set -euo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +export MUJOCO_GL=disable OMP_NUM_THREADS=1 MKL_NUM_THREADS=1 OPENBLAS_NUM_THREADS=1 +exec venv_rsm/bin/python scripts/real/pt_capmatch_declare.py \ + --out status/real/pt_capmatch_declare_w100_goal_vs_cook \ + --entry-window 100 --lengths 8 --seeds 0 1 2 \ + --stat-models logreg mlp \ + --draws 1000 --jobs 16 diff --git a/rsm_rise/scripts/real/pt_capmatch_typei.py b/rsm_rise/scripts/real/pt_capmatch_typei.py new file mode 100644 index 0000000000000000000000000000000000000000..8dc41e63ec94e776a590e0ab5998a35dfe9f9276 --- /dev/null +++ b/rsm_rise/scripts/real/pt_capmatch_typei.py @@ -0,0 +1,175 @@ +#!/usr/bin/env python +"""gen_q#280 / jmarangola/rsm_real#2 -- PROPOSAL_TEST run 38c. + +IS THE Y-RESAMPLE NULL VALID FOR THE CAPACITY-MATCHED STATISTIC? +---------------------------------------------------------------- +Run 38 measured the y-resample null's type-I rate for `both:logreg - anchor:logreg` under the gb H0 DGP at +37/40 = 0.925 (raw) and 34/40 = 0.850 (resid), against a bar of <= 0.10: INVALID. Run 38b then measured +WHY, and confirmed the mechanism against a pre-registered kill condition: the artefact is the chunk acting +as a better ANCHOR basis for an under-capacity anchor arm, and it vanishes when the arm can already +exploit that basis -- artefact +0.0250 +- 0.0014 for the logreg statistic (credential gap +0.0506) against +**-0.0020 +- 0.0024** for the capacity-matched mlp statistic (gap +0.0080), paired difference +-0.0271 +- 0.0017. + +If that mechanism is the WHOLE story, the null must be VALID for the mlp statistic, because the quantity +that inflated it is gone. That is the last untested link in the chain and this script tests it. + +PRE-REGISTERED PREDICTION AND KILL CONDITION (fixed before any number here exists): + * PREDICTION: type-I rate of the y-resample null for `both:mlp - anchor:mlp` under the gb DGP is + <= 0.10 on the raw arm. If it holds, this stream has a VALID null for the first time and the + capacity-matched marginal becomes declarable. + * KILL: if it still exceeds 0.10, the inflation has a SECOND source beyond the anchor-basis artefact, + run 38b's mechanism is necessary but not sufficient, and TASK A stays UNDECLARED -- to be said in + public in the next comment, not quietly dropped. + * This script DECLARES NOTHING about the real data either way. It measures a type-I rate only. + +EXACT-REPRODUCTION GUARD. The `logreg` rung is run with bit-identical seeding to run 38's gb rung +(`rngm = default_rng([90210, 0, m])`, null `default_rng([7700+m, 0, rep])`, 200 draws, M=40), so it must +reproduce **37/40 raw and 34/40 resid exactly**. If it does not, the statistic-model refactor changed +something it should not have and every number here is void. + +Definitions imported from proposal_ceiling.py, pt_yresample_null.py and pt_capmatch_artefact.py; none of +the three is edited. +""" +import argparse, importlib.util, json, time +from pathlib import Path +from types import SimpleNamespace + +import numpy as np + +ROOT = "/proj/dmfexp/zwhong/rsm_rise" + + +def _load(name, path): + spec = importlib.util.spec_from_file_location(name, path) + m = importlib.util.module_from_spec(spec) + spec.loader.exec_module(m) + return m + + +YR = _load("yr", f"{ROOT}/scripts/real/pt_yresample_null.py") +CAP = _load("cap", f"{ROOT}/scripts/real/pt_capmatch_artefact.py") +PC = YR.PC +stat_model = CAP.stat_model +q95 = YR.q95 + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--out", required=True) + ap.add_argument("--hdf5", default=f"{ROOT}/data/raw/cooking_v5_expert_suboptimal.hdf5") + ap.add_argument("--split", default=f"{ROOT}/data/derived/cooking_v5_split.json") + ap.add_argument("--state", type=int, default=2) + ap.add_argument("--route-pos", default="[2, 3, 4]") + ap.add_argument("--route-neg", default="[0, 2, 3]") + ap.add_argument("--contrast", default="goal_vs_cook") + ap.add_argument("--stride", type=int, default=5) + ap.add_argument("--entry-window", type=int, default=100) + ap.add_argument("--lengths", type=int, nargs="+", default=[8]) + ap.add_argument("--folds", type=int, default=5) + ap.add_argument("--seeds", type=int, nargs="+", default=[0]) + # order matters: the guard rung runs FIRST and cheapest, so a refactor break is caught before the + # expensive rung is paid for. + ap.add_argument("--stat-models", nargs="+", default=["logreg", "mlp"]) + ap.add_argument("--dgp", default="gb") + ap.add_argument("--dgp-ix", type=int, default=0, help="run 38 used dgp_ix=0 for gb; keep it for the guard") + ap.add_argument("--m", type=int, default=40) + ap.add_argument("--draws", type=int, default=200) + ap.add_argument("--declare-lam", type=float, default=1.0) + ap.add_argument("--min-per-class", type=int, default=8) + ap.add_argument("--bar", type=float, default=0.10) + ap.add_argument("--jobs", type=int, default=32) + ap.add_argument("--expect", default='{"logreg": [37, 34]}', + help="JSON {stat: [raw_k, resid_k]} run 38 measured; the exact-reproduction guard.") + a = ap.parse_args() + t0 = time.time() + out = Path(a.out); out.mkdir(parents=True, exist_ok=True) + from joblib import Parallel, delayed + + rows, n_drop, n_ep = PC.build(SimpleNamespace( + hdf5=a.hdf5, split=a.split, state=a.state, route_pos=a.route_pos, route_neg=a.route_neg, + stride=a.stride, entry_window=a.entry_window, lengths=a.lengths)) + ep = np.array([r["ep"] for r in rows]); y = np.array([r["y"] for r in rows]) + AN = np.stack([r["anchor"] for r in rows]); CH = np.stack([r["chunk"] for r in rows]) + Lt = a.lengths[0]; seed = int(a.seeds[0]) + CFw, GF = PC.chunk_feat(CH, Lt, "waypoints"), PC.geom_feat(CH, Lt) + print(f"[cti] contrast={a.contrast} anchors={len(rows)} episodes={len(np.unique(ep))}/{n_ep} " + f"window={a.entry_window} L={Lt} seed={seed} dropped={n_drop}", flush=True) + + # ---- the H0 generator: gb, identical to run 38's rung. + p_d = YR.fit_arm_ext(AN, y, ep, a.folds, seed, a.dgp) + ok_d = ~np.isnan(p_d) + cred = float(PC.auc(y[ok_d], p_d[ok_d])) + ue, l_d, _, base = YR.episode_logits(p_d, y, ep) + print(f"[cti] DGP={a.dgp} credential={cred:.4f} base={base:.4f}", flush=True) + + expect = json.loads(a.expect) + from scipy.stats import beta as _beta + + def cp(k, n): + """Clopper-Pearson 95%, same convention as run 37/38's type-I tables.""" + return (float(_beta.ppf(0.025, k, n - k + 1)) if k else 0.0, + float(_beta.ppf(0.975, k + 1, n - k)) if k < n else 1.0) + + allrec, rates, verdicts = [], {}, {} + for model in a.stat_models: + # admissibility of the DGP for THIS statistic, under the run-37 rule. + s_a0 = PC.fit_arm(AN, y, ep, a.folds, seed, model) + ok0 = ~np.isnan(s_a0) + bar_auc = float(PC.auc(y[ok0], s_a0[ok0])) + print(f"[cti] ADMISSIBILITY stat={model:6s}: own anchor arm {bar_auc:.4f} vs DGP credential " + f"{cred:.4f} -> admissible={cred >= bar_auc} (gap {cred-bar_auc:+.4f})", flush=True) + if cred < bar_auc: + print(f"[cti] SKIP stat={model}: DGP not admissible for it.", flush=True) + continue + recs = [] + for m in range(a.m): + rngm = np.random.default_rng([90210, a.dgp_ix, m]) # run 38's exact stream + ystar, _ = YR.draw_y(ue, l_d, 1.0, ep, rngm, a.min_per_class) + raw_m, rsd_m, _, aa_m, _ = stat_model(AN, CFw, GF, ystar, ep, a.folds, seed, model) + # the null refitted ON THE RESAMPLED DATA, with the generator MATCHED to the statistic. + p_a = PC.fit_arm(AN, ystar, ep, a.folds, seed, model) + ue2, l2, _, _ = YR.episode_logits(p_a, ystar, ep) + + def one(rep): + rng = np.random.default_rng([7700 + m, a.dgp_ix, rep]) + yy, _ = YR.draw_y(ue2, l2, a.declare_lam, ep, rng, a.min_per_class) + r, d, _, _, _ = stat_model(AN, CFw, GF, yy, ep, a.folds, seed, model) + return r, d + + res = Parallel(n_jobs=a.jobs, prefer="processes")(delayed(one)(r) for r in range(a.draws)) + nr = np.array([r[0] for r in res]); nd = np.array([r[1] for r in res]) + rec = dict(stat=model, m=m, raw_obs=raw_m, resid_obs=rsd_m, raw_q95=q95(nr), + resid_q95=q95(nd), raw_clears=bool(raw_m > q95(nr)), + resid_clears=bool(rsd_m > q95(nd)), anchor_auc=aa_m) + recs.append(rec); allrec.append(rec) + print(f"[cti] TYPEI stat={model} m={m:2d} raw={raw_m:+.4f} vs q95={q95(nr):+.4f} " + f"({rec['raw_clears']}) resid={rsd_m:+.4f} vs q95={q95(nd):+.4f} " + f"({rec['resid_clears']}) anchorAUC={aa_m:.3f} [{time.time()-t0:.0f}s]", flush=True) + for arm in ("raw", "resid"): + k = int(sum(r[f"{arm}_clears"] for r in recs)); n = len(recs) + lo, hi = cp(k, n) + rates[f"{model}_{arm}"] = dict(k=k, n=n, rate=k / n, ci=[float(lo), float(hi)]) + print(f"[cti] TYPE-I RATE stat={model} {arm}: {k}/{n} = {k/n:.3f} CP95 " + f"[{lo:.3f},{hi:.3f}] (bar <= {a.bar}; a valid test sits at 0.05)", flush=True) + if model in expect: + want = expect[model][0 if arm == "raw" else 1] + ok = (k == want) if n == a.m else None + print(f"[cti] [GUARD] stat={model} {arm}: run 38 measured {want}/{a.m}, this run {k}/{n} " + f"-> {'EXACT MATCH' if ok else 'MISMATCH -- every number here is void'}", flush=True) + if model != "logreg": + k = rates[f"{model}_raw"]["k"]; n = rates[f"{model}_raw"]["n"] + verdicts[model] = ("PREDICTION HELD -- the null is VALID for this statistic" + if k / n <= a.bar else + "KILL CONDITION MET -- inflation has a second source; TASK A stays UNDECLARED") + print(f"[cti] VERDICT stat={model} (raw arm, pre-registered): {verdicts[model]}", flush=True) + + json.dump(dict(contrast=a.contrast, entry_window=a.entry_window, n_anchors=len(rows), + n_episodes=int(len(np.unique(ep))), dgp=a.dgp, credential=cred, base_rate=base, + typei=allrec, typei_rate=rates, verdicts=verdicts, config=vars(a)), + open(out / "capmatch_typei.json", "w"), indent=1) + print(f"[cti] done {time.time()-t0:.0f}s -> {out}/capmatch_typei.json", flush=True) + + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/real/pt_capmatch_typei.sh b/rsm_rise/scripts/real/pt_capmatch_typei.sh new file mode 100644 index 0000000000000000000000000000000000000000..87ff9127607ceb70488cb60908b3c8dbf96c6c2c --- /dev/null +++ b/rsm_rise/scripts/real/pt_capmatch_typei.sh @@ -0,0 +1,10 @@ +#!/bin/bash +# PROPOSAL_TEST run 38c -- type-I rate of the y-resample null for the CAPACITY-MATCHED statistic. +set -euo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +export MUJOCO_GL=disable OMP_NUM_THREADS=1 MKL_NUM_THREADS=1 OPENBLAS_NUM_THREADS=1 +exec venv_rsm/bin/python scripts/real/pt_capmatch_typei.py \ + --out status/real/pt_capmatch_typei_w100_goal_vs_cook \ + --entry-window 100 --lengths 8 --seeds 0 \ + --stat-models logreg mlp --dgp gb --dgp-ix 0 \ + --m 40 --draws 200 --jobs 16 diff --git a/rsm_rise/scripts/real/pt_capmatch_typei160.sh b/rsm_rise/scripts/real/pt_capmatch_typei160.sh new file mode 100644 index 0000000000000000000000000000000000000000..dcf290aa3d7431ce3d3f7cf9b3c6e14a9e2a2427 --- /dev/null +++ b/rsm_rise/scripts/real/pt_capmatch_typei160.sh @@ -0,0 +1,15 @@ +#!/bin/bash +# PROPOSAL_TEST run 39 successor -- ONE CHANGE from run 38c: M = 40 -> 160 on the mlp type-I arm. +# Tightens condition (i), which passed at exactly 4/40 = 0.100 with CP95 [0.028, 0.237]. +# The logreg rung is DROPPED: its 37/40 is already reproduced exactly and paying 40 more draws for it +# buys nothing. The guard instead lives in the mlp rung's first 40 draws, which use identical seed +# streams to run 38c and must return 4/40 raw and 2/40 resid. +set -euo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +export MUJOCO_GL=disable OMP_NUM_THREADS=1 MKL_NUM_THREADS=1 OPENBLAS_NUM_THREADS=1 +exec venv_rsm/bin/python scripts/real/pt_capmatch_typei.py \ + --out status/real/pt_capmatch_typei160_w100_goal_vs_cook \ + --entry-window 100 --lengths 8 --seeds 0 \ + --stat-models mlp --dgp gb --dgp-ix 0 \ + --m 160 --draws 200 --jobs 16 \ + --expect '{}' diff --git a/rsm_rise/scripts/real/pt_ceil_w100_table.py b/rsm_rise/scripts/real/pt_ceil_w100_table.py new file mode 100644 index 0000000000000000000000000000000000000000..32cad199697628975ec6d809a4399bb8186e17cc --- /dev/null +++ b/rsm_rise/scripts/real/pt_ceil_w100_table.py @@ -0,0 +1,50 @@ +#!/usr/bin/env python +"""Reduce the entry-window supervised-ceiling runs (job 1885397) into one table. + +Averages over the three episode-split seeds, keeps the 'waypoints' chunk feature for the +chunk-bearing arms (plus dir3/mag1/metaheur which have their own feature), and prints the +MARGINAL information the chunk carries over the anchor alone (both - anchor), which is the +quantity TASK A asks for. Reads json only; no compute. +""" +import json, sys, statistics as st + +CONTRASTS = ["goal_vs_cook", "goal_vs_fail", "cook_vs_fail"] +KEEP = ["both:logreg", "both:mlp", "chunk:logreg", "chunk:mlp", + "anchor:logreg", "anchor:mlp", "chunkdir:logreg", "chunkmag:logreg", "metaheur", + "labelperm_both", "labelperm_anchor", "labelperm_chunk", "random"] + +def agg(rows, arm, L): + sel = [r for r in rows if r["arm"] == arm and r["L"] == L + and r["chunk_feat"] in ("waypoints", "dir3", "mag1", "dir", "-")] + if not sel: + return None + aucs = [r["auc"] for r in sel] + ses = [r["se"] for r in sel] + return (sum(aucs)/len(aucs), max(ses), len(sel), sel[0]["n"], sel[0]["n_eps"]) + +for c in CONTRASTS: + try: + d = json.load(open(f"status/real/pt_ceiling_w100_{c}/ceiling.json")) + except FileNotFoundError: + print(f"## {c}: NOT FINISHED\n"); continue + rows = d["results"] + Ls = sorted({r["L"] for r in rows}) + print(f"## {c} entry_window={d['entry_window']} anchors={d['n_anchors']} " + f"episodes={d['n_episodes']} dropped_by_Lmax={d['dropped_by_Lmax']}") + hdr = "| arm | " + " | ".join(f"L={L}" for L in Ls) + " |" + print(hdr); print("|" + "---|" * (len(Ls)+1)) + for arm in KEEP: + cells = [] + for L in Ls: + a = agg(rows, arm, L) + cells.append("--" if a is None else f"{a[0]:.3f} +-{a[1]:.3f}") + if all(x == "--" for x in cells): continue + print(f"| `{arm}` | " + " | ".join(cells) + " |") + # marginal: chunk information over the anchor + for pair in [("both:mlp", "anchor:mlp"), ("both:logreg", "anchor:logreg")]: + cells = [] + for L in Ls: + a, b = agg(rows, pair[0], L), agg(rows, pair[1], L) + cells.append("--" if (a is None or b is None) else f"{a[0]-b[0]:+.3f}") + print(f"| **MARGINAL {pair[0]} - {pair[1]}** | " + " | ".join(cells) + " |") + print() diff --git a/rsm_rise/scripts/real/pt_ceiling.sh b/rsm_rise/scripts/real/pt_ceiling.sh new file mode 100644 index 0000000000000000000000000000000000000000..1aa4bc8f8615a12225858425e1e3691c95fd26b0 --- /dev/null +++ b/rsm_rise/scripts/real/pt_ceiling.sh @@ -0,0 +1,6 @@ +#!/bin/bash +# gen_q#280 / rsm_real#2 TASK A -- supervised ceiling of the proposal test (CPU only) +set -euo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +export MUJOCO_GL=disable OMP_NUM_THREADS=8 +venv_rsm/bin/python scripts/real/proposal_ceiling.py --out status/real/pt_ceiling "$@" diff --git a/rsm_rise/scripts/real/pt_ceiling_entry.sh b/rsm_rise/scripts/real/pt_ceiling_entry.sh new file mode 100644 index 0000000000000000000000000000000000000000..e4fa1103b3c2879df9a81b24e55d5ed940fcc213 --- /dev/null +++ b/rsm_rise/scripts/real/pt_ceiling_entry.sh @@ -0,0 +1,32 @@ +#!/bin/bash +# gen_q#280 / rsm_real#2 -- TASK A's supervised ceiling RE-MEASURED on the 18:15Z anchor set. +# +# WHY this must be re-run and not read off the 17:20Z table: TASK A was measured over anchors spread across +# the WHOLE of S2 (6254 anchors), but every proposal-test number now reported is read on anchors within 100 +# frames of S2 ENTRY, because the direction proxy is only label-sound there (92.2% assignment accuracy, +# oracle 0.917, against 47.7% / 0.467 over the whole state). A ceiling measured on a different anchor set +# is not the ceiling for the numbers being compared to it. ONE CHANGE from the 17:20Z run: --entry-window. +# +# Three contrasts, because the route label is perfectly confounded with the demonstrator: +# C1 goal_vs_fail [2,3,4] vs [0,2,6] -- as the spec says; expert vs suboptimal, CONFOUNDED +# C2 goal_vs_cook [2,3,4] vs [0,2,3] -- both EXPERT: destiny with the generator held fixed. THE ANSWER. +# C3 cook_vs_fail [0,2,3] vs [0,2,6] -- both non-goal: pure generator identity = the size of C1's confound +# Each carries an episode-level LABEL PERMUTATION as its measured zero line. Chunk lengths 8/16/32/64 on a +# FIXED anchor set so L varies temporal span only. CPU only, no checkpoint is loaded. +set -uo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +export MUJOCO_GL=disable OMP_NUM_THREADS=8 +PY=venv_rsm/bin/python +W=${W:-100} +run () { # name route_pos route_neg + echo "=============== $1 entry window $W ===============" + $PY scripts/real/proposal_ceiling.py \ + --out "status/real/pt_ceiling_w${W}_$1" --contrast "$1" \ + --route-pos "$2" --route-neg "$3" \ + --entry-window "$W" --state 2 --stride 5 --lengths 8 16 32 64 \ + --folds 5 --seeds 0 1 2 --boot 2000 || echo "[ceil] FAILED $1" +} +run goal_vs_fail "[2, 3, 4]" "[0, 2, 6]" +run goal_vs_cook "[2, 3, 4]" "[0, 2, 3]" +run cook_vs_fail "[0, 2, 3]" "[0, 2, 6]" +echo "[ceil] done" diff --git a/rsm_rise/scripts/real/pt_ceiling_paired.sh b/rsm_rise/scripts/real/pt_ceiling_paired.sh new file mode 100644 index 0000000000000000000000000000000000000000..e482b65a391a3021aabaa58c1be44d90e95da160 --- /dev/null +++ b/rsm_rise/scripts/real/pt_ceiling_paired.sh @@ -0,0 +1,18 @@ +#!/bin/bash +# gen_q#280 / rsm_real#2 -- the ONE caveat flagged on the TASK A post (5802069886 / 5802070131): +# the marginal "chunk over anchor" (+0.034 mlp / +0.061 logreg at L=8) was read off two SEPARATE episode +# bootstraps, so it has no interval and I refused to claim it. This gives it one: a PAIRED episode +# bootstrap that resamples episodes ONCE and takes AUC(both) - AUC(anchor) on the same resample, beside a +# permuted-label paired zero line (a permuted marginal need not be 0). +# ONE CHANGE from job 1885397: the paired difference. Same anchors, same folds, same seeds, same window. +# C2 goal_vs_cook ONLY -- it is the provenance-matched contrast and the only one the marginal means +# anything on (C1's anchor-only arm is already 0.990, marginal +0.008 = pure provenance). +set -uo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +export MUJOCO_GL=disable OMP_NUM_THREADS=8 +venv_rsm/bin/python scripts/real/proposal_ceiling.py \ + --out status/real/pt_ceiling_w100_paired_goal_vs_cook --contrast goal_vs_cook \ + --route-pos "[2, 3, 4]" --route-neg "[0, 2, 3]" \ + --entry-window 100 --state 2 --stride 5 --lengths 8 16 32 64 \ + --folds 5 --seeds 0 1 2 --boot 2000 +echo "[ceil-paired] done" diff --git a/rsm_rise/scripts/real/pt_ceiling_permnull.sh b/rsm_rise/scripts/real/pt_ceiling_permnull.sh new file mode 100644 index 0000000000000000000000000000000000000000..299015c71228c2a12de56224be229aa579d0cef3 --- /dev/null +++ b/rsm_rise/scripts/real/pt_ceiling_permnull.sh @@ -0,0 +1,19 @@ +#!/bin/bash +# gen_q#280 / rsm_real#2 -- run 11. CALIBRATE the paired marginal. +# Job 1885826 gave the marginal its interval: +0.034 (mlp) / +0.061 (logreg) at L=8, CI excluding 0 on all +# three seeds (2.7-3.6 SE from 0). But the project's rule is that a number is quoted against its MEASURED +# zero line, and the single permuted draw in that job has an episode-bootstrap SE of ~0.026, so the real +# marginal sits only 1.0 SE (mlp) / 1.8 SE (logreg) above it -- an uncalibrated comparison, because one +# permuted draw is one sample of the null, not the null. +# ONE CHANGE from 1885826: 200 episode-level label permutations, each refit end to end, giving the null +# DISTRIBUTION of the paired marginal and hence a q95 bar. C2 goal_vs_cook only, L=8 only, seed 0 only. +set -uo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +export MUJOCO_GL=disable OMP_NUM_THREADS=8 +venv_rsm/bin/python scripts/real/proposal_ceiling.py \ + --out status/real/pt_ceiling_w100_permnull_goal_vs_cook --contrast goal_vs_cook \ + --route-pos "[2, 3, 4]" --route-neg "[0, 2, 3]" \ + --entry-window 100 --state 2 --stride 5 --lengths 8 \ + --folds 5 --seeds 0 --boot 1000 \ + --perm-null 200 --perm-null-models logreg mlp --perm-null-lengths 8 +echo "[permnull] done" diff --git a/rsm_rise/scripts/real/pt_ceiling_resid.sh b/rsm_rise/scripts/real/pt_ceiling_resid.sh new file mode 100644 index 0000000000000000000000000000000000000000..27e330832569068433995346343e92a0618366b2 --- /dev/null +++ b/rsm_rise/scripts/real/pt_ceiling_resid.sh @@ -0,0 +1,49 @@ +#!/bin/bash +# gen_q#280 / rsm_real#2 -- PROPOSAL_TEST run 32. +# +# THE QUESTION. FT_EVAL run 23 reports the S2 gate as `gatexf`, which residualises every score against the +# candidate's own geometry -- `basis(disp, mag, "quad")`, scripts/tmp/edge_gate_power.py -- under a 5-fold +# cross-fit, and reports 0/20 arms above its +0.020 seed null. Nobody has measured what a PERFECT scorer +# could reach on that statistic. TASK A's remit is exactly that: measure the ceiling before reading a 0/20 +# as a defect. My own TASK A ceiling (PT_CEILING_W100.md) is a RAW ceiling -- `both:mlp` 0.988 against +# permuted 0.526, marginal over the anchor +0.034 / +0.061 at L=8 -- and says nothing about the residualised +# one, because its chunk features INCLUDE the direction and magnitude that `gatexf` removes. +# +# ONE CHANGE from the W100 run: one new arm, `anchorgeom` = anchor features + the gate's own geometry basis. +# The paired marginal `both - anchorgeom` is the route information the chunk still carries once direction and +# magnitude are ALREADY KNOWN, which is the ceiling for any geometry-residualised gate on this anchor set. +# The `basis` definition is extracted by ast from the gate's source and its sha256 printed, so it is the same +# definition and not a retyped copy. +# +# PRE-REGISTERED READING, fixed before the number exists (posted to both issues before submission): +# (A) marginal `both - anchorgeom` is at or below its own permuted ZEROLINE -> the chunk carries NOTHING +# about the route beyond its geometry, the residualised gate's ceiling is ~0, and FT_EVAL's 0/20 is +# AT THE CEILING and must not be read as a defect of any checkpoint. +# (B) the marginal is clearly positive and above its ZEROLINE -> the residualised gate can in principle be +# won, 0/20 is a real negative about the models, and the ceiling is the number to size it against. +# (C) undefined/degenerate (e.g. `anchorgeom` >= `both`) -> reported as UNDEFINED, loudly, not as (A). +# Either way this is a CEILING, not a scorer and not a pass candidate: no row here may be quoted as a pass. +# +# REGRESSION GUARD: every arm that existed before this change is diffed against the published +# status/real/pt_ceiling_w100_/ceiling.json and the job FAILS if any of them moved. +# Contrast of record C2 goal_vs_cook (both routes EXPERT, generator held fixed); C1/C3 are the controls. +# CPU only, no checkpoint is loaded. +set -uo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +export MUJOCO_GL=disable OMP_NUM_THREADS=8 +PY=venv_rsm/bin/python +W=100 +run () { # name route_pos route_neg + echo "=============== $1 entry window $W (resid arm) ===============" + $PY scripts/real/proposal_ceiling.py \ + --out "status/real/pt_ceilresid_w${W}_$1" --contrast "$1" \ + --route-pos "$2" --route-neg "$3" \ + --entry-window "$W" --state 2 --stride 5 --lengths 8 16 32 64 \ + --folds 5 --seeds 0 1 2 --boot 2000 || echo "[ceil] FAILED $1" +} +run goal_vs_cook "[2, 3, 4]" "[0, 2, 3]" +run goal_vs_fail "[2, 3, 4]" "[0, 2, 6]" +run cook_vs_fail "[0, 2, 3]" "[0, 2, 6]" +echo "=============== REGRESSION GUARD ===============" +$PY scripts/real/pt_resid_table.py +echo "[ceil] done" diff --git a/rsm_rise/scripts/real/pt_combine.py b/rsm_rise/scripts/real/pt_combine.py new file mode 100644 index 0000000000000000000000000000000000000000..e7ad1016439be0b44f7f03a6dd5a1bad1435ff2a --- /dev/null +++ b/rsm_rise/scripts/real/pt_combine.py @@ -0,0 +1,259 @@ +#!/usr/bin/env python +"""gen_q#280 / rsm_real#2 -- the PRE-REGISTERED combined `rsm` + `pose_cont` scorer. + +Pre-registration: gen_q#281 comment 5808912052 / jmarangola/rsm_real#3 comment 5808912260, posted BEFORE +this script was written or run. Nothing here may deviate from it; if a definition below disagrees with +that comment, the comment wins and the disagreement is a bug in this file. + +Why it exists. `scripts/real/pt_residual.py` (jobs 1891306/1891307) measured `rsm` and `pose_cont` to be +statistically INDEPENDENT at the anchor level: per-anchor Spearman over 17 scored blocks, median +0.0240, +range [-0.0617, +0.0554], 15 of 17 CIs straddling zero. Two independent weak scorers combine. This is +the only untried idea left on the proposal test after the sweep closed negative, and because the +motivation came from looking at labelled results it is a NEW scorer and had to be pre-registered rather +than slipped into an existing table as a read-out change. + +The scorer, exactly as pre-registered. + comb PRIMARY. Within-anchor average ranks of the two components, summed with EQUAL WEIGHTS. + Zero free parameters, nothing fitted to labels. + comb_fit SECONDARY, and labelled FITTED on every row. Logistic regression on the two normalised + within-anchor ranks, with EPISODE-NESTED leave-one-episode-out CV, so no anchor is ever + scored by a model that saw its own episode. Reported beside the primary, never instead. + +Ranks rather than raw values for the two reasons pt_residual.py gives: the AUC is itself a rank statistic +(so a prob-vs-logit or beta change must not move the combination), and the RSM score's scale varies by +orders of magnitude across arms while pose_cont is millimetres, so an unranked sum would be a units +comparison. + +Orientation is FIXED A PRIORI: both components keep exactly the sign convention they already carry in the +existing tables. If a combined row comes out below 0.5 it is reported below 0.5; flipping the sign after +seeing the result is forbidden by the pre-registration. + +Pre-registered prediction, printed per route so "the combination helped" is testable and not a post-hoc +reading: under independence the expected combined AUC is 0.5 + (d_rsm + d_pose)/sqrt(2), d = AUC - 0.5. +Expected and observed are printed side by side. + +Also declared in advance: `0->2->6` CANNOT produce a pass whatever it reads. Its oracle ceiling is 0.561 +and its components already sit at 0.4988-0.5549, so any combined value that looks good there is at or +above the ceiling and is pre-committed to the FLAGGED column. + +Every definition -- `auc`, `spearman`, `perm_auc`, `ep_bootstrap`, `model_free_scores`, `load_cell`, +`oracle_ceiling`, the family-wise `calibrate`, `ranks` and `rows_for` -- is IMPORTED from the scripts that +produced the plain rows, never restated, so the combined row comes from the same code path as the rows it +is compared against. No checkpoint is loaded and nothing is re-sampled: this reads the saved npz parts. +Reported per route, never pooled, every row with its measured permuted column (which for `comb` IS the +pre-registered `permuted:comb` line), its own anchor set's oracle ceiling, the calibrated family-wise q95, +ties@max, score CV and the kept anchor/episode counts. +""" +from __future__ import annotations +import argparse, json, sys +from pathlib import Path +import numpy as np + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from proposal_report import (load_cell, auc, spearman, perm_auc, ep_bootstrap, # noqa: E402 + model_free_scores, oracle_ceiling) +from pt_nullcal import calibrate # noqa: E402 +from pt_residual import ranks, score_of, rows_for # noqa: E402 + + +def unit_ranks(v): + """Within-anchor average ranks mapped to (0,1) by r/(n+1), so anchors with different candidate counts + contribute on the same scale. Monotone in the raw score, so it changes no AUC on its own.""" + r = ranks(v) + return r / (len(r) + 1.0) + + +def comb_score(r): + a, b = score_of(r, "rsm"), score_of(r, "pose_cont") + if a is None or b is None: + return None + return unit_ranks(a) + unit_ranks(b) + + +def feature_matrix(r, feature_names): + """Within-anchor unit ranks of the listed component scorers, one column each. Returns None if ANY + listed component is missing from this record, which is the same all-or-nothing gate the two-feature + `comb_score` applies.""" + cols = [] + for nm in feature_names: + v = score_of(r, nm) + if v is None: + return None + cols.append(unit_ranks(v)) + return np.column_stack(cols) + + +def loeo_logistic(gated, feature_names=("rsm", "pose_cont")): + """Episode-nested leave-one-episode-out logistic fit. Returns {anchor index -> score vector}. + + Every anchor is scored by a model fitted on the OTHER episodes only, so the fitted row cannot be + reported as if it had never seen labels but also cannot leak its own episode's labels into its own + score. Anchors whose held-out fit has only one label class in training are skipped and counted -- + they are reported as dropped rather than scored by a degenerate model. + + `feature_names` defaults to the pre-registered two-feature combination, so the behaviour of every + row already posted from this file is unchanged. It is a parameter only so that the SAME definition + can be applied to a single component (`scripts/real/pt_epcv.py`) instead of being restated there. + """ + from sklearn.linear_model import LogisticRegression + eps = sorted({r["episode"] for r in gated}) + out, skipped = {}, 0 + feats, labs, epi = [], [], [] + for r in gated: + x = feature_matrix(r, feature_names) + if x is None: + continue + feats.append(x); labs.append(np.asarray(r["margin"], float) > 0); epi.append(r["episode"]) + if not feats: + return out, len(gated) + idx_of = {id(r): i for i, r in enumerate(gated)} + for ho in eps: + tr = [i for i, e in enumerate(epi) if e != ho] + te = [i for i, e in enumerate(epi) if e == ho] + if not tr or not te: + continue + X = np.concatenate([feats[i] for i in tr]); y = np.concatenate([labs[i] for i in tr]) + if len(np.unique(y)) < 2: + skipped += len(te); continue + m = LogisticRegression(max_iter=1000).fit(X, y) + for i in te: + out[i] = m.decision_function(feats[i]) + # map positional -> record identity used by rows_for + keyed = {} + pos = 0 + for r in gated: + if feature_matrix(r, feature_names) is None: + continue + if pos in out: + keyed[idx_of[id(r)]] = out[pos] + pos += 1 + return keyed, skipped + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--cells", nargs="+", required=True) + ap.add_argument("--root", default="status/real") + ap.add_argument("--entry-window", type=int, default=100) + ap.add_argument("--oracle-chunk", type=int, default=8) + ap.add_argument("--state", type=int, default=2) + ap.add_argument("--gate-min-anchors", type=int, default=30) + ap.add_argument("--reps", type=int, default=4000) + ap.add_argument("--boot", type=int, default=400) + ap.add_argument("--perm-reps", type=int, default=200) + ap.add_argument("--n-scorers", type=int, default=7) + ap.add_argument("--json", default=None) + ap.add_argument("--md", default=None) + a = ap.parse_args() + + rng = np.random.default_rng(7) + blocks = [] + for cell in a.cells: + d = Path(cell) + if not d.is_absolute() and not d.exists(): + d = Path(a.root) / cell + recs, cfg = load_cell(d, entry_window=a.entry_window) + if not recs: + print(f"[comb] {d.name}: no anchors", file=sys.stderr); continue + for route in sorted({r["path"] for r in recs}): + gated = [r for r in recs if r["gate"] and r["path"] == route] + neps = len({r["episode"] for r in gated}) + if len(gated) < a.gate_min_anchors or neps < 4: + blocks.append(dict(cell=d.name, route=route, undefined=True, + anchors=len(gated), episodes=neps, + reason=f"below #280 floor (30 anchors / 4 episodes): " + f"{len(gated)} anchors / {neps} episodes")) + print(f"[comb] UNDEFINED {d.name} {route}: {len(gated)} anchors / {neps} eps", + file=sys.stderr) + continue + if score_of(gated[0], "rsm") is None or score_of(gated[0], "pose_cont") is None: + print(f"[comb] {d.name} {route}: missing a component column", file=sys.stderr); continue + fitted, skipped = loeo_logistic(gated) + for i, r in enumerate(gated): + r["_idx"] = i + fit_by_idx = {} + for k, v in fitted.items(): + fit_by_idx[k] = v + pairs = [ + ("rsm", lambda r: score_of(r, "rsm")), + ("pose_cont", lambda r: score_of(r, "pose_cont")), + ("comb (PRIMARY, unfitted)", comb_score), + ("comb_fit (FITTED, LOEO-CV)", lambda r: fit_by_idx.get(r.get("_idx"))), + ("permuted:rsm", lambda r: score_of(r, "permuted:rsm")), + ("idql", lambda r: score_of(r, "idql")), + ("random", lambda r: score_of(r, "random")), + ] + rows = rows_for(gated, pairs) + by = {r["scorer"]: r for r in rows} + d_rsm = by["rsm"]["auc"] - 0.5 if "rsm" in by else float("nan") + d_pose = by["pose_cont"]["auc"] - 0.5 if "pose_cont" in by else float("nan") + expected = 0.5 + (d_rsm + d_pose) / np.sqrt(2.0) + cal = calibrate(gated, a.reps, a.boot, a.perm_reps, rng, n_scorers=a.n_scorers) + orc = oracle_ceiling([(r["episode"], r["frame"]) for r in gated], a.oracle_chunk, a.state) + blocks.append(dict(cell=d.name, route=route, undefined=False, + anchors=len(gated), episodes=neps, fit_skipped=int(skipped), + beta_mode=cfg.get("beta_mode"), beta=cfg.get("beta"), + ckpt=cfg.get("ckpt") or cfg.get("successor"), + cands_from=cfg.get("cands_from"), + expected_comb_auc=float(expected), + q95_fwer=cal.get("q95_fwer"), null_mean=cal.get("null_mean"), + oracle=orc, rows=rows)) + obs = by.get("comb (PRIMARY, unfitted)", {}).get("auc", float("nan")) + print(f"[comb] {d.name} {route}: {len(gated)} anchors / {neps} eps " + f"q95_fwer={cal.get('q95_fwer'):.4f} ceiling={orc.get('auc'):.3f} " + f"expected={expected:.4f} observed={obs:.4f}", file=sys.stderr) + + if a.json: + Path(a.json).parent.mkdir(parents=True, exist_ok=True) + json.dump(blocks, open(a.json, "w"), indent=1, default=float) + + lines = ["# PRE-REGISTERED combined `rsm` + `pose_cont` scorer -- gen_q#280 / rsm_real#2", + "", + "Pre-registration: gen_q#281 comment **5808912052** / rsm_real#3 comment **5808912260**, " + "posted BEFORE this was written or run. `comb` = equal-weight sum of the two within-anchor " + "unit ranks, **zero free parameters**. `comb_fit` = logistic on the same two features with " + "**episode-nested leave-one-episode-out CV**, labelled FITTED. Orientation fixed a priori. " + "The `permuted` column of each row IS that row's measured zero line (for `comb` it is the " + "pre-registered `permuted:comb`); **never read it as a nominal 0.5**. " + "CLEARS = above the permutation-calibrated FAMILY-WISE q95 of its own route/anchor set. " + "FLAG = at or above that anchor set's oracle ceiling, i.e. exploiting the label, NOT passing.", + "", + "Pre-declared before any number was seen: **`0->2->6` cannot produce a pass** -- ceiling " + "0.561 against components already at 0.4988-0.5549, so anything good there is at ceiling.", + ""] + for b in blocks: + if b["undefined"]: + lines += [f"## {b['cell']} -- `{b['route']}` -- **UNDEFINED**: {b['reason']}", ""] + continue + o = b["oracle"] + obs = next((r["auc"] for r in b["rows"] if r["scorer"].startswith("comb (")), float("nan")) + lines += [f"## {b['cell']} -- route `{b['route']}`", + "", + f"anchors **{b['anchors']}** / episodes **{b['episodes']}** · oracle ceiling " + f"**{o.get('auc'):.3f}** (acc {o.get('acc'):.3f}, n {o.get('n')}) · family-wise q95 " + f"**{b['q95_fwer']:.4f}** · measured null mean {b['null_mean']:.4f} · " + f"anchors dropped by the LOEO fit (single-class training fold) **{b['fit_skipped']}**", + "", + f"**pre-registered expectation under independence** 0.5 + (d_rsm + d_pose)/sqrt(2) = " + f"**{b['expected_comb_auc']:.4f}** · **observed `comb` {obs:.4f}** · " + f"difference **{obs - b['expected_comb_auc']:+.4f}**", + "", + "| scorer | AUC (SE) | permuted | clears q95 | at/above ceiling | rho vs margin | lift | ties@max | CV |", + "|---|---|---|---|---|---|---|---|---|"] + for r in b["rows"]: + clears = "**CLEARS**" if r["auc"] > b["q95_fwer"] else "--" + above = "**FLAG**" if np.isfinite(o.get("auc", np.nan)) and r["auc"] >= o["auc"] else "" + lines.append(f"| `{r['scorer']}` | {r['auc']:.4f} ({r['auc_se']:.4f}) | {r['auc_permuted']:.4f} | " + f"{clears} | {above} | {r['rho']:+.4f} | {r['lift']:+.4f} | " + f"{r['ties_at_max']:.2f} | " + f"{'n/a (mean-zero)' if not np.isfinite(r['cv']) else format(r['cv'], '.3g')} |") + lines.append("") + md = "\n".join(lines) + if a.md: + Path(a.md).parent.mkdir(parents=True, exist_ok=True) + Path(a.md).write_text(md) + print(md) + + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/real/pt_cond_ladder.sh b/rsm_rise/scripts/real/pt_cond_ladder.sh new file mode 100644 index 0000000000000000000000000000000000000000..16f3903063a3e660a2aedf43066b316a5a23600d --- /dev/null +++ b/rsm_rise/scripts/real/pt_cond_ladder.sh @@ -0,0 +1,29 @@ +#!/bin/bash +# gen_q#280 / jmarangola/rsm_real#2 -- PROPOSAL_TEST run 36, MECHANISM ladder. +# +# Job 1898185 measured the conditional null's type-I rate at 18/20 (raw) and 14/20 (resid) against a +# nominal 0.05, so that null is ANTICONSERVATIVE and (A) STANDS. This run measures the SIZE and SHAPE of +# the artifact rather than only its existence: data permuted at coherence level `k_fine`, scored against +# the SAME pre-registered K=20 null. Rising `k_fine` = a finer permutation = more chunk<->anchor +# coherence retained, and the statistic is expected to rise with it under NO label information at all. +# +# VALIDITY LIMIT, printed on every rung: `data_same_ep`, the fraction of anchors whose donor chunk came +# from their OWN episode. A same-episode donor keeps the chunk's own label link intact, so a rung whose +# `data_same_ep` is large is no longer signal-free and its point is not interpretable as pure artifact. +# The ladder is read only over the rungs where that fraction stays small. DECLARES NOTHING: the verdict +# is already fixed by job 1898185 against the pre-registration in comment 5815059930 / 5815060174. +set -uo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +export MUJOCO_GL=disable OMP_NUM_THREADS=1 OPENBLAS_NUM_THREADS=1 MKL_NUM_THREADS=1 +PY=venv_rsm/bin/python +for KF in 40 160 320 640; do + echo "=============== LADDER rung k_fine=$KF (null fixed at K=20) ===============" + $PY scripts/real/pt_cond_null.py \ + --out "status/real/pt_condladder_kf${KF}" --contrast goal_vs_cook \ + --route-pos "[2, 3, 4]" --route-neg "[0, 2, 3]" \ + --entry-window 100 --state 2 --stride 5 --lengths 8 \ + --seeds 0 --k-primary 20 --k-fine "$KF" \ + --typei-m 8 --typei-draws 60 --typei-length 8 \ + --skip-primary --skip-diag --jobs 8 || echo "[cond] FAILED rung $KF" +done +echo "[cond] ladder done" diff --git a/rsm_rise/scripts/real/pt_cond_null.py b/rsm_rise/scripts/real/pt_cond_null.py new file mode 100644 index 0000000000000000000000000000000000000000..2922c6dac5fe5a747f2ced75fa24fbb8adf92528 --- /dev/null +++ b/rsm_rise/scripts/real/pt_cond_null.py @@ -0,0 +1,283 @@ +#!/usr/bin/env python +"""gen_q#280 / jmarangola/rsm_real#2 -- PROPOSAL_TEST run 36. + +THE DEFECT THIS MEASURES, stated as a number before any result exists +-------------------------------------------------------------------- +Runs 33-35 calibrated the nested marginal `AUC(both) - AUC(anchor[geom])` against an EPISODE-LEVEL +LABEL PERMUTATION null and declared (A): 0 of 24 cells cleared q95. That null permutes the LABEL, so +under it the anchor arm ALSO collapses to chance. It is therefore the distribution of the statistic +under + + H0' : "neither the anchor nor the chunk carries route information" + +whereas the question asked is + + H0 : "the chunk carries no route information BEYOND the anchor". + +Those are different hypotheses and they have different null distributions. The mismatch is measured, +not asserted: the label-permutation null has sd 0.0238-0.0551 while the observed statistic's paired +EPISODE bootstrap SE is 0.0087-0.0156 -- a factor of 2-3. Under H0' both AUCs sit near 0.5 where the +fit is unstable and their difference is wide; in the real data both arms are strongly determined +(anchorgeom 0.937, both 0.977) and the difference is narrow. Testing H0 with H0' quantiles is a +mis-specified test, and it is mis-specified in the CONSERVATIVE direction. + +THE FIX: a conditional randomization null. +Keep y, ep and the anchor block EXACTLY as they are. Permute the CHUNK rows within LABEL-FREE strata +of the anchor features (KMeans on standardised AN), across episodes. That destroys chunk<->label +association while preserving chunk<->anchor coupling to the resolution of the stratum. Both CFw and +the geometry block GF are rebuilt from the SAME permuted chunk, so the raw and residualised pairs stay +coherent. The anchor-only arm does not depend on the chunk, so it is fitted once and is constant +across draws -- which is exactly why this null is narrower, and the reason it is narrower is the point. + +THE RISK, and the validation that is not optional. +If the strata are too coarse, a permuted chunk is mismatched to its anchor, the `both` arm loses AUC +through feature INCOHERENCE rather than through lost label information, the null deflates, and the +test becomes ANTICONSERVATIVE -- i.e. a weaker guard dressed as a better one. This script therefore +measures its own type-I rate: build M signal-free-but-anchor-COHERENT datasets by permuting the chunk +within FINE strata (K_FINE), then test each one against the ordinary K_PRIMARY null built from that +same dataset. Those datasets satisfy H0 by construction, so a correctly specified test clears q95 on +about 5% of them. A rate well above 5% means the conditional null is anticonservative and (A) STANDS. + +This is a CEILING, not a scorer. Every arm is fitted on the label; no row here is a pass candidate +for #280. The label-permutation null is NOT replaced -- it is reported beside this one on every row. + +q95 uses the published convention sorted[int(0.95*n)] (NOT np.quantile's interpolation); run 35 item 3 +records the cell that convention flips. +""" +import argparse, importlib.util, json, os, time +from pathlib import Path +from types import SimpleNamespace + +import numpy as np + +ROOT = "/proj/dmfexp/zwhong/rsm_rise" + + +def _load_ceiling_module(): + """Import proposal_ceiling.py for build/chunk_feat/geom_feat/fit_arm/auc -- the SAME definitions the + published table used, not retyped copies of them.""" + spec = importlib.util.spec_from_file_location("pc", f"{ROOT}/scripts/real/proposal_ceiling.py") + m = importlib.util.module_from_spec(spec) + spec.loader.exec_module(m) + return m + + +PC = _load_ceiling_module() + + +def q95(x): + """The published convention. np.quantile interpolates and gives a different bar.""" + s = np.sort(np.asarray(x, float)) + return float(s[int(0.95 * len(s))]) + + +def qq(x, p): + s = np.sort(np.asarray(x, float)) + return float(s[min(len(s) - 1, int(p * len(s)))]) + + +def make_strata(AN, K, seed=0): + """LABEL-FREE strata: KMeans on the standardised anchor block. Uses no y anywhere.""" + from sklearn.cluster import KMeans + from sklearn.preprocessing import StandardScaler + Z = StandardScaler().fit_transform(AN.astype(np.float64)) + km = KMeans(n_clusters=K, n_init=10, random_state=seed).fit(Z) + return km.labels_.astype(int) + + +def cond_perm(strata, rng): + """Plain shuffle of the chunk index WITHIN each stratum. Unrestricted, so the permuted data are + exchangeable with the observed data within a stratum -- no cross-episode restriction, which would + break that exchangeability for a negligible gain (with 98 episodes the same-episode donor rate is + a couple of percent, and it is reported as `same_ep_frac`).""" + pi = np.arange(len(strata)) + for s in np.unique(strata): + idx = np.where(strata == s)[0] + pi[idx] = rng.permutation(idx) + return pi + + +def stat_for_perm(pi, AN, CH, y, ep, L, folds, seed, s_anchor_auc): + """The two nested marginals for one chunk permutation. Returns (raw, resid).""" + CHp = CH[pi] + CFw = PC.chunk_feat(CHp, L, "waypoints") + GF = PC.geom_feat(CHp, L) + s_both = PC.fit_arm(np.concatenate([AN, CFw], 1), y, ep, folds, seed, "logreg") + s_geom = PC.fit_arm(np.concatenate([AN, GF], 1), y, ep, folds, seed, "logreg") + ok = ~(np.isnan(s_both) | np.isnan(s_geom)) + a_both = PC.auc(y[ok], s_both[ok]) + a_geom = PC.auc(y[ok], s_geom[ok]) + return float(a_both - s_anchor_auc), float(a_both - a_geom), float(a_both), float(a_geom) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--out", required=True) + ap.add_argument("--hdf5", default=f"{ROOT}/data/raw/cooking_v5_expert_suboptimal.hdf5") + ap.add_argument("--split", default=f"{ROOT}/data/derived/cooking_v5_split.json") + ap.add_argument("--state", type=int, default=2) + ap.add_argument("--route-pos", default="[2, 3, 4]") + ap.add_argument("--route-neg", default="[0, 2, 3]") + ap.add_argument("--contrast", default="goal_vs_cook") + ap.add_argument("--stride", type=int, default=5) + ap.add_argument("--entry-window", type=int, default=100) + ap.add_argument("--lengths", type=int, nargs="+", default=[8, 32]) + ap.add_argument("--folds", type=int, default=5) + ap.add_argument("--seeds", type=int, nargs="+", default=[0, 1, 2]) + ap.add_argument("--k-primary", type=int, default=20, help="PRE-REGISTERED primary stratum count") + ap.add_argument("--k-diag", type=int, nargs="+", default=[10, 40], help="sensitivity only, never declares") + ap.add_argument("--k-fine", type=int, default=80, help="strata for the signal-free type-I datasets") + ap.add_argument("--draws", type=int, default=200) + ap.add_argument("--typei-m", type=int, default=20, help="signal-free datasets for the type-I rate") + ap.add_argument("--typei-draws", type=int, default=100) + ap.add_argument("--typei-length", type=int, default=8) + ap.add_argument("--jobs", type=int, default=8) + ap.add_argument("--skip-primary", action="store_true", + help="ladder rungs only need the type-I arm; the primary grid is already measured") + ap.add_argument("--skip-diag", action="store_true") + ap.add_argument("--published", default=f"{ROOT}/status/real/pt_ceilresid_w100_goal_vs_cook/ceiling.json") + a = ap.parse_args() + t0 = time.time() + out = Path(a.out); out.mkdir(parents=True, exist_ok=True) + from joblib import Parallel, delayed + + rows, n_drop, n_ep = PC.build(SimpleNamespace( + hdf5=a.hdf5, split=a.split, state=a.state, route_pos=a.route_pos, route_neg=a.route_neg, + stride=a.stride, entry_window=a.entry_window, lengths=a.lengths)) + if not rows: + raise SystemExit("no anchors") + ep = np.array([r["ep"] for r in rows]); y = np.array([r["y"] for r in rows]) + AN = np.stack([r["anchor"] for r in rows]); CH = np.stack([r["chunk"] for r in rows]) + print(f"[cond] contrast={a.contrast} anchors={len(rows)} episodes={len(np.unique(ep))}/{n_ep} " + f"goal={int((y==1).sum())} fail={int((y==0).sum())} window={a.entry_window}", flush=True) + + STR = {K: make_strata(AN, K) for K in sorted({a.k_primary, a.k_fine, *a.k_diag})} + for K, s in STR.items(): + cnt = np.bincount(s) + print(f"[cond] K={K:3d} strata: min={cnt.min()} med={int(np.median(cnt))} max={cnt.max()} " + f"n_strata={len(cnt)}", flush=True) + + # ---- anchor-only arm: independent of the chunk, so constant across every draw. + anchor_auc = {} + for seed in a.seeds: + s_a = PC.fit_arm(AN, y, ep, a.folds, seed, "logreg") + ok = ~np.isnan(s_a) + anchor_auc[seed] = float(PC.auc(y[ok], s_a[ok])) + print(f"[cond] seed{seed} anchor:logreg AUC={anchor_auc[seed]:.4f}", flush=True) + + # ---- OBSERVED statistics (identity permutation) + REGRESSION GUARD against the published table. + pub = json.load(open(a.published)) + pubmap = {(p["pair"], p["L"], p["seed"]): p["diff"] for p in pub["paired"]} + obs, guard = {}, [] + for seed in a.seeds: + for L in a.lengths: + raw, rsd, ab, ag = stat_for_perm(np.arange(len(y)), AN, CH, y, ep, L, a.folds, seed, + anchor_auc[seed]) + obs[(seed, L)] = dict(raw=raw, resid=rsd, auc_both=ab, auc_anchorgeom=ag, + auc_anchor=anchor_auc[seed]) + for key, val in (("both:logreg - anchor:logreg", raw), + ("both:logreg - anchorgeom:logreg", rsd)): + if (key, L, seed) in pubmap: + guard.append(dict(pair=key, L=L, seed=seed, mine=val, published=pubmap[(key, L, seed)], + delta=abs(val - pubmap[(key, L, seed)]))) + print(f"[cond] OBSERVED L={L:3d} seed{seed} raw={raw:+.6f} resid={rsd:+.6f} " + f"(both={ab:.4f} anchorgeom={ag:.4f})", flush=True) + worst = max([g["delta"] for g in guard], default=float("nan")) + print(f"[cond] [GUARD] {len(guard)} published rows reproduced, worst |delta| = {worst:.3e}", flush=True) + if not (worst < 1e-9): + print("[cond] [GUARD] FAIL -- my observed statistic does not reproduce the published table; " + "every number below is void.", flush=True) + + def null_dist(K, L, seed, ndraws, CHbase, base_seed): + """ndraws conditional draws of (raw, resid) at stratum count K.""" + strata = STR[K] # strata are a function of AN alone, so they are the same for any CHbase + def one(rep): + rng = np.random.default_rng([base_seed, K, L, seed, rep]) + pi = cond_perm(strata, rng) + r, d, _, _ = stat_for_perm(pi, AN, CHbase, y, ep, L, a.folds, seed, anchor_auc[seed]) + return r, d, float((ep[pi] == ep).mean()) + res = Parallel(n_jobs=a.jobs, prefer="processes")(delayed(one)(r) for r in range(ndraws)) + return (np.array([r[0] for r in res]), np.array([r[1] for r in res]), + float(np.mean([r[2] for r in res]))) + + # ---- PRIMARY: the pre-registered K, every seed, every L. + prim = [] + for seed in (a.seeds if not a.skip_primary else []): + for L in a.lengths: + tA = time.time() + nr, nd, sef = null_dist(a.k_primary, L, seed, a.draws, CH, 4242) + o = obs[(seed, L)] + row = dict(K=a.k_primary, L=L, seed=seed, draws=a.draws, same_ep_frac=sef) + for tag, nul, ov in (("raw", nr, o["raw"]), ("resid", nd, o["resid"])): + p = (1.0 + int((nul >= ov).sum())) / (1.0 + len(nul)) + row.update({f"{tag}_obs": ov, f"{tag}_null_mean": float(nul.mean()), + f"{tag}_null_sd": float(nul.std(ddof=1)), f"{tag}_q95": q95(nul), + f"{tag}_q99": qq(nul, 0.99), f"{tag}_p": float(p), + f"{tag}_clears": bool(ov > q95(nul))}) + print(f"[cond] PRIMARY K={a.k_primary} L={L:3d} seed{seed} {tag:5s} obs={ov:+.4f} " + f"null {nul.mean():+.4f}+-{nul.std(ddof=1):.4f} q95={q95(nul):+.4f} " + f"p={p:.3f} clears={ov > q95(nul)}", flush=True) + row["null_raw"] = nr.tolist(); row["null_resid"] = nd.tolist() + prim.append(row) + print(f"[cond] (same-episode donor rate {sef:.3f}, {time.time()-tA:.0f}s)", flush=True) + + # ---- TYPE-I VALIDATION. Signal-free-but-anchor-COHERENT data, tested by the primary null. + Lt = a.typei_length + fine = STR[a.k_fine] + typei = [] + for m in range(a.typei_m): + rngm = np.random.default_rng([31337, m]) + sig = cond_perm(fine, rngm) # H0 holds by construction, anchor coupling preserved + CHm = CH[sig] + data_same_ep = float((ep[sig] == ep).mean()) # validity limit of this rung: a donor from the SAME + # episode keeps the chunk's own label link intact + seed = int(a.seeds[0]) + raw_m, rsd_m, _, _ = stat_for_perm(np.arange(len(y)), AN, CHm, y, ep, Lt, a.folds, seed, + anchor_auc[seed]) + nr, nd, _ = null_dist(a.k_primary, Lt, seed, a.typei_draws, CHm, 8100 + m) + rec = dict(m=m, raw_obs=raw_m, resid_obs=rsd_m, raw_q95=q95(nr), resid_q95=q95(nd), + raw_clears=bool(raw_m > q95(nr)), resid_clears=bool(rsd_m > q95(nd)), + k_fine=int(a.k_fine), data_same_ep_frac=data_same_ep) + typei.append(rec) + print(f"[cond] TYPEI kfine={a.k_fine} m={m:2d} raw={raw_m:+.4f} vs q95={q95(nr):+.4f} " + f"({rec['raw_clears']}) resid={rsd_m:+.4f} vs q95={q95(nd):+.4f} ({rec['resid_clears']}) " + f"data_same_ep={data_same_ep:.3f}", flush=True) + def cp(k, n): + """Clopper-Pearson 95% interval, so the type-I rate is reported with its own uncertainty.""" + from scipy.stats import beta as B + lo = 0.0 if k == 0 else float(B.ppf(0.025, k, n - k + 1)) + hi = 1.0 if k == n else float(B.ppf(0.975, k + 1, n - k)) + return lo, hi + rates = {} + for tag in ("raw", "resid"): + k = int(sum(r[f"{tag}_clears"] for r in typei)); n = len(typei) + lo, hi = cp(k, n) if n else (float("nan"),) * 2 + rates[tag] = dict(k=k, n=n, rate=(k / n if n else float("nan")), ci=[lo, hi]) + print(f"[cond] TYPE-I RATE {tag}: {k}/{n} = {k/max(n,1):.3f} CP95 [{lo:.3f},{hi:.3f}] " + f"(a valid test sits at 0.05)", flush=True) + + # ---- SENSITIVITY: other stratum counts. Diagnostic only; the pre-registration declares on K only. + diag = [] + for K in (a.k_diag if not a.skip_diag else []): + seed, L = int(a.seeds[0]), a.lengths[0] + nr, nd, sef = null_dist(K, L, seed, a.draws, CH, 4242) + o = obs[(seed, L)] + d = dict(K=K, L=L, seed=seed, same_ep_frac=sef, + raw_obs=o["raw"], raw_q95=q95(nr), raw_clears=bool(o["raw"] > q95(nr)), + resid_obs=o["resid"], resid_q95=q95(nd), resid_clears=bool(o["resid"] > q95(nd)), + raw_null_sd=float(nr.std(ddof=1)), resid_null_sd=float(nd.std(ddof=1))) + diag.append(d) + print(f"[cond] DIAG K={K:3d} L={L} seed{seed} raw {o['raw']:+.4f} vs q95 {q95(nr):+.4f} " + f"({d['raw_clears']}) resid {o['resid']:+.4f} vs q95 {q95(nd):+.4f} ({d['resid_clears']})", + flush=True) + + json.dump(dict(contrast=a.contrast, entry_window=a.entry_window, n_anchors=len(rows), + n_episodes=int(len(np.unique(ep))), anchor_auc=anchor_auc, observed={f"{k[0]}_{k[1]}": v + for k, v in obs.items()}, guard=guard, guard_worst=worst, primary=prim, + typei=typei, typei_rate=rates, diag=diag, config=vars(a)), + open(out / "cond_null.json", "w"), indent=1) + print(f"[cond] done {time.time()-t0:.0f}s -> {out}/cond_null.json", flush=True) + + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/real/pt_cond_null.sh b/rsm_rise/scripts/real/pt_cond_null.sh new file mode 100644 index 0000000000000000000000000000000000000000..f3fc64e0227aa7266662017747a59e6973b1331f --- /dev/null +++ b/rsm_rise/scripts/real/pt_cond_null.sh @@ -0,0 +1,49 @@ +#!/bin/bash +# gen_q#280 / jmarangola/rsm_real#2 -- PROPOSAL_TEST run 36. +# +# ONE CHANGE from runs 33-35: the NULL's specification, and nothing else. Same anchors (C2 +# goal_vs_cook, S2, entry window 100, stride 5), same folds, same features, same arms, same observed +# statistic -- which is regression-guarded against the published table inside the script. +# +# WHY. Runs 33-35 calibrated `AUC(both) - AUC(anchor[geom])` against an episode-level LABEL +# permutation, under which the ANCHOR arm also collapses to chance. That is the null for "nothing is +# informative", not for "the chunk adds nothing beyond the anchor". The mismatch is measured: null sd +# 0.0238-0.0551 against a paired episode-bootstrap SE of 0.0087-0.0156. +# +# WHAT REPLACES IT (as an ADDITIONAL null, never as a substitute -- the label null is reported on every +# row). Conditional randomization: y, ep and the anchor block are untouched; the CHUNK rows are +# permuted within LABEL-FREE KMeans strata of the anchor features. +# +# PRE-REGISTERED READING, fixed before the number exists. (B) is declared ONLY if BOTH hold: +# (i) the measured TYPE-I rate of this test on signal-free-but-anchor-coherent data is <= 0.10 +# (point estimate, M=20; its Clopper-Pearson interval is printed beside it), AND +# (ii) the observed RESID marginal exceeds the conditional null's q95 at 3/3 seeds and BOTH lengths. +# If (i) fails the conditional null is anticonservative and (A) STANDS on the label null -- the number +# in (ii) is then not reportable as a verdict at all, whichever way it lands. +# If (i) holds and (ii) fails, (A) stands and is now confirmed under a correctly specified null. +# K=20 is the pre-registered stratum count; K=10/40 are printed as sensitivity and DECLARE NOTHING. +# +# This is a CEILING, not a scorer. No row here is a pass candidate for #280. +set -uo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +export MUJOCO_GL=disable OMP_NUM_THREADS=1 OPENBLAS_NUM_THREADS=1 MKL_NUM_THREADS=1 +PY=venv_rsm/bin/python + +echo "=============== SMOKE (tiny, proves the path and prints per-cell timing) ===============" +$PY scripts/real/pt_cond_null.py \ + --out status/real/pt_condnull_SMOKE --contrast goal_vs_cook \ + --route-pos "[2, 3, 4]" --route-neg "[0, 2, 3]" \ + --entry-window 100 --state 2 --stride 5 --lengths 8 \ + --seeds 0 --draws 4 --typei-m 2 --typei-draws 4 --k-diag 10 --jobs 8 +rc=$? +if [ $rc -ne 0 ]; then echo "[cond] SMOKE FAILED rc=$rc -- not running the full grid"; exit $rc; fi + +echo "=============== FULL (C2 goal_vs_cook, S2, window 100, logreg) ===============" +$PY scripts/real/pt_cond_null.py \ + --out status/real/pt_condnull_w100_goal_vs_cook --contrast goal_vs_cook \ + --route-pos "[2, 3, 4]" --route-neg "[0, 2, 3]" \ + --entry-window 100 --state 2 --stride 5 --lengths 8 32 \ + --seeds 0 1 2 --draws 200 --k-primary 20 --k-diag 10 40 --k-fine 80 \ + --typei-m 20 --typei-draws 100 --typei-length 8 --jobs 8 \ + || echo "[cond] FAILED full" +echo "[cond] done" diff --git a/rsm_rise/scripts/real/pt_conditional.sh b/rsm_rise/scripts/real/pt_conditional.sh new file mode 100644 index 0000000000000000000000000000000000000000..c58436b6859a6914b13dfecc2f1d42e8a933ad2f --- /dev/null +++ b/rsm_rise/scripts/real/pt_conditional.sh @@ -0,0 +1,21 @@ +#!/bin/bash +# gen_q#280 / rsm_real#2 TASK A follow-up -- the CONDITIONAL (anchor-matched) ceiling at S2. +# ONE CHANGE from job 1886496: the quantity. 1886496 measured the POOLED nested marginal +# AUC(anchor+chunk) - AUC(anchor) and a 200-permutation refit null refused it (perm p 0.055 logreg / +# 0.254 mlp). The proposal test, however, ranks candidates AT ONE ANCHOR, so the quantity it needs is +# the chunk's discriminability CONDITIONAL ON the anchor. Here that is measured directly by caliper +# matching: within-pair win rate over goal-vs-cook anchor pairs matched in standardised anchor space. +# Same anchor gate (S2, entry window 100), same contrast (C2, both routes EXPERT), same episode-disjoint +# folds, same L=8. Chance is 0.5 BY CONSTRUCTION and the null is still measured, not assumed. +# The `anchor:logreg` row is the GUARD: if matching worked it must read ~0.5 at the tight calipers. +set -uo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +export MUJOCO_GL=disable +export OMP_NUM_THREADS=2 OPENBLAS_NUM_THREADS=2 MKL_NUM_THREADS=2 +venv_rsm/bin/python scripts/real/pt_conditional_ceiling.py \ + --out status/real/pt_cond_w100_goal_vs_cook \ + --contrast goal_vs_cook --route-pos "[2, 3, 4]" --route-neg "[0, 2, 3]" \ + --entry-window 100 --lengths 8 --seeds 0 1 2 --folds 5 --boot 2000 \ + --calipers 0.05 0.1 0.25 0.5 1.0 2.0 \ + --perm-null 200 --perm-null-arms chunk:logreg +echo "[cond] shell done" diff --git a/rsm_rise/scripts/real/pt_conditional2.sh b/rsm_rise/scripts/real/pt_conditional2.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a48e4c34d9c5ba59e63b9a9fbeb099ff81e5e4a --- /dev/null +++ b/rsm_rise/scripts/real/pt_conditional2.sh @@ -0,0 +1,23 @@ +#!/bin/bash +# gen_q#280 / rsm_real#2 -- conditional ceiling, PASS 2. TWO CHANGES from 1887248, both forced by its own +# output and both stated: +# (1) the caliper grid was too coarse at the informative end: 0.05-0.5 gave ZERO pairs, 1.0 gave 59 and +# 2.0 gave 323, so the only guard-clean point was a single caliper with 59 pairs. Refine to +# 0.6 ... 1.5 to map where the `anchor:logreg` GUARD departs from 0.5. +# (2) 1887248 auto-placed its permutation null at the tightest caliper with >=200 pairs, which was 2.0 -- +# and at 2.0 the GUARD reads 0.715, i.e. the pairs are NOT anchor-matched there. A null at a caliper +# where the guard leaks is the wrong null for a row where it does not. Pin the null to 1.0, the +# guard-clean caliper, and run it on the DIRECTION arm as well as the full chunk, because the two +# read very differently (0.763 vs 0.983) and the direction arm is the one the proposal test uses. +set -uo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +export MUJOCO_GL=disable +export OMP_NUM_THREADS=2 OPENBLAS_NUM_THREADS=2 MKL_NUM_THREADS=2 +venv_rsm/bin/python scripts/real/pt_conditional_ceiling.py \ + --out status/real/pt_cond2_w100_goal_vs_cook \ + --contrast goal_vs_cook --route-pos "[2, 3, 4]" --route-neg "[0, 2, 3]" \ + --entry-window 100 --lengths 8 --seeds 0 1 2 --folds 5 --boot 2000 \ + --calipers 0.6 0.7 0.8 0.9 1.0 1.1 1.25 1.5 \ + --perm-null 200 --perm-null-caliper 1.0 \ + --perm-null-arms chunk:logreg chunkdir:logreg +echo "[cond2] shell done" diff --git a/rsm_rise/scripts/real/pt_conditional_ceiling.py b/rsm_rise/scripts/real/pt_conditional_ceiling.py new file mode 100644 index 0000000000000000000000000000000000000000..a901b713824ba05e2a5d3e9ad3c46656394babd2 --- /dev/null +++ b/rsm_rise/scripts/real/pt_conditional_ceiling.py @@ -0,0 +1,246 @@ +#!/usr/bin/env python +"""gen_q#280 / rsm_real#2 TASK A, follow-up -- the CONDITIONAL ceiling, at a FIXED anchor. + +WHY THIS AND NOT THE MARGINAL. TASK A measured AUC(anchor+chunk) - AUC(anchor alone) = +0.034 (mlp) / ++0.067 (logreg) and a 200-permutation refit null then refused both (exact perm p = 0.254 / 0.055, job +1886496). But that marginal is a POOLED proxy for the quantity the proposal test actually needs. The +proposal test ranks 128 candidates AT ONE ANCHOR: the anchor feature is constant inside the comparison, +so the reachable signal is the discriminability of the chunk CONDITIONAL ON the anchor. A nested AUC +difference computed over a pool of different anchors is not that quantity; it can be diluted by, or +inflated by, how the anchor channel and the chunk channel co-vary across the pool. + +SO MEASURE IT DIRECTLY, by matching. Logged data cannot give two routes at literally the same anchor -- +every anchor belongs to one episode and therefore one route. The standard substitute is a matched pair: +take a goal-route anchor and the nearest fail/cook-route anchor FROM A DIFFERENT EPISODE in standardised +anchor-feature space, within a caliper, 1-1 without replacement. Inside a pair the anchor state is held +(approximately) fixed by construction, so + + conditional AUC = fraction of matched pairs where score(goal chunk) > score(other chunk) + +is exactly the within-anchor ranking the proposal test asks for, and its chance level is 0.5 BY +CONSTRUCTION because every pair is one of each label. + +THE GUARD THAT MAKES IT READABLE, printed on every row. The `anchor:logreg` arm is scored on the SAME +matched pairs. If matching worked, the anchor state can no longer separate the pair and that row must +read ~0.5. If it reads well above 0.5 the caliper is too loose, residual anchor confounding is left in +the pairs, and any chunk row at that caliper is reading leftover anchor and not the chunk. That is why +the caliper is SWEPT rather than chosen: the tight end is the honest conditional number, the loose end +should reproduce the pooled result, and the anchor guard says which is which. + +THE ZERO LINE IS MEASURED, NOT ASSUMED. Under a permuted route label the matching itself changes (it is +label-dependent: goal side vs other side), so the null must permute the label ACROSS EPISODES, REMATCH, +and REFIT end to end. n = --perm-null draws. Reported beside every conditional AUC, with an exact +permutation p. A nominal 0.5 is not used anywhere. + +Episode hygiene is inherited unchanged from proposal_ceiling.py: out-of-fold scores under +StratifiedGroupKFold over EPISODES, the chunk taken relative to its first action, no time index, and a +pair is required to span two DIFFERENT episodes. The bootstrap is clustered on the goal-side episode. +""" +from __future__ import annotations +import argparse, json, sys, time, warnings +from pathlib import Path +import numpy as np + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from proposal_ceiling import (ROOT, unit, auc, build, chunk_feat, fit_arm, + metaheur_oof, dir_feat, perm_labels) + +warnings.filterwarnings("ignore") + + +def match_pairs(Z, y, ep, caliper, seed=0): + """Greedy 1-1 nearest-neighbour matching of y==1 to y==0 anchors, cross-episode, within `caliper` + standardised-anchor-space distance. Returns (i_goal, i_other, dist) arrays. + + Greedy in ascending distance over all admissible pairs: this is the usual deterministic caliper + matching, and it makes the pair set a function of (Z, y, ep, caliper) alone, so the permutation null + rebuilds it the same way it was built on the real label.""" + pos = np.flatnonzero(y == 1) + neg = np.flatnonzero(y == 0) + if len(pos) == 0 or len(neg) == 0: + return np.array([], int), np.array([], int), np.array([], float) + # full distance matrix; anchors are ~2k and the feature is 13-d, so this is small. + D = np.linalg.norm(Z[pos][:, None, :] - Z[neg][None, :, :], axis=2) + # forbid same-episode pairs (they would share the episode's own idiosyncrasies AND, for y!=y, cannot + # occur anyway; kept explicit so the constraint is visible) + same = ep[pos][:, None] == ep[neg][None, :] + D = np.where(same | (D > caliper), np.inf, D) + order = np.argsort(D, axis=None, kind="stable") + usedP, usedN = np.zeros(len(pos), bool), np.zeros(len(neg), bool) + ip, io, dd = [], [], [] + for flat in order: + a, b = np.unravel_index(flat, D.shape) + d = D[a, b] + if not np.isfinite(d): + break + if usedP[a] or usedN[b]: + continue + usedP[a] = usedN[b] = True + ip.append(pos[a]); io.append(neg[b]); dd.append(d) + return np.array(ip, int), np.array(io, int), np.array(dd, float) + + +def cond_auc(s, ip, io): + """Within-pair win rate = conditional AUC. Ties count 0.5, and are reported separately.""" + a, b = np.asarray(s)[ip], np.asarray(s)[io] + ok = np.isfinite(a) & np.isfinite(b) + if ok.sum() == 0: + return float("nan"), 0, 0 + a, b = a[ok], b[ok] + ties = int((a == b).sum()) + return float(((a > b).sum() + 0.5 * ties) / len(a)), int(len(a)), ties + + +def cond_boot(s, ip, io, ep, B=2000, seed=0): + """Cluster bootstrap on the GOAL-side episode: resample episodes, keep the pairs whose goal member + belongs to a resampled episode. Clustering on one side is the standard choice when the pair spans + two clusters; it is stated rather than hidden.""" + rng = np.random.default_rng([seed, 991]) + g = ep[ip] + ue = np.unique(g) + by = {e: np.flatnonzero(g == e) for e in ue} + out = [] + for _ in range(B): + pick = rng.choice(ue, len(ue), replace=True) + sel = np.concatenate([by[e] for e in pick]) + v, n, _ = cond_auc(s, ip[sel], io[sel]) + if np.isfinite(v): + out.append(v) + if not out: + return float("nan"), float("nan"), float("nan") + o = np.array(out) + return float(o.mean()), float(o.std(ddof=1)), (float(np.quantile(o, .025)), float(np.quantile(o, .975))) + + +def arms_for(A, CH, y, ep, L, folds, seed, which): + """OOF scores for the arms we condition. `anchor` is the GUARD, not a competitor.""" + out = {} + if "anchor:logreg" in which: out["anchor:logreg"] = fit_arm(A, y, ep, folds, seed, "logreg") + if "chunk:logreg" in which: out["chunk:logreg"] = fit_arm(chunk_feat(CH, L, "waypoints"), y, ep, folds, seed, "logreg") + if "chunk:mlp" in which: out["chunk:mlp"] = fit_arm(chunk_feat(CH, L, "waypoints"), y, ep, folds, seed, "mlp") + if "chunkdir:logreg" in which:out["chunkdir:logreg"] = fit_arm(dir_feat(CH, L, "dir"), y, ep, folds, seed, "logreg") + if "metaheur" in which: out["metaheur"] = metaheur_oof(CH, y, ep, L, folds, seed) + if "random" in which: out["random"] = np.random.default_rng([seed, 5]).normal(size=len(y)) + return out + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--out", required=True) + ap.add_argument("--hdf5", default=f"{ROOT}/data/raw/cooking_v5_expert_suboptimal.hdf5") + ap.add_argument("--split", default=f"{ROOT}/data/derived/cooking_v5_split.json") + ap.add_argument("--state", type=int, default=2) + ap.add_argument("--route-pos", default="[2, 3, 4]") + ap.add_argument("--route-neg", default="[0, 2, 3]", + help="default is C2 goal_vs_cook: BOTH routes are expert, so provenance is held fixed") + ap.add_argument("--contrast", default="goal_vs_cook") + ap.add_argument("--stride", type=int, default=5) + ap.add_argument("--entry-window", type=int, default=100) + ap.add_argument("--lengths", type=int, nargs="+", default=[8]) + ap.add_argument("--folds", type=int, default=5) + ap.add_argument("--seeds", type=int, nargs="+", default=[0, 1, 2]) + ap.add_argument("--calipers", type=float, nargs="+", default=[0.05, 0.1, 0.25, 0.5, 1.0, 2.0]) + ap.add_argument("--boot", type=int, default=2000) + ap.add_argument("--perm-null", type=int, default=0) + ap.add_argument("--perm-null-arms", nargs="+", default=["chunk:logreg"]) + ap.add_argument("--perm-null-caliper", type=float, default=None, + help="caliper at which the null is drawn; default = the tightest that keeps >=200 pairs") + a = ap.parse_args() + t0 = time.time() + a.lengths = sorted(set(a.lengths)) + Lmax = max(a.lengths) + + rows, n_drop, n_eps_lab = build(a) + if not rows: + print("[cond] NO ANCHORS", flush=True); sys.exit(2) + ep = np.array([r["ep"] for r in rows]) + y = np.array([r["y"] for r in rows], int) + A = np.stack([r["anchor"] for r in rows]) + CH = np.stack([r["chunk"] for r in rows]) + print(f"[cond] contrast={a.contrast} pos={a.route_pos} neg={a.route_neg} window={a.entry_window}", flush=True) + print(f"[cond] anchors={len(y)} episodes={len(np.unique(ep))} goal={int(y.sum())} other={int((1-y).sum())} " + f"dropped_by_Lmax={n_drop} anchor_dim={A.shape[1]}", flush=True) + + # standardise the anchor feature ONCE, on all anchors, so the caliper is in a fixed unit across + # calipers, seeds and permutations. + Z = (A - A.mean(0)) / np.maximum(A.std(0), 1e-8) + Z = Z.astype(np.float64) + + ARMS = ["anchor:logreg", "chunk:logreg", "chunk:mlp", "chunkdir:logreg", "metaheur", "random"] + res, pairinfo = [], [] + + for L in a.lengths: + # OOF scores do NOT depend on the caliper, so fit once per (L, seed) and condition many ways. + oof = {s: arms_for(A, CH, y, ep, L, a.folds, s, ARMS) for s in a.seeds} + for cal in a.calipers: + ip, io, dd = match_pairs(Z, y, ep, cal) + npair = len(ip) + neps = len(np.unique(np.concatenate([ep[ip], ep[io]]))) if npair else 0 + print(f"\n[cond] L={L} caliper={cal:g}: pairs={npair} episodes={neps} " + f"median_d={np.median(dd) if npair else float('nan'):.4f} " + f"max_d={dd.max() if npair else float('nan'):.4f}", flush=True) + pairinfo.append(dict(L=L, caliper=cal, n_pairs=npair, n_eps=neps, + median_d=float(np.median(dd)) if npair else None, + max_d=float(dd.max()) if npair else None)) + if npair < 30: + print(f"[cond] L={L} caliper={cal:g} UNDEFINED: {npair} pairs < 30", flush=True) + continue + for arm in ARMS: + vs = [] + for s in a.seeds: + v, n, ties = cond_auc(oof[s][arm], ip, io) + vs.append(v) + v0, n0, ties0 = cond_auc(oof[a.seeds[0]][arm], ip, io) + bm, se, ci = cond_boot(oof[a.seeds[0]][arm], ip, io, ep, B=a.boot, seed=a.seeds[0]) + sc = oof[a.seeds[0]][arm] + sc = sc[np.isfinite(sc)] + cv = float(np.std(sc) / max(abs(np.mean(sc)), 1e-9)) + tag = "GUARD" if arm == "anchor:logreg" else "" + res.append(dict(L=L, caliper=cal, arm=arm, auc=v0, seeds=vs, se=se, ci=ci, + n_pairs=n0, ties=ties0, score_cv=cv, guard=(arm == "anchor:logreg"))) + print(f"[cond] L={L:3d} cal={cal:<5g} {arm:<16s} condAUC={v0:.4f} +-{se:.4f} " + f"[{ci[0]:.3f},{ci[1]:.3f}] seeds={['%.3f'%x for x in vs]} " + f"pairs={n0} ties={ties0} cv={cv:.3g} {tag}", flush=True) + + # ---- permutation null: permute route label across EPISODES, REMATCH, REFIT, recompute. + pn = [] + if a.perm_null > 0: + cal = a.perm_null_caliper + if cal is None: + ok = [p for p in pairinfo if p["n_pairs"] >= 200] + cal = min([p["caliper"] for p in ok]) if ok else max(a.calipers) + L = a.lengths[0] + print(f"\n[cond] PERMNULL at L={L} caliper={cal:g}, n={a.perm_null}, arms={a.perm_null_arms} " + f"(rematch + refit each draw)", flush=True) + for r in range(a.perm_null): + yp = perm_labels(y, ep, 10_000 + r) + ipp, iop, _ = match_pairs(Z, yp, ep, cal) + if len(ipp) < 30: + continue + o = arms_for(A, CH, yp, ep, L, a.folds, a.seeds[0], a.perm_null_arms) + for arm in a.perm_null_arms: + v, n, _ = cond_auc(o[arm], ipp, iop) + if np.isfinite(v): + pn.append(dict(arm=arm, L=L, caliper=cal, rep=r, auc=v, n_pairs=n)) + if (r + 1) % 25 == 0: + print(f"[cond] permnull {r+1}/{a.perm_null} {time.time()-t0:.0f}s", flush=True) + for arm in a.perm_null_arms: + v = np.array([x["auc"] for x in pn if x["arm"] == arm]) + if not len(v): + print(f"[cond] PERMNULL {arm}: NO DRAWS", flush=True); continue + real = [x for x in res if x["arm"] == arm and x["caliper"] == cal and x["L"] == L] + rv = real[0]["auc"] if real else float("nan") + p = (1 + int((v >= rv).sum())) / (1 + len(v)) if np.isfinite(rv) else float("nan") + print(f"[cond] PERMNULL {arm} L={L} cal={cal:g} n={len(v)} mean={v.mean():.4f} " + f"sd={v.std(ddof=1):.4f} q95={np.quantile(v,.95):.4f} q99={np.quantile(v,.99):.4f} " + f"REAL={rv:.4f} exact_perm_p={p:.3f}", flush=True) + + out = Path(a.out); out.mkdir(parents=True, exist_ok=True) + json.dump(dict(contrast=a.contrast, entry_window=a.entry_window, n_anchors=int(len(y)), + n_episodes=int(len(np.unique(ep))), pairs=pairinfo, results=res, perm_null=pn, + config=vars(a)), open(out / "conditional.json", "w"), indent=1, default=str) + print(f"[cond] done {time.time()-t0:.0f}s -> {out}/conditional.json", flush=True) + + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/real/pt_cov_entry_table.py b/rsm_rise/scripts/real/pt_cov_entry_table.py new file mode 100644 index 0000000000000000000000000000000000000000..c6c8db9ed98572434098668b6bd29bbf4e0f2f24 --- /dev/null +++ b/rsm_rise/scripts/real/pt_cov_entry_table.py @@ -0,0 +1,73 @@ +#!/usr/bin/env python +"""gen_q#280 / #281 -- COVERAGE AT ENTRY, the whole proposer grid. + +Under the 18:15Z directive the only label-sound anchor set is S2 within W frames of meta-state ENTRY. +This asks, per proposer and per route, whether the proposal test EXISTS there at all: does the proposer +put >=16 of its 128 draws on each side of the direction label, at >=30 anchors across >=4 episodes? +Every row carries the ORACLE CEILING of its own GATED anchor set, so a cell that gates can still be +unreportable because the label at the surviving anchors does not track the route. +No value is read anywhere in this script. +""" +import json, sys +from pathlib import Path + +WINDOWS = ["25", "50", "100", "200", "all"] +ROUTES = ["0->2->3", "0->2->6", "2->3->4"] +data = {W: json.load(open(f"status/real/PT_WINCOV_w{W}.json")) for W in WINDOWS} +cells = sorted({k for k in data["100"] if "|" not in k}) + +def num(x, f="%.3f"): + return (f % x) if isinstance(x, float) and x == x else "--" + +def blk(W, key): + return (data[W].get(key) or {}).get("coverage") + +out = [] +PRIM = "100" +out.append(f"### Coverage at entry, whole proposer grid, window {PRIM} (the directive's gate)") +out.append("") +out.append("`gated` = anchors with >=16 of 128 draws on EACH side of the direction label. The spec's " + "coverage gate is >=30 gated anchors across >=4 episodes. `orc gated` is the oracle ceiling " + "of that exact gated anchor set (nearest-centroid assignment of the LOGGED chunk direction " + "against the edge the episode actually took, 8-frame chunks); a cell that gates but whose " + "gated ceiling is at or below 0.5 has nothing for any scorer to find.") +out.append("") +out.append("| proposer cell | route | anchors | eps | **gated** | gated eps | dropped all-succ | " + "dropped all-fail | succ-side med/128 | spread mm | **orc gated** | GATE |") +out.append("|---|---|---|---|---|---|---|---|---|---|---|---|") +for c in cells: + for r in ["pooled"] + ROUTES: + key = c if r == "pooled" else f"{c} | {r}" + b = blk(PRIM, key) + if b is None: + out.append(f"| `{c}` | {r} | -- | -- | **--** | -- | -- | -- | -- | -- | -- | NO ANCHORS |") + continue + o = b.get("oracle") or {} + gp = b["gated_anchors"] >= 30 and b["gated_episodes"] >= 4 + out.append(f"| `{c}` | {r} | {b['anchors']} | {b['episodes']} | **{b['gated_anchors']}** | " + f"{b['gated_episodes']} | {b['dropped_all_success']} | {b['dropped_all_failure']} | " + f"{b['succ_side_med']:.0f} | {b['dir_spread_mm']:.1f} | **{num(o.get('auc'))}** | " + f"{'PASS' if gp else 'FAIL'} |") + +out.append("") +out.append("### The goal route `2->3->4` across every window, every proposer") +out.append("") +out.append("| proposer cell | " + " | ".join(f"w{W} gated" for W in WINDOWS) + " | " + + " | ".join(f"w{W} orc" for W in WINDOWS) + " |") +out.append("|---|" + "---|" * (2 * len(WINDOWS))) +for c in cells: + g, oc = [], [] + for W in WINDOWS: + b = blk(W, f"{c} | 2->3->4") + if b is None: + g.append("--"); oc.append("--"); continue + gp = b["gated_anchors"] >= 30 and b["gated_episodes"] >= 4 + g.append(f"**{b['gated_anchors']}**" + ("" if gp else "*")) + oc.append(num(((b.get("oracle") or {}).get("auc")))) + out.append(f"| `{c}` | " + " | ".join(g) + " | " + " | ".join(oc) + " |") +out.append("") +out.append("`*` = fails the >=30 anchors / >=4 episodes gate.") + +md = "\n".join(out) +print(md) +Path("status/real/PT_COV_ENTRY.md").write_text(md + "\n") diff --git a/rsm_rise/scripts/real/pt_epcv.py b/rsm_rise/scripts/real/pt_epcv.py new file mode 100644 index 0000000000000000000000000000000000000000..9def03aa850dfd745d0466c3c77eb061a484b528 --- /dev/null +++ b/rsm_rise/scripts/real/pt_epcv.py @@ -0,0 +1,253 @@ +#!/usr/bin/env python +"""gen_q#280 / rsm_real#2 -- EPISODE-NESTED re-check of this stream's surviving `0->2->6` positives. + +WHAT THIS IS, AND WHAT IT CANNOT DO. This is a GUARD applied to numbers that are already reported, not +a new scorer and not a new candidate for a pass. It can only ever DOWNGRADE an existing positive or +leave it standing; there is no arrangement of its output that turns a failing row into a passing one. +No row from this file may be quoted as a pass. + +Why it exists, and where it was committed to in advance. Run 27 (`scripts/real/pt_combine.py`, jobs +1892861/1892862; posted as gen_q#280 comment 5808966565 / rsm_real#2 comment 5808966798) found that the +episode-nested FITTED arm of the combined scorer reads 0.3615-0.3775 on `0->2->6` in 4 of 6 cells against +a measured permutation line of 0.499 -- i.e. a rule learned on the other episodes ANTI-predicts the +held-out one. That run's item 6 stated the consequence publicly and pre-committed this stream to it: + + "Any surviving `0->2->6` positive should be treated as unconfirmed until re-checked with nested CV." + +`0->2->6` is the route carrying this stream's most persistent both-seeds clears -- `rsm` reads 0.5200 to +0.5549 there against a family-wise q95 of ~0.516 in 5 of 6 cells. Those five numbers are the ones the +commitment above names, and this file is that re-check. + +THE POINT, STATED SO THE OUTPUT CANNOT BE OVER-READ. The episode bootstrap and episode-nested CV are +different guards and they answer different questions. The bootstrap resamples episodes to put an +interval on a POOLED statistic; it never asks whether a rule fitted on some episodes holds on a held-out +one. A scorer whose rank-to-label relationship is episode-specific and flips sign between episodes can +have a pooled AUC comfortably above its bootstrap interval and still carry no transferable signal. That +is exactly the failure run 27 measured on the fitted arm, and the question here is whether the PLAIN +`rsm` column on the same route has it too. + +THE PRIMARY STATISTIC HAS ZERO FREE PARAMETERS. `loeo_sign`: for each held-out episode h, take the +orientation s_h = sign(mean AUC over the anchors NOT in h, minus 0.5) -- learned from training episodes +only -- and re-score h's anchors as 0.5 + s_h * (A_i - 0.5). Pool. Nothing is fitted beyond one bit per +fold, and for a single monotone feature under a rank read-out that one bit IS the leave-one-episode-out +model. Read it as: + + loeo_sign ~= pooled the effect is episode-general and the pooled number stands; + loeo_sign ~= 0.5 the pooled positive comes from a subset of episodes; the sign does not transfer; + loeo_sign < 0.5 the sign systematically FLIPS between episodes -- run 27's failure mode. + +`loeo_logit1` is the same guard run through the SAME code path run 27 used for the two-feature fitted +arm, `pt_combine.loeo_logistic`, with the feature list cut to one column. That function was generalised +(default unchanged, so every row already posted from it is untouched) rather than restated here, because +a guard that used its own private copy of the definition would not be comparable to the run-27 numbers it +exists to follow up. + +THE NULL IS MEASURED, NOT ASSUMED. Under the null `loeo_sign` is 0.5 in expectation -- s_h depends only +on the training episodes and is independent of the held-out episode's deviation -- but this stream does +not quote nominal zero lines, so `permuted:rsm` and `random` are carried through every statistic in the +table and ARE the zero line for the LOEO columns. A `loeo_sign` for `rsm` is only interpretable beside +the `loeo_sign` of `permuted:rsm` on the same block. + +Every other definition -- `load_cell`, `auc`, `ep_bootstrap`, `oracle_ceiling`, `model_free_scores`, the +family-wise `calibrate`, and `rows_for`/`score_of` -- is IMPORTED. The pooled AUC column is produced by +`rows_for`, the same call that produced the rows being re-checked, so the pooled figure in this table is +the run-27 figure and not a re-derivation of it. Nothing is re-sampled and no checkpoint is loaded: this +reads the saved npz parts, which is why it is CPU. Reported per route, never pooled across routes, every +row with its measured permuted column, its own anchor set's oracle ceiling, the calibrated family-wise +q95, ties@max, score CV and kept anchor/episode counts. +""" +from __future__ import annotations +import argparse, json, sys +from pathlib import Path +import numpy as np + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from proposal_report import (load_cell, auc, ep_bootstrap, oracle_ceiling) # noqa: E402 +from pt_nullcal import calibrate # noqa: E402 +from pt_residual import score_of, rows_for # noqa: E402 +from pt_combine import loeo_logistic # noqa: E402 + +SCORERS = ["rsm", "pose_cont", "idql", "permuted:rsm", "random"] + + +def per_anchor_auc(gated, get): + """Per-anchor AUC and the episode each anchor came from -- the same per-anchor quantity `rows_for` + averages, kept unaveraged so it can be split by episode.""" + A, epi, keep = [], [], [] + for r in gated: + sc = get(r) + if sc is None: + continue + lab = np.asarray(r["margin"], float) > 0 + A.append(auc(sc, lab)); epi.append(r["episode"]); keep.append(r) + return np.asarray(A, float), np.asarray(epi), keep + + +def loeo_sign(A, epi): + """Leave-one-episode-out ORIENTATION transfer. Returns (oriented per-anchor AUCs, folds skipped). + + The orientation for a held-out episode is decided by the other episodes alone. A fold whose training + mean lands exactly on 0.5 has no orientation to transfer; it is skipped and counted rather than + silently assigned one.""" + out = np.full(len(A), np.nan) + skipped = 0 + for h in sorted(set(epi.tolist())): + te = epi == h + tr = ~te + if tr.sum() == 0 or te.sum() == 0: + continue + s = np.sign(A[tr].mean() - 0.5) + if s == 0: + skipped += int(te.sum()); continue + out[te] = 0.5 + s * (A[te] - 0.5) + return out, skipped + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--cells", nargs="+", required=True) + ap.add_argument("--root", default="status/real") + ap.add_argument("--entry-window", type=int, default=100) + ap.add_argument("--oracle-chunk", type=int, default=8) + ap.add_argument("--state", type=int, default=2) + ap.add_argument("--gate-min-anchors", type=int, default=30) + ap.add_argument("--reps", type=int, default=4000) + ap.add_argument("--boot", type=int, default=400) + ap.add_argument("--perm-reps", type=int, default=200) + ap.add_argument("--json", default=None) + ap.add_argument("--md", default=None) + a = ap.parse_args() + + rng = np.random.default_rng(11) + blocks = [] + for cell in a.cells: + d = Path(cell) + if not d.is_absolute() and not d.exists(): + d = Path(a.root) / cell + recs, cfg = load_cell(d, entry_window=a.entry_window) + if not recs: + print(f"[epcv] {d.name}: no anchors", file=sys.stderr); continue + for route in sorted({r["path"] for r in recs}): + gated = [r for r in recs if r["gate"] and r["path"] == route] + neps = len({r["episode"] for r in gated}) + if len(gated) < a.gate_min_anchors or neps < 4: + blocks.append(dict(cell=d.name, route=route, undefined=True, + anchors=len(gated), episodes=neps, + reason=f"below #280 floor (30 anchors / 4 episodes): " + f"{len(gated)} anchors / {neps} episodes")) + print(f"[epcv] UNDEFINED {d.name} {route}: {len(gated)} anchors / {neps} eps", + file=sys.stderr) + continue + + pairs = [(nm, (lambda n: (lambda r: score_of(r, n)))(nm)) for nm in SCORERS] + rows = rows_for(gated, pairs) + by = {r["scorer"]: r for r in rows} + + for nm in SCORERS: + if nm not in by: + continue + get = (lambda n: (lambda r: score_of(r, n)))(nm) + A, epi, kept = per_anchor_auc(gated, get) + if len(A) == 0: + continue + # per-episode decomposition + ep_rows = [] + for h in sorted(set(epi.tolist())): + m = epi == h + ep_rows.append(dict(episode=str(h), anchors=int(m.sum()), + auc=float(A[m].mean()))) + above = sum(1 for e in ep_rows if e["auc"] > 0.5) + + ori, sk = loeo_sign(A, epi) + ok = np.isfinite(ori) + if ok.sum(): + ls = float(ori[ok].mean()) + ls_se, ls_ci = ep_bootstrap(list(ori[ok]), list(epi[ok]), rng) + else: + ls, ls_se, ls_ci = float("nan"), float("nan"), [float("nan")] * 2 + + # same code path as run 27's two-feature fitted arm, cut to one feature + fit, fit_skipped = loeo_logistic(gated, feature_names=(nm,)) + for i, r in enumerate(gated): + r["_idx"] = i + Af, epif, _ = per_anchor_auc(gated, lambda r: fit.get(r.get("_idx"))) + if len(Af): + lg = float(Af.mean()) + lg_se, lg_ci = ep_bootstrap(list(Af), list(epif), rng) + else: + lg, lg_se, lg_ci = float("nan"), float("nan"), [float("nan")] * 2 + + by[nm].update(dict( + per_episode=ep_rows, episodes_above_half=above, + loeo_sign=ls, loeo_sign_se=ls_se, loeo_sign_ci=ls_ci, + loeo_sign_skipped=int(sk), + loeo_logit1=lg, loeo_logit1_se=lg_se, loeo_logit1_ci=lg_ci, + loeo_logit1_skipped=int(fit_skipped))) + + cal = calibrate(gated, a.reps, a.boot, a.perm_reps, rng, n_scorers=len(SCORERS)) + orc = oracle_ceiling([(r["episode"], r["frame"]) for r in gated], a.oracle_chunk, a.state) + blocks.append(dict(cell=d.name, route=route, undefined=False, + anchors=len(gated), episodes=neps, + beta_mode=cfg.get("beta_mode"), beta=cfg.get("beta"), + ckpt=cfg.get("ckpt") or cfg.get("successor"), + cands_from=cfg.get("cands_from"), + q95_fwer=cal.get("q95_fwer"), null_mean=cal.get("null_mean"), + oracle=orc, rows=rows)) + r0 = by.get("rsm", {}) + print(f"[epcv] {d.name} {route}: {len(gated)} anchors / {neps} eps " + f"rsm pooled={r0.get('auc', float('nan')):.4f} " + f"loeo_sign={r0.get('loeo_sign', float('nan')):.4f} " + f"loeo_logit1={r0.get('loeo_logit1', float('nan')):.4f} " + f"eps>0.5={r0.get('episodes_above_half')}/{neps} " + f"q95={cal.get('q95_fwer'):.4f} ceiling={orc.get('auc'):.3f}", file=sys.stderr) + + if a.json: + Path(a.json).parent.mkdir(parents=True, exist_ok=True) + json.dump(blocks, open(a.json, "w"), indent=1, default=float) + + L = ["# Episode-nested re-check of the surviving `0->2->6` positives -- gen_q#280 / rsm_real#2", "", + "A **guard on already-reported numbers, not a scorer and not a candidate for a pass**: it can " + "only downgrade an existing positive or leave it standing. Committed to in advance as run 27 " + "item 6 (gen_q#280 comment 5808966565 / rsm_real#2 comment 5808966798).", "", + "`pooled` is produced by the same `rows_for` call as the rows being re-checked, so it IS the " + "run-27 figure. `loeo_sign` (PRIMARY, **zero free parameters**) orients each held-out episode by " + "the OTHER episodes only. `loeo_logit1` is run 27's own two-feature LOEO code path cut to one " + "feature. **`permuted:rsm` and `random` carry the measured zero line for the LOEO columns** -- a " + "`loeo_sign` is only interpretable beside theirs on the same block.", ""] + for b in blocks: + if b.get("undefined"): + L += [f"## `{b['cell']}` -- {b['route']}", "", f"**UNDEFINED**: {b['reason']}", ""] + continue + orc = (b.get("oracle") or {}).get("auc", float("nan")) + L += [f"## `{b['cell']}` -- {b['route']}", "", + f"{b['anchors']} anchors / {b['episodes']} episodes kept; beta_mode " + f"`{b.get('beta_mode')}` beta `{b.get('beta')}`; proposer `{b.get('cands_from')}`; " + f"family-wise q95 **{b.get('q95_fwer'):.4f}**; oracle ceiling for THIS anchor set " + f"**{orc:.3f}**.", "", + "| scorer | pooled AUC +- SE | permuted | loeo_sign +- SE | loeo_logit1 +- SE | " + "eps > 0.5 | ties@max | score CV |", + "|---|---|---|---|---|---|---|---|"] + for r in b["rows"]: + cv = r.get("cv", float("nan")) + L.append(f"| `{r['scorer']}` | {r['auc']:.4f} +- {r['auc_se']:.4f} | " + f"{r['auc_permuted']:.4f} | " + f"{r.get('loeo_sign', float('nan')):.4f} +- {r.get('loeo_sign_se', float('nan')):.4f} | " + f"{r.get('loeo_logit1', float('nan')):.4f} +- {r.get('loeo_logit1_se', float('nan')):.4f} | " + f"{r.get('episodes_above_half')}/{b['episodes']} | {r['ties_at_max']:.2f} | " + + ("n/a" if not np.isfinite(cv) else f"{cv:.4f}") + " |") + L.append("") + rr = {x["scorer"]: x for x in b["rows"]}.get("rsm") + if rr and rr.get("per_episode"): + L += ["Per-episode AUC for `rsm` (the decomposition the pooled number hides):", "", + "| episode | anchors | AUC |", "|---|---|---|"] + for e in rr["per_episode"]: + L.append(f"| `{e['episode']}` | {e['anchors']} | {e['auc']:.4f} |") + L.append("") + if a.md: + Path(a.md).parent.mkdir(parents=True, exist_ok=True) + Path(a.md).write_text("\n".join(L)) + print("\n".join(L)) + + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/real/pt_floor_analyze.py b/rsm_rise/scripts/real/pt_floor_analyze.py new file mode 100644 index 0000000000000000000000000000000000000000..80bac4add89dacc420cbd18c501b4993c84bcbff --- /dev/null +++ b/rsm_rise/scripts/real/pt_floor_analyze.py @@ -0,0 +1,126 @@ +#!/usr/bin/env python +"""PROPOSAL_TEST run 43 -- the DETERMINISM FLOOR, and the REPLACEMENT reproduction bar it fixes. + +Pre-registered in gen_q#280 5822858562 / rsm_real#2 5822859924 BEFORE any rung coverage number was read: + + PREDICTION : replicate-vs-replicate delta sits at the SAME order as replicate-vs-published + (median ~3e-4 raw, ~0.5 mm displacement) -> the divergence is a hardware determinism floor. + KILL : the four replicates agree with EACH OTHER at |delta| = 0 while still differing from the + published cell -> pt_proposer_temp.py changes the computation at scale 1.0, where it is + supposed to install nothing. A code defect; no rung may be read until it is fixed. + REPLACEMENT GUARD : scale-1.0 vs published must sit within the 99th percentile of the measured + replicate-vs-replicate floor, in BOTH raw units and displacement mm. + +Reads only `cands`. NO ruler (`margin`, `cand_dir_mm` are never touched) and NO coverage number is +computed here, so this job cannot see any rung result. +""" +import glob, itertools, json +from pathlib import Path +import numpy as np + +ROOT = "/proj/dmfexp/zwhong/rsm_rise" +REPS = [f"pt_cov_sn1_knn0p03_REP{i}" for i in (1, 2, 3, 4)] +PUB = "pt_cov_sn1_knn0p03" +RUNG10 = "pt_cov_sn1_knn0p03_T10" + + +def load(tag): + out = {} + for f in sorted(glob.glob(f"{ROOT}/status/real/{tag}/parts/*.npz")): + z = np.load(f, allow_pickle=True) + meta = json.loads(bytes(z["__meta__"]).decode()) + if not meta.get("n_anchors", 0) or "cands" not in z.files: + continue + out[Path(f).name] = np.asarray(z["cands"]).astype(np.float64) + return out + + +def disp_mm(c): + return np.linalg.norm(c[..., -1, :3] - c[..., 0, :3], axis=-1) * 1000.0 + + +def compare(a, b): + """elementwise delta stats over the episodes both sides have, plus displacement-space delta in mm.""" + shared = sorted(set(a) & set(b)) + ds, dd, nan = [], [], 0 + for k in shared: + if a[k].shape != b[k].shape: + continue + ds.append(np.abs(a[k] - b[k]).ravel()) + dd.append(np.abs(disp_mm(a[k]) - disp_mm(b[k])).ravel()) + nan += a[k].shape[0] + if not ds: + return None + ds = np.concatenate(ds); dd = np.concatenate(dd) + return dict(n_ep=len(shared), n_anchor=nan, + med=float(np.median(ds)), p99=float(np.percentile(ds, 99)), max=float(ds.max()), + mm_med=float(np.median(dd)), mm_p99=float(np.percentile(dd, 99)), mm_max=float(dd.max()), + exact_zero=bool(ds.max() == 0.0)) + + +cache = {t: load(t) for t in REPS + [PUB, RUNG10]} +for t in REPS + [PUB, RUNG10]: + print(f"[floor] {t}: {len(cache[t])} anchored episode(s)") + +print("\n[floor] === replicate vs replicate (the FLOOR) ===") +floor_p99 = []; floor_mm_p99 = []; floor_rows = []; n_exact = 0; n_pair = 0 +for x, y in itertools.combinations(REPS, 2): + r = compare(cache[x], cache[y]) + if r is None: + print(f"[floor] {x} vs {y}: no shared anchored episode yet"); continue + n_pair += 1; n_exact += int(r["exact_zero"]) + floor_p99.append(r["p99"]); floor_mm_p99.append(r["mm_p99"]) + floor_rows.append(dict(pair=f"{x} vs {y}", **r)) + print(f"[floor] {x[-4:]} vs {y[-4:]}: ep={r['n_ep']} anch={r['n_anchor']} " + f"med={r['med']:.3e} p99={r['p99']:.3e} max={r['max']:.3e} | " + f"mm med={r['mm_med']:.4f} p99={r['mm_p99']:.4f} max={r['mm_max']:.4f} " + f"| exact-zero={r['exact_zero']}") + +print("\n[floor] === each replicate vs the published cell ===") +pub_rows = [] +for x in REPS: + r = compare(cache[x], cache[PUB]) + if r is None: + print(f"[floor] {x} vs {PUB}: no shared anchored episode yet"); continue + pub_rows.append(dict(pair=f"{x} vs {PUB}", **r)) + print(f"[floor] {x[-4:]} vs PUB : ep={r['n_ep']} anch={r['n_anchor']} " + f"med={r['med']:.3e} p99={r['p99']:.3e} max={r['max']:.3e} | " + f"mm med={r['mm_med']:.4f} p99={r['mm_p99']:.4f} max={r['mm_max']:.4f} " + f"| exact-zero={r['exact_zero']}") + +verdict = {} +if floor_p99 and pub_rows: + bar, bar_mm = max(floor_p99), max(floor_mm_p99) + print(f"\n[floor] REPLACEMENT BAR (max over replicate pairs of the p99 delta): " + f"{bar:.3e} raw, {bar_mm:.4f} mm") + all_exact_floor = (n_exact == n_pair and n_pair > 0) + pub_differs = all(not r["exact_zero"] for r in pub_rows) + if all_exact_floor and pub_differs: + verdict["kill"] = ("KILL CONDITION MET -- the replicates are bit-identical to each other but " + "differ from the published cell: pt_proposer_temp.py changes the computation " + "at scale 1.0. CODE DEFECT; no rung may be read.") + else: + verdict["kill"] = ("KILL did NOT fire -- the replicates diverge from each other too, so the " + "divergence is a determinism floor, as predicted.") + print(f"[floor] {verdict['kill']}") + # apply the replacement guard to the scale-1.0 rung + r10 = compare(cache[RUNG10], cache[PUB]) + if r10 is None: + print("[floor] rung T10 vs PUB: no shared anchored episode yet -- guard NOT evaluated") + else: + ok = (r10["p99"] <= bar) and (r10["mm_p99"] <= bar_mm) + verdict["guard"] = dict(rung_p99=r10["p99"], rung_mm_p99=r10["mm_p99"], + bar=bar, bar_mm=bar_mm, passes=bool(ok)) + print(f"[floor] rung T10 vs PUB: p99={r10['p99']:.3e} (bar {bar:.3e}), " + f"mm p99={r10['mm_p99']:.4f} (bar {bar_mm:.4f})") + print(f"[floor] REPLACEMENT REPRODUCTION GUARD {'PASSES' if ok else 'FAILS'} " + f"-- {'the run-42 caches are readable as run-43 rungs' if ok else 'the caches stay VOID'}") + verdict["noise_floor_mm_med"] = float(np.median([r["mm_med"] for r in floor_rows])) + print(f"[floor] INSTRUMENT NOISE FLOOR to print on every rung row: " + f"{verdict['noise_floor_mm_med']:.4f} mm median displacement divergence") +else: + print("\n[floor] not enough replicate output yet -- rerun when the pack has anchored episodes") + +json.dump(dict(floor=floor_rows, vs_published=pub_rows, verdict=verdict), + open(f"{ROOT}/status/real/pt_r43_floor.json", "w"), indent=1) +print("[floor] wrote status/real/pt_r43_floor.json") diff --git a/rsm_rise/scripts/real/pt_floor_analyze.sh b/rsm_rise/scripts/real/pt_floor_analyze.sh new file mode 100644 index 0000000000000000000000000000000000000000..f7af384a1781f14dc684629c3e74a5ecc3f4d537 --- /dev/null +++ b/rsm_rise/scripts/real/pt_floor_analyze.sh @@ -0,0 +1,7 @@ +#!/usr/bin/env bash +set -uo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +export MUJOCO_GL=disable +echo "[floor-run] start $(date)" +/proj/dmfexp/zwhong/rsm_rise/venv_rsm/bin/python scripts/real/pt_floor_analyze.py +echo "[floor-run] exit=$? $(date)" diff --git a/rsm_rise/scripts/real/pt_floor_equiv.py b/rsm_rise/scripts/real/pt_floor_equiv.py new file mode 100644 index 0000000000000000000000000000000000000000..67d018d2b0dcff996e67cf196c72094b2650de2e --- /dev/null +++ b/rsm_rise/scripts/real/pt_floor_equiv.py @@ -0,0 +1,123 @@ +#!/usr/bin/env python +"""PROPOSAL_TEST run 45c -- is the base rung's divergence from the published cell DISTINGUISHABLE from the +pure cross-host floor? Pre-registered before the number is read. + +The run-45b matched guard FAILED (raw 1.000x PASS, mm 1.010x FAIL, both limbs required). That verdict +STANDS and is not overturned here. But it compared two POINT ESTIMATES of a p99 with no interval on either +side and decided at 1.010x, so it has no power at the resolution it was asked to decide. This is the same +question asked with an interval. + +Contrasts, all on the MATCHED anchors (ep000105 + ep000179, 183 anchors): + A = |T10 - REP1| pure cross-host, IDENTICAL code / scale / seed (p6-r29-n2 vs p5-r16-n2) + B = |T10 - PUB | the ladder's base against the published cell +If pt_proposer_temp.py installed anything at scale 1.0, B must be stochastically LARGER than A. + +Reads only `cands`. NO ruler (`margin`, `cand_dir_mm` never touched) and NO coverage number. +""" +import glob, json +from pathlib import Path +import numpy as np + +ROOT = "/proj/dmfexp/zwhong/rsm_rise" +REP, PUB, T10 = "pt_cov_sn1_knn0p03_REP1", "pt_cov_sn1_knn0p03", "pt_cov_sn1_knn0p03_T10" +RNG = np.random.default_rng(90210) +NBOOT = 2000 + + +def load(tag): + out = {} + for f in sorted(glob.glob(f"{ROOT}/status/real/{tag}/parts/*.npz")): + z = np.load(f, allow_pickle=True) + if not json.loads(bytes(z["__meta__"]).decode()).get("n_anchors", 0) or "cands" not in z.files: + continue + out[Path(f).name] = np.asarray(z["cands"]).astype(np.float64) + return out + + +def disp_mm(c): + return np.linalg.norm(c[..., -1, :3] - c[..., 0, :3], axis=-1) * 1000.0 + + +c = {t: load(t) for t in (REP, PUB, T10)} +KEYS = sorted(set(c[REP]) & set(c[PUB]) & set(c[T10])) +print(f"[equiv] matched episodes = {[k[:8] for k in KEYS]}") + +# per-anchor statistics for each contrast +def per_anchor(x, y): + raw_p99, raw_med, mm_p99, zero = [], [], [], [] + ep_of = [] + for k in KEYS: + a, b = x[k], y[k] + d = np.abs(a - b) # (n_anchor, n_cand, T, D) + dm = np.abs(disp_mm(a) - disp_mm(b)) # (n_anchor, n_cand) + for i in range(d.shape[0]): + f = d[i].ravel() + raw_p99.append(np.percentile(f, 99)); raw_med.append(np.median(f)) + zero.append((f == 0.0).mean()) + mm_p99.append(np.percentile(dm[i].ravel(), 99)) + ep_of.append(k) + return (np.array(raw_p99), np.array(raw_med), np.array(mm_p99), np.array(zero), np.array(ep_of)) + +A = per_anchor(c[T10], c[REP]) +B = per_anchor(c[T10], c[PUB]) +C = per_anchor(c[REP], c[PUB]) +names = ["raw_p99", "raw_med", "mm_p99", "frac_exact_zero"] +print("\n[equiv] === per-anchor means (n_anchor = %d) ===" % len(A[0])) +for j, nm in enumerate(names): + print(f"[equiv] {nm:16s} A(T10-REP, cross-host same code)={A[j].mean():.6e} " + f"B(T10-PUB)={B[j].mean():.6e} C(REP-PUB)={C[j].mean():.6e}") + +print("\n[equiv] === STRUCTURAL: host clustering ===") +print(f"[equiv] frac of elements bit-identical: A={A[3].mean():.4f} B={B[3].mean():.4f} C={C[3].mean():.4f}") +print(f"[equiv] (C >> A,B would say REP and PUB share a host class, which is what H_host predicts)") + +out = {"n_anchor": int(len(A[0])), "n_ep": len(KEYS), "episodes": [k[:8] for k in KEYS]} +print("\n[equiv] === PAIRED per-anchor difference B - A, anchor bootstrap (%d draws) ===" % NBOOT) +n = len(A[0]); res = {} +for j, nm in enumerate(names[:3]): + d = B[j] - A[j] + idx = RNG.integers(0, n, size=(NBOOT, n)) + bs = d[idx].mean(axis=1) + lo, hi = np.percentile(bs, [2.5, 97.5]) + contains0 = bool(lo <= 0.0 <= hi) + print(f"[equiv] {nm:8s}: mean(B-A)={d.mean():+.4e} CI95=[{lo:+.4e}, {hi:+.4e}] " + f"contains0={contains0} (A mean {A[j].mean():.4e})") + res[nm] = dict(mean_diff=float(d.mean()), lo=float(lo), hi=float(hi), contains0=contains0) +out["paired"] = res + +sign = float((B[0] > A[0]).mean()) +idx = RNG.integers(0, n, size=(NBOOT, n)) +sb = (B[0] > A[0])[idx].mean(axis=1) +slo, shi = np.percentile(sb, [2.5, 97.5]) +print(f"[equiv] sign test: frac anchors with B>A = {sign:.4f} CI95=[{slo:.4f}, {shi:.4f}] " + f"(0.5 under equivalence)") +out["sign"] = dict(frac=sign, lo=float(slo), hi=float(shi)) + +# episode-level bootstrap, reported with its limitation stated +print(f"\n[equiv] episode-level bootstrap is UNDERPOWERED at n_ep = {len(KEYS)} and is reported as such:") +for j, nm in enumerate(names[:3]): + per_ep = [float((B[j][B[4] == k] - A[j][A[4] == k]).mean()) for k in KEYS] + print(f"[equiv] {nm:8s}: per-episode mean(B-A) = {['%+.3e' % v for v in per_ep]}") + out.setdefault("per_episode", {})[nm] = per_ep + +print("\n[equiv] === VERDICT (branches fixed before the number was read) ===") +all0 = all(res[nm]["contains0"] for nm in names[:3]) +signok = bool(0.45 <= sign <= 0.55) +struct = bool(C[3].mean() > A[3].mean() and C[3].mean() > B[3].mean()) +print(f"[equiv] all three paired CIs contain 0 : {all0}") +print(f"[equiv] sign fraction within [0.45,0.55]: {signok} ({sign:.4f})") +print(f"[equiv] structural host clustering C>A,B: {struct}") +if all0 and signok and struct: + v = ("EQUIVALENT -- the base rung's divergence from the published cell is indistinguishable from the " + "pure cross-host floor measured with identical code, on all three limbs plus the sign test plus " + "the structural check. No residual code component. The run-42 caches are READABLE as run-45 rungs.") +elif any(res[nm]["lo"] > 0 for nm in names[:3]): + v = ("RESIDUAL -- B is significantly LARGER than the pure cross-host floor on at least one limb, so " + "pt_proposer_temp.py contributes a divergence beyond the host. Caches stay VOID.") +else: + v = (f"INCONCLUSIVE -- CIs contain 0 ({all0}) but sign ({signok}) or structural ({struct}) check did " + f"not hold. Neither branch applies; reported as such rather than resolved by picking one.") +print(f"[equiv] {v}") +out["verdict"] = v +json.dump(out, open(f"{ROOT}/status/real/pt_r45_equiv.json", "w"), indent=1, default=str) +print("[equiv] wrote status/real/pt_r45_equiv.json") diff --git a/rsm_rise/scripts/real/pt_floor_equiv.sh b/rsm_rise/scripts/real/pt_floor_equiv.sh new file mode 100644 index 0000000000000000000000000000000000000000..f944a3483ed2c4bd10418bf4f7a6b19671fae2b8 --- /dev/null +++ b/rsm_rise/scripts/real/pt_floor_equiv.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +set -uo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +export MUJOCO_GL=disable +/proj/dmfexp/zwhong/rsm_rise/venv_rsm/bin/python scripts/real/pt_floor_equiv.py diff --git a/rsm_rise/scripts/real/pt_floor_host.py b/rsm_rise/scripts/real/pt_floor_host.py new file mode 100644 index 0000000000000000000000000000000000000000..b03ee4dd197209363698438cc17b36cc12b6f110 --- /dev/null +++ b/rsm_rise/scripts/real/pt_floor_host.py @@ -0,0 +1,152 @@ +#!/usr/bin/env python +"""PROPOSAL_TEST run 44 -- DISCRIMINATOR: is the run-43 KILL a CODE DEFECT or a PER-HOST determinism floor? + +Run 43's pre-registered KILL fired literally: the four scale-1.0 replicates (LSF 1906024) are bit-identical +to EACH OTHER (6/6 pairs, max|delta| = 0.0, 183 anchors) while every one of them differs from the published +cell `pt_cov_sn1_knn0p03` by the SAME delta (p99 1.654e-03, max 6.041e-02, mm p99 0.8387). + +BUT THAT KILL WAS CONFOUNDED BY CONSTRUCTION, AND THE CONFOUND IS MINE. All four replicates were payloads +of ONE 4-GPU pack and therefore ran on ONE node (p5-r16-n2), same GPU model, same driver, same process +image. "Bit-identical to each other" therefore cannot separate + + H_code : pt_proposer_temp.py changes the computation at scale 1.0, where it installs nothing + H_host : the computation is exactly deterministic WITHIN a host and differs ACROSS hosts + +because the replicates never crossed a host boundary. The published cell ran elsewhere. + +THE DISCRIMINATOR, and it needs no new GPU work. Rung `_T10` is the SAME script at the SAME scale 1.0 with +the SAME seed and config, and it ran on a DIFFERENT node (p6-r29-n2, LSF 1905660). It shares episode +ep000105 with the replicates. So: + + * T10 == REP bit-exactly -> every run of pt_proposer_temp.py agrees regardless of host, and only the + published cell differs. H_code. The KILL STANDS: the ladder is wrong at its base and no rung may be + read until pt_proposer_temp.py is fixed. + * T10 != REP -> two runs of IDENTICAL code at scale 1.0 diverge across hosts while agreeing + within a host. H_host. The KILL's premise is confounded and a code defect is NOT established by it; + the divergence is a per-host determinism floor and the reproduction bar must be built from a + CROSS-HOST floor, which the replicate pack could not measure. + +Pre-registered before the number was read. Reads only `cands`. NO ruler (`margin`, `cand_dir_mm` never +touched) and NO coverage number, so this job cannot see any rung result. +""" +import glob, itertools, json +from pathlib import Path +import numpy as np + +ROOT = "/proj/dmfexp/zwhong/rsm_rise" +REPS = [f"pt_cov_sn1_knn0p03_REP{i}" for i in (1, 2, 3, 4)] +PUB = "pt_cov_sn1_knn0p03" +T10 = "pt_cov_sn1_knn0p03_T10" +HOST = {**{r: "p5-r16-n2 (LSF 1906024)" for r in REPS}, + T10: "p6-r29-n2 (LSF 1905660)", PUB: "published cell, host not recorded"} + + +def load(tag): + out = {} + for f in sorted(glob.glob(f"{ROOT}/status/real/{tag}/parts/*.npz")): + z = np.load(f, allow_pickle=True) + meta = json.loads(bytes(z["__meta__"]).decode()) + if not meta.get("n_anchors", 0) or "cands" not in z.files: + continue + out[Path(f).name] = np.asarray(z["cands"]).astype(np.float64) + return out + + +def disp_mm(c): + return np.linalg.norm(c[..., -1, :3] - c[..., 0, :3], axis=-1) * 1000.0 + + +def compare(a, b): + shared = sorted(set(a) & set(b)) + ds, dd, corr, nan, eps = [], [], [], 0, [] + for k in shared: + if a[k].shape != b[k].shape: + continue + eps.append(k) + ds.append(np.abs(a[k] - b[k]).ravel()) + dd.append(np.abs(disp_mm(a[k]) - disp_mm(b[k])).ravel()) + x, y = a[k].ravel(), b[k].ravel() + corr.append(float(np.corrcoef(x, y)[0, 1])) + nan += a[k].shape[0] + if not ds: + return None + ds = np.concatenate(ds); dd = np.concatenate(dd) + return dict(eps=eps, n_ep=len(eps), n_anchor=nan, + med=float(np.median(ds)), p99=float(np.percentile(ds, 99)), max=float(ds.max()), + mm_med=float(np.median(dd)), mm_p99=float(np.percentile(dd, 99)), mm_max=float(dd.max()), + corr=float(np.min(corr)), exact_zero=bool(ds.max() == 0.0)) + + +def row(label, r): + if r is None: + print(f"[host] {label:34s}: NO SHARED ANCHORED EPISODE -- undefined"); return + print(f"[host] {label:34s}: ep={r['n_ep']} ({','.join(e[:8] for e in r['eps'])}) anch={r['n_anchor']:4d} " + f"med={r['med']:.3e} p99={r['p99']:.3e} max={r['max']:.3e} | mm med={r['mm_med']:.4f} " + f"p99={r['mm_p99']:.4f} max={r['mm_max']:.4f} | corr={r['corr']:.9f} | exact-zero={r['exact_zero']}") + + +cache = {t: load(t) for t in REPS + [PUB, T10]} +print("[host] provenance:") +for t in REPS + [T10, PUB]: + print(f"[host] {t:32s} {len(cache[t]):2d} anchored ep host={HOST[t]}") + +out = {} +print("\n[host] === WITHIN host: replicate vs replicate (all on p5-r16-n2) ===") +within = [] +for x, y in itertools.combinations(REPS, 2): + r = compare(cache[x], cache[y]); row(f"{x[-4:]} vs {y[-4:]}", r) + if r: within.append(r) +out["within_host"] = within + +print("\n[host] === ACROSS hosts: T10 (p6-r29-n2) vs each replicate (p5-r16-n2), SAME CODE SAME SCALE ===") +across = [] +for x in REPS: + r = compare(cache[T10], cache[x]); row(f"T10 vs {x[-4:]}", r) + if r: across.append(r) +out["across_host_same_code"] = across + +print("\n[host] === each against the published cell ===") +vs_pub = {} +for x in REPS + [T10]: + r = compare(cache[x], cache[PUB]); row(f"{x[-4:] if x != T10 else 'T10 '} vs PUB", r) + vs_pub[x] = r +out["vs_published"] = vs_pub + +print("\n[host] === VERDICT (branches fixed before the number was read) ===") +n_w = len(within); n_w_zero = sum(r["exact_zero"] for r in within) +n_a = len(across); n_a_zero = sum(r["exact_zero"] for r in across) +print(f"[host] within-host pairs exact-zero: {n_w_zero}/{n_w}") +print(f"[host] across-host pairs exact-zero: {n_a_zero}/{n_a}") +if n_a == 0: + v = "UNDEFINED -- T10 shares no anchored episode with any replicate; the discriminator cannot run." +elif n_a_zero == n_a and n_w_zero == n_w: + v = ("H_code -- every run of pt_proposer_temp.py agrees bit-exactly ACROSS hosts, and only the " + "published cell differs. The run-43 KILL STANDS: pt_proposer_temp.py changes the computation " + "at scale 1.0 where it installs nothing. CODE DEFECT; no rung may be read until it is fixed.") +elif n_w_zero == n_w and n_a_zero == 0: + v = ("H_host -- identical code at scale 1.0 is bit-exact WITHIN a host and diverges ACROSS hosts. " + "The run-43 KILL's premise is CONFOUNDED by co-location of the four replicates and a code defect " + "is NOT established by it. The reproduction bar must be built from a CROSS-HOST floor, which " + "the replicate pack could not measure.") +else: + v = (f"MIXED -- within {n_w_zero}/{n_w} exact, across {n_a_zero}/{n_a} exact. Neither pre-registered " + f"branch applies cleanly; reported as such rather than resolved by picking one.") +print(f"[host] {v}") +out["verdict"] = v + +if across: + bar = max(r["p99"] for r in across); bar_mm = max(r["mm_p99"] for r in across) + print(f"\n[host] CROSS-HOST FLOOR (max p99 over T10-vs-replicate pairs): {bar:.3e} raw, {bar_mm:.4f} mm") + print(f"[host] cross-host median mm divergence: " + f"{np.median([r['mm_med'] for r in across]):.4f} mm") + out["cross_host_floor"] = dict(p99=bar, mm_p99=bar_mm, + mm_med=float(np.median([r["mm_med"] for r in across]))) + rp = vs_pub[REPS[0]] + if rp: + print(f"[host] for scale: REP-vs-PUB p99 = {rp['p99']:.3e} ({rp['mm_p99']:.4f} mm); " + f"same order as the cross-host floor? " + f"{'YES' if rp['p99'] <= 10 * bar else 'NO'}") + out["cross_host_floor"]["pub_same_order"] = bool(rp["p99"] <= 10 * bar) + +json.dump(out, open(f"{ROOT}/status/real/pt_r44_host.json", "w"), indent=1, default=str) +print("[host] wrote status/real/pt_r44_host.json") diff --git a/rsm_rise/scripts/real/pt_floor_host.sh b/rsm_rise/scripts/real/pt_floor_host.sh new file mode 100644 index 0000000000000000000000000000000000000000..7dccb864f322aad4cc093f05e3b1a29dae12fb43 --- /dev/null +++ b/rsm_rise/scripts/real/pt_floor_host.sh @@ -0,0 +1,7 @@ +#!/usr/bin/env bash +set -uo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +export MUJOCO_GL=disable +echo "[host-run] start $(date)" +/proj/dmfexp/zwhong/rsm_rise/venv_rsm/bin/python scripts/real/pt_floor_host.py +echo "[host-run] exit=$? $(date)" diff --git a/rsm_rise/scripts/real/pt_floor_matched.py b/rsm_rise/scripts/real/pt_floor_matched.py new file mode 100644 index 0000000000000000000000000000000000000000..6d9e536d417bdbdfcab64ecd1392c060134f5948 --- /dev/null +++ b/rsm_rise/scripts/real/pt_floor_matched.py @@ -0,0 +1,91 @@ +#!/usr/bin/env python +"""PROPOSAL_TEST run 45 -- apply the CROSS-HOST reproduction bar on MATCHED ANCHORS. + +Run 44's pre-registration said: if H_host, "the reproduction bar must be rebuilt from a CROSS-HOST floor +... and the cross-host floor measured here becomes that bar." H_host is what the discriminator found +(LSF 1907327: within-host 6/6 exact-zero, across-host 0/4). But that pre-registration was SILENT on anchor +matching, and the two sides of the comparison as printed do not use the same anchors: + + cross-host FLOOR (T10 vs REP) : 2 episodes / 183 anchors p99 = 2.895e-03 + the rung reading (T10 vs PUB) : 15 episodes / 1043 anchors p99 = 3.132e-03 + +A p99 over a 5.7x larger and more diverse anchor set reaches higher for reasons that have nothing to do with +reproduction, so comparing those two numbers is not a matched test. This script computes BOTH readings on +the SAME anchors. The bar is unchanged; only the anchor sets are aligned. Reads only `cands`: NO ruler +(`margin`, `cand_dir_mm` never touched) and NO coverage number. +""" +import glob, itertools, json +from pathlib import Path +import numpy as np + +ROOT = "/proj/dmfexp/zwhong/rsm_rise" +REPS = [f"pt_cov_sn1_knn0p03_REP{i}" for i in (1, 2, 3, 4)] +PUB, T10 = "pt_cov_sn1_knn0p03", "pt_cov_sn1_knn0p03_T10" + + +def load(tag): + out = {} + for f in sorted(glob.glob(f"{ROOT}/status/real/{tag}/parts/*.npz")): + z = np.load(f, allow_pickle=True) + meta = json.loads(bytes(z["__meta__"]).decode()) + if not meta.get("n_anchors", 0) or "cands" not in z.files: + continue + out[Path(f).name] = np.asarray(z["cands"]).astype(np.float64) + return out + + +def disp_mm(c): + return np.linalg.norm(c[..., -1, :3] - c[..., 0, :3], axis=-1) * 1000.0 + + +def compare(a, b, keys): + ds, dd, n = [], [], 0 + eps = [] + for k in sorted(keys): + if k not in a or k not in b or a[k].shape != b[k].shape: + continue + eps.append(k); n += a[k].shape[0] + ds.append(np.abs(a[k] - b[k]).ravel()) + dd.append(np.abs(disp_mm(a[k]) - disp_mm(b[k])).ravel()) + if not ds: + return None + ds = np.concatenate(ds); dd = np.concatenate(dd) + return dict(n_ep=len(eps), n_anchor=n, eps=[e[:8] for e in eps], + med=float(np.median(ds)), p99=float(np.percentile(ds, 99)), max=float(ds.max()), + mm_med=float(np.median(dd)), mm_p99=float(np.percentile(dd, 99)), mm_max=float(dd.max()), + exact_zero=bool(ds.max() == 0.0)) + + +cache = {t: load(t) for t in REPS + [PUB, T10]} +# the matched anchor set is exactly what the FLOOR could be measured on +MATCHED = set(cache[REPS[0]]) & set(cache[T10]) & set(cache[PUB]) +print(f"[matched] matched anchor set = {sorted(e[:8] for e in MATCHED)}") + +rows = {} +rows["floor_cross_host_T10_vs_REP"] = compare(cache[T10], cache[REPS[0]], MATCHED) +rows["rung_T10_vs_PUB_matched"] = compare(cache[T10], cache[PUB], MATCHED) +rows["REP_vs_PUB_matched"] = compare(cache[REPS[0]], cache[PUB], MATCHED) +rows["rung_T10_vs_PUB_ALL_eps_unmatched"] = compare(cache[T10], cache[PUB], set(cache[T10]) & set(cache[PUB])) + +for k, r in rows.items(): + if r is None: + print(f"[matched] {k:38s}: UNDEFINED"); continue + print(f"[matched] {k:38s}: ep={r['n_ep']:2d} anch={r['n_anchor']:4d} med={r['med']:.3e} " + f"p99={r['p99']:.3e} max={r['max']:.3e} | mm med={r['mm_med']:.4f} p99={r['mm_p99']:.4f}") + +f, g = rows["floor_cross_host_T10_vs_REP"], rows["rung_T10_vs_PUB_matched"] +print("\n[matched] === GUARD, bar = cross-host floor p99 on the SAME anchors ===") +print(f"[matched] bar (floor p99) : {f['p99']:.3e} raw | {f['mm_p99']:.4f} mm") +print(f"[matched] rung T10 vs PUB : {g['p99']:.3e} raw | {g['mm_p99']:.4f} mm") +ok_raw, ok_mm = g["p99"] <= f["p99"], g["mm_p99"] <= f["mm_p99"] +print(f"[matched] raw {'PASS' if ok_raw else 'FAIL'} ({g['p99']/f['p99']:.3f}x) " + f"mm {'PASS' if ok_mm else 'FAIL'} ({g['mm_p99']/f['mm_p99']:.3f}x)") +verdict = "PASS" if (ok_raw and ok_mm) else "FAIL" +print(f"[matched] MATCHED GUARD: {verdict}") +u = rows["rung_T10_vs_PUB_ALL_eps_unmatched"] +print(f"[matched] (unmatched reading, reported not used: {u['p99']:.3e} raw / {u['mm_p99']:.4f} mm over " + f"{u['n_ep']} ep / {u['n_anchor']} anchors = {u['p99']/f['p99']:.3f}x the bar)") +json.dump(dict(rows=rows, bar=dict(p99=f["p99"], mm_p99=f["mm_p99"]), verdict=verdict, + ok_raw=bool(ok_raw), ok_mm=bool(ok_mm)), + open(f"{ROOT}/status/real/pt_r45_matched.json", "w"), indent=1, default=str) +print("[matched] wrote status/real/pt_r45_matched.json") diff --git a/rsm_rise/scripts/real/pt_floor_matched.sh b/rsm_rise/scripts/real/pt_floor_matched.sh new file mode 100644 index 0000000000000000000000000000000000000000..cab747cbf6f41fa6e31cde4cc46a1c5b770997bb --- /dev/null +++ b/rsm_rise/scripts/real/pt_floor_matched.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +set -uo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +export MUJOCO_GL=disable +/proj/dmfexp/zwhong/rsm_rise/venv_rsm/bin/python scripts/real/pt_floor_matched.py diff --git a/rsm_rise/scripts/real/pt_gate_r46.sh b/rsm_rise/scripts/real/pt_gate_r46.sh new file mode 100644 index 0000000000000000000000000000000000000000..79bbd67f9bf810dae41fa42091098d72951510ee --- /dev/null +++ b/rsm_rise/scripts/real/pt_gate_r46.sh @@ -0,0 +1,18 @@ +#!/usr/bin/env bash +# PROPOSAL_TEST run 47 -- STEP (iii) of the pre-registered read order (5825155807 / 5825156755): +# the GATE RATE per rung of the R46 fine ladder. Instrument is pt_spread_required.py, UNEDITED except for +# the backwards-compatible PT_RULER_FROM override, and already self-validated in run 46: at K=1 it +# reproduces the published cell's margin to 1.3e-07 and its gate rate exactly. A rung's own gate rate is +# therefore its K=1 row. The in-wave scale-1.00 rung (T10) is the MATCHED baseline and also re-derives the +# requirement curve on exactly these anchors, so the prediction check needs no cross-anchor comparison. +set -uo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +export MUJOCO_GL=disable OMP_NUM_THREADS=8 MKL_NUM_THREADS=8 OPENBLAS_NUM_THREADS=8 +PUB=/proj/dmfexp/zwhong/rsm_rise/status/real/pt_cov_sn1_knn0p03 +for t in T10 F105 F110 F115 F120 F125 F130 F140; do + echo "############################## rung $t" + PT_CELL=/proj/dmfexp/zwhong/rsm_rise/status/real/pt_R46_cov_sn1_knn0p03_$t \ + PT_RULER_FROM=$PUB \ + PT_OUT=/proj/dmfexp/zwhong/rsm_rise/status/real/pt_r47_req_$t.json \ + venv_rsm/bin/python scripts/real/pt_spread_required.py +done diff --git a/rsm_rise/scripts/real/pt_gen_readout.sh b/rsm_rise/scripts/real/pt_gen_readout.sh new file mode 100644 index 0000000000000000000000000000000000000000..d2222bf7f8487269de197aada938580af176a5d2 --- /dev/null +++ b/rsm_rise/scripts/real/pt_gen_readout.sh @@ -0,0 +1,35 @@ +#!/usr/bin/env bash +# gen_q#280 phase 2, axis = READ-OUT. Generates one payload per read-out cell for a FIXED reward head +# (chosen by the head axis, passed in), all re-scoring the SAME cached draws, so two cells differ only by +# the one knob named in their filename. ONE CHANGE PER MEASUREMENT. +# usage: pt_gen_readout.sh [cands-from-cell] +# The grid, with the default in brackets: +# beta 0.9 0.95 [0.99] 0.999 gamma 0.99 [0.999] 0.9999 +# beta==gamma the DEGENERATE negative control the spec asks for (0.999/0.999) +# particles 4 [16] 64 score-kind [prob] logit +# mode [chain] (with the hop head) vs d1 (depth 1, no hop) -- rsm_scorer _MODES = d1/fold/recursive/chain/... +set -euo pipefail +TAG=${1:?head tag}; CK=${2:?head ckpt}; FROM=${3:-cov_sn1_knn0p03} +PL=/proj/dmfexp/zwhong/rsm_rise/scripts/real/payloads +POL="openpi:pi05_cooking_sn1_knn0p03:/proj/dmfexp/zwhong/rsm_rise/runs/openpi/checkpoints/pi05_cooking_sn1_knn0p03/ws_s0/9999" +emit () { # emit + local cell=$1; shift + { echo '#!/usr/bin/env bash' + echo "# gen_q#280 phase 2 read-out cell '$cell' on head $TAG ($CK), cached draws from pt_$FROM." + echo 'set -uo pipefail' + echo "PT_CANDS_FROM=$FROM PT_NAME=ro_${TAG}_${cell} PT_RSM=\"$CK\" PT_POLICY=\"$POL\" $* \\" + echo ' exec /proj/dmfexp/zwhong/rsm_rise/scripts/real/proposal_screen.sh ${1:-0} ${2:-1}' + } > "$PL/pt_ro_${TAG}_${cell}.sh" + chmod +x "$PL/pt_ro_${TAG}_${cell}.sh"; echo "pt_ro_${TAG}_${cell}.sh" +} +emit default # beta .99 gamma .999 p16 prob chain +emit b0p9 PT_BETA=0.9 +emit b0p95 PT_BETA=0.95 +emit b0p999 PT_BETA=0.999 +emit g0p99 PT_GAMMA=0.99 +emit g0p9999 PT_GAMMA=0.9999 +emit bEQg PT_BETA=0.999 PT_GAMMA=0.999 # DEGENERATE negative control +emit p4 PT_PARTICLES=4 +emit p64 PT_PARTICLES=64 +emit logit PT_SCOREKIND=logit +emit d1 PT_MODE=d1 PT_DEPTH=1 # depth 1, no hop head (rsm_scorer _MODES) diff --git a/rsm_rise/scripts/real/pt_inert.py b/rsm_rise/scripts/real/pt_inert.py new file mode 100644 index 0000000000000000000000000000000000000000..adc4d2d06a6c8059d484b4f079148387295268f5 --- /dev/null +++ b/rsm_rise/scripts/real/pt_inert.py @@ -0,0 +1,105 @@ +#!/usr/bin/env python +"""PROPOSAL_TEST run 45d -- IS THE NOISE-SCALE LADDER INERT? A mechanical check of a code reading. + +Read from the source, not inferred statistically: + * pt_proposer_temp.py installs `_ScaledNormal` on `self.rng` in TempOpenpiPolicy.__init__ (once, at + construction) and prints "wrapper INSTALLED". + * proposal_test.py:274, INSIDE the per-episode loop, does + if pol is not None and hasattr(pol, "rng"): pol.rng = np.random.default_rng([a.seed, ep]) + which REPLACES pol.rng with a plain Generator and so DESTROYS the wrapper before the first measured + anchor of the first episode. + +If that reading is right the ladder is INERT and the scale knob never reached the sampler. The prediction is +mechanically forced, not statistical: rungs that ran on the SAME HOST must be BIT-IDENTICAL to each other. + p6-r29-n2 (LSF 1905660): T10 T15 T20 T25 (scales 1.0 1.5 2.0 2.5) + p2-r13-n2 (LSF 1905661): T30 T40 T60 T80 (scales 3.0 4.0 6.0 8.0) + + INERT : within-host rung pairs max|delta| == 0.0 AND mean displacement flat in the scale. + WORKING: displacement grows with the scale and the pairs differ. + +Reads only `cands`. NO ruler (`margin`, `cand_dir_mm` never touched) and NO coverage number. +""" +import glob, itertools, json +from pathlib import Path +import numpy as np + +ROOT = "/proj/dmfexp/zwhong/rsm_rise" +PACK = {"p6-r29-n2 (LSF 1905660)": [("T10", 1.0), ("T15", 1.5), ("T20", 2.0), ("T25", 2.5)], + "p2-r13-n2 (LSF 1905661)": [("T30", 3.0), ("T40", 4.0), ("T60", 6.0), ("T80", 8.0)]} + + +def load(tag): + out = {} + for f in sorted(glob.glob(f"{ROOT}/status/real/pt_cov_sn1_knn0p03_{tag}/parts/*.npz")): + z = np.load(f, allow_pickle=True) + if not json.loads(bytes(z["__meta__"]).decode()).get("n_anchors", 0) or "cands" not in z.files: + continue + out[Path(f).name] = np.asarray(z["cands"]).astype(np.float64) + return out + + +def disp_mm(c): + return np.linalg.norm(c[..., -1, :3] - c[..., 0, :3], axis=-1) * 1000.0 + + +tags = [t for v in PACK.values() for t, _ in v] +cache = {t: load(t) for t in tags} +out = {} + +print("[inert] === mean candidate displacement per rung (mm) ===") +disp = {} +for host, rungs in PACK.items(): + for t, s in rungs: + if not cache[t]: + print(f"[inert] {t} scale={s}: NO CACHE"); continue + d = np.concatenate([disp_mm(v).ravel() for v in cache[t].values()]) + disp[t] = (s, float(d.mean()), float(np.median(d)), len(cache[t]), int(d.size)) + print(f"[inert] {t} scale={s:4.1f} host={host:24s} mean={d.mean():8.4f} med={np.median(d):8.4f}" + f" ep={len(cache[t]):2d} n={d.size}") +out["disp"] = disp + +print("\n[inert] === WITHIN-HOST rung pairs (the mechanically forced check) ===") +verdict_bits = [] +for host, rungs in PACK.items(): + print(f"[inert] -- {host}") + for (a, sa), (b, sb) in itertools.combinations(rungs, 2): + keys = sorted(set(cache[a]) & set(cache[b])) + ds, n = [], 0 + for k in keys: + if cache[a][k].shape != cache[b][k].shape: + continue + ds.append(np.abs(cache[a][k] - cache[b][k]).ravel()); n += cache[a][k].shape[0] + if not ds: + print(f"[inert] {a} vs {b}: NO SHARED EPISODE"); continue + ds = np.concatenate(ds) + ez = bool(ds.max() == 0.0) + verdict_bits.append(ez) + print(f"[inert] {a}(s={sa}) vs {b}(s={sb}): ep={len(keys)} anch={n:4d} " + f"max|delta|={ds.max():.3e} med={np.median(ds):.3e} BIT-IDENTICAL={ez}") + out.setdefault("pairs", []).append(dict(a=a, b=b, scale_a=sa, scale_b=sb, host=host, + n_ep=len(keys), n_anchor=n, max=float(ds.max()), + bit_identical=ez)) + +print("\n[inert] === VERDICT ===") +allbit = bool(verdict_bits) and all(verdict_bits) +if disp: + ss = np.array([v[0] for v in disp.values()]); mm = np.array([v[1] for v in disp.values()]) + spread = float(mm.max() - mm.min()) + corr = float(np.corrcoef(ss, mm)[0, 1]) if len(set(ss.tolist())) > 1 else float("nan") + print(f"[inert] displacement spread across scales 1.0..8.0 = {spread:.4f} mm; corr(scale, mean disp) = {corr:.4f}") + out["disp_spread_mm"], out["corr_scale_disp"] = spread, corr +print(f"[inert] within-host pairs bit-identical: {sum(verdict_bits)}/{len(verdict_bits)}") +if allbit: + v = ("INERT -- every within-host rung pair is BIT-IDENTICAL across scales 1.0..2.5 and 3.0..8.0. The " + "scale knob never reached the sampler: proposal_test.py:274 overwrites pol.rng per episode and " + "destroys the _ScaledNormal wrapper. CODE DEFECT, confirmed empirically. The whole run-42 ladder " + "measured ONE setting eight times and is VOID for this reason, independent of the floor guards.") +elif not any(verdict_bits): + v = ("WORKING -- no within-host rung pair is bit-identical, so the scale knob did reach the sampler and " + "the inertness reading is WRONG.") +else: + v = f"MIXED -- {sum(verdict_bits)}/{len(verdict_bits)} pairs bit-identical. Reported as such." +print(f"[inert] {v}") +out["verdict"] = v +json.dump(out, open(f"{ROOT}/status/real/pt_r45_inert.json", "w"), indent=1, default=str) +print("[inert] wrote status/real/pt_r45_inert.json") diff --git a/rsm_rise/scripts/real/pt_inert.sh b/rsm_rise/scripts/real/pt_inert.sh new file mode 100644 index 0000000000000000000000000000000000000000..bcb8cc4cc63c9065dd6a76f29df7f7d4d6906803 --- /dev/null +++ b/rsm_rise/scripts/real/pt_inert.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +set -uo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +export MUJOCO_GL=disable +/proj/dmfexp/zwhong/rsm_rise/venv_rsm/bin/python scripts/real/pt_inert.py diff --git a/rsm_rise/scripts/real/pt_inert_r45.py b/rsm_rise/scripts/real/pt_inert_r45.py new file mode 100644 index 0000000000000000000000000000000000000000..d271765c966a4073140f0e52b45e7cd3e9b5a7e8 --- /dev/null +++ b/rsm_rise/scripts/real/pt_inert_r45.py @@ -0,0 +1,109 @@ +#!/usr/bin/env python +"""PROPOSAL_TEST run 45d -- IS THE NOISE-SCALE LADDER INERT? A mechanical check of a code reading. + +Read from the source, not inferred statistically: + * pt_proposer_temp.py installs `_ScaledNormal` on `self.rng` in TempOpenpiPolicy.__init__ (once, at + construction) and prints "wrapper INSTALLED". + * proposal_test.py:274, INSIDE the per-episode loop, does + if pol is not None and hasattr(pol, "rng"): pol.rng = np.random.default_rng([a.seed, ep]) + which REPLACES pol.rng with a plain Generator and so DESTROYS the wrapper before the first measured + anchor of the first episode. + +If that reading is right the ladder is INERT and the scale knob never reached the sampler. The prediction is +mechanically forced, not statistical: rungs that ran on the SAME DEVICE must be bit-identical; same-host is NOT sufficient (one payload per GPU), so that limb is reported, not used. + pack p4a (rr_pt45ladder_p4a): T10 T15 T20 T25 (scales 1.0 1.5 2.0 2.5) + pack p4b (rr_pt45ladder_p4b): T30 T40 T60 T80 (scales 3.0 4.0 6.0 8.0) + + INERT : within-host rung pairs max|delta| == 0.0 AND mean displacement flat in the scale. + WORKING: displacement grows with the scale and the pairs differ. + +Reads only `cands`. NO ruler (`margin`, `cand_dir_mm` never touched) and NO coverage number. +""" +import glob, itertools, json +from pathlib import Path +import numpy as np + +ROOT = "/proj/dmfexp/zwhong/rsm_rise" +# run-45 corrected ladder: hosts are NOT the run-42 ones and are resolved from the job at read time, so +# they are left unlabelled here rather than carrying a stale attribution forward. The INERTNESS GUARD +# only needs the displacement column; the bit-exactness limb was MIS-SPECIFIED in run 45 (same host is +# not same device -- the pack puts one payload per GPU) and is reported but NOT used as a discriminator. +PACK = {"pack p4a (rr_pt45ladder_p4a)": [("T10", 1.0), ("T15", 1.5), ("T20", 2.0), ("T25", 2.5)], + "pack p4b (rr_pt45ladder_p4b)": [("T30", 3.0), ("T40", 4.0), ("T60", 6.0), ("T80", 8.0)]} + + +def load(tag): + out = {} + for f in sorted(glob.glob(f"{ROOT}/status/real/pt_R45_cov_sn1_knn0p03_{tag}/parts/*.npz")): + z = np.load(f, allow_pickle=True) + if not json.loads(bytes(z["__meta__"]).decode()).get("n_anchors", 0) or "cands" not in z.files: + continue + out[Path(f).name] = np.asarray(z["cands"]).astype(np.float64) + return out + + +def disp_mm(c): + return np.linalg.norm(c[..., -1, :3] - c[..., 0, :3], axis=-1) * 1000.0 + + +tags = [t for v in PACK.values() for t, _ in v] +cache = {t: load(t) for t in tags} +out = {} + +print("[inert] === mean candidate displacement per rung (mm) ===") +disp = {} +for host, rungs in PACK.items(): + for t, s in rungs: + if not cache[t]: + print(f"[inert] {t} scale={s}: NO CACHE"); continue + d = np.concatenate([disp_mm(v).ravel() for v in cache[t].values()]) + disp[t] = (s, float(d.mean()), float(np.median(d)), len(cache[t]), int(d.size)) + print(f"[inert] {t} scale={s:4.1f} host={host:24s} mean={d.mean():8.4f} med={np.median(d):8.4f}" + f" ep={len(cache[t]):2d} n={d.size}") +out["disp"] = disp + +print("\n[inert] === WITHIN-HOST rung pairs (the mechanically forced check) ===") +verdict_bits = [] +for host, rungs in PACK.items(): + print(f"[inert] -- {host}") + for (a, sa), (b, sb) in itertools.combinations(rungs, 2): + keys = sorted(set(cache[a]) & set(cache[b])) + ds, n = [], 0 + for k in keys: + if cache[a][k].shape != cache[b][k].shape: + continue + ds.append(np.abs(cache[a][k] - cache[b][k]).ravel()); n += cache[a][k].shape[0] + if not ds: + print(f"[inert] {a} vs {b}: NO SHARED EPISODE"); continue + ds = np.concatenate(ds) + ez = bool(ds.max() == 0.0) + verdict_bits.append(ez) + print(f"[inert] {a}(s={sa}) vs {b}(s={sb}): ep={len(keys)} anch={n:4d} " + f"max|delta|={ds.max():.3e} med={np.median(ds):.3e} BIT-IDENTICAL={ez}") + out.setdefault("pairs", []).append(dict(a=a, b=b, scale_a=sa, scale_b=sb, host=host, + n_ep=len(keys), n_anchor=n, max=float(ds.max()), + bit_identical=ez)) + +print("\n[inert] === VERDICT ===") +allbit = bool(verdict_bits) and all(verdict_bits) +if disp: + ss = np.array([v[0] for v in disp.values()]); mm = np.array([v[1] for v in disp.values()]) + spread = float(mm.max() - mm.min()) + corr = float(np.corrcoef(ss, mm)[0, 1]) if len(set(ss.tolist())) > 1 else float("nan") + print(f"[inert] displacement spread across scales 1.0..8.0 = {spread:.4f} mm; corr(scale, mean disp) = {corr:.4f}") + out["disp_spread_mm"], out["corr_scale_disp"] = spread, corr +print(f"[inert] within-host pairs bit-identical: {sum(verdict_bits)}/{len(verdict_bits)}") +if allbit: + v = ("INERT -- every within-host rung pair is BIT-IDENTICAL across scales 1.0..2.5 and 3.0..8.0. The " + "scale knob never reached the sampler: proposal_test.py:274 overwrites pol.rng per episode and " + "destroys the _ScaledNormal wrapper. CODE DEFECT, confirmed empirically. The whole run-42 ladder " + "measured ONE setting eight times and is VOID for this reason, independent of the floor guards.") +elif not any(verdict_bits): + v = ("WORKING -- no within-host rung pair is bit-identical, so the scale knob did reach the sampler and " + "the inertness reading is WRONG.") +else: + v = f"MIXED -- {sum(verdict_bits)}/{len(verdict_bits)} pairs bit-identical. Reported as such." +print(f"[inert] {v}") +out["verdict"] = v +json.dump(out, open(f"{ROOT}/status/real/pt_r45_inert.json", "w"), indent=1, default=str) +print("[inert] wrote status/real/pt_r45_inert.json") diff --git a/rsm_rise/scripts/real/pt_inert_r45.sh b/rsm_rise/scripts/real/pt_inert_r45.sh new file mode 100644 index 0000000000000000000000000000000000000000..f6b465a897d0d07e947a6a0d8e090204f5de1509 --- /dev/null +++ b/rsm_rise/scripts/real/pt_inert_r45.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +set -uo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +export MUJOCO_GL=disable +/proj/dmfexp/zwhong/rsm_rise/venv_rsm/bin/python scripts/real/pt_inert_r45.py diff --git a/rsm_rise/scripts/real/pt_inert_r46.py b/rsm_rise/scripts/real/pt_inert_r46.py new file mode 100644 index 0000000000000000000000000000000000000000..99edab038845fcc5583ca2b38e93f7089e15db53 --- /dev/null +++ b/rsm_rise/scripts/real/pt_inert_r46.py @@ -0,0 +1,109 @@ +#!/usr/bin/env python +"""PROPOSAL_TEST run 45d -- IS THE NOISE-SCALE LADDER INERT? A mechanical check of a code reading. + +Read from the source, not inferred statistically: + * pt_proposer_temp.py installs `_ScaledNormal` on `self.rng` in TempOpenpiPolicy.__init__ (once, at + construction) and prints "wrapper INSTALLED". + * proposal_test.py:274, INSIDE the per-episode loop, does + if pol is not None and hasattr(pol, "rng"): pol.rng = np.random.default_rng([a.seed, ep]) + which REPLACES pol.rng with a plain Generator and so DESTROYS the wrapper before the first measured + anchor of the first episode. + +If that reading is right the ladder is INERT and the scale knob never reached the sampler. The prediction is +mechanically forced, not statistical: rungs that ran on the SAME DEVICE must be bit-identical; same-host is NOT sufficient (one payload per GPU), so that limb is reported, not used. + pack p4a (rr_pt45ladder_p4a): T10 T15 T20 T25 (scales 1.0 1.5 2.0 2.5) + pack p4b (rr_pt45ladder_p4b): T30 T40 T60 T80 (scales 3.0 4.0 6.0 8.0) + + INERT : within-host rung pairs max|delta| == 0.0 AND mean displacement flat in the scale. + WORKING: displacement grows with the scale and the pairs differ. + +Reads only `cands`. NO ruler (`margin`, `cand_dir_mm` never touched) and NO coverage number. +""" +import glob, itertools, json +from pathlib import Path +import numpy as np + +ROOT = "/proj/dmfexp/zwhong/rsm_rise" +# run-45 corrected ladder: hosts are NOT the run-42 ones and are resolved from the job at read time, so +# they are left unlabelled here rather than carrying a stale attribution forward. The INERTNESS GUARD +# only needs the displacement column; the bit-exactness limb was MIS-SPECIFIED in run 45 (same host is +# not same device -- the pack puts one payload per GPU) and is reported but NOT used as a discriminator. +PACK = {"pack p4a (rr_pt46fine_p4a)": [("T10", 1.00), ("F105", 1.05), ("F110", 1.10), ("F115", 1.15)], + "pack p4b (rr_pt46fine_p4b)": [("F120", 1.20), ("F125", 1.25), ("F130", 1.30), ("F140", 1.40)]} + + +def load(tag): + out = {} + for f in sorted(glob.glob(f"{ROOT}/status/real/pt_R46_cov_sn1_knn0p03_{tag}/parts/*.npz")): + z = np.load(f, allow_pickle=True) + if not json.loads(bytes(z["__meta__"]).decode()).get("n_anchors", 0) or "cands" not in z.files: + continue + out[Path(f).name] = np.asarray(z["cands"]).astype(np.float64) + return out + + +def disp_mm(c): + return np.linalg.norm(c[..., -1, :3] - c[..., 0, :3], axis=-1) * 1000.0 + + +tags = [t for v in PACK.values() for t, _ in v] +cache = {t: load(t) for t in tags} +out = {} + +print("[inert] === mean candidate displacement per rung (mm) ===") +disp = {} +for host, rungs in PACK.items(): + for t, s in rungs: + if not cache[t]: + print(f"[inert] {t} scale={s}: NO CACHE"); continue + d = np.concatenate([disp_mm(v).ravel() for v in cache[t].values()]) + disp[t] = (s, float(d.mean()), float(np.median(d)), len(cache[t]), int(d.size)) + print(f"[inert] {t} scale={s:4.1f} host={host:24s} mean={d.mean():8.4f} med={np.median(d):8.4f}" + f" ep={len(cache[t]):2d} n={d.size}") +out["disp"] = disp + +print("\n[inert] === WITHIN-HOST rung pairs (the mechanically forced check) ===") +verdict_bits = [] +for host, rungs in PACK.items(): + print(f"[inert] -- {host}") + for (a, sa), (b, sb) in itertools.combinations(rungs, 2): + keys = sorted(set(cache[a]) & set(cache[b])) + ds, n = [], 0 + for k in keys: + if cache[a][k].shape != cache[b][k].shape: + continue + ds.append(np.abs(cache[a][k] - cache[b][k]).ravel()); n += cache[a][k].shape[0] + if not ds: + print(f"[inert] {a} vs {b}: NO SHARED EPISODE"); continue + ds = np.concatenate(ds) + ez = bool(ds.max() == 0.0) + verdict_bits.append(ez) + print(f"[inert] {a}(s={sa}) vs {b}(s={sb}): ep={len(keys)} anch={n:4d} " + f"max|delta|={ds.max():.3e} med={np.median(ds):.3e} BIT-IDENTICAL={ez}") + out.setdefault("pairs", []).append(dict(a=a, b=b, scale_a=sa, scale_b=sb, host=host, + n_ep=len(keys), n_anchor=n, max=float(ds.max()), + bit_identical=ez)) + +print("\n[inert] === VERDICT ===") +allbit = bool(verdict_bits) and all(verdict_bits) +if disp: + ss = np.array([v[0] for v in disp.values()]); mm = np.array([v[1] for v in disp.values()]) + spread = float(mm.max() - mm.min()) + corr = float(np.corrcoef(ss, mm)[0, 1]) if len(set(ss.tolist())) > 1 else float("nan") + print(f"[inert] displacement spread across the R46 FINE grid 1.00..1.40 = {spread:.4f} mm; corr(scale, mean disp) = {corr:.4f}") + out["disp_spread_mm"], out["corr_scale_disp"] = spread, corr +print(f"[inert] within-host pairs bit-identical: {sum(verdict_bits)}/{len(verdict_bits)}") +if allbit: + v = ("INERT -- every within-host rung pair is BIT-IDENTICAL across the R46 fine grid. The " + "scale knob never reached the sampler: proposal_test.py:274 overwrites pol.rng per episode and " + "destroys the _ScaledNormal wrapper. CODE DEFECT, confirmed empirically. The whole run-42 ladder " + "measured ONE setting eight times and is VOID for this reason, independent of the floor guards.") +elif not any(verdict_bits): + v = ("WORKING -- no within-host rung pair is bit-identical, so the scale knob did reach the sampler and " + "the knob reached the sampler. Run-42 phrasing about a stale wrong reading does not apply here.") +else: + v = f"MIXED -- {sum(verdict_bits)}/{len(verdict_bits)} pairs bit-identical. Reported as such." +print(f"[inert] {v}") +out["verdict"] = v +json.dump(out, open(f"{ROOT}/status/real/pt_r46_inert.json", "w"), indent=1, default=str) +print("[inert] wrote status/real/pt_r46_inert.json") diff --git a/rsm_rise/scripts/real/pt_inert_r46.sh b/rsm_rise/scripts/real/pt_inert_r46.sh new file mode 100644 index 0000000000000000000000000000000000000000..8dc236c814e37797d34b7130bf87c4fe77731d97 --- /dev/null +++ b/rsm_rise/scripts/real/pt_inert_r46.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +set -uo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +export MUJOCO_GL=disable +/proj/dmfexp/zwhong/rsm_rise/venv_rsm/bin/python scripts/real/pt_inert_r46.py diff --git a/rsm_rise/scripts/real/pt_mcspread.py b/rsm_rise/scripts/real/pt_mcspread.py new file mode 100644 index 0000000000000000000000000000000000000000..29207f7e6c688c4894cfe8a8ffcc042a1b89a784 --- /dev/null +++ b/rsm_rise/scripts/real/pt_mcspread.py @@ -0,0 +1,104 @@ +#!/usr/bin/env python +"""gen_q#280 / rsm_real#2 run 49 -- the READ-OUT's own Monte Carlo error bar, and the validity check that +replaces run 48's mis-specified tolerance-0 VOID condition. + +Within a cell, `rsm` and every `rsm@repN` row are the SAME checkpoint, read-out, cached draws, anchors and +gate; they differ only in the scorer's index in sorted(scorers), which seeds the chain +(proposal_test.py:276 -> twin_rollout.py:302 -> rsm_scorer.py:631). So the spread across those rows is the +read-out's Monte Carlo error and nothing else. + +Reads only the reduce JSONs. Loads no checkpoint and re-scores nothing. + usage: pt_mcspread.py [cell ...] [--window 100] [--ref cell:row] [--repsrc cell] + +--repsrc names the cell whose replicates define the error bar for the validity check. It MUST be the cell +whose read-out is identical to the reference row's, which for `cap_ab_s0:rsm@M_capped` is the DEFAULT +read-out, i.e. `ro_mcrep`. Earlier this took the replicates from cells[0] -- whichever cell happened to be +complete -- so if `ro_mcrep` was skipped as INCOMPLETE the check would silently measure `rsm@M_capped` +against a DIFFERENT read-out's noise (`ro_logit` changes score_kind, `ro_p4`/`ro_p64` the particle count, +`ro_d1` the sampler). That is a number comparable to nothing. The check now names its source and reports +NO CHECK, loudly, when that source is absent. +""" +import json, sys +from pathlib import Path + +args = [a for a in sys.argv[1:]] +W = "100" +if "--window" in args: + i = args.index("--window"); W = args[i + 1]; del args[i:i + 2] +REF = None +if "--ref" in args: + i = args.index("--ref"); REF = args[i + 1]; del args[i:i + 2] +REPSRC = "ro_mcrep" +if "--repsrc" in args: + i = args.index("--repsrc"); REPSRC = args[i + 1]; del args[i:i + 2] +cells = args +if not cells: + print("usage: pt_mcspread.py [cell ...] [--window 100] [--ref cell:row]"); sys.exit(2) + + +def rows(cell): + p = Path(f"status/real/PT_WIN_{cell}_w{W}.json") + if not p.exists(): + return None + return json.load(open(p)) + + +out = ["### READ-OUT MONTE CARLO SPREAD -- identical checkpoint/read-out/draws, scorer index only", + f"entry window {W}. `rsm` and `rsm@repN` are the same file; the spread IS the error bar.", "", + "| cell | group | n reps | min | max | **spread** | mean | gated anchors | eps | ties@max |", + "|---|---|---|---|---|---|---|---|---|---|"] +spreads = {} +for cell in cells: + d = rows(cell) + if d is None: + out.append(f"| `{cell}` | -- | **MISSING** (not reduced yet) | | | | | | | |"); continue + for g, blk in d.items(): + reps = [r for r in blk["scorers"] if r["scorer"] == "rsm" or r["scorer"].startswith("rsm@rep")] + if len(reps) < 2: + out.append(f"| `{cell}` | `{g}` | {len(reps)} | | | **NO CHECK -- fewer than 2 replicates** | | | | |") + continue + a = [r["auc"] for r in reps] + c = blk["coverage"] + ties = sorted({round(float(r.get("ties_at_max") or -1), 4) for r in reps}) + spreads[(cell, g)] = max(a) - min(a) + out.append(f"| `{cell}` | `{g}` | {len(a)} | {min(a):.4f} | {max(a):.4f} | **{max(a)-min(a):.4f}** | " + f"{sum(a)/len(a):.4f} | {c['gated_anchors']} | {c['gated_episodes']} | " + f"{'/'.join(str(t) for t in ties)} |") +out.append("") +if REF: + rc, rr = REF.split(":", 1) + rd = rows(rc) + out.append(f"### VALIDITY CHECK -- does `{rr}` (pt_{rc}) fall inside the measured spread of `{REPSRC}`?") + out.append("") + out.append(f"Replicate source is `{REPSRC}`, whose read-out must be identical to the reference row's; " + "a different cell's replicates are a different read-out's noise and are not a valid bar.") + out.append("") + out.append("| group | reference AUC | replicate min | replicate max | inside? |") + out.append("|---|---|---|---|---|") + d0 = rows(REPSRC) if REPSRC in cells else None + if REPSRC not in cells: + out.append(f"| -- | **NO CHECK -- replicate source `{REPSRC}` was not reduced (INCOMPLETE or not " + "requested). The validity check is UNDEFINED; it is NOT substituted from another cell.** | | | |") + elif rd is None or d0 is None: + out.append("| -- | **MISSING reduce JSON -- check not run** | | | |") + else: + gs0 = list(d0) + for g, blk in rd.items(): + row = next((r for r in blk["scorers"] if r["scorer"] == rr), None) + suffix = g.split("|", 1)[1].strip() if "|" in g else "" + gm = next((x for x in gs0 if (x.split("|", 1)[1].strip() if "|" in x else "") == suffix), None) + if row is None or gm is None: + out.append(f"| `{g}` | -- | -- | -- | **NO MATCH** |"); continue + reps = [r["auc"] for r in d0[gm]["scorers"] + if r["scorer"] == "rsm" or r["scorer"].startswith("rsm@rep")] + if len(reps) < 2: + out.append(f"| `{g}` | {row['auc']:.4f} | -- | -- | **NO CHECK** |"); continue + ok = min(reps) <= row["auc"] <= max(reps) + out.append(f"| `{g}` | {row['auc']:.4f} | {min(reps):.4f} | {max(reps):.4f} | " + f"{'yes -- VALID' if ok else '**NO -- the reference is outside the read-out noise**'} |") +txt = "\n".join(out) +print(txt) +Path(f"status/real/PT_MCSPREAD_w{W}.md").write_text(txt + "\n") +json.dump({f"{c}|{g}": s for (c, g), s in spreads.items()}, + open(f"status/real/PT_MCSPREAD_w{W}.json", "w"), indent=1) +print(f"\n[mcspread] wrote status/real/PT_MCSPREAD_w{W}.md/.json") diff --git a/rsm_rise/scripts/real/pt_mcspread_prelim.sh b/rsm_rise/scripts/real/pt_mcspread_prelim.sh new file mode 100644 index 0000000000000000000000000000000000000000..c71439f5a7a8c947214da48d431ea81ece852eb7 --- /dev/null +++ b/rsm_rise/scripts/real/pt_mcspread_prelim.sh @@ -0,0 +1,39 @@ +#!/usr/bin/env bash +# gen_q#280 / rsm_real#2 run 51 -- PRELIMINARY Monte Carlo spread from the ro_mcrep parts that exist NOW. +# +# Why this is legitimate while the run-49 completeness guard still stands. That guard exists because the +# gated anchor set is a function of WHICH episodes are present, so reducing cell A at 18 parts and cell B +# at 25 compares two different anchor sets. The mcrep spread is a WITHIN-cell quantity: all 8 replicate +# rows are produced in the same pass over the same episodes, so at any part count they share one anchor set +# exactly. The spread is therefore comparable to itself at 18 parts; it is NOT the final 163-anchor number +# and every line of output says so. It is published under a PRELIM name so it cannot be mistaken for the +# 25/25 figure, and no published CLEARS mark is reclassified on it. +set -uo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +export MUJOCO_GL=disable +PY=venv_rsm/bin/python +SRC=status/real/pt_ro_mcrep +N=$(ls "$SRC/parts" 2>/dev/null | wc -l) +if [ "$N" -lt 2 ]; then echo "[prelim] only $N parts -- nothing to do"; exit 0; fi +CELL="ro_mcrep_p${N}" +D="status/real/pt_${CELL}" +rm -rf "$D"; mkdir -p "$D/parts" +for f in "$SRC"/parts/*; do ln -s "$(readlink -f "$f")" "$D/parts/$(basename "$f")"; done +echo "[prelim] $CELL: $(ls "$D/parts" | wc -l) parts symlinked from $SRC (PRELIMINARY -- final cell is 25 parts)" +$PY scripts/real/proposal_report.py "$D" --entry-window 100 --oracle-chunk 8 --by-route \ + --md "status/real/PT_WIN_${CELL}_w100.md" --json "status/real/PT_WIN_${CELL}_w100.json" || exit 1 +$PY scripts/real/pt_mcspread.py "$CELL" --window 100 --repsrc "$CELL" --ref cap_ab_s0:rsm@M_capped || exit 1 +mv status/real/PT_MCSPREAD_w100.md "status/real/PT_MCSPREAD_PRELIM_${CELL}.md" +mv status/real/PT_MCSPREAD_w100.json "status/real/PT_MCSPREAD_PRELIM_${CELL}.json" +echo "[prelim] wrote status/real/PT_MCSPREAD_PRELIM_${CELL}.md -- PRELIMINARY, ${N}/25 episodes" +echo "=============== then the standard 25/25 reduce (ro_logit is newly complete) ===============" +bash scripts/real/pt_window_readout.sh +echo "=============== spread recheck at the PRELIMINARY spread (conditional, not a reclassification) ===" +# The published PT_SPREAD_RECHECK_w100.md must keep saying UNDEFINED until the 25/25 spread lands, so the +# preliminary verdict is written to its own file and the published one is restored afterwards. +cp -p status/real/PT_SPREAD_RECHECK_w100.md status/real/.PT_SPREAD_RECHECK_w100.published 2>/dev/null +$PY scripts/real/pt_spread_recheck.py --spread "status/real/PT_MCSPREAD_PRELIM_${CELL}.json" \ + --repsrc "$CELL" || echo "[prelim] recheck failed" +mv status/real/PT_SPREAD_RECHECK_w100.md "status/real/PT_SPREAD_RECHECK_PRELIM_${CELL}.md" 2>/dev/null +mv status/real/.PT_SPREAD_RECHECK_w100.published status/real/PT_SPREAD_RECHECK_w100.md 2>/dev/null +echo "[prelim] wrote status/real/PT_SPREAD_RECHECK_PRELIM_${CELL}.md (PRELIMINARY, ${N}/25 episodes)" diff --git a/rsm_rise/scripts/real/pt_mlong_void.py b/rsm_rise/scripts/real/pt_mlong_void.py new file mode 100644 index 0000000000000000000000000000000000000000..55cd68d4181bba7aebd3cdcdcc400629cab6a732 --- /dev/null +++ b/rsm_rise/scripts/real/pt_mlong_void.py @@ -0,0 +1,64 @@ +#!/usr/bin/env python +"""gen_q#280 / rsm_real#2 run 48 -- the VOID CHECK pre-registered in 5825763200 / 5825764160 before the +cell ran. + +`rsm@M_100k` in pt_mlong_s0 is R_M/ckpt_s100000.pt scored on the SAME cached draws at the SAME default +read-out as `rsm@M_capped` in pt_cap_ab_s0. It must reproduce EXACTLY. If it does not, pt_mlong_s0 is +VOID and no rung in it is readable. + +Reads only the two reduce JSONs. Loads no checkpoint and re-scores nothing. +""" +import json, sys +from pathlib import Path + +W = sys.argv[1] if len(sys.argv) > 1 else "100" +REF_CELL, REF_ROW = "cap_ab_s0", "rsm@M_capped" +NEW_CELL, NEW_ROW = "mlong_s0", "rsm@M_100k" +# Bit-exactness is the claim; float64 round-trip through JSON is exact, so the tolerance is 0. +TOL = 0.0 + +ref_p = Path(f"status/real/PT_WIN_{REF_CELL}_w{W}.json") +new_p = Path(f"status/real/PT_WIN_{NEW_CELL}_w{W}.json") +for p in (ref_p, new_p): + if not p.exists(): + print(f"[void] MISSING {p} -- check not run, and the cell stays UNREADABLE until it is") + sys.exit(2) +ref, new = json.load(open(ref_p)), json.load(open(new_p)) + + +def pick(blk, row): + for r in blk["scorers"]: + if r["scorer"] == row: + return r + return None + + +lines, verdict_void = [], False +lines.append(f"### VOID CHECK -- `{NEW_ROW}` (pt_{NEW_CELL}) against `{REF_ROW}` (pt_{REF_CELL}), entry window {W}") +lines.append("") +lines.append("| group | reference AUC | this cell's AUC | delta | gated anchors ref/new | eps ref/new | verdict |") +lines.append("|---|---|---|---|---|---|---|") +for g in ref: + gn = g.replace(REF_CELL, NEW_CELL) + if gn not in new: + lines.append(f"| `{g}` | -- | GROUP ABSENT | -- | -- | -- | **VOID** |") + verdict_void = True + continue + a, b = pick(ref[g], REF_ROW), pick(new[gn], NEW_ROW) + if a is None or b is None: + lines.append(f"| `{g}` | -- | ROW ABSENT | -- | -- | -- | **VOID** |") + verdict_void = True + continue + d = b["auc"] - a["auc"] + ca, cb = ref[g]["coverage"], new[gn]["coverage"] + ok = abs(d) <= TOL and ca["gated_anchors"] == cb["gated_anchors"] and ca["gated_episodes"] == cb["gated_episodes"] + verdict_void |= not ok + lines.append(f"| `{g}` | {a['auc']:.16f} | {b['auc']:.16f} | {d:+.3e} | " + f"{ca['gated_anchors']}/{cb['gated_anchors']} | {ca['gated_episodes']}/{cb['gated_episodes']} | " + f"{'reproduces' if ok else '**MISMATCH**'} |") +lines.append("") +lines.append(f"**VERDICT: pt_{NEW_CELL} is {'VOID -- no rung in it is readable' if verdict_void else 'VALID -- the harness reproduced exactly, so the ladder rungs are readable'}.**") +md = "\n".join(lines) +print(md) +Path(f"status/real/PT_MLONG_VOID_w{W}.md").write_text(md + "\n") +sys.exit(1 if verdict_void else 0) diff --git a/rsm_rise/scripts/real/pt_nullblock.py b/rsm_rise/scripts/real/pt_nullblock.py new file mode 100644 index 0000000000000000000000000000000000000000..cf651eb0ac1477bb90b3b7e9699abfa28d48ae8d --- /dev/null +++ b/rsm_rise/scripts/real/pt_nullblock.py @@ -0,0 +1,259 @@ +#!/usr/bin/env python +"""gen_q#281 / rsm_real#3 -- is the family-wise q95 in the spec the RIGHT WIDTH for a statistic whose +per-anchor values cluster by EPISODE? A guard on already-reported numbers, never a pass candidate. + +WHAT THIS IS AND WHAT IT CANNOT DO. #281 judges a row against a family-wise q95 calibrated by +WITHIN-ANCHOR label permutation (`pt_nullcal.calibrate`): each anchor's labels are shuffled +independently, so the null per-anchor AUCs are independent across anchors and the null SD of their mean +falls like 1/sqrt(anchors). If the OBSERVED per-anchor AUCs are correlated within an episode -- which +run 28 (gen_q#280 comment 5809421797) measured directly on `0->2->6`, where episode 223 reads 0.355-0.473 +and episode 231 reads 0.526-0.740 in every one of five cells -- then the observed statistic has +episode-level dispersion that the within-anchor null does not contain, and the bar is too narrow. This +file measures how much too narrow, with an episode-aware randomisation null, and re-reads the published +rows against it. It can only DOWNGRADE a published clear or leave it standing. There is no arrangement +of its output that turns a failing row into a passing one, and no row from it may be quoted as a pass. + +THE READING RULE IS FIXED BEFORE THE NUMBERS ARE SEEN (pre-registered on #281/#3 before this ran): + * block q95 <= within-anchor q95 at every block -> the #281 definition stands as written, the + published sign column stands, and I withdraw run 28's item-5 concern as unsupported; + * block q95 > within-anchor q95 -> #281's bar is too narrow for episode-clustered + statistics, the correction is posted with the measured ratio, and every published "CLEARS" whose + observed AUC falls between the two bars is demoted to UNRESOLVED (not to a negative). +Either outcome is reported. The ratio is the deliverable, not the direction. + +THE NULL. Episode-level sign-flip randomisation (the standard block/exchangeability analogue of the +within-anchor permutation). For a sign vector s in {+-1}^E, one sign per EPISODE, + stat(s) = 0.5 + mean_i s_{e(i)} * (A_i - 0.5), +with A_i the per-anchor AUC and e(i) its episode. s = (+1,...,+1) reproduces the observed pooled AUC +exactly, so the observed value is a member of its own randomisation distribution and the p-value is exact. +The null it tests is "the per-anchor deviations have zero mean and their EPISODE-level deviations are +sign-symmetric" -- i.e. it keeps whatever within-episode correlation the data have instead of destroying +it, which is the single thing the within-anchor permutation cannot do. + +FAMILY-WISE THE SAME WAY THE SPEC ASKS FOR IT. Westfall-Young max-T: ONE sign vector is applied to every +scorer in the family, the maximum over scorers is taken per draw, and the bar is the 95th percentile of +that maximum. Using one shared sign vector preserves the cross-scorer correlation, which independent +per-scorer draws would not. Family = the same 5 scorers `pt_epcv` used, so the bar here and run 28's are +directly comparable and any difference is the null and not the family size. + +THE GRANULARITY LIMIT, STATED UP FRONT BECAUSE IT BOUNDS WHAT THIS CAN CONCLUDE. With E episodes there +are only 2^E sign vectors; at E = 5 that is 32, so the smallest attainable one-sided p is 1/32 = 0.031 and +a 95th percentile is read off 32 points. Every block enumerates its sign vectors EXHAUSTIVELY when +E <= 16 (so the test is exact, not sampled) and the count is printed on every row. A bar read off 32 +points is coarse; it is reported with `null_draws` beside it and must not be quoted to more precision +than that. This coarseness is a property of having 5 episodes, not of the method, and it is exactly why +a five-episode table cannot support fine distinctions at any bar. + +EVERY OTHER DEFINITION IS IMPORTED, NEVER RESTATED: `load_cell`, `auc`, `ep_bootstrap`, `oracle_ceiling` +from `proposal_report`; the within-anchor `calibrate` from `pt_nullcal`; `score_of` / `rows_for` from +`pt_residual`; `per_anchor_auc` from `pt_epcv`. The observed AUC column is produced by the same +`rows_for` call that produced the rows being re-read, so it IS the published figure. Nothing is +re-sampled and no checkpoint is loaded: this reads the saved npz parts, which is why it is CPU. +Per route, never pooled across routes, with the measured permuted column, the anchor set's oracle +ceiling, and kept anchor/episode counts on every row. +""" +from __future__ import annotations +import argparse, itertools, json, sys +from pathlib import Path +import numpy as np + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from proposal_report import (load_cell, auc, ep_bootstrap, oracle_ceiling) # noqa: E402,F401 +from pt_nullcal import calibrate # noqa: E402 +from pt_residual import score_of, rows_for # noqa: E402 +from pt_epcv import per_anchor_auc, SCORERS # noqa: E402 + +MAX_EXACT_EPISODES = 16 + + +def sign_vectors(n_ep, rng, max_exact=MAX_EXACT_EPISODES, sampled=4000): + """All 2^n_ep sign vectors when that is enumerable, else `sampled` draws. The all-+1 vector is + guaranteed present either way, because the observed statistic must be a member of its own null.""" + if n_ep <= max_exact: + S = np.array(list(itertools.product([1.0, -1.0], repeat=n_ep))) + return S, True + S = rng.choice([1.0, -1.0], size=(sampled, n_ep)) + S[0] = 1.0 + return S, False + + +def block_null(A_by_scorer, epi, rng): + """Episode sign-flip randomisation. Returns per-scorer null statistics (draws,) and the shared + max-T distribution. One sign vector per draw is applied to EVERY scorer.""" + eps = sorted(set(epi.tolist())) + idx = np.array([eps.index(e) for e in epi]) # anchor -> episode slot + S, exact = sign_vectors(len(eps), rng) # (draws, E) + per = {} + for nm, A in A_by_scorer.items(): + dev = np.asarray(A, float) - 0.5 # (anchors,) + per[nm] = 0.5 + (S[:, idx] * dev[None, :]).mean(axis=1) # (draws,) + M = np.max(np.stack([per[nm] for nm in A_by_scorer]), axis=0) + return per, M, S.shape[0], exact + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--cells", nargs="+", required=True) + ap.add_argument("--root", default="status/real") + ap.add_argument("--entry-window", type=int, default=100) + ap.add_argument("--oracle-chunk", type=int, default=8) + ap.add_argument("--state", type=int, default=2) + ap.add_argument("--gate-min-anchors", type=int, default=30) + ap.add_argument("--reps", type=int, default=4000) + ap.add_argument("--boot", type=int, default=400) + ap.add_argument("--perm-reps", type=int, default=200) + ap.add_argument("--json", default=None) + ap.add_argument("--md", default=None) + a = ap.parse_args() + + rng = np.random.default_rng(28) + blocks = [] + for cell in a.cells: + d = Path(cell) + if not d.is_absolute() and not d.exists(): + d = Path(a.root) / cell + recs, cfg = load_cell(d, entry_window=a.entry_window) + if not recs: + print(f"[nullblock] {d.name}: no anchors", file=sys.stderr); continue + for route in sorted({r["path"] for r in recs}): + gated = [r for r in recs if r["gate"] and r["path"] == route] + neps = len({r["episode"] for r in gated}) + if len(gated) < a.gate_min_anchors or neps < 4: + blocks.append(dict(cell=d.name, route=route, undefined=True, + anchors=len(gated), episodes=neps, + reason=f"below #280 floor (30 anchors / 4 episodes): " + f"{len(gated)} anchors / {neps} episodes")) + print(f"[nullblock] UNDEFINED {d.name} {route}: {len(gated)} anchors / {neps} eps", + file=sys.stderr) + continue + + pairs = [(nm, (lambda n: (lambda r: score_of(r, n)))(nm)) for nm in SCORERS] + rows = rows_for(gated, pairs) # the PUBLISHED observed column + by = {r["scorer"]: r for r in rows} + + A_by, epi_ref = {}, None + for nm in SCORERS: + if nm not in by: + continue + A, epi, _ = per_anchor_auc(gated, (lambda n: (lambda r: score_of(r, n)))(nm)) + if len(A) == 0: + continue + A_by[nm] = A + epi_ref = epi if epi_ref is None else epi_ref + if len(epi) != len(epi_ref): + print(f"[nullblock] {d.name} {route} {nm}: anchor count differs from the family; " + f"max-T needs one shared sign vector, so this block is UNDEFINED", + file=sys.stderr) + A_by = {}; break + if not A_by: + blocks.append(dict(cell=d.name, route=route, undefined=True, + anchors=len(gated), episodes=neps, + reason="scorers cover different anchor sets; shared-sign max-T undefined")) + continue + + per, M, ndraw, exact = block_null(A_by, epi_ref, rng) + q95_block = float(np.percentile(M, 95)) + max_block = float(M.max()) + cal = calibrate(gated, a.reps, a.boot, a.perm_reps, rng, n_scorers=len(SCORERS)) + orc = oracle_ceiling([(r["episode"], r["frame"]) for r in gated], a.oracle_chunk, a.state) + + for nm, A in A_by.items(): + obs = float(np.mean(A)) + nulls = per[nm] + sd_block = float(np.std(nulls, ddof=1)) + p_marg = float(np.mean(nulls >= obs - 1e-12)) + p_adj = float(np.mean(M >= obs - 1e-12)) + se = by[nm]["auc_se"] + by[nm].update(dict( + obs_auc=obs, block_sd=sd_block, block_q95=q95_block, block_max=max_block, + block_p=p_marg, block_p_adj=p_adj, null_draws=int(ndraw), null_exact=bool(exact), + within_q95_fwer=cal.get("q95_fwer"), within_null_sd=cal.get("null_sd"), + sd_ratio_block_over_within=(sd_block / cal["null_sd"]) if cal.get("null_sd") else None, + se_ratio_boot_over_within=(se / cal["null_sd"]) if cal.get("null_sd") else None, + clears_within=bool(obs > cal.get("q95_fwer", np.inf)), + clears_block=bool(obs > q95_block), + # #280 as literally written: above 0.5 and above the measured permuted line, each by + # more than the row's own episode-bootstrap SE. + clears_280=bool((obs - 0.5 > se) and (obs - by[nm]["auc_permuted"] > se)), + at_or_above_ceiling=bool(orc and orc.get("auc") is not None + and obs >= orc["auc"]))) + + blocks.append(dict(cell=d.name, route=route, undefined=False, + anchors=len(gated), episodes=neps, + beta_mode=cfg.get("beta_mode"), beta=cfg.get("beta"), + ckpt=cfg.get("ckpt") or cfg.get("successor"), + cands_from=cfg.get("cands_from"), + q95_fwer=cal.get("q95_fwer"), null_mean=cal.get("null_mean"), + null_sd=cal.get("null_sd"), boot_se_med=cal.get("boot_se_med"), + boot_se_over_null_sd=cal.get("boot_se_over_null_sd"), + block_q95=q95_block, block_max=max_block, + null_draws=int(ndraw), null_exact=bool(exact), + min_attainable_p=1.0 / ndraw, + oracle=orc, rows=rows)) + r0 = by.get("rsm", {}) + print(f"[nullblock] {d.name} {route}: {len(gated)} anchors / {neps} eps " + f"within_q95={cal.get('q95_fwer'):.4f} block_q95={q95_block:.4f} " + f"ratio_sd={r0.get('sd_ratio_block_over_within', float('nan')):.2f} " + f"rsm={r0.get('obs_auc', float('nan')):.4f} " + f"p_adj={r0.get('block_p_adj', float('nan')):.4f} draws={ndraw}", + file=sys.stderr) + + if a.json: + Path(a.json).write_text(json.dumps(blocks, indent=1)) + md = render(blocks) + if a.md: + Path(a.md).write_text(md) + print(md) + + +def f(x, n=4): + try: + return "n/a" if x is None or not np.isfinite(float(x)) else f"{float(x):.{n}f}" + except Exception: + return "n/a" + + +def render(blocks): + L = ["# Is #281's family-wise q95 the right WIDTH for an episode-clustered statistic?", + "", + "GUARD on already-reported numbers -- it can only demote a published clear or leave it standing; " + "no row here is a pass candidate. `within q95` is #281's bar as written (within-anchor label " + "permutation, family-wise over the same 5 scorers). `block q95` is the same family-wise " + "construction under an EPISODE sign-flip randomisation, which keeps within-episode correlation " + "instead of destroying it. Observed AUC is the PUBLISHED column (`pt_residual.rows_for`), not a " + "re-derivation. `p_adj` is the exact Westfall-Young max-T p; its floor is 1/draws and is printed.", + ""] + for b in blocks: + head = f"## {b['cell']} -- route `{b['route']}`" + if b.get("undefined"): + L += [head, "", f"**UNDEFINED** -- {b['reason']}", ""] + continue + orc = b.get("oracle") or {} + L += [head, "", + f"anchors **{b['anchors']}** / episodes **{b['episodes']}** · oracle ceiling " + f"**{f(orc.get('auc'), 3)}** · **within q95 {f(b['q95_fwer'])}** · " + f"**block q95 {f(b['block_q95'])}** (null max {f(b['block_max'])}) · " + f"null draws **{b['null_draws']}**{' (EXACT, exhaustive)' if b['null_exact'] else ' (sampled)'} · " + f"smallest attainable p **{f(b['min_attainable_p'], 4)}** · " + f"within-anchor null sd {f(b['null_sd'])} · median episode-bootstrap SE under that null " + f"{f(b['boot_se_med'])} (ratio {f(b['boot_se_over_null_sd'], 2)})", + "", + "| scorer | AUC (ep-boot SE) | permuted | block sd | sd ratio blk/within | clears within q95 | " + "clears block q95 | exact p | max-T p_adj | clears #280 as written | >= ceiling |", + "|---|---|---|---|---|---|---|---|---|---|---|"] + for r in b["rows"]: + if "obs_auc" not in r: + continue + L.append( + f"| `{r['scorer']}` | {f(r['obs_auc'])} ({f(r['auc_se'])}) | {f(r['auc_permuted'])} | " + f"{f(r['block_sd'])} | {f(r.get('sd_ratio_block_over_within'), 2)} | " + f"{'**CLEARS**' if r['clears_within'] else '--'} | " + f"{'**CLEARS**' if r['clears_block'] else '--'} | {f(r['block_p'], 4)} | " + f"{f(r['block_p_adj'], 4)} | {'yes' if r['clears_280'] else '--'} | " + f"{'**FLAG**' if r['at_or_above_ceiling'] else ''} |") + L.append("") + return "\n".join(L) + + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/real/pt_nullcal.py b/rsm_rise/scripts/real/pt_nullcal.py new file mode 100644 index 0000000000000000000000000000000000000000..5d10a8b281be9ca07beb6d2baa74f12d71176f56 --- /dev/null +++ b/rsm_rise/scripts/real/pt_nullcal.py @@ -0,0 +1,178 @@ +#!/usr/bin/env python +"""gen_q#280 / rsm_real#2 -- CALIBRATE the pass bar by measuring the null distribution of the whole +statistic, not just its mean. + +Why this exists, with the number that forced it. The pre-registered bar is "AUC above 0.5 by more than +its episode-bootstrapped SE, and above the permuted scorer by the same margin". In the TASK C cap A/B +table the PERMUTED scorer itself cleared that bar on one route (`permuted:rsm`, 0.508 +- 0.004 on +`0->2->6`). A one-sided 1-SE rule has a ~16% false-positive rate by construction, so a table with a +dozen scorer rows is expected to show one or two spurious PASSes -- and this project has already recorded +"random clears the 1-SE bar" twice. A point estimate of the zero line cannot catch that; the DISTRIBUTION +of the zero line can. + +What is measured. Under the within-anchor permutation null, the score vector carries no information +about the label, so the per-anchor AUC is the Mann-Whitney statistic of a uniformly random ranking of N +candidates split n_pos / n_neg. That is sampled EXACTLY here (a random rank subset), so no scorer needs +to be re-run and no checkpoint is loaded: the null depends only on the per-anchor label split and the +episode grouping, both of which are on disk in the cell's parts. Ties are not modelled because every +reported row has ties@max = 1.0. + +Reported per group (pooled and per route): + null mean / null sd the true sampling sd of the mean-over-anchors AUC under the null + q95 / q99 the CALIBRATED one-sided critical AUC -- the number a row must beat + boot SE (median) the episode-bootstrap SE the reducer would have printed for a null row + false-pass 1SE / 2SE the measured rate at which a null scorer passes each rule +Then every scorer row in the supplied report JSONs is re-flagged against the calibrated q95. +""" +from __future__ import annotations +import argparse, json, sys +from pathlib import Path +import numpy as np + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from proposal_report import load_cell # noqa: E402 + + +def null_auc_draws(n_pos: int, N: int, reps: int, rng) -> np.ndarray: + """`reps` exact draws of the per-anchor AUC under the within-anchor permutation null. + + Under the null the scorer's ranking is a uniformly random permutation, so the ranks held by the + n_pos success-side candidates are a uniformly random n_pos-subset of {1..N}. Sampling that subset + directly is exact and costs nothing, which is what lets this run 4000 replicates of the FULL table + statistic on a login-node-sized CPU job. + """ + n_neg = N - n_pos + if n_pos <= 0 or n_neg <= 0: + return np.full(reps, np.nan) + idx = np.argsort(rng.random((reps, N)), axis=1)[:, :n_pos] # random n_pos-subset of 0..N-1 + ranksum = (idx + 1).sum(axis=1).astype(float) + return (ranksum - n_pos * (n_pos + 1) / 2.0) / (n_pos * n_neg) + + +def ep_boot_se(a: np.ndarray, ep: np.ndarray, rng, boot: int) -> float: + ue = np.unique(ep) + byep = [a[ep == x] for x in ue] + draws = np.empty(boot) + for b in range(boot): + pick = rng.integers(0, len(ue), len(ue)) + draws[b] = np.concatenate([byep[i] for i in pick]).mean() + return float(draws.std(ddof=1)) + + +def calibrate(gated, reps, boot, perm_reps, rng, n_scorers=13): + """gated: list of records. Returns the null distribution of the reducer's headline statistic.""" + ep = np.array([r["episode"] for r in gated]) + N = len(gated[0]["margin"]) + npos = np.array([int((np.asarray(r["margin"]) > 0).sum()) for r in gated]) + # A x reps matrix of null per-anchor AUCs, one independent permutation per anchor per replicate -- + # exactly what `permuted:` does in the reducer, just sampled 4000 times instead of once. + A = np.stack([null_auc_draws(int(p), N, reps, rng) for p in npos]) # (anchors, reps) + stat = np.nanmean(A, axis=0) # (reps,) + # The permuted COLUMN the reducer prints is itself a mean of `perm_reps` shuffles per anchor, then a + # mean over anchors. Drawn independently here so the "AUC - perm > SE" clause is evaluated honestly. + perm_col = float(np.nanmean([null_auc_draws(int(p), N, perm_reps, rng).mean() for p in npos])) + # Episode-bootstrap SE for a subsample of replicates (the expensive part), so the false-pass rate is + # evaluated with the SAME SE estimator the reducer uses, not an analytic stand-in. + sub = min(reps, 400) + ses = np.array([ep_boot_se(A[:, i], ep, rng, boot) for i in range(sub)]) + s = stat[:sub] + fp1 = float(np.mean((s - 0.5 > ses) & (s - perm_col > ses))) + fp2 = float(np.mean((s - 0.5 > 2 * ses) & (s - perm_col > 2 * ses))) + # FAMILY-WISE bar. A table is read row by row, so a per-row q95 is the wrong bar for a table with + # `n_scorers` rows: at q95 per row a 13-row group is EXPECTED to show 0.65 spurious passes, and the + # reader will quote the winner. Under the null the rows are independent permutations, so the + # family-wise bar is the 95th percentile of the MAXIMUM over n_scorers independent null statistics. + mx = np.stack([np.nanmean(np.stack([null_auc_draws(int(p), N, reps // 4, rng) for p in npos]), axis=0) + for _ in range(n_scorers)]).max(axis=0) + q95_fwer = float(np.nanpercentile(mx, 95)) + return dict(anchors=len(gated), episodes=int(len(np.unique(ep))), n_cand=N, + npos_med=float(np.median(npos)), + null_mean=float(np.nanmean(stat)), null_sd=float(np.nanstd(stat, ddof=1)), + q95=float(np.nanpercentile(stat, 95)), q99=float(np.nanpercentile(stat, 99)), + q05=float(np.nanpercentile(stat, 5)), + perm_col=perm_col, boot_se_med=float(np.median(ses)), + n_scorers=n_scorers, q95_fwer=q95_fwer, + boot_se_over_null_sd=float(np.median(ses) / np.nanstd(stat, ddof=1)), + false_pass_1se=fp1, false_pass_2se=fp2, reps=reps, reps_se=sub) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("cells", nargs="+") + ap.add_argument("--reps", type=int, default=4000) + ap.add_argument("--boot", type=int, default=400) + ap.add_argument("--perm-reps", type=int, default=200) + ap.add_argument("--n-scorers", type=int, default=13, + help="rows per group in the table the bar will be read against; sets the " + "family-wise (max-statistic) bar") + ap.add_argument("--by-route", action="store_true") + ap.add_argument("--entry-window", type=int, default=None, + help="gen_q#281 18:15Z: calibrate on the SAME entry-restricted anchor set the reducer " + "used. The null sd grows as anchors shrink, so a bar calibrated on 335 anchors is " + "the wrong bar for a 100-anchor window cell.") + ap.add_argument("--reflag", default="", help="report JSON to re-flag against the calibrated q95") + ap.add_argument("--md", default="") + ap.add_argument("--json", default="") + a = ap.parse_args() + + rng = np.random.default_rng(20260923) + out, rows = {}, [] + for c in a.cells: + d = Path(c) + recs, _ = load_cell(d, entry_window=a.entry_window) + if not recs: + print(f"[nullcal] {d.name}: no anchors", file=sys.stderr); continue + groups = [(d.name.replace("pt_", ""), recs)] + if a.by_route: + for rt in sorted({r["path"] for r in recs}): + groups.append((f"{d.name.replace('pt_', '')} | {rt}", [r for r in recs if r["path"] == rt])) + for gname, grecs in groups: + gated = [r for r in grecs if r["gate"]] + if len(gated) < 30: + print(f"[nullcal] {gname}: only {len(gated)} gated anchors, skipped", file=sys.stderr) + continue + res = calibrate(gated, a.reps, a.boot, a.perm_reps, rng, a.n_scorers) + res["group"] = gname + out[gname] = res; rows.append(res) + print(f"[nullcal] {gname}: null {res['null_mean']:.4f} +- {res['null_sd']:.4f} " + f"q95={res['q95']:.4f} bootSE={res['boot_se_med']:.4f} " + f"fp1={res['false_pass_1se']:.3f} fp2={res['false_pass_2se']:.3f}", flush=True) + + o = ["### Calibrated zero line: the null DISTRIBUTION of the mean-over-anchors AUC", "", + "Sampled exactly from the within-anchor permutation null (a uniformly random ranking of the N " + "candidates at each anchor), so it reads only the per-anchor label split and the episode grouping " + "off disk -- no checkpoint, no scorer.", "", + "| group | gated anchors | eps | null mean | null sd | **q95 (per row)** | q99 | " + "**q95 family-wise** | perm column | episode-boot SE (med) | bootSE/null sd | " + "false-pass @1SE | false-pass @2SE |", + "|---|---|---|---|---|---|---|---|---|---|---|---|---|"] + for r in rows: + o.append(f"| {r['group']} | {r['anchors']} | {r['episodes']} | {r['null_mean']:.4f} | " + f"{r['null_sd']:.4f} | **{r['q95']:.4f}** | {r['q99']:.4f} | " + f"**{r['q95_fwer']:.4f}** | {r['perm_col']:.4f} | " + f"{r['boot_se_med']:.4f} | {r['boot_se_over_null_sd']:.2f} | " + f"{r['false_pass_1se']*100:.1f}% | {r['false_pass_2se']*100:.1f}% |") + + if a.reflag: + rep = json.load(open(a.reflag)) + o += ["", "### Every scorer row in `" + Path(a.reflag).name + "` re-flagged against the calibrated q95", "", + "| group | scorer | AUC | reducer PASS (1SE) | calibrated q95 | CLEARS q95 | " + "q95 family-wise | CLEARS FWER |", + "|---|---|---|---|---|---|---|---|"] + for gname, blk in rep.items(): + cal = out.get(gname) + for sr in blk.get("scorers", []): + q = cal["q95"] if cal else float("nan") + qf = cal["q95_fwer"] if cal else float("nan") + o.append(f"| {gname} | {sr['scorer']} | {sr['auc']:.3f} | " + f"{'PASS' if sr['passes'] else '--'} | " + f"{q:.4f} | {'**YES**' if (cal and sr['auc'] > q) else 'no'} | " + f"{qf:.4f} | {'**YES**' if (cal and sr['auc'] > qf) else 'no'} |") + md = "\n".join(o) + print(md) + if a.md: open(a.md, "w").write(md + "\n") + if a.json: json.dump(out, open(a.json, "w"), indent=1) + + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/real/pt_nullcal.sh b/rsm_rise/scripts/real/pt_nullcal.sh new file mode 100644 index 0000000000000000000000000000000000000000..cb926f7398102a3d251d353321c4e03af7956b47 --- /dev/null +++ b/rsm_rise/scripts/real/pt_nullcal.sh @@ -0,0 +1,8 @@ +#!/bin/bash +# gen_q#280 / rsm_real#2 -- calibrate the pass bar (CPU only, reads the saved npz parts) +set -euo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +export MUJOCO_GL=disable +TAG="${1:?tag}"; shift +venv_rsm/bin/python scripts/real/pt_nullcal.py "$@" \ + --md "status/real/PT_NULLCAL_${TAG}.md" --json "status/real/PT_NULLCAL_${TAG}.json" diff --git a/rsm_rise/scripts/real/pt_pairs_cell.sh b/rsm_rise/scripts/real/pt_pairs_cell.sh new file mode 100644 index 0000000000000000000000000000000000000000..2224c5f237d2cdd91bd67fece9a35fbd7b65995d --- /dev/null +++ b/rsm_rise/scripts/real/pt_pairs_cell.sh @@ -0,0 +1,21 @@ +#!/usr/bin/env bash +# gen_q#280 / rsm_real#2 -- ONE cell of "the RSM on the caliper-matched pairs" (see pt_pairs_score.py). +# usage: PP_NAME= PP_RSM= [PP_BETA=..] [PP_BETAMODE=..] pt_pairs_cell.sh [shard-i shard-n] +# Parts are per-episode and resumed, so a preempted cell restarts where it stopped. +set -uo pipefail +ROOT=/proj/dmfexp/zwhong/rsm_rise +I=${1:-0}; K=${2:-1} +NAME=${PP_NAME:?set PP_NAME} +OUT=$ROOT/status/real/pp_$NAME +mkdir -p "$OUT" +ARGS=(--out "$OUT" --tag "$NAME" --state "${PP_STATE:-2}" --entry-window "${PP_WINDOW:-100}" + --stride "${PP_STRIDE:-5}" --lengths ${PP_L:-8} --bank "${PP_BANK:-16}" + --ep-shard "$I/$K" --seed "${PP_SEED:-0}" + --idql-ckpt "${PP_IDQL:-$ROOT/runs/cooking_v5_expert_suboptimal/policy/S0Aidql_seed1/cooking_v5_expert_suboptimal_S0Aidql_s1/20260921235824/models/model_epoch_3000.pth}" + --rsm-ckpt "${PP_RSM:-$ROOT/runs/real_cooking_v5/rsm/R_M/ckpt_s100000.pt}" + --rsm-mode "${PP_MODE:-chain}" --rsm-depth "${PP_DEPTH:-1}" + --rsm-beta "${PP_BETA:-0.99}" --rsm-gamma "${PP_GAMMA:-0.999}" + --rsm-particles "${PP_PARTICLES:-16}" --rsm-score-kind "${PP_SCOREKIND:-prob}" + --rsm-temperature "${PP_TEMP:-25}" --rsm-beta-mode "${PP_BETAMODE:-fixed}" + --beta-trunc-eps "${PP_BETAEPS:-0.02}") +exec $ROOT/scripts/real/run_env_openpi.sh $ROOT/scripts/real/pt_pairs_score.py "${ARGS[@]}" diff --git a/rsm_rise/scripts/real/pt_pairs_reduce.py b/rsm_rise/scripts/real/pt_pairs_reduce.py new file mode 100644 index 0000000000000000000000000000000000000000..785d1371b928761e72b82616c45588cc02e2f3b7 --- /dev/null +++ b/rsm_rise/scripts/real/pt_pairs_reduce.py @@ -0,0 +1,257 @@ +#!/usr/bin/env python +"""Reduce the pp_* cells written by pt_pairs_score.py into ONE table: the RSM's conditional AUC on the +SAME caliper-matched S2 pairs where a supervised read of the logged chunk reaches 0.983. + +Every row carries, as the brief requires: its MEASURED permuted zero line (label permuted across episodes, +pairs REMATCHED, conditional AUC recomputed -- not a nominal 0.5), the supervised CEILING on its own pair +set, the anchor GUARD on that same pair set, ties, score CV, pairs kept and episodes kept. A caliper with +fewer than --min-pairs pairs is printed UNDEFINED rather than scored, and a caliper whose GUARD is far from +0.5 is flagged LOOSE because a chunk row there may be reading leftover anchor. + +Two arms per cell, and the difference between them is the point: + raw V(anchor, its own logged chunk) -- can be won by anchor level + centered V(anchor, chunk) - mean_m V(anchor, bank_m) -- anchor level subtracted in the value's + own units, so it cannot be +The bank is the SAME 16 logged chunks at every anchor in every cell, so `centered` is a within-anchor +contrast and is directly comparable across cells. +""" +from __future__ import annotations +import argparse, json, sys, time +from pathlib import Path +import numpy as np + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from proposal_ceiling import ROOT, fit_arm, chunk_feat, perm_labels +from pt_conditional_ceiling import match_pairs, cond_auc, cond_boot + + +def load_cell(d: Path): + parts = sorted((d / "parts").glob("ep*.npz")) + recs = [] + for p in parts: + z = np.load(p, allow_pickle=True) + m = json.loads(bytes(z["__meta__"]).decode()) + recs.append((m, z)) + return recs + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--cells", nargs="+", required=True, help="pp_ directory names under status/real") + ap.add_argument("--root", default=f"{ROOT}/status/real") + ap.add_argument("--out", default=f"{ROOT}/status/real/PT_PAIRS_RSM.md") + ap.add_argument("--calipers", type=float, nargs="+", default=[0.9, 1.0, 1.25, 1.5, 2.0]) + ap.add_argument("--report-caliper", type=float, default=1.0) + ap.add_argument("--min-pairs", type=int, default=30) + ap.add_argument("--boot", type=int, default=2000) + ap.add_argument("--perm-null", type=int, default=200) + ap.add_argument("--folds", type=int, default=5) + ap.add_argument("--seed", type=int, default=0) + ap.add_argument("--subset", default="all", choices=["all", "valid", "train"]) + a = ap.parse_args() + t0 = time.time() + + # ---- load every cell and REFUSE if the anchor sets differ; a table whose rows sit on different + # anchors is not a comparison, which is the failure this stream keeps finding elsewhere. + cells, ref_key = {}, None + for name in a.cells: + d = Path(a.root) / name + recs = load_cell(d) + if not recs: + print(f"[red] {name}: NO PARTS -- skipped", flush=True); continue + key, rows = [], [] + for m, z in sorted(recs, key=lambda r: r[0]["episode"]): + if a.subset != "all" and m["split"] != a.subset: + continue + for j, t in enumerate(z["t"]): + key.append((int(m["episode"]), int(t))) + rows.append((m, z)) + if not rows: + print(f"[red] {name}: no episodes in subset={a.subset} -- skipped", flush=True); continue + cells[name] = (rows, key) + if ref_key is None: + ref_key = key + elif key != ref_key: + raise SystemExit(f"[red] {name} has {len(key)} anchors, reference has {len(ref_key)}, and they " + f"differ -- the cells are not on a shared anchor set; refusing to table them") + if not cells: + raise SystemExit("[red] no cells loaded") + + name0 = list(cells)[0] + rows0, key = cells[name0] + ep = np.array([k[0] for k in key]) + y = np.array([m["y"] for m, z in rows0 for _ in range(len(z["t"]))], int) + A = np.concatenate([z["anchor"] for m, z in rows0], 0).astype(np.float64) + CH = np.concatenate([z["chunk"] for m, z in rows0], 0).astype(np.float64) + nep_cell = len(rows0) + print(f"[red] anchors={len(y)} episodes={len(np.unique(ep))} goal={int(y.sum())} other={int((1-y).sum())} " + f"subset={a.subset} cells={list(cells)}", flush=True) + + Z = (A - A.mean(0)) / np.maximum(A.std(0), 1e-8) + + # ---- the supervised reference arms, on THESE anchors: the ceiling and the guard, PLUS the cheap + # baseline ladder gen_q#280 names as the legitimate comparison columns (pose continuity, random) and a + # single-statistic ladder that prices WHICH part of the logged chunk carries the route. + # + # WHY SINGLE-FEATURE LOGREG AND NOT A SIGNED SCALAR. A raw signed statistic (say +dz, "success lifts") + # needs a sign, and choosing that sign after seeing the table is label peeking dressed as a baseline. + # Every arm here is therefore fitted OUT OF FOLD under the same StratifiedGroupKFold over EPISODES as + # the ceiling, so its sign is learned on training episodes and never on the episode it is scored on. + # That also makes each arm directly comparable to `CEILING chunk:logreg`, which is the same estimator + # on the full 87-d chunk feature. ALL of these are supervised reference arms, NOT value functions: + # they say what is in the chunk, not what the RSM reads out of it. + # + # `chunk_feat` is relative to the chunk's OWN first action, so none of these can smuggle in the anchor; + # `pose-continuity` is the one arm that deliberately spans both (chunk start vs the anchor's eef_pos) + # and is labelled as such. Anchor layout is concat(ee_state[t] 10-d, eef_pos[t] 3-d) from + # proposal_ceiling.build, and the 10-d action is [pos 0:3, rot6d 3:9, gripper 9]. + L8 = 8 + dvec = (CH[:, L8 - 1, :3] - CH[:, 0, :3]).astype(np.float64) # translation over the chunk, m + dmag = np.linalg.norm(dvec, axis=1) + with np.errstate(invalid="ignore", divide="ignore"): + dunit = dvec / np.maximum(dmag, 1e-12)[:, None] + dgrip = (CH[:, L8 - 1, 9] - CH[:, 0, 9]).astype(np.float64) # gripper channel change + posc = np.linalg.norm(CH[:, 0, :3].astype(np.float64) - A[:, 10:13], axis=1) # |a_0 - p_t| + CF = chunk_feat(CH, L8, "waypoints") + CH_ng = CH.copy(); CH_ng[:, :, 9] = 0.0 # chunk with the gripper removed + CF_nogrip = chunk_feat(CH_ng, L8, "waypoints") + CF_grip = np.stack([CH[:, k, 9] - CH[:, 0, 9] for k in range(L8)], 1).astype(np.float64) + + fit_specs = { + "CEILING chunk:logreg": (CF, "logreg"), + "GUARD anchor:logreg": (A, "logreg"), + "ABL chunk-no-gripper:logreg": (CF_nogrip, "logreg"), + "ABL chunk-gripper-only:logreg": (CF_grip, "logreg"), + "1f dz:logreg": (1000.0 * dvec[:, 2:3], "logreg"), + "1f |dxyz|:logreg": (1000.0 * dmag[:, None], "logreg"), + "3f unit(d):logreg": (dunit, "logreg"), + "1f dgripper:logreg": (dgrip[:, None], "logreg"), + "BASELINE pose-continuity:logreg": (1000.0 * posc[:, None], "logreg"), + } + ref_scores = {k: fit_arm(X, y, ep, a.folds, a.seed, m) for k, (X, m) in fit_specs.items()} + ref_scores["random"] = np.random.default_rng([a.seed, 5]).normal(size=len(y)) + # `greedy index` is in gen_q#280's baseline list but is UNDEFINED here and is reported as such rather + # than omitted: greedy ranks WITHIN a candidate set, and this test scores exactly ONE logged chunk per + # anchor, so there is no set to take the first element of. It belongs to the proposer-draw arm. + print(f"[red] baseline ladder: {len(fit_specs)} fitted arms + random; " + f"`greedy index` UNDEFINED here (one chunk per anchor, no candidate set)", flush=True) + + # ---- the value arms, per cell. + val_scores = {} + idql_seen = {} + for name, (rows, _) in cells.items(): + m0 = rows[0][0] + for mm in m0["modes"]: + k = mm.replace(":", "__") + raw = np.concatenate([z[f"raw__{k}"] for _, z in rows]).astype(np.float64) + ref = np.concatenate([z[f"ref__{k}"] for _, z in rows]).astype(np.float64) + if mm.endswith("idql"): + idql_seen.setdefault(mm, {})[name] = (raw, ref) + continue + val_scores[f"{name}|{mm}:raw"] = raw + val_scores[f"{name}|{mm}:centered"] = raw - ref + # the IQL critic does not depend on the RSM checkpoint, so it must read IDENTICALLY in every cell. + for mm, per in idql_seen.items(): + base = list(per)[0] + for n2 in per: + d = float(np.max(np.abs(per[n2][0] - per[base][0]))) + if d > 1e-5: + print(f"[red] WARNING {mm} differs between {base} and {n2} by {d:.3g} -- " + f"a checkpoint-independent scorer should not", flush=True) + val_scores[f"(shared)|{mm}:raw"] = per[base][0] + val_scores[f"(shared)|{mm}:centered"] = per[base][0] - per[base][1] + + ALL = {**ref_scores, **val_scores} + + # ---- caliper ladder + pairs = {} + for cal in a.calipers: + ip, io, dd = match_pairs(Z, y, ep, cal) + neps = len(np.unique(np.concatenate([ep[ip], ep[io]]))) if len(ip) else 0 + pairs[cal] = (ip, io, neps) + print(f"[red] caliper={cal:g}: pairs={len(ip)} episodes={neps} " + f"median_d={np.median(dd) if len(ip) else float('nan'):.4f}", flush=True) + + # ---- permuted zero line, at the REPORT caliper: permute route across episodes, REMATCH, recompute. + # The value arms need no refit (the RSM is a fixed model), so this null prices exactly the matching + # and the label, which is what a conditional AUC on matched pairs is at risk from. + cal_r = a.report_caliper + perm = {k: [] for k in ALL} + if a.perm_null > 0 and len(pairs[cal_r][0]) >= a.min_pairs: + print(f"[red] PERMNULL n={a.perm_null} at caliper {cal_r:g} (rematch; refit for the two " + f"supervised arms, none needed for the values)", flush=True) + for r in range(a.perm_null): + yp = perm_labels(y, ep, 10_000 + r) + ipp, iop, _ = match_pairs(Z, yp, ep, cal_r) + if len(ipp) < a.min_pairs: + continue + sp = dict(ALL) + # every FITTED arm is refit on the permuted label; the value arms are fixed models and are not. + for kf, (Xf, mf) in fit_specs.items(): + sp[kf] = fit_arm(Xf, yp, ep, a.folds, a.seed, mf) + for k in ALL: + v, _, _ = cond_auc(sp[k], ipp, iop) + if np.isfinite(v): + perm[k].append(v) + if (r + 1) % 50 == 0: + print(f"[red] permnull {r+1}/{a.perm_null} {time.time()-t0:.0f}s", flush=True) + + res = [] + for cal in a.calipers: + ip, io, neps = pairs[cal] + if len(ip) < a.min_pairs: + print(f"[red] caliper={cal:g} UNDEFINED: {len(ip)} pairs < {a.min_pairs}", flush=True) + continue + for k, s in ALL.items(): + v, n, ties = cond_auc(s, ip, io) + bm, se, ci = cond_boot(s, ip, io, ep, B=a.boot, seed=a.seed) + sf = s[np.isfinite(s)] + cv = float(np.std(sf) / max(abs(np.mean(sf)), 1e-9)) + pv = np.array(perm[k]) if cal == cal_r else np.array([]) + row = dict(caliper=cal, arm=k, auc=v, se=se, ci=ci, n_pairs=n, n_eps=neps, ties=ties, + score_cv=cv, + perm_mean=float(pv.mean()) if len(pv) else None, + perm_q95=float(np.quantile(pv, .95)) if len(pv) else None, + perm_n=int(len(pv)), + perm_p=(float((1 + int((pv >= v).sum())) / (1 + len(pv))) if len(pv) else None)) + res.append(row) + tag = "" + if len(pv): + tag = f"perm={row['perm_mean']:.4f} q95={row['perm_q95']:.4f} p={row['perm_p']:.3f}" + print(f"[red] cal={cal:<5g} {k:<34s} condAUC={v:.4f} +-{se:.4f} [{ci[0]:.3f},{ci[1]:.3f}] " + f"pairs={n} eps={neps} ties={ties} cv={cv:.3g} {tag}", flush=True) + + guard = [r for r in res if r["caliper"] == cal_r and r["arm"].startswith("GUARD")] + ceil = [r for r in res if r["caliper"] == cal_r and r["arm"].startswith("CEILING")] + g = guard[0] if guard else None + c = ceil[0] if ceil else None + + out = Path(a.out) + with open(out, "w") as fh: + fh.write("# The RSM on the caliper-matched S2 pairs (gen_q#280 / rsm_real#2)\n\n") + fh.write(f"Anchors {len(y)} over {len(np.unique(ep))} episodes, subset={a.subset}, S2, entry window " + f"{rows0[0][0]['entry_window']}, stride {rows0[0][0]['stride']}, L={rows0[0][0]['L']}, " + f"reference bank M={len(rows0[0][0]['bank'])} (label-balanced, shared across every anchor " + f"and every cell).\n\n") + if g and c: + fh.write(f"At the report caliper {cal_r:g}: **{g['n_pairs']} pairs over {g['n_eps']} episodes**, " + f"anchor GUARD `anchor:logreg` **{g['auc']:.3f}** (must be ~0.5 for the caliper to be " + f"clean), supervised CEILING `chunk:logreg` **{c['auc']:.3f}**, measured permuted zero " + f"line per row.\n\n") + fh.write("| caliper | arm | condAUC | +-SE | 95% CI | permuted mean | perm q95 | exact p | pairs | eps | ties | score CV |\n") + fh.write("|---|---|---|---|---|---|---|---|---|---|---|---|\n") + for r in res: + pm = f"{r['perm_mean']:.4f}" if r["perm_mean"] is not None else "--" + pq = f"{r['perm_q95']:.4f}" if r["perm_q95"] is not None else "--" + pp = f"{r['perm_p']:.3f}" if r["perm_p"] is not None else "--" + fh.write(f"| {r['caliper']:g} | `{r['arm']}` | {r['auc']:.4f} | {r['se']:.4f} | " + f"[{r['ci'][0]:.3f},{r['ci'][1]:.3f}] | {pm} | {pq} | {pp} | {r['n_pairs']} | " + f"{r['n_eps']} | {r['ties']} | {r['score_cv']:.3g} |\n") + json.dump(dict(results=res, config=vars(a), n_anchors=int(len(y)), + n_episodes=int(len(np.unique(ep)))), + open(str(out).replace(".md", ".json"), "w"), indent=1, default=str) + print(f"[red] done {time.time()-t0:.0f}s -> {out}", flush=True) + + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/real/pt_pairs_rsm_reduce.sh b/rsm_rise/scripts/real/pt_pairs_rsm_reduce.sh new file mode 100644 index 0000000000000000000000000000000000000000..b4da5aa6d5030e25b7af03cb1bf182514ca377ed --- /dev/null +++ b/rsm_rise/scripts/real/pt_pairs_rsm_reduce.sh @@ -0,0 +1,38 @@ +#!/bin/bash +# gen_q#280 / rsm_real#2 -- the OWED table: the RSM's conditional AUC on the SAME caliper-matched S2 pairs +# where a supervised read of the logged chunk reaches 0.983 and a ONE-SCALAR read of dz reaches 0.881. +# Run 17 moved the bar from 0.509 to 0.881 and it is read on `centered` ONLY (raw can be won by anchor +# level; centered subtracts the anchor's own mean over the shared 16-chunk bank in the value's own units). +# Nine cells reached 98/98 parts at 2026-09-24 02:07Z; every partial cell is EXCLUDED, not reported partial. +# pp_RM_b099 / pp_RMs1_b099 -- base R_M, the seed pair +# pp_RMnt_b099 / pp_RMnts1_b099 -- TASK C cap isolation at width 1024, the seed pair +# pp_XL_b099 / pp_XLnt_b099 -- TASK C cap isolation at width 2048 (the untested sim recipe) +# pp_RM_peranchor -- TASK B arm 2, each anchor at a beta its own cap supports +# pp_RM_bg_degen -- beta == gamma, #280's own declared NEGATIVE CONTROL +# pp_IDQLCPU -- the IQL baseline column, already reported, re-reduced on the +# SAME pair set so the comparison is within one anchor set +set -uo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +export MUJOCO_GL=disable +PY=venv_rsm/bin/python +CELLS="pp_IDQLCPU pp_RM_b099 pp_RMs1_b099 pp_RMnt_b099 pp_RMnts1_b099 pp_XL_b099 pp_XLnt_b099 pp_RM_peranchor pp_RM_bg_degen" + +echo "=============== part counts at reduce time ===============" +for C in $CELLS; do echo " $C $(ls status/real/${C}/parts 2>/dev/null | wc -l)/98"; done + +# Do not reduce a cell that is not complete: its pairs would sit on fewer episodes than its row-mates. +USE="" +for C in $CELLS; do + N=$(ls status/real/${C}/parts 2>/dev/null | wc -l) + if [ "$N" -ge 98 ]; then USE="$USE $C"; else echo "[pairs] PENDING ${C} ${N}/98 -- EXCLUDED from the table"; fi +done +echo "[pairs] reducing:$USE" + +# Calipers: run 17 established that >= 1.25 must not be quoted (the guard drifts off 0.5 there, so a chunk +# row can read leftover anchor). They are still COMPUTED so the ladder is visible, and the reported +# caliper stays 1.0. +$PY scripts/real/pt_pairs_reduce.py --cells $USE \ + --calipers 0.9 1.0 1.25 1.5 2.0 --report-caliper 1.0 --min-pairs 30 \ + --out status/real/PT_PAIRS_RSM.md 2>&1 +echo "[pairs] exit=$?" +echo "[pairs] done" diff --git a/rsm_rise/scripts/real/pt_pairs_score.py b/rsm_rise/scripts/real/pt_pairs_score.py new file mode 100644 index 0000000000000000000000000000000000000000..c347663cbc420d61d62c6cfdbca6fd690f77c163 --- /dev/null +++ b/rsm_rise/scripts/real/pt_pairs_score.py @@ -0,0 +1,222 @@ +#!/usr/bin/env python +"""gen_q#280 / rsm_real#2 -- score the RSM on the SAME caliper-matched S2 pairs where a supervised read +of the logged 8-frame chunk reaches conditional AUC 0.983. + +WHY THIS MEASUREMENT AND NOT ANOTHER SWEEP WAVE. Job 1887248/1887256 measured a CEILING: at S2 anchors +matched 1-1 across routes in standardised anchor space (caliper 1.0, anchor GUARD `anchor:logreg` 0.509 on +those same pairs), a logistic read of the logged chunk separates goal-route from cook-route at conditional +AUC 0.983 against a MEASURED rematch-and-refit permuted zero line of 0.468 (exact perm p <= 0.005). That +says the signal exists. It does NOT say the RSM finds any of it, because the RSM has never been scored on +those pairs -- every RSM number in this stream comes from ranking 128 PROPOSER draws under a DIRECTION +margin, a ruler that the same job showed discards ~0.22 AUC (full chunk 0.983 vs direction-only 0.763 on +the identical pairs). So the RSM's 0.46-0.55 confounds three things: a weak value, a lossy label, and a +candidate set that may not span the branch. This script removes two of them at once -- TRUE route labels, +LOGGED chunks, no direction clustering anywhere -- and leaves exactly one question: does the value rank the +goal-route chunk above the cook-route chunk at a matched anchor? + +WHAT IS AND IS NOT A PASS HERE. This is NOT the owner's proposal test and must never be reported as one: +the proposal test scores the proposer's own draws, and that arm is unchanged and still failing. This is +the diagnostic that says whether the defect is in the value or in the ruler, and its ceiling (0.983) and +its zero line (0.468) are printed beside every row. + +THE ANCHOR-LEVEL PROBLEM, AND THE CONTROL FOR IT. A pair's two members sit at two different (matched) +anchors, so a scorer that reads only the anchor could win without reading the chunk at all. The supervised +table handles this with the `anchor:logreg` GUARD, which reads 0.509 at caliper 1.0. The RSM has no such +decomposition, so this script measures one directly: at every anchor it scores the logged chunk AND a +SHARED reference bank of M logged chunks (the same bank at every anchor, drawn label-balanced with a fixed +seed), and emits two arms + + raw = V(anchor, its own logged chunk) + centered = V(anchor, its own logged chunk) - mean_m V(anchor, bank_m) + +`centered` subtracts the anchor's own level in the value's units, so it cannot be won by anchor level; the +gap between `raw` and `centered` is how much of any raw number was anchor and not action. The bank chunks +are off-manifold at most anchors, which is stated rather than hidden -- it is the same off-manifold status +a proposer draw has, and the bank is IDENTICAL across anchors, routes and cells, so it cannot tilt a pair. + +Episode hygiene: anchors come from proposal_ceiling.build unchanged (S2, entry window, stride, t+L<=T), so +the anchor set is byte-identical to the one the 0.983 ceiling was measured on. The RSM is a fixed model +and needs no fold, but its TRAINING set is not episode-disjoint from these anchors; every anchor therefore +carries its SELECT/CONFIRM split tag so the reduction can subset to held-out episodes and report both. +""" +from __future__ import annotations +import argparse, json, sys, time +from pathlib import Path +import numpy as np + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from proposal_ceiling import ROOT, build + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--out", required=True) + ap.add_argument("--tag", required=True) + ap.add_argument("--hdf5", default=f"{ROOT}/data/raw/cooking_v5_expert_suboptimal.hdf5") + ap.add_argument("--split", default=f"{ROOT}/data/derived/cooking_v5_split.json") + ap.add_argument("--state", type=int, default=2) + ap.add_argument("--route-pos", default="[2, 3, 4]") + ap.add_argument("--route-neg", default="[0, 2, 3]") + ap.add_argument("--stride", type=int, default=5) + ap.add_argument("--entry-window", type=int, default=100) + ap.add_argument("--lengths", type=int, nargs="+", default=[8]) + ap.add_argument("--bank", type=int, default=16, help="shared reference chunks per anchor (label-balanced)") + ap.add_argument("--bank-seed", type=int, default=7) + ap.add_argument("--ep-shard", default="") + ap.add_argument("--no-resume", action="store_true") + # scorers + ap.add_argument("--idql-ckpt", default="") + ap.add_argument("--rsm-ckpt", default="") + ap.add_argument("--rsm-cache", default=f"{ROOT}/cache/real_cooking_v5") + ap.add_argument("--rsm-hop-ckpt", default=f"{ROOT}/runs/real_cooking_v5/hop/flow/policy_r1.pt") + ap.add_argument("--rsm-backend", default="mlp") + ap.add_argument("--rsm-mode", default="chain") + ap.add_argument("--rsm-depth", type=int, default=1) + ap.add_argument("--rsm-beta", type=float, default=0.99) + ap.add_argument("--rsm-gamma", type=float, default=0.999) + ap.add_argument("--rsm-particles", type=int, default=16) + ap.add_argument("--rsm-score-kind", default="prob") + ap.add_argument("--rsm-temperature", type=float, default=25.0) + ap.add_argument("--rsm-beta-mode", default="fixed", choices=["fixed", "per_anchor"]) + ap.add_argument("--beta-trunc-eps", type=float, default=0.02) + ap.add_argument("--seed", type=int, default=0) + a = ap.parse_args() + t0 = time.time() + import h5py + out = Path(a.out); out.mkdir(parents=True, exist_ok=True) + parts = out / "parts"; parts.mkdir(exist_ok=True) + Lmax = max(a.lengths) + + rows, n_drop, n_eps_lab = build(a) + if not rows: + print("[pairs] NO ANCHORS", flush=True); sys.exit(2) + ep_all = np.array([r["ep"] for r in rows]) + y_all = np.array([r["y"] for r in rows], int) + print(f"[pairs] anchors={len(rows)} episodes={len(np.unique(ep_all))} goal={int(y_all.sum())} " + f"other={int((1-y_all).sum())} dropped_by_L={n_drop} window={a.entry_window}", flush=True) + + # ---- the SHARED reference bank: label-balanced, fixed seed, identical at every anchor and every cell. + rng = np.random.default_rng(a.bank_seed) + half = a.bank // 2 + pick = [] + for lab in (1, 0): + ii = np.flatnonzero(y_all == lab) + pick.append(rng.choice(ii, min(half, len(ii)), replace=False)) + bank_idx = np.concatenate(pick) + BANK = np.stack([rows[i]["chunk"] for i in bank_idx]).astype(np.float32) # [M, Lmax, 10] + bank_src = [[int(rows[i]["ep"]), int(rows[i]["t"]), int(rows[i]["y"])] for i in bank_idx] + print(f"[pairs] reference bank M={len(BANK)} (label-balanced, seed {a.bank_seed}) " + f"src={bank_src[:3]}...", flush=True) + + # ---- scorers. Same construction as proposal_test.py, so a row here and a row there differ only in + # what is being scored, never in how the value is read out. + from twin_rollout import Scorer # noqa + with h5py.File(a.hdf5, "r") as f: + lo = np.array(json.loads(f["data"].attrs["action_min"]), np.float32) + hi = np.array(json.loads(f["data"].attrs["action_max"]), np.float32) + grip_thresh = float(f["data"].attrs["gripper_thresh"]) + modes = ([] if not a.idql_ckpt else ["idql", "permuted:idql"]) \ + + ([] if not a.rsm_ckpt else ["rsm", "permuted:rsm"]) + if not modes: + print("[pairs] no scorer requested", flush=True); sys.exit(2) + zfeat = pfeat = mu = sd = zclip = ep_from = None + d_in = 1546 + if a.rsm_ckpt: + cache = Path(a.rsm_cache) + zfeat = np.load(cache / "z.f16.npy", mmap_mode="r") + pfeat = np.load(cache / "proprio.f32.npy", mmap_mode="r") + st = np.load(cache / "feat_stats.npz"); m = np.load(cache / "meta.npz", allow_pickle=True) + d_in = zfeat.shape[1] + pfeat.shape[1] + mu, sd = st["mu"][:d_in].astype(np.float32), st["sd"][:d_in].astype(np.float32) + zclip = float(st["z_clip"]) if "z_clip" in st else 10.0 + ep_from = {int(e): int(v) for e, v in enumerate(m["ep_from"])} + kw = dict(rsm_backend=a.rsm_backend, rsm_mode=a.rsm_mode, rsm_depth=a.rsm_depth, + rsm_beta=a.rsm_beta, rsm_gamma=a.rsm_gamma, rsm_particles=a.rsm_particles, + rsm_hop_ckpt=(a.rsm_hop_ckpt if a.rsm_mode.startswith("chain") else ""), + rsm_score_kind=a.rsm_score_kind, rsm_temperature=a.rsm_temperature, rsm_dim=d_in) + scorers = {mm: Scorer(mm, lo, hi, idql_ckpt=(a.idql_ckpt or None), + rsm_ckpt=(a.rsm_ckpt or None), seed=a.seed, **kw) for mm in modes} + print(f"[pairs] tag={a.tag} scorers={modes} beta={a.rsm_beta} mode={a.rsm_beta_mode} " + f"rsm={a.rsm_ckpt or '-'}", flush=True) + + split = json.load(open(a.split))["episodes"] + eps = sorted(set(int(x) for x in ep_all)) + if a.ep_shard: + si, sn = (int(x) for x in a.ep_shard.split("/")) + eps = eps[si::sn] + print(f"[pairs] shard {si}/{sn}: {len(eps)} episodes", flush=True) + by_ep = {} + for i, r in enumerate(rows): + by_ep.setdefault(int(r["ep"]), []).append(i) + + def _k(s): return s.replace(":", "__") + + with h5py.File(a.hdf5, "r") as f: + for ep in eps: + dst = parts / f"ep{ep:06d}.npz" + if dst.exists() and not a.no_resume: + print(f"[pairs] ep {ep} RESUMED", flush=True); continue + ii = by_ep[ep] + g = f["data"][f"demo_{ep}"] + T = len(g["annot"]["edge_from"]) + S = g["obs"]["ee_state"][()].astype(np.float32) + im = {"global": g["obs"]["agentview_image"], "wrist": g["obs"]["robot0_eye_in_hand_image"]} + ts = np.array([rows[i]["t"] for i in ii], int) + # TASK B per-anchor cap, identical formula to proposal_test.py + BCAP = np.clip(a.beta_trunc_eps ** (1.0 / np.maximum(T - ts.astype(np.float64), 1.0)), 0.0, 0.999999) + BUSED = (np.minimum(a.rsm_beta, BCAP) if a.rsm_beta_mode == "per_anchor" + else np.full(len(ts), float(a.rsm_beta))) + RAW = {mm: np.zeros(len(ii), np.float32) for mm in modes} + REF = {mm: np.zeros(len(ii), np.float32) for mm in modes} + REFSD = {mm: np.zeros(len(ii), np.float32) for mm in modes} + # run 21 (gen_q#280): retain the FULL score vector, slot 0 = the episode's own logged chunk, + # slots 1.. = the shared bank. Run 20's slot-0 rank diagnostic had to approximate the rank as + # 1+16*Phi((raw-ref)/refsd) because only the three summaries were stored; with the vector on + # disk the rank, the ties and the argmax are EXACT. Storage is ~17x4 floats per anchor. + SC = {mm: np.zeros((len(ii), 1 + len(BANK)), np.float32) for mm in modes} + for i_t, i in enumerate(ii): + t = int(rows[i]["t"]) + obs = {"state": S[t], "grip_thresh": grip_thresh, + "images84": {c: im[c][t] for c in im}, "images": None, "history": []} + if zfeat is not None: + gi = ep_from[ep] + t + z = np.concatenate([np.asarray(zfeat[gi], np.float32), np.asarray(pfeat[gi], np.float32)]) + obs["rsm_feat"] = np.clip((z - mu) / sd, -zclip, zclip) + cands = np.concatenate([rows[i]["chunk"][None].astype(np.float32), BANK], 0) + for mm in modes: + b_ = float(BUSED[i_t]) if a.rsm_beta_mode == "per_anchor" else None + _, sc = scorers[mm].pick(cands, obs, beta=b_) + sc = np.asarray(sc, np.float64) + RAW[mm][i_t] = sc[0] + REF[mm][i_t] = sc[1:].mean() + REFSD[mm][i_t] = sc[1:].std() + SC[mm][i_t] = sc + meta = dict(episode=int(ep), tag=a.tag, state=a.state, entry_window=a.entry_window, + stride=a.stride, L=Lmax, n_anchors=len(ii), episode_length=int(T), + frames=[int(x) for x in ts], y=int(rows[ii[0]]["y"]), + route=split[str(ep)]["path"], split=split[str(ep)]["split"], + beta_mode=a.rsm_beta_mode, beta_nominal=float(a.rsm_beta), + beta_cap=[float(x) for x in BCAP], beta_used=[float(x) for x in BUSED], + beta_trunc_eps=float(a.beta_trunc_eps), bank=bank_src, modes=modes, + rsm_ckpt=a.rsm_ckpt, idql_ckpt=a.idql_ckpt, rsm_mode=a.rsm_mode, + rsm_depth=a.rsm_depth, rsm_gamma=a.rsm_gamma, rsm_particles=a.rsm_particles, + rsm_score_kind=a.rsm_score_kind, rsm_temperature=a.rsm_temperature) + payload = {f"raw__{_k(mm)}": RAW[mm] for mm in modes} + payload.update({f"ref__{_k(mm)}": REF[mm] for mm in modes}) + payload.update({f"refsd__{_k(mm)}": REFSD[mm] for mm in modes}) + payload.update({f"scores__{_k(mm)}": SC[mm] for mm in modes}) + payload["anchor"] = np.stack([rows[i]["anchor"] for i in ii]).astype(np.float32) + payload["chunk"] = np.stack([rows[i]["chunk"] for i in ii]).astype(np.float32) + payload["t"] = ts.astype(np.int32) + payload["__meta__"] = np.frombuffer(json.dumps(meta).encode(), np.uint8) + tmp = parts / f"ep{ep:06d}.tmp.npz" + np.savez_compressed(tmp, **payload); tmp.rename(dst) + d = {mm: float(np.mean(RAW[mm] - REF[mm])) for mm in modes} + print(f"[pairs] ep {ep} {meta['route']} {meta['split']} anchors={len(ii)} " + f"cap_med={np.median(BCAP):.4f} used_med={np.median(BUSED):.4f} " + f"mean(raw-ref)={ {k: round(v,5) for k,v in d.items()} } {time.time()-t0:.0f}s", flush=True) + print(f"[pairs] done {time.time()-t0:.0f}s -> {out}", flush=True) + + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/real/pt_permnull_verdict.py b/rsm_rise/scripts/real/pt_permnull_verdict.py new file mode 100644 index 0000000000000000000000000000000000000000..543a9da677a1d28dc290fe061f5455218fae7d96 --- /dev/null +++ b/rsm_rise/scripts/real/pt_permnull_verdict.py @@ -0,0 +1,124 @@ +#!/usr/bin/env python +"""gen_q#280 / rsm_real#2 -- PROPOSAL_TEST run 35. + +Reads the calibrated-null jsons written by `pt_resid_permnull.sh` (job 1897123) and the published +residualised ceiling json, and prints the pre-registered verdict table: for each (model, L), the +observed nested marginal at every seed beside the 200-draw episode-level permutation null's mean, +sd, q95 and q99, plus the empirical one-sided p with the (+1/+1) correction. + +PRE-REGISTERED READING (comment 5813378103 / 5813378398, fixed before the mlp numbers existed): + (B) CONFIRMED if the observed marginal exceeds the null's q95 for that model and L. + (A) fires otherwise. +This is a CEILING, not a scorer: every arm is fitted on the label and no row is a pass candidate. +""" +import json, sys +import numpy as np + +CEIL = "status/real/pt_ceilresid_w100_goal_vs_cook/ceiling.json" +NULLS = {"logreg": "status/real/pt_permnull_w100_goal_vs_cook_logreg/ceiling.json", + "mlp": "status/real/pt_permnull_w100_goal_vs_cook_mlp/ceiling.json"} +# tag as stored in the published ceiling json -> (null field, pair name, label) +PAIRS = [("real", "diff", "both:{m} - anchor:{m}", "raw "), + ("resid", "diff_resid", "both:{m} - anchorgeom:{m}", "resid")] + +ceil = json.load(open(CEIL)) +obs = {} +for r in ceil["paired"]: + obs[(r["tag"], r["pair"], r["L"], r["seed"])] = r +n_anch, n_eps = ceil["n_anchors"], ceil["n_episodes"] + +print(f"C2 goal_vs_cook, S2, entry window 100, {n_anch} anchors / {n_eps} episodes, " + f"5-fold episode-disjoint CV, 200 episode-level label permutations refit end to end.\n") +hdr = (f"{'arm':<40} {'L':>3} {'null mean':>10} {'null sd':>8} {'q95':>9} {'q99':>9} " + f"{'s0':>9} {'s1':>9} {'s2':>9} {'>q95':>6} {'emp p (s0/s1/s2)':>22}") +print(hdr); print("-" * len(hdr)) +verdicts = {} +for model, path in NULLS.items(): + try: + nl = json.load(open(path))["perm_null"] + except FileNotFoundError: + print(f"{model:<40} -- null json not written yet ({path}) -- UNDEFINED") + continue + for tag, field, pat, lab in PAIRS: + pair = pat.format(m=model) + for L in sorted({d["L"] for d in nl if d["model"] == model}): + draws = np.sort(np.array([d[field] for d in nl if d["model"] == model and d["L"] == L], float)) + # EXACTLY the convention proposal_ceiling.py printed and this stream published: + # the sorted draw at index int(q*n), i.e. the conservative upper order statistic. + q95, q99 = draws[int(0.95 * len(draws))], draws[int(0.99 * len(draws))] + cells, ps, above = [], [], 0 + for s in (0, 1, 2): + r = obs.get((tag, pair, L, s)) + if r is None: + cells.append(" -- "); ps.append(" -- "); continue + d = r["diff"]; cells.append(f"{d:+.4f}") + ps.append(f"{(int((draws >= d).sum()) + 1) / (len(draws) + 1):.3f}") + above += int(d > q95) + verdicts[(model, tag, L)] = above + print(f"{lab+' '+pair:<40} {L:>3} {draws.mean():>+10.4f} {draws.std(ddof=1):>8.4f} " + f"{q95:>+9.4f} {q99:>+9.4f} {cells[0]:>9} {cells[1]:>9} {cells[2]:>9} " + f"{str(above)+'/3':>6} {'/'.join(ps):>22} n={len(draws)}") +print() +tot = sum(verdicts.values()); ncell = 3 * len(verdicts) +print(f"VERDICT: {tot} of {ncell} (model x arm x L x seed) cells above their own null q95.") +print("(B) CONFIRMED on those cells" if tot else + "(A) FIRES -- no cell clears its calibrated null; the marginal is UNDECLARED, raw and residualised alike.") + +# --------------------------------------------------------------------------- +# RESOLUTION, so that (A) is not over-read as "the chunk carries nothing". +# q95 is the smallest marginal this design could have DECLARED; the paired +# episode-bootstrap CI upper end is the largest the data are consistent with. +# An observed value that sits between them is undeclared for want of power, +# which is a different statement from a measured zero. +print("\nRESOLUTION of this design (MDE = the null q95 it must clear; UB = widest bootstrap CI upper over seeds):") +for model, path in NULLS.items(): + try: + nl = json.load(open(path))["perm_null"] + except FileNotFoundError: + print(f" {model:<7} -- UNDEFINED, null json not written"); continue + for tag, field, pat, lab in PAIRS: + pair = pat.format(m=model) + for L in sorted({d["L"] for d in nl if d["model"] == model}): + draws = np.sort(np.array([d[field] for d in nl + if d["model"] == model and d["L"] == L], float)) + mde = draws[int(0.95 * len(draws))] + rows = [obs[(tag, pair, L, s)] for s in (0, 1, 2) if (tag, pair, L, s) in obs] + if not rows: + continue + best = max(r["diff"] for r in rows) + ub = max(r["ci_hi"] for r in rows) + print(f" {lab} {pair:<36} L={L:<3} MDE(q95)={mde:+.4f} best obs={best:+.4f} " + f"bootstrap UB={ub:+.4f} -> true effect not excluded below {ub:+.4f}, " + f"not declarable below {mde:+.4f}") + +# --------------------------------------------------------------------------- +# REGRESSION GUARD. The null jobs re-fit the whole ceiling at seed0 before drawing +# the null, so every arm and paired row they share with the PUBLISHED ceiling must +# reproduce bit-for-bit -- otherwise the null is calibrating a different effect. +# NOTE the key: `arm` alone COLLIDES (the same arm appears under several +# `chunk_feat` variants), and keying on it alone fabricates deltas up to 3e-3. +print("\nREGRESSION GUARD against the published ceiling:") +pubres = {(r["arm"], r.get("chunk_feat"), r["L"], r["seed"]): r for r in ceil["results"]} +pubpair = {(r["tag"], r["pair"], r["L"], r["seed"]): r for r in ceil["paired"]} +tot = miss = 0; worst = 0.0; worstk = None +for model, path in NULLS.items(): + try: + d = json.load(open(path)) + except FileNotFoundError: + print(f" {model}: null json absent -- GUARD UNDEFINED"); continue + for r in d["results"]: + k = (r["arm"], r.get("chunk_feat"), r["L"], r["seed"]) + if k not in pubres: miss += 1; continue + for f in ("auc", "se", "ci_lo", "ci_hi", "auc_episode", "n", "n_eps"): + delta = abs(r[f] - pubres[k][f]); tot += 1 + if delta > worst: worst, worstk = delta, (model, k, f) + for r in d["paired"]: + k = (r["tag"], r["pair"], r["L"], r["seed"]) + if k not in pubpair: miss += 1; continue + for f in ("diff", "se", "ci_lo", "ci_hi", "n", "n_eps"): + delta = abs(r[f] - pubpair[k][f]); tot += 1 + if delta > worst: worst, worstk = delta, (model, k, f) +ok = worst == 0.0 and miss == 0 +print(f" [GUARD] {'PASS' if ok else 'FAIL'}: {tot} published fields reproduced, " + f"worst |delta| = {worst:.3e} at {worstk}, {miss} unmatched") +sys.exit(0 if ok else 1) diff --git a/rsm_rise/scripts/real/pt_plaus.py b/rsm_rise/scripts/real/pt_plaus.py new file mode 100644 index 0000000000000000000000000000000000000000..3afb734579b8bf8682bea81f55ba9601f1946bda --- /dev/null +++ b/rsm_rise/scripts/real/pt_plaus.py @@ -0,0 +1,140 @@ +#!/usr/bin/env python +""" +PROPOSAL_TEST run 42 -- the PLAUSIBILITY GUARD, pre-registered in gen_q#280 / rsm_real#2 before the +noise-scale wave was submitted. It is a guard, not a result, and it can only DISQUALIFY a rung. + +WHY IT EXISTS. Run 41 recorded as MY ERROR that its KILL branch carried no plausibility constraint on the +draws, which let `pt_cov_risebn` clear the coverage gate at 210/210 anchors on a 332 mm mean candidate +displacement -- a uniform workspace point, not a proposal. Scaling a flow model's initial noise moves the +start point off the N(0, I) pi0.5 was trained to integrate from, so the large rungs of run 42's ladder are +out-of-distribution queries by construction and are EXPECTED to degrade. The two disqualifiers were +therefore written down as numbers in advance: + (a) realised mean candidate displacement > 32.2 mm (2x the logged 16.1 mm); + (b) mean distance to the NEAREST logged chunk at the same anchor > 3x the scale-1.0 rung's. +(a) is already measured by `pt_proposer_destiny.py` as `disp_prop`. This file measures (b). + +DEFINITION of (b), fixed here so it cannot drift. At each matched anchor, the logged pool is the +`--donors` logged S2 chunks drawn from OTHER episodes by the same RNG the destiny arm uses +(`rng_seed = 90210`, the run-40 value), and the distance is Euclidean in the destiny instrument's OWN +feature space, `proposal_ceiling.chunk_feat(..., "waypoints")` -- chunk waypoints relative to the chunk's +first action, in mm. Per anchor: mean over the 128 draws of the min over the pool. Also reported in raw +metres-of-displacement terms so the number is physically readable. + +`pt_proposer_destiny.py`, `pt_within_anchor.py` and `proposal_ceiling.py` are IMPORTED UNEDITED. +NO AUC is computed anywhere in this file; proposer draws carry no route label. +NO-RULER: `margin` and `cand_dir_mm` are never read. +""" +import argparse, json, time +from pathlib import Path +from types import SimpleNamespace +import numpy as np + +ROOT = "/proj/dmfexp/zwhong/rsm_rise" +_T0 = [time.time()] + +import importlib.util +def _load(name, path): + spec = importlib.util.spec_from_file_location(name, path) + m = importlib.util.module_from_spec(spec); spec.loader.exec_module(m); return m + +PD = _load("pt_proposer_destiny", f"{ROOT}/scripts/real/pt_proposer_destiny.py") +PC = PD.PC +WA = PD.WA + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--out", required=True) + ap.add_argument("--tags", nargs="+", required=True) + ap.add_argument("--ref-tag", required=True, help="the scale-1.0 rung, the denominator of disqualifier (b)") + ap.add_argument("--cache-root", default=f"{ROOT}/status/real") + ap.add_argument("--hdf5", default=f"{ROOT}/data/raw/cooking_v5_expert_suboptimal.hdf5") + ap.add_argument("--split", default=f"{ROOT}/data/derived/cooking_v5_split.json") + ap.add_argument("--state", type=int, default=2) + ap.add_argument("--route-pos", default="[2, 3, 4]") + ap.add_argument("--route-neg", default="[0, 2, 3]") + ap.add_argument("--stride", type=int, default=5) + ap.add_argument("--entry-window", type=int, default=100) + ap.add_argument("--length", type=int, default=8) + ap.add_argument("--donors", type=int, default=128) + ap.add_argument("--rng-seed", type=int, default=90210) + ap.add_argument("--boot", type=int, default=2000) + a = ap.parse_args() + + L = a.length + # ---- host anchors: built by proposal_ceiling.build, the SAME call pt_proposer_destiny.main makes, + # with the same fields. Not re-implemented here. + hrows, n_drop, n_ep = PC.build(SimpleNamespace( + hdf5=a.hdf5, split=a.split, state=a.state, route_pos=a.route_pos, route_neg=a.route_neg, + stride=a.stride, entry_window=a.entry_window, lengths=[L])) + ep = np.array([r["ep"] for r in hrows]); y = np.array([r["y"] for r in hrows]) + fr = np.array([r["t"] for r in hrows]); CH = np.stack([r["chunk"] for r in hrows]) + print(f"[plaus] HOST anchors={len(hrows)} episodes={len(np.unique(ep))}/{n_ep} " + f"window={a.entry_window} L={L} stride={a.stride} dropped={n_drop} " + f"pos={int((y==1).sum())} neg={int((y==0).sum())} [{time.time()-_T0[0]:.0f}s]", flush=True) + + CFlog = PC.chunk_feat(CH, L, "waypoints") + rows = {} + for tag in a.tags: + cands, ceps = PD.load_proposer(tag, a.cache_root) + nn_feat, nn_mm, disp, n = [], [], [], 0 + rng = np.random.default_rng([a.rng_seed, 0, 0]) + for i in range(len(y)): + key = (int(ep[i]), int(fr[i])) + if key not in cands: + continue + pool = np.where(ep != ep[i])[0] + if len(pool) < a.donors: + continue + don = rng.choice(pool, a.donors, replace=False) + C = cands[key][:, :L, :] + CFp = PC.chunk_feat(C, L, "waypoints") + d = np.linalg.norm(CFp[:, None, :] - CFlog[don][None, :, :], axis=-1) # [K, donors] + nn_feat.append(float(d.min(1).mean())) + # raw physical reading: displacement-vector distance in mm + vp = 1000.0 * (C[:, -1, :3] - C[:, 0, :3]) + vl = 1000.0 * (CH[don][:, L - 1, :3] - CH[don][:, 0, :3]) + dm = np.linalg.norm(vp[:, None, :] - vl[None, :, :], axis=-1) + nn_mm.append(float(dm.min(1).mean())) + disp.append(float(np.linalg.norm(vp, axis=-1).mean())) + n += 1 + if not n: + rows[tag] = dict(status="UNDEFINED", reason="no matched anchors"); continue + eps_ = np.array([int(ep[i]) for i in range(len(y)) + if (int(ep[i]), int(fr[i])) in cands and len(np.where(ep != ep[i])[0]) >= a.donors]) + d = dict(status="OK", n=n, n_ep=int(len(np.unique(eps_)))) + for k, v in (("nn_feat", nn_feat), ("nn_mm", nn_mm), ("disp_mm", disp)): + m, se, lo, hi = WA.ep_boot_mean(np.array(v), eps_, B=a.boot, seed=0) + d[k], d[k + "_se"] = float(m), float(se) + rows[tag] = d + print(f"[plaus] {tag:34s} n={n:4d}/{d['n_ep']:2d}ep nn_feat={d['nn_feat']:9.2f} " + f"nn_mm={d['nn_mm']:7.2f} disp_mm={d['disp_mm']:7.2f}", flush=True) + + ref = rows.get(a.ref_tag, {}) + if ref.get("status") == "OK": + for tag, r in rows.items(): + if r.get("status") != "OK": + continue + r["nn_feat_ratio_vs_ref"] = r["nn_feat"] / ref["nn_feat"] + r["disq_disp_gt_32p2mm"] = bool(r["disp_mm"] > 32.2) + r["disq_nn_gt_3x_ref"] = bool(r["nn_feat_ratio_vs_ref"] > 3.0) + r["DISQUALIFIED"] = bool(r["disq_disp_gt_32p2mm"] or r["disq_nn_gt_3x_ref"]) + print(f"[plaus] {tag:34s} nn_ratio={r['nn_feat_ratio_vs_ref']:5.2f}x " + f"disp>32.2mm={r['disq_disp_gt_32p2mm']} nn>3x={r['disq_nn_gt_3x_ref']} " + f"=> DISQUALIFIED={r['DISQUALIFIED']}", flush=True) + else: + print(f"[plaus] REFERENCE RUNG {a.ref_tag} IS NOT OK -- disqualifier (b) is UNDEFINED for every " + f"row and only (a), the 32.2 mm displacement bar, can be applied.", flush=True) + for tag, r in rows.items(): + if r.get("status") == "OK": + r["disq_disp_gt_32p2mm"] = bool(r["disp_mm"] > 32.2) + r["disq_nn_gt_3x_ref"] = None + r["DISQUALIFIED"] = r["disq_disp_gt_32p2mm"] + + out = Path(a.out); out.mkdir(parents=True, exist_ok=True) + json.dump(dict(config=vars(a), rows=rows), open(out / "plaus.json", "w"), indent=1) + print(f"[plaus] wrote {out/'plaus.json'} [{time.time()-_T0[0]:.0f}s]", flush=True) + + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/real/pt_plaus_grid.sh b/rsm_rise/scripts/real/pt_plaus_grid.sh new file mode 100644 index 0000000000000000000000000000000000000000..ec9b7bd5b388d265dddc75f1a6099125d8ba9207 --- /dev/null +++ b/rsm_rise/scripts/real/pt_plaus_grid.sh @@ -0,0 +1,16 @@ +#!/bin/bash +# PROPOSAL_TEST run 47 -- the PLAUSIBILITY GUARD applied to the ALREADY-MEASURED sn x knn proposer grid. +# Run 47 established that candidate spread can be bought with sampling temperature but only OFF the logged +# action manifold (nn ratio 3.0x at scale 1.10). The grid's coverage was measured long ago and never +# plausibility-checked, and `cov_risebn` gates 315/315 anchors / 15 eps. The question this answers is +# whether that pass is real or the same near-isotropic artefact. Reference is the published default cell. +set -euo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +export MUJOCO_GL=disable OMP_NUM_THREADS=8 MKL_NUM_THREADS=8 OPENBLAS_NUM_THREADS=8 +exec venv_rsm/bin/python scripts/real/pt_plaus.py \ + --out status/real/pt_R47_grid_plaus \ + --tags pt_cov_sn1_knn0p03 pt_cov_risebn pt_cov_rise pt_cov_riseadv pt_cov_wsctrl pt_cov_stock \ + pt_cov_sn1_knn0p05 pt_cov_sn0p3_knn0p03 pt_cov_sn0p3_knn0p01 pt_cov_sn0p1_knn0p03 \ + pt_cov_sn0p1_knn0p05 pt_cov_sn0p03_knn0p01 \ + --ref-tag pt_cov_sn1_knn0p03 \ + --entry-window 100 --length 8 --donors 128 --rng-seed 90210 --boot 2000 diff --git a/rsm_rise/scripts/real/pt_plaus_r46.sh b/rsm_rise/scripts/real/pt_plaus_r46.sh new file mode 100644 index 0000000000000000000000000000000000000000..2641986ffe5688314e6bc4487f66108eac85cb01 --- /dev/null +++ b/rsm_rise/scripts/real/pt_plaus_r46.sh @@ -0,0 +1,15 @@ +#!/bin/bash +# PROPOSAL_TEST run 47 -- the pre-registered PLAUSIBILITY GUARD on the R46 FINE noise-scale ladder. Reference rung +# is scale 1.0. Disqualifiers, both fixed before the wave was submitted: disp > 32.2 mm (2x the logged +# 16.1 mm), or nearest-logged-chunk distance > 3x the scale-1.0 rung's. +set -euo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +export MUJOCO_GL=disable OMP_NUM_THREADS=8 MKL_NUM_THREADS=8 OPENBLAS_NUM_THREADS=8 +exec venv_rsm/bin/python scripts/real/pt_plaus.py \ + --out status/real/pt_R47_fine_plaus \ + --tags pt_cov_sn1_knn0p03 \ + pt_R46_cov_sn1_knn0p03_T10 pt_R46_cov_sn1_knn0p03_F105 pt_R46_cov_sn1_knn0p03_F110 \ + pt_R46_cov_sn1_knn0p03_F115 pt_R46_cov_sn1_knn0p03_F120 pt_R46_cov_sn1_knn0p03_F125 \ + pt_R46_cov_sn1_knn0p03_F130 pt_R46_cov_sn1_knn0p03_F140 \ + --ref-tag pt_R46_cov_sn1_knn0p03_T10 \ + --entry-window 100 --length 8 --donors 128 --rng-seed 90210 --boot 2000 diff --git a/rsm_rise/scripts/real/pt_plaus_smoke.sh b/rsm_rise/scripts/real/pt_plaus_smoke.sh new file mode 100644 index 0000000000000000000000000000000000000000..d03e8b09abd231c59777763329ec3d6b26431138 --- /dev/null +++ b/rsm_rise/scripts/real/pt_plaus_smoke.sh @@ -0,0 +1,13 @@ +#!/bin/bash +# PROPOSAL_TEST run 42 -- validate the pre-registered PLAUSIBILITY GUARD on the EXISTING caches, before the +# noise-scale caches land. POSITIVE CONTROL: `pt_cov_risebn` must be DISQUALIFIED -- run 41 measured its +# mean candidate displacement at 332.0 mm against 10.7-12.5 mm for every other cell, and it cleared the +# coverage gate 210/210 on that basis. A guard that does not flag it is not a guard. NOT A RESULT. +set -euo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +export MUJOCO_GL=disable OMP_NUM_THREADS=8 MKL_NUM_THREADS=8 OPENBLAS_NUM_THREADS=8 +exec venv_rsm/bin/python scripts/real/pt_plaus.py \ + --out status/real/pt_plaus_smoke \ + --tags pt_cov_sn1_knn0p03 pt_cov_stock pt_cov_sn0p1_knn0p03 pt_cov_risebn \ + --ref-tag pt_cov_sn1_knn0p03 \ + --entry-window 100 --length 8 --donors 128 --rng-seed 90210 --boot 2000 diff --git a/rsm_rise/scripts/real/pt_post.sh b/rsm_rise/scripts/real/pt_post.sh new file mode 100644 index 0000000000000000000000000000000000000000..c15be13bbb3b52487a0f6f682e20d4285459e4b3 --- /dev/null +++ b/rsm_rise/scripts/real/pt_post.sh @@ -0,0 +1,16 @@ +#!/usr/bin/env bash +# gen_q#280 / rsm_real#2 -- post a markdown body to BOTH issues. usage: pt_post.sh +set -euo pipefail +B=${1:?body.md} +TOK=$(grep -m1 'https://richardrl:' ~/.git-credentials | sed -E 's|https://richardrl:([^@]*)@.*|\1|') +python3 - "$B" > /tmp/pt_body.$$.json <<'PY' +import json,sys +json.dump({"body": open(sys.argv[1]).read()}, sys.stdout) +PY +for U in https://api.github.com/repos/williamd4112/gen_q/issues/280/comments \ + https://api.github.com/repos/jmarangola/rsm_real/issues/2/comments; do + code=$(curl -sS -o /tmp/pt_resp.$$ -w '%{http_code}' -X POST -H "Authorization: token $TOK" \ + -d @/tmp/pt_body.$$.json "$U") + echo "$U -> HTTP $code $(python3 -c "import json;print(json.load(open('/tmp/pt_resp.$$')).get('html_url','')) " 2>/dev/null)" +done +rm -f /tmp/pt_body.$$.json /tmp/pt_resp.$$ diff --git a/rsm_rise/scripts/real/pt_propmatch.sh b/rsm_rise/scripts/real/pt_propmatch.sh new file mode 100644 index 0000000000000000000000000000000000000000..4cf88d1d803cb9805f4eba0dbdbc9c883b4f7342 --- /dev/null +++ b/rsm_rise/scripts/real/pt_propmatch.sh @@ -0,0 +1,16 @@ +#!/bin/bash +# gen_q#280 / rsm_real#2 -- second-proposer confirmation on MATCHED anchors (see pt_proposer_match.py). +set -uo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +export MUJOCO_GL=disable +PY=venv_rsm/bin/python +$PY scripts/real/pt_proposer_match.py \ + status/real/pt_betaB_peranchor status/real/pt_betaB_peranchor_ws \ + --entry-window 100 --oracle-chunk 8 \ + --md status/real/PT_PROPMATCH_peranchor.md \ + --json status/real/PT_PROPMATCH_peranchor.json +echo "[propmatch] peranchor done rc=$?" +# beta 0.99 fixed arm as the seed-mate cross-check: same proposer pair is not available at b099, so only +# the per-anchor pair is matched here. Named explicitly rather than silently omitted. +echo "[propmatch] NOTE: only the per-anchor beta arm has a second-proposer sibling on disk (peranchor_ws)." +echo "[propmatch] done" diff --git a/rsm_rise/scripts/real/pt_proposer_destiny.py b/rsm_rise/scripts/real/pt_proposer_destiny.py new file mode 100644 index 0000000000000000000000000000000000000000..3e14f3a7cf1194c28b20d9dae02086a92dd9b0c5 --- /dev/null +++ b/rsm_rise/scripts/real/pt_proposer_destiny.py @@ -0,0 +1,296 @@ +#!/usr/bin/env python +""" +PROPOSAL_TEST run 41 -- ONE CHANGE from run 40 (`pt_within_anchor.py`): at each host anchor the candidate +set stops being 128 LOGGED donor chunks from other episodes and becomes the PROPOSER'S OWN 128 cached +draws at that same anchor. Everything else -- host anchors, features, models, episode folds, seeds -- +is identical and is imported unedited. + +WHY. Run 40 measured within-anchor ranking AUC 0.95-0.97 for a directly supervised destiny model, but on +LOGGED donors. The proposal test's pass path scores PROPOSER draws. The bridge between the two has never +been measured. This script measures it WITHOUT any direction ruler: the 18:15Z stop-and-reread showed the +nearest-centroid direction proxy is below chance at S2 (47.7 % vs 50 %, oracle AUC 0.467), so the published +coverage gate -- which is defined on that proxy -- cannot be trusted to say whether the proposer spans the +branch. The destiny model here is trained on GROUND-TRUTH route labels of logged episodes, so it is the +clean instrument the coverage question deserves. + +Proposer draws carry NO route label, so NO AUC is computed on them and none is reported. The quantity is +the SPREAD of the destiny score across the proposer's own draws at one anchor, against the spread across +the logged donors at the SAME anchor, plus where the proposer's draws sit inside the logged-donor score +distribution. A collapsed spread means no scorer that is a monotone function of destiny can rank these +candidates, whatever the value function is. + +GUARDS (all printed, all fail loudly): + * REPRODUCTION -- the logged-donor arm re-runs run 40's code path unchanged and must reproduce its + published AUCs to <= 5e-5. + * STRUCTURAL -- the anchor-only arm is constant across candidates by construction: spread must be + exactly 0 at every anchor. + * SCALE -- logged vs proposer chunk displacement in mm at the matched anchors, so a unit or + action-convention mismatch cannot hide. + * NO-RULER -- `margin` and `cand_dir_mm` are never read on any scoring path; asserted at load time. +""" +import argparse, json, time +from pathlib import Path +from types import SimpleNamespace +import numpy as np + +ROOT = "/proj/dmfexp/zwhong/rsm_rise" +_T0 = [time.time()] + +import importlib.util +def _load(name, path): + spec = importlib.util.spec_from_file_location(name, path) + m = importlib.util.module_from_spec(spec); spec.loader.exec_module(m); return m + +PC = _load("proposal_ceiling", f"{ROOT}/scripts/real/proposal_ceiling.py") +WA = _load("pt_within_anchor", f"{ROOT}/scripts/real/pt_within_anchor.py") + +# ---- NO-RULER guard: these keys exist in the cache and must never reach a scoring path here. +_BANNED_KEYS = ("margin", "cand_dir_mm") + + +def load_proposer(tag, cache_root): + """(ep, frame) -> [128, L, 10] absolute-pose candidate chunks. Reads ONLY `cands`.""" + import glob + d = Path(cache_root) / tag + out = {} + eps = set() + for f in sorted(glob.glob(str(d / "parts" / "*.npz"))): + z = np.load(f, allow_pickle=True) + m = json.loads(bytes(z["__meta__"]).decode()) + if not m.get("n_anchors", 0): + continue + for k in _BANNED_KEYS: + assert k != "cands", "NO-RULER guard misconfigured" + C = z["cands"] # <- the ONLY array read + fr = m["frames"] + assert len(fr) == len(C), f"{f}: frames {len(fr)} != cands {len(C)}" + ep = int(m["episode"]); eps.add(ep) + for i, t in enumerate(fr): + out[(ep, int(t))] = C[i] + return out, eps + + +def band(sp, sl): + """Where the proposer's draws sit inside the logged-donor score distribution, as quantiles.""" + q = np.searchsorted(np.sort(sl), sp, side="left") / max(len(sl), 1) + return float(q.min()), float(q.max()), float(np.median(q)) + + +def run_all(AN, CFw, CH, y, ep, fr, a, tagcands, L): + """Fit ONCE per (model, seed, fold); score EVERY tag's draws inside that fold. + + The models depend only on (model, seed, fold), never on the tag, so refitting per tag would be pure + waste and would also invite a seed drift between tags. Fitting once makes every tag's column a + comparison against the SAME destiny model, which is what "one change, the proposer" requires. + """ + from sklearn.model_selection import StratifiedGroupKFold + n = len(y) + XB = np.concatenate([AN, CFw], 1) + keys = ("sd_prop", "sd_log", "sd_prop_chunk", "sd_log_chunk", "sd_anchor", + "rng_prop", "rng_log", "frac_goal_prop", "frac_goal_log", + "qmin", "qmax", "qmed", "disp_prop", "disp_log", "med_prop", "med_log") + store = {} + for model in a.models: + for seed in a.seeds: + for tag in tagcands: + store[(tag, model, seed)] = ( + {k: np.full(n, np.nan) for k in keys}, np.zeros(n, bool)) + skf = StratifiedGroupKFold(n_splits=a.folds, shuffle=True, random_state=seed) + for tr, va in skf.split(XB, y, groups=ep): + mb = WA._mk(model, seed); mb.fit(XB[tr], y[tr]) + ma = WA._mk(model, seed); ma.fit(AN[tr], y[tr]) + mc = WA._mk(model, seed); mc.fit(CFw[tr], y[tr]) + rng = np.random.default_rng([a.rng_seed, seed, int(va[0])]) + pos = va[y[va] == 1]; neg = va[y[va] == 0] + if len(pos) < a.min_side or len(neg) < a.min_side: + continue + dp = rng.choice(pos, min(a.donors // 2, len(pos)), replace=False) + dn = rng.choice(neg, min(a.donors // 2, len(neg)), replace=False) + don = np.concatenate([dp, dn]); dep = ep[don] + anchor_s = np.asarray(ma.predict_proba(AN[va])[:, 1], dtype=np.float64) + chunk_log = np.asarray(mc.predict_proba(CFw[don])[:, 1], dtype=np.float64) + for h, i in enumerate(va): + keep = dep != ep[i] + if keep.sum() < 2 * a.min_side: + continue + Bl = np.concatenate([np.repeat(AN[i][None], int(keep.sum()), 0), + CFw[don][keep]], 1) + sl = np.asarray(mb.predict_proba(Bl)[:, 1], dtype=np.float64) + for tag, cands in tagcands.items(): + key = (int(ep[i]), int(fr[i])) + if key not in cands: + continue + rec, kept = store[(tag, model, seed)] + C = cands[key][:, :L, :] # [K, L, 10] + CFp = PC.chunk_feat(C, L, "waypoints") + Bp = np.concatenate([np.repeat(AN[i][None], len(CFp), 0), CFp], 1) + sp = np.asarray(mb.predict_proba(Bp)[:, 1], dtype=np.float64) + kept[i] = True + rec["sd_prop"][i] = sp.std(); rec["sd_log"][i] = sl.std() + rec["rng_prop"][i] = sp.max() - sp.min() + rec["rng_log"][i] = sl.max() - sl.min() + rec["med_prop"][i] = np.median(sp); rec["med_log"][i] = np.median(sl) + rec["frac_goal_prop"][i] = float((sp > 0.5).mean()) + rec["frac_goal_log"][i] = float((sl > 0.5).mean()) + rec["sd_prop_chunk"][i] = np.asarray( + mc.predict_proba(CFp)[:, 1], dtype=np.float64).std() + rec["sd_log_chunk"][i] = chunk_log[keep].std() + # STRUCTURAL guard, in float64 so the zero is exact and not a float32 artefact. + rec["sd_anchor"][i] = float( + np.full(len(sp), float(anchor_s[h]), dtype=np.float64).std()) + qm, qM, qd = band(sp, sl) + rec["qmin"][i] = qm; rec["qmax"][i] = qM; rec["qmed"][i] = qd + rec["disp_prop"][i] = 1000.0 * np.linalg.norm( + C[:, -1, :3] - C[:, 0, :3], axis=-1).mean() + rec["disp_log"][i] = 1000.0 * np.linalg.norm( + CH[i, L - 1, :3] - CH[i, 0, :3]) + print(f"[pd] fitted+scored {model} s{seed} over {a.folds} folds " + f"[{time.time() - _T0[0]:.0f}s]", flush=True) + return [dict(tag=t, model=m, seed=s_, rec=store[(t, m, s_)][0], kept=store[(t, m, s_)][1]) + for (t, m, s_) in store] + + +def summarise(r, y, ep, a): + rec, kept = r["rec"], r["kept"] + out = {} + for stratum, sel in (("host_goal", kept & (y == 1)), + ("host_cook", kept & (y == 0)), + ("all_hosts", kept)): + idx = np.where(sel)[0] + if len(idx) < a.min_anchors or len(np.unique(ep[idx])) < a.min_eps: + out[stratum] = dict(status="UNDEFINED", n=int(len(idx)), + n_ep=int(len(np.unique(ep[idx]))) if len(idx) else 0, + reason=f"kept {len(idx)} anchors / " + f"{len(np.unique(ep[idx])) if len(idx) else 0} episodes " + f"< bar {a.min_anchors}/{a.min_eps}") + continue + d = dict(status="OK", n=int(len(idx)), n_ep=int(len(np.unique(ep[idx])))) + for k, v in rec.items(): + m, se, lo, hi = WA.ep_boot_mean(v[idx], ep[idx], B=a.boot, seed=0) + d[k] = float(m); d[k + "_se"] = float(se) + ratio = rec["sd_prop"][idx] / np.maximum(rec["sd_log"][idx], 1e-12) + m, se, lo, hi = WA.ep_boot_mean(ratio, ep[idx], B=a.boot, seed=0) + d["spread_ratio"] = float(m); d["spread_ratio_se"] = float(se) + d["spread_ratio_lo"] = float(lo); d["spread_ratio_hi"] = float(hi) + d["straddle_frac"] = float(((rec["frac_goal_prop"][idx] * 128 >= a.min_side) & + ((1 - rec["frac_goal_prop"][idx]) * 128 >= a.min_side)).mean()) + d["n_straddle"] = int((((rec["frac_goal_prop"][idx] * 128 >= a.min_side) & + ((1 - rec["frac_goal_prop"][idx]) * 128 >= a.min_side))).sum()) + d["n_straddle_ep"] = int(len(np.unique(ep[idx][ + ((rec["frac_goal_prop"][idx] * 128 >= a.min_side) & + ((1 - rec["frac_goal_prop"][idx]) * 128 >= a.min_side))]))) + out[stratum] = d + return out + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--out", required=True) + ap.add_argument("--tags", nargs="+", required=True) + ap.add_argument("--cache-root", default=f"{ROOT}/status/real") + ap.add_argument("--hdf5", default=f"{ROOT}/data/raw/cooking_v5_expert_suboptimal.hdf5") + ap.add_argument("--split", default=f"{ROOT}/data/derived/cooking_v5_split.json") + ap.add_argument("--state", type=int, default=2) + ap.add_argument("--route-pos", default="[2, 3, 4]") + ap.add_argument("--route-neg", default="[0, 2, 3]") + ap.add_argument("--contrast", default="goal_vs_cook") + ap.add_argument("--stride", type=int, default=5) + ap.add_argument("--entry-window", type=int, default=100) + ap.add_argument("--lengths", type=int, nargs="+", default=[8]) + ap.add_argument("--folds", type=int, default=5) + ap.add_argument("--seeds", type=int, nargs="+", default=[0, 1, 2]) + ap.add_argument("--models", nargs="+", default=["logreg", "mlp"]) + ap.add_argument("--donors", type=int, default=128) + ap.add_argument("--min-side", type=int, default=16) + ap.add_argument("--min-anchors", type=int, default=30) + ap.add_argument("--min-eps", type=int, default=4) + ap.add_argument("--boot", type=int, default=2000) + ap.add_argument("--rng-seed", type=int, default=90210) # MUST match pt_within_anchor.main (run 40) + ap.add_argument("--repro-guard", type=int, default=1) + a = ap.parse_args() + t0 = time.time(); _T0[0] = t0 + out = Path(a.out); out.mkdir(parents=True, exist_ok=True) + + rows, n_drop, n_ep = PC.build(SimpleNamespace( + hdf5=a.hdf5, split=a.split, state=a.state, route_pos=a.route_pos, route_neg=a.route_neg, + stride=a.stride, entry_window=a.entry_window, lengths=a.lengths)) + ep = np.array([r["ep"] for r in rows]); y = np.array([r["y"] for r in rows]) + fr = np.array([r["t"] for r in rows]) + AN = np.stack([r["anchor"] for r in rows]); CH = np.stack([r["chunk"] for r in rows]) + L = a.lengths[0] + CFw = PC.chunk_feat(CH, L, "waypoints") + print(f"[pd] HOST anchors={len(rows)} episodes={len(np.unique(ep))}/{n_ep} window={a.entry_window} " + f"L={L} stride={a.stride} contrast={a.contrast}", flush=True) + print(f"[pd] NO-RULER guard: banned keys {_BANNED_KEYS} are never read; only `cands` is loaded.", + flush=True) + print(f"[pd] ORACLE CEILING (cross-anchor, direction scorer, 18:15Z gate) = " + f"{WA.ORACLE_CEILING_CROSS_ANCHOR:.3f} -- printed as required; it bounds neither the " + f"within-anchor AUC nor the spread statistics below.", flush=True) + + results = {"config": vars(a), "host": dict(anchors=len(rows), episodes=int(len(np.unique(ep))), + n_ep_total=n_ep, dropped=n_drop), "tags": {}} + + # ---- REPRODUCTION GUARD: run 40's own code path, unchanged, on the same host anchors. + if a.repro_guard: + acc, ties, cvs, kept40, npos, nneg = WA.run_one( + AN, CFw, y, ep, a.folds, 0, "mlp", a.donors, a.min_side, a.rng_seed) + pub = {"all_hosts": 0.9726, "host_goal": 0.9697, "host_fail": 0.9755} + got = {} + for nm, sel in (("all_hosts", kept40), ("host_goal", kept40 & (y == 1)), + ("host_fail", kept40 & (y == 0))): + idx = np.where(sel)[0] + m, se, lo, hi = WA.ep_boot_mean(acc["both"][idx], ep[idx], B=a.boot, seed=0) + got[nm] = float(m) + worst = max(abs(got[k] - pub[k]) for k in pub) + print(f"[pd] [GUARD] REPRODUCTION vs run 40 (mlp seed 0, rng_seed must match 1904198): " + f"{ {k: round(v,4) for k,v in got.items()} } worst |delta| = {worst:.3e}", flush=True) + results["repro_guard"] = dict(published=pub, measured=got, worst=worst, + passes=bool(worst <= 5e-5)) + if worst > 5e-5: + print("[pd] [GUARD] REPRODUCTION FAILED -- every row in this job is VOID.", flush=True) + + tagcands = {} + for tag in a.tags: + cands, ceps = load_proposer(tag, a.cache_root) + have = np.array([(int(e), int(t)) in cands for e, t in zip(ep, fr)]) + nm = int(have.sum()); ne = int(len(np.unique(ep[have]))) if have.any() else 0 + print(f"[pd] {tag}: cached episodes={len(ceps)} cached anchors={len(cands)}; " + f"MATCHED to host set: {nm} of {len(have)} anchors, {ne} episodes", flush=True) + results["tags"][tag] = dict(cached_eps=len(ceps), cached_anchors=len(cands), + matched_anchors=nm, matched_eps=ne, cells={}) + if nm == 0: + results["tags"][tag]["status"] = "NO_MATCHED_ANCHORS" + continue + tagcands[tag] = cands + + for r in run_all(AN, CFw, CH, y, ep, fr, a, tagcands, L): + tag = r["tag"] + s_ = summarise(r, y, ep, a) + results["tags"][tag]["cells"][f"{r['model']}_s{r['seed']}"] = s_ + sd_anch = r["rec"]["sd_anchor"][r["kept"]] + bad = int((np.abs(sd_anch) > 1e-12).sum()) + print(f"[pd] {tag} {r['model']} s{r['seed']} [GUARD] STRUCTURAL anchor-arm spread: " + f"{bad} of {int(r['kept'].sum())} anchors non-zero (must be 0)", flush=True) + for st in ("host_goal", "host_cook", "all_hosts"): + d = s_[st] + if d["status"] != "OK": + print(f"[pd] {tag:22s} {r['model']:6s} s{r['seed']} {st:10s} UNDEFINED -- " + f"{d['reason']}", flush=True) + continue + print(f"[pd] {tag:22s} {r['model']:6s} s{r['seed']} {st:10s} " + f"sd_prop={d['sd_prop']:.4f}+-{d['sd_prop_se']:.4f} " + f"sd_log={d['sd_log']:.4f}+-{d['sd_log_se']:.4f} " + f"ratio={d['spread_ratio']:.3f}+-{d['spread_ratio_se']:.3f} " + f"frac_goal_prop={d['frac_goal_prop']:.3f} (log {d['frac_goal_log']:.3f}) " + f"band q[{d['qmin']:.3f},{d['qmax']:.3f}] med {d['qmed']:.3f} " + f"straddle={d['n_straddle']}/{d['n']} in {d['n_straddle_ep']}ep " + f"disp {d['disp_prop']:.1f}mm vs logged {d['disp_log']:.1f}mm " + f"n={d['n']}/{d['n_ep']}ep [{time.time()-t0:.0f}s]", flush=True) + + p = out / "proposer_destiny.json" + json.dump(results, open(p, "w"), indent=1, default=float) + print(f"[pd] wrote {p} [{time.time()-t0:.0f}s]", flush=True) + + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/real/pt_proposer_destiny.sh b/rsm_rise/scripts/real/pt_proposer_destiny.sh new file mode 100644 index 0000000000000000000000000000000000000000..79d99269c973aa97ead95f7ed1d1eee9848143b7 --- /dev/null +++ b/rsm_rise/scripts/real/pt_proposer_destiny.sh @@ -0,0 +1,13 @@ +#!/bin/bash +# PROPOSAL_TEST run 41 -- the proposer-draw arm: does the proposer's own candidate set span the destiny +# branch under a clean ground-truth-label-trained scorer? Pre-registered in gen_q#280 / rsm_real#2. +set -euo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +export MUJOCO_GL=disable OMP_NUM_THREADS=1 MKL_NUM_THREADS=1 OPENBLAS_NUM_THREADS=1 +exec venv_rsm/bin/python scripts/real/pt_proposer_destiny.py \ + --out status/real/pt_proposer_destiny_w100_goal_vs_cook \ + --tags pt_cov_sn1_knn0p03 pt_cov_sn0p3_knn0p03 pt_cov_sn1_knn0p05 pt_cov_sn0p3_knn0p01 \ + pt_cov_sn0p1_knn0p03 pt_cov_sn0p1_knn0p05 pt_cov_sn0p03_knn0p01 \ + pt_cov_stock pt_cov_rise pt_cov_riseadv pt_cov_risebn pt_cov_wsctrl \ + --entry-window 100 --lengths 8 --seeds 0 1 2 --models logreg mlp \ + --donors 128 --min-side 16 --min-anchors 30 --min-eps 4 --boot 2000 --repro-guard 1 diff --git a/rsm_rise/scripts/real/pt_proposer_destiny_smoke.sh b/rsm_rise/scripts/real/pt_proposer_destiny_smoke.sh new file mode 100644 index 0000000000000000000000000000000000000000..b6a278a5df32ce6daf8eeefae014eca47d81e7a2 --- /dev/null +++ b/rsm_rise/scripts/real/pt_proposer_destiny_smoke.sh @@ -0,0 +1,9 @@ +#!/bin/bash +# SMOKE ONLY -- one tag, one model, one seed, small bootstrap. NOT a result. +set -euo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +export MUJOCO_GL=disable OMP_NUM_THREADS=1 MKL_NUM_THREADS=1 OPENBLAS_NUM_THREADS=1 +exec venv_rsm/bin/python scripts/real/pt_proposer_destiny.py \ + --out status/real/_smoke_pt_proposer_destiny \ + --tags pt_cov_sn1_knn0p03 pt_cov_stock \ + --models logreg --seeds 0 --boot 200 --repro-guard 0 diff --git a/rsm_rise/scripts/real/pt_proposer_inflate.py b/rsm_rise/scripts/real/pt_proposer_inflate.py new file mode 100644 index 0000000000000000000000000000000000000000..73488e8942029e4c7cd390536aa976903cb2f29b --- /dev/null +++ b/rsm_rise/scripts/real/pt_proposer_inflate.py @@ -0,0 +1,159 @@ +#!/usr/bin/env python +""" +PROPOSAL_TEST run 41 successor -- a SIZING measurement, not a proposer. + +ONE CHANGE from `pt_proposer_destiny.py`: each anchor's 128 cached draws have their DISPLACEMENT rescaled +about that anchor's own mean draw by a factor `k`, sweeping k = 1, 1.5, 2, 3, 5, 8. Directional structure +is preserved; only the spread grows, which is what raising the sampling temperature does to first order. + +Run 41 measured that at S2 goal-route anchors the default proposer puts 98.0-98.8 % of its draws on the +goal side and clears the 16-per-side gate at 0-2 anchors of 105. The question this answers is HOW MUCH +more spread the sampler would need, so the GPU wave targets a number instead of guessing a temperature. + +INFLATED DRAWS ARE OFF-MANIFOLD AND NO INFLATED CELL MAY EVER BE REPORTED AS A PASSING PROPOSER. +The realised displacement is printed at every rung and any rung above 3x the logged 15.3 mm is flagged the +way `pt_cov_risebn` (332 mm) is flagged. + +GUARDS: k = 1 must reproduce run 41's published table exactly (delta 0); the run-41 reproduction guard +against run 40, the structural zero and the no-ruler ban all carry over unchanged from the imported module. +""" +import argparse, json, time +from pathlib import Path +from types import SimpleNamespace +import numpy as np + +ROOT = "/proj/dmfexp/zwhong/rsm_rise" +import importlib.util +def _load(name, path): + spec = importlib.util.spec_from_file_location(name, path) + m = importlib.util.module_from_spec(spec); spec.loader.exec_module(m); return m + +PD = _load("pt_proposer_destiny", f"{ROOT}/scripts/real/pt_proposer_destiny.py") +PC = PD.PC +WA = PD.WA + +LOGGED_DISP_MM = 15.3 # run 40/41 measured mean logged chunk displacement at these anchors +FLAG_FACTOR = 3.0 # a rung above this multiple of LOGGED_DISP_MM is flagged off-manifold + + +def inflate(C, k): + """Rescale each draw's DISPLACEMENT about the anchor's mean draw by k. C is [K, L, 10]. + + Only the xyz channels move. k = 1 must return C bit-identically, which is the reproduction guard. + """ + if k == 1.0: + return C + out = C.copy() + mu = C[:, :, :3].mean(axis=0, keepdims=True) # [1, L, 3] the anchor's mean trajectory + out[:, :, :3] = mu + k * (C[:, :, :3] - mu) + return out + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--out", required=True) + ap.add_argument("--tags", nargs="+", required=True) + ap.add_argument("--ks", type=float, nargs="+", default=[1.0, 1.5, 2.0, 3.0, 5.0, 8.0]) + ap.add_argument("--cache-root", default=f"{ROOT}/status/real") + ap.add_argument("--hdf5", default=f"{ROOT}/data/raw/cooking_v5_expert_suboptimal.hdf5") + ap.add_argument("--split", default=f"{ROOT}/data/derived/cooking_v5_split.json") + ap.add_argument("--state", type=int, default=2) + ap.add_argument("--route-pos", default="[2, 3, 4]") + ap.add_argument("--route-neg", default="[0, 2, 3]") + ap.add_argument("--contrast", default="goal_vs_cook") + ap.add_argument("--stride", type=int, default=5) + ap.add_argument("--entry-window", type=int, default=100) + ap.add_argument("--lengths", type=int, nargs="+", default=[8]) + ap.add_argument("--folds", type=int, default=5) + ap.add_argument("--seeds", type=int, nargs="+", default=[0, 1, 2]) + ap.add_argument("--models", nargs="+", default=["logreg", "mlp"]) + ap.add_argument("--donors", type=int, default=128) + ap.add_argument("--min-side", type=int, default=16) + ap.add_argument("--min-anchors", type=int, default=30) + ap.add_argument("--min-eps", type=int, default=4) + ap.add_argument("--boot", type=int, default=2000) + ap.add_argument("--rng-seed", type=int, default=90210) + a = ap.parse_args() + t0 = time.time(); PD._T0[0] = t0 + out = Path(a.out); out.mkdir(parents=True, exist_ok=True) + + rows, n_drop, n_ep = PC.build(SimpleNamespace( + hdf5=a.hdf5, split=a.split, state=a.state, route_pos=a.route_pos, route_neg=a.route_neg, + stride=a.stride, entry_window=a.entry_window, lengths=a.lengths)) + ep = np.array([r["ep"] for r in rows]); y = np.array([r["y"] for r in rows]) + fr = np.array([r["t"] for r in rows]) + AN = np.stack([r["anchor"] for r in rows]); CH = np.stack([r["chunk"] for r in rows]) + L = a.lengths[0] + CFw = PC.chunk_feat(CH, L, "waypoints") + print(f"[inf] HOST anchors={len(rows)} episodes={len(np.unique(ep))}/{n_ep} window={a.entry_window} " + f"L={L} stride={a.stride} contrast={a.contrast}", flush=True) + print(f"[inf] SIZING ONLY -- inflated draws are OFF-MANIFOLD and are never a passing proposer. " + f"Rungs above {FLAG_FACTOR:.0f}x the logged {LOGGED_DISP_MM} mm are flagged.", flush=True) + print(f"[inf] NO-RULER guard inherited: banned keys {PD._BANNED_KEYS} are never read.", flush=True) + print(f"[inf] ORACLE CEILING (cross-anchor, direction scorer, 18:15Z gate) = " + f"{WA.ORACLE_CEILING_CROSS_ANCHOR:.3f} -- printed as required; not a bound on these " + f"spread statistics.", flush=True) + + base = {} + for tag in a.tags: + cands, ceps = PD.load_proposer(tag, a.cache_root) + nm = int(sum((int(e), int(t)) in cands for e, t in zip(ep, fr))) + print(f"[inf] {tag}: cached eps={len(ceps)} cached anchors={len(cands)}; " + f"MATCHED {nm} of {len(ep)} host anchors", flush=True) + if nm: + base[tag] = cands + + results = {"config": vars(a), "rungs": {}} + published_k1 = {} + for k in a.ks: + tagcands = {t: {key: inflate(C, k) for key, C in c.items()} for t, c in base.items()} + rs = PD.run_all(AN, CFw, CH, y, ep, fr, a, tagcands, L) + results["rungs"][f"k{k}"] = {} + for r in rs: + s = PD.summarise(r, y, ep, a) + results["rungs"][f"k{k}"].setdefault(r["tag"], {})[f"{r['model']}_s{r['seed']}"] = s + bad = int((np.abs(r["rec"]["sd_anchor"][r["kept"]]) > 1e-12).sum()) + if bad: + print(f"[inf] [GUARD] STRUCTURAL FAILED k={k} {r['tag']} {r['model']} s{r['seed']}: " + f"{bad} non-zero", flush=True) + for st in ("host_goal", "host_cook", "all_hosts"): + d = s[st] + tagm = f"{r['tag']} {r['model']} s{r['seed']} {st}" + if d["status"] != "OK": + print(f"[inf] k={k:4.1f} {tagm:52s} UNDEFINED -- {d['reason']}", flush=True) + continue + gate = "PASS" if (d["n_straddle"] >= a.min_anchors and + d["n_straddle_ep"] >= a.min_eps) else "FAIL" + flag = " OFF-MANIFOLD" if d["disp_prop"] > FLAG_FACTOR * LOGGED_DISP_MM else "" + print(f"[inf] k={k:4.1f} {tagm:52s} ratio={d['spread_ratio']:.3f}+-" + f"{d['spread_ratio_se']:.3f} frac_goal_prop={d['frac_goal_prop']:.3f} " + f"straddle={d['n_straddle']}/{d['n_straddle_ep']}ep of {d['n']}/{d['n_ep']}ep " + f"GATE={gate} disp={d['disp_prop']:.1f}mm (logged {d['disp_log']:.1f}mm)" + f"{flag} [{time.time()-t0:.0f}s]", flush=True) + if k == 1.0: + published_k1[(r["tag"], r["model"], r["seed"], st)] = d["spread_ratio"] + + # ---- k = 1 reproduction guard against run 41's own job, recomputed here from the same code path. + ref = Path(f"{ROOT}/status/real/pt_proposer_destiny_w100_goal_vs_cook/proposer_destiny.json") + if ref.exists() and published_k1: + R = json.load(open(ref)) + worst = 0.0; n = 0 + for (tag, model, seed, st), v in published_k1.items(): + try: + w = R["tags"][tag]["cells"][f"{model}_s{seed}"][st] + except KeyError: + continue + if w.get("status") != "OK": + continue + worst = max(worst, abs(w["spread_ratio"] - v)); n += 1 + print(f"[inf] [GUARD] k=1 REPRODUCTION vs run 41 job 1904864: {n} rows, " + f"worst |delta| = {worst:.3e} (must be 0)", flush=True) + results["k1_repro"] = dict(rows=n, worst=worst, passes=bool(worst == 0.0)) + + p = out / "proposer_inflate.json" + json.dump(results, open(p, "w"), indent=1, default=float) + print(f"[inf] wrote {p} [{time.time()-t0:.0f}s]", flush=True) + + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/real/pt_proposer_inflate.sh b/rsm_rise/scripts/real/pt_proposer_inflate.sh new file mode 100644 index 0000000000000000000000000000000000000000..98644d06cde86cf6b2836f8c9aab71d7e0ef9c8c --- /dev/null +++ b/rsm_rise/scripts/real/pt_proposer_inflate.sh @@ -0,0 +1,11 @@ +#!/bin/bash +# PROPOSAL_TEST run 41 successor -- SIZING ONLY. Pre-registered in gen_q#280 / rsm_real#2. +set -euo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +export MUJOCO_GL=disable OMP_NUM_THREADS=1 MKL_NUM_THREADS=1 OPENBLAS_NUM_THREADS=1 +exec venv_rsm/bin/python scripts/real/pt_proposer_inflate.py \ + --out status/real/pt_proposer_inflate_w100_goal_vs_cook \ + --tags pt_cov_sn1_knn0p03 pt_cov_sn1_knn0p05 pt_cov_stock \ + --ks 1 1.5 2 3 5 8 \ + --entry-window 100 --lengths 8 --seeds 0 1 2 --models logreg mlp \ + --donors 128 --min-side 16 --min-anchors 30 --min-eps 4 --boot 2000 diff --git a/rsm_rise/scripts/real/pt_proposer_match.py b/rsm_rise/scripts/real/pt_proposer_match.py new file mode 100644 index 0000000000000000000000000000000000000000..c98c8d40f862aca0d00a56300bebffff5feee5eb --- /dev/null +++ b/rsm_rise/scripts/real/pt_proposer_match.py @@ -0,0 +1,173 @@ +#!/usr/bin/env python +"""gen_q#280 / rsm_real#2 -- the SECOND-PROPOSER confirmation, on MATCHED ANCHORS. + +Why this exists, with the number that forced it. Run 22 closed the betaB table and found exactly one +thing in it that satisfies #280's both-seeds requirement AND beats every trivial baseline: on the FAILURE +route `0->2->6`, capped `R_M` clears the family-wise q95 at BOTH seeds in 3 of 3 available seed pairs +(0.5254/0.5281 at beta 0.99; 0.5549/0.5266 at 0.97; 0.5457/0.5200 per-anchor), while pose_cont (0.4988), +greedy_index (0.5043), random (0.4943) and idql (0.3854) all fail on the same anchors. + +#280 requires a second PROPOSER before a lead is called. The second-proposer arm exists -- `peranchor_ws` +differs from `peranchor` in exactly one field, `cands_from` (`pt_cov_wsctrl` instead of +`pt_cov_sn1_knn0p03`) -- and it reads 0.483 on `0->2->6`, i.e. it FAILS. But it fails on a DIFFERENT +ANCHOR SET: its coverage gate passes at 57 anchors against the default proposer's 82, because which +anchors can show 16 candidates on each side depends on the proposer's own spread. Comparing 0.5457 on 82 +anchors against 0.483 on 57 anchors is the cross-anchor-set non-comparison this stream keeps catching +elsewhere, so it was correctly flagged and not counted. + +This script removes that confound with ONE change and nothing else: restrict BOTH cells to the anchors +(episode, frame) that are GATED IN BOTH, then re-run the reducer and the null calibration verbatim. +Every definition -- the AUC, the episode bootstrap, the oracle ceiling, the within-anchor permutation +null, the family-wise q95 -- is IMPORTED from `proposal_report.py` and `pt_nullcal.py` rather than +restated here, so the matched numbers are computed by the same code as the unmatched ones and the only +difference between the two tables is the anchor set. No checkpoint is loaded and nothing is re-sampled: +this reads the saved npz parts, which already carry every per-anchor, per-candidate score. + +The intersection is applied by setting `gate = False` on any record outside it. That is the correct +lever because `summarise()` scores only gated records and `calibrate()` is handed only gated records, so +the restriction propagates to the AUC, the ceiling, the bootstrap AND the bar together -- a matched table +whose bar was calibrated on the unmatched anchors would be the same error in a different place. + +Reported per route, never pooled: each cell's AUC on the matched anchors with its episode-bootstrapped +SE, its measured permuted column, the oracle ceiling OF THE MATCHED SET, the calibrated family-wise q95 +OF THE MATCHED SET, ties@max, score CV, and the kept anchor/episode counts -- plus, for reference, the +unmatched numbers beside them so the size of the anchor-set effect is visible rather than assumed. +""" +from __future__ import annotations +import argparse, json, sys +from pathlib import Path +import numpy as np + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from proposal_report import load_cell, summarise # noqa: E402 +from pt_nullcal import calibrate # noqa: E402 + + +def gated_keys(recs): + return {(r["episode"], int(r["frame"])) for r in recs if r["gate"]} + + +def apply_mask(recs, keep): + """Return copies with gate cleared outside `keep`. Copies, not in-place, so the unmatched table can + be computed from the same loaded records without being silently mutated.""" + out = [] + for r in recs: + r2 = dict(r) + if (r["episode"], int(r["frame"])) not in keep: + r2["gate"] = False + out.append(r2) + return out + + +def routes_of(recs): + return sorted({r["path"] for r in recs}) + + +def run(cells, entry_window, oracle_chunk, state, gate_min, reps, boot, perm_reps, n_scorers, rng): + loaded = {} + for c in cells: + d = Path(c) + recs, cfg = load_cell(d, entry_window=entry_window) + if not recs: + print(f"[match] {d.name}: no anchors", file=sys.stderr) + continue + loaded[d.name] = (recs, cfg) + if len(loaded) < 2: + print("[match] need at least two cells", file=sys.stderr) + return {}, [] + + names = list(loaded) + all_routes = sorted(set().union(*[set(routes_of(r)) for r, _ in loaded.values()])) + out, rows = {}, [] + for rt in all_routes: + per = {n: [r for r in loaded[n][0] if r["path"] == rt] for n in names} + if any(not v for v in per.values()): + print(f"[match] route {rt}: absent from at least one cell, skipped", file=sys.stderr) + continue + keep = set.intersection(*[gated_keys(v) for v in per.values()]) + print(f"[match] route {rt}: gated per cell " + f"{ {n: len(gated_keys(v)) for n, v in per.items()} } -> intersection {len(keep)}", flush=True) + if len(keep) < 30: + print(f"[match] route {rt}: intersection {len(keep)} < 30 anchors -- UNDEFINED, not scored. " + f"#280 forbids widening the anchor set to make a gate pass.", file=sys.stderr) + out[f"MATCHED | {rt}"] = dict(undefined=True, reason="intersection < 30 anchors", + intersection=len(keep), + per_cell={n: len(gated_keys(v)) for n, v in per.items()}) + continue + for n in names: + masked = apply_mask(per[n], keep) + gname = f"{n.replace('pt_', '')} | {rt} | MATCHED" + cov, srows = summarise(masked, gname, gate_min, entry_window=entry_window, + oracle_chunk=oracle_chunk, state=state) + cov["policy"] = loaded[n][1].get("config", {}).get("policy", "?") + cov["cands_from"] = loaded[n][1].get("config", {}).get("cands_from", "?") + gated = [r for r in masked if r["gate"]] + cal = calibrate(gated, reps, boot, perm_reps, rng, n_scorers) + # the UNMATCHED row for the same cell/route, so the anchor-set effect is visible + ucov, usrows = summarise(per[n], gname.replace(" | MATCHED", ""), gate_min, + entry_window=entry_window, oracle_chunk=oracle_chunk, state=state) + uby = {s["scorer"]: s for s in usrows} + out[gname] = dict(coverage=cov, scorers=srows, cal=cal, unmatched_coverage=ucov, + unmatched_scorers=usrows) + for s in srows: + rows.append(dict(route=rt, cell=n, scorer=s["scorer"], auc=s["auc"], se=s["auc_se"], + perm=s["auc_permuted"], q95f=cal["q95_fwer"], q95=cal["q95"], + ceiling=s["oracle_auc"], ties=s["ties_at_max"], cv=s["cv"], + anchors=s["anchors"], episodes=s["episodes"], + unmatched_auc=uby.get(s["scorer"], {}).get("auc", float("nan")), + unmatched_anchors=uby.get(s["scorer"], {}).get("anchors", 0), + cands_from=cov["cands_from"])) + return out, rows + + +def md_table(rows, keep_scorers): + o = ["### Second-proposer confirmation on MATCHED anchors (gated in BOTH cells)", "", + "One change only: the anchor set is the intersection of the two cells' gated anchors. The AUC, " + "the episode bootstrap, the oracle ceiling and the permutation-calibrated family-wise q95 are all " + "recomputed ON THE MATCHED SET by the same imported code that produced the unmatched table. " + "`unmatched AUC` is the previously-reported number on that cell's own larger anchor set, shown so " + "the size of the anchor-set effect is visible rather than assumed.", "", + "| route | cell | candidates from | scorer | **AUC (SE)** | perm | ceiling | q95 FWER | CLEARS | " + "ties@max | CV | anchors | eps | unmatched AUC (anchors) |", + "|---|---|---|---|---|---|---|---|---|---|---|---|---|---|"] + for r in rows: + if keep_scorers and r["scorer"] not in keep_scorers: + continue + clears = "**YES**" if r["auc"] > r["q95f"] else "no" + flag = "" + if np.isfinite(r["ceiling"]) and r["auc"] >= r["ceiling"]: + flag = " **AT/ABOVE CEILING -- flagged, not a pass**" + o.append(f"| {r['route']} | `{r['cell']}` | `{Path(str(r['cands_from'])).name}` | {r['scorer']} | " + f"**{r['auc']:.4f}** ({r['se']:.4f}) | {r['perm']:.4f} | {r['ceiling']:.3f} | " + f"{r['q95f']:.4f} | {clears}{flag} | {r['ties']:.2f} | {r['cv']:.4f} | " + f"{r['anchors']} | {r['episodes']} | {r['unmatched_auc']:.4f} ({r['unmatched_anchors']}) |") + return "\n".join(o) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("cells", nargs="+", help="two or more cell dirs differing in ONE field (cands_from)") + ap.add_argument("--entry-window", type=int, default=100) + ap.add_argument("--oracle-chunk", type=int, default=8) + ap.add_argument("--state", type=int, default=2) + ap.add_argument("--gate-min", type=int, default=16) + ap.add_argument("--reps", type=int, default=3000) + ap.add_argument("--boot", type=int, default=300) + ap.add_argument("--perm-reps", type=int, default=200) + ap.add_argument("--n-scorers", type=int, default=13) + ap.add_argument("--scorers", default="rsm,permuted:rsm,idql,pose_cont,greedy_index,random") + ap.add_argument("--md", default="") + ap.add_argument("--json", default="") + a = ap.parse_args() + rng = np.random.default_rng(20260924) + out, rows = run(a.cells, a.entry_window, a.oracle_chunk, a.state, a.gate_min, + a.reps, a.boot, a.perm_reps, a.n_scorers, rng) + keep = [s for s in a.scorers.split(",") if s] if a.scorers else [] + md = md_table(rows, keep) + print(md) + if a.md: open(a.md, "w").write(md + "\n") + if a.json: json.dump(out, open(a.json, "w"), indent=1, default=float) + + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/real/pt_proposer_temp.py b/rsm_rise/scripts/real/pt_proposer_temp.py new file mode 100644 index 0000000000000000000000000000000000000000..3f06f9b1ca186133bebeedba185d4f5e2c44ad92 --- /dev/null +++ b/rsm_rise/scripts/real/pt_proposer_temp.py @@ -0,0 +1,148 @@ +#!/usr/bin/env python +""" +PROPOSAL_TEST run 42 -- ONE CHANGE from the published coverage cells (`proposal_screen.sh` -> +`proposal_test.py`): the pi0.5 flow's INITIAL NOISE is scaled by `PT_NOISE_SCALE`. Nothing else moves -- +same checkpoint, same anchors, same stride, same seed, same n_cand, same horizon, same ruler. + +WHY. Run 41 measured, with a ground-truth-route-label destiny model and no direction ruler anywhere, that +at goal-route S2 anchors the default proposer `pi05_cooking_sn1_knn0p03` puts 98.0-98.8 % of its 128 draws +on the goal side and clears the 16-per-side coverage gate at 0-2 of 105 anchors. The proposal test is +therefore CANDIDATE-limited there, not value-limited. Run 41's sizing arm (`pt_proposer_inflate.py`) +rescaled the draws POST HOC about their mean and found the seed- and model-stable first gate pass at +k = 8x spread, realised displacement 33.7 mm = 2.1x the logged 16.1 mm. Those rungs are off-manifold by +construction and were labelled sizing-only. This script asks the same question of the PROPOSER ITSELF: +draws still come out of pi0.5's own decoder, so they are actual policy outputs, and the knob is the one a +flow model actually exposes. + +THE IMPLEMENTATION IS DELIBERATELY ONE LINE OF BEHAVIOUR. `OpenpiPolicy.candidates` draws +`self.rng.standard_normal((H, D))` per candidate and hands it to `policy.infer(..., noise=...)`. We wrap +`self.rng` so `standard_normal` returns the SAME underlying normal draw multiplied by the scale. Two +consequences that are the point of doing it this way: + * at `PT_NOISE_SCALE == 1.0` the wrapper is not installed at all, so the rung is BYTE-IDENTICAL to the + published cell -- that is the reproduction guard, checked against `status/real/pt_cov_sn1_knn0p03`; + * across rungs the underlying normal stream is shared, so rung k and rung k' are PAIRED at the noise + level and differ only by the multiplier. No `proposal_test.py` / `twin_rollout.py` line is edited. + +WHAT THIS IS NOT. Scaling a flow model's initial noise moves the start point off the N(0, I) the model was +trained to integrate from, so a large scale is an out-of-distribution query and the draws can degrade. The +PLAUSIBILITY of every rung is therefore measured, not assumed, and is a pre-registered disqualifier: run 41 +recorded as MY ERROR that its KILL branch had no plausibility constraint, which let `pt_cov_risebn` clear +the gate 210/210 with a 332 mm mean displacement -- a uniform workspace point, not a proposal. A rung whose +realised mean displacement exceeds ~2x the logged 16.1 mm, or whose draws sit further from the logged chunk +manifold than the k=1 rung by more than a stated factor, is reported as DISQUALIFIED, not as a pass. + +NO AUC IS COMPUTED HERE. This script only draws and caches candidates (`--coverage-only`); the coverage +reading is done afterwards by `pt_proposer_destiny.py`, whose instrument is trained on ground-truth route +labels, because the 18:15Z stop-and-reread measured the nearest-centroid direction proxy BELOW CHANCE at S2 +(47.7 % vs 50 %, oracle AUC 0.467) and the published coverage gate is defined on that proxy. +""" +import os, sys + +ROOT = "/proj/dmfexp/zwhong/rsm_rise" +if f"{ROOT}/scripts/real" not in sys.path: + sys.path.insert(0, f"{ROOT}/scripts/real") + +import numpy as np +import twin_rollout as TR + +SCALE = float(os.environ.get("PT_NOISE_SCALE", "1.0")) +_BaseOpenpi = TR.OpenpiPolicy + + +class _ScaledNormal: + """Passes every Generator call through untouched EXCEPT `standard_normal`, which is multiplied by the + scale. Wrapping the generator rather than the sampling loop is what keeps the rungs paired: the + underlying normal stream is identical across scales.""" + + def __init__(self, rng, scale): + self._rng, self._scale = rng, float(scale) + + def standard_normal(self, *a, **k): + return self._rng.standard_normal(*a, **k) * self._scale + + def __getattr__(self, name): + return getattr(self._rng, name) + + +class TempOpenpiPolicy(_BaseOpenpi): + """The scale must survive proposal_test.py:274. + + RUN 45 DEFECT AND FIX. proposal_test.py:274, inside the per-episode loop, does + if pol is not None and hasattr(pol, "rng"): pol.rng = np.random.default_rng([a.seed, ep]) + so assigning a wrapper ONCE in __init__ was destroyed before the first measured anchor of the first + episode, and every run-42 rung sampled at the SAME effective scale. Measured: mean candidate + displacement 14.1908 -> 14.2110 mm across scales 1.0 -> 8.0, a spread of 0.0234 mm (0.16 %), smaller + than the per-device numerical floor. The ladder was INERT. + + The fix makes `rng` a PROPERTY whose setter re-wraps whatever is assigned, so the published file's + per-episode reseed keeps the scale instead of removing it. proposal_test.py is NOT edited. + """ + + _rng_raw = None + + @property + def rng(self): + return self._rng_wrapped + + @rng.setter + def rng(self, g): + # unwrap first so a re-assignment never stacks two scalings + g = getattr(g, "_rng", g) + self._rng_raw = g + self._rng_wrapped = _ScaledNormal(g, SCALE) if SCALE != 1.0 else g + + def __init__(self, *a, **k): + super().__init__(*a, **k) + if SCALE != 1.0: + print(f"[pt-temp] flow initial noise scaled by {SCALE:g} " + f"(H={self.H} D={self.D}); wrapper INSTALLED VIA PROPERTY, survives per-episode reseed", + flush=True) + else: + print("[pt-temp] PT_NOISE_SCALE=1.0 -- no scaling, this rung must reproduce the " + "published cell to within the per-device floor (REPRODUCTION GUARD)", flush=True) + + +def _selftest(): + """CPU-only, no jax, no checkpoint: asserts the one behaviour this file adds.""" + base = np.random.default_rng(0) + ref = np.random.default_rng(0) + w = _ScaledNormal(base, 3.0) + a = w.standard_normal((4, 10)) + b = ref.standard_normal((4, 10)) + assert np.allclose(a, b * 3.0), "scaled stream is not 3x the base stream" + assert w.integers(0, 10) is not None # passthrough works + # the SCALE==1.0 path must not wrap at all + assert _BaseOpenpi is not TempOpenpiPolicy + assert TempOpenpiPolicy.__mro__[1] is _BaseOpenpi, "patch would not inherit the published sampler" + # candidates() is NOT overridden -- the only difference is the generator + assert "candidates" not in TempOpenpiPolicy.__dict__, "candidates() must stay the published one" + + # RUN 45 REGRESSION: the scale must survive a per-episode reseed like proposal_test.py:274. + # This is the assertion whose absence let the whole run-42 ladder run inert. + class _Fake: + H, D = 10, 32 + def __init__(self): + self.rng = np.random.default_rng(0) + Probe = type("Probe", (TempOpenpiPolicy,), {}) + pr = _Fake.__new__(type("P2", (_Fake, TempOpenpiPolicy), {})) + pr.rng = np.random.default_rng(0) # construction-time assignment + pr.rng = np.random.default_rng(0) # <- the per-episode reseed, line 274 + got = pr.rng.standard_normal((4, 10)) + want = np.random.default_rng(0).standard_normal((4, 10)) + if SCALE != 1.0: + assert np.allclose(got, want * SCALE), ( + "SCALE DID NOT SURVIVE THE PER-EPISODE RESEED -- this is the run-42 defect") + # and it must not stack: two assignments must not give SCALE**2 + assert not np.allclose(got, want * SCALE * SCALE), "scaling stacked on re-assignment" + else: + assert np.allclose(got, want), "scale 1.0 must be the untouched stream" + print(f"[pt-temp selftest] OK scale-in-env={SCALE:g} " + f"(incl. run-45 per-episode-reseed regression)") + + +if __name__ == "__main__": + if "--selftest" in sys.argv: + _selftest(); raise SystemExit(0) + import proposal_test as PT + TR.OpenpiPolicy = TempOpenpiPolicy # main() does `from twin_rollout import ...` at call time + PT.main() diff --git a/rsm_rise/scripts/real/pt_range_beta.sh b/rsm_rise/scripts/real/pt_range_beta.sh new file mode 100644 index 0000000000000000000000000000000000000000..628735f32f789b756dc1032673fa60eb5ab55b44 --- /dev/null +++ b/rsm_rise/scripts/real/pt_range_beta.sh @@ -0,0 +1,26 @@ +#!/bin/bash +# gen_q#280 / rsm_real#2 TASK B -- is the ROUTE ASYMMETRY in action-sensitivity a BETA artefact? +# Job 1889772 measured, over 3 cells x 7 RSM variants, that at fixed beta 0.99 the value's action-induced +# spread is 3-25% of its state-induced spread on the two GOAL routes (eta2 0.91-0.998) but 35-110% on the +# FAILURE route 0->2->6 (eta2 0.40-0.85). TASK B's audit (job 1883723) says 100% of goal-route anchors +# support beta 0.99 and 0.0% of failure-route anchors do, so fixed 0.99 reads the failure route OUT OF +# DISTRIBUTION. If that is the cause, the asymmetry must SHRINK at per-anchor beta and at matched 0.95 +# (which both routes support) and persist at 0.99. eta2 and W/B are dimensionless, so they compare across +# beta settings where the raw score scale does not. Complete 25/25 cells only; eval-free, no GPU. +set -uo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +export MUJOCO_GL=disable CUDA_VISIBLE_DEVICES="" OMP_NUM_THREADS=8 MKL_NUM_THREADS=8 +echo "[pt_range_beta] host=$(hostname) job=${LSB_JOBID:-none} $(date -u)" +CELLS="" +# Run 20: the second successor seed and the second proposer landed (1888534 DONE / 1888535), so the +# per-anchor arm is now a seed pair AND has a ws-proposer cell -- which is what says whether run 19's +# finding 5 (per-anchor beta does NOT remove the route asymmetry) is seed-stable or a single-cell read. +for C in b099_RM b099_RMs1 b099_notrunc b099_notruncs1 b097_RM b097_RMs1 b097_notrunc b097_notruncs1 \ + b095_RM b095_notrunc b095_notruncs1 \ + peranchor peranchor_RMs1 peranchor_notrunc peranchor_notruncs1 peranchor_ws; do + N=$(ls status/real/pt_betaB_${C}/parts 2>/dev/null | wc -l) + if [ "$N" -ge 25 ]; then CELLS="$CELLS pt_betaB_${C}"; else echo "[pt_range_beta] SKIP ${C}: only ${N}/25 parts"; fi +done +echo "[pt_range_beta] cells:$CELLS" +exec venv_rsm/bin/python scripts/real/pt_score_range.py $CELLS --entry-window 100 \ + --md status/real/PT_SCORE_RANGE_betaB.md --json status/real/PT_SCORE_RANGE_betaB.json diff --git a/rsm_rise/scripts/real/pt_reduce.sh b/rsm_rise/scripts/real/pt_reduce.sh new file mode 100644 index 0000000000000000000000000000000000000000..d60625722612c6250012ad5339e03b39561580e4 --- /dev/null +++ b/rsm_rise/scripts/real/pt_reduce.sh @@ -0,0 +1,9 @@ +#!/bin/bash +# gen_q#280 / rsm_real#2 -- reduce the proposal-test cells (CPU only, reads the saved npz parts) +set -euo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +export MUJOCO_GL=disable +TAG="${1:-prelim}" +shift || true +venv_rsm/bin/python scripts/real/proposal_report.py "$@" \ + --md "status/real/PT_COVERAGE_${TAG}.md" --json "status/real/PT_COVERAGE_${TAG}.json" diff --git a/rsm_rise/scripts/real/pt_resid_permnull.sh b/rsm_rise/scripts/real/pt_resid_permnull.sh new file mode 100644 index 0000000000000000000000000000000000000000..0eaa35ca3c39dcd11a3c9f2cf6c29cd891ced5ca --- /dev/null +++ b/rsm_rise/scripts/real/pt_resid_permnull.sh @@ -0,0 +1,39 @@ +#!/bin/bash +# gen_q#280 / rsm_real#2 -- PROPOSAL_TEST run 33. +# +# THE QUESTION. Run 32 measured the RESIDUALISED ceiling `both - anchorgeom` on C2 goal_vs_cook as +# +0.0378 (mlp) / +0.0379 (logreg) at L=8, with the paired episode-bootstrap CI excluding zero at 3/3 +# seeds and 4/4 chunk lengths, and read that as (B): the geometry-residualised gate can in principle be +# won. IT CANNOT BE DECLARED ON THAT EVIDENCE. The only null beside it is the SINGLE-draw ZEROLINE row +# (`labelperm_both - labelperm_anchorgeom` = -0.0038, CI [-0.044,+0.036]), whose interval OVERLAPS the +# effect's CI [+0.017,+0.063]. "CI excludes zero" is not "above the measured zero line", and #280's +# standing rule is that no number is quoted without its measured zero line. +# +# ONE CHANGE from run 32: the residualised pair gets the SAME N-draw permutation null the raw pair +# already had (`--perm-null`), so `both - anchorgeom` is scored against the null's q95/q99 instead of +# against one draw. Nothing else moves: same anchors (S2, entry window 100), same folds, same features. +# +# PRE-REGISTERED READING, fixed before the number exists: +# (B) CONFIRMED if the observed resid marginal exceeds the RESID null's q95 for that model and L. +# (A) fires if it does not -- the residualised chunk carries nothing beyond its geometry, and +# FT_EVAL's 0/20 on `gatexf` is at the ceiling, not a defect of any checkpoint. +# In either case run 32's (B) reading is superseded by this job, and item 3 of run 32 must be quoted +# with whichever verdict lands here. +# This is a CEILING, not a scorer: no row here is a pass candidate for #280. +set -uo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +export MUJOCO_GL=disable OMP_NUM_THREADS=8 +PY=venv_rsm/bin/python +run () { # model ndraws + echo "=============== RESID PERMNULL model=$1 draws=$2 (C2 goal_vs_cook, S2, window 100) ===============" + $PY scripts/real/proposal_ceiling.py \ + --out "status/real/pt_permnull_w100_goal_vs_cook_$1" --contrast goal_vs_cook \ + --route-pos "[2, 3, 4]" --route-neg "[0, 2, 3]" \ + --entry-window 100 --state 2 --stride 5 --lengths 8 32 \ + --folds 5 --seeds 0 --boot 2000 \ + --perm-null "$2" --perm-null-models "$1" --perm-null-lengths 8 32 \ + || echo "[ceil] FAILED permnull $1" +} +run logreg 200 +run mlp 200 +echo "[ceil] done" diff --git a/rsm_rise/scripts/real/pt_resid_table.py b/rsm_rise/scripts/real/pt_resid_table.py new file mode 100644 index 0000000000000000000000000000000000000000..99af93f4e7884097cf5e17aec3bea4d89684e07f --- /dev/null +++ b/rsm_rise/scripts/real/pt_resid_table.py @@ -0,0 +1,110 @@ +#!/usr/bin/env python +"""PROPOSAL_TEST run 32 -- the GEOMETRY-RESIDUALISED ceiling, plus a regression guard on the published one. + +This is a CEILING measurement, not a scorer and not a pass candidate. No row it prints may be quoted as a +pass for gen_q#280. What it answers: FT_EVAL's S2 gate reports `gatexf`, which residualises every score +against the candidate's own geometry, and reads 0/20 arms above its +0.020 seed null. The raw supervised +ceiling (PT_CEILING_W100.md) does not bound that statistic, because its chunk features contain exactly the +direction and magnitude `gatexf` removes. The bound is the paired marginal `both - anchorgeom`. + +GUARD FIRST: every arm that existed before the `anchorgeom` change is diffed against the published +status/real/pt_ceiling_w100_/ceiling.json. If any published number moved, this exits non-zero and +prints nothing else -- the new arm is only readable if it left the old ones alone. +""" +import json, sys +from pathlib import Path + +ROOT = Path("/proj/dmfexp/zwhong/rsm_rise") +CONTRASTS = ["goal_vs_cook", "goal_vs_fail", "cook_vs_fail"] +KEY = ("arm", "L", "chunk_feat", "seed") +NEW = {"anchorgeom:logreg", "anchorgeom:mlp", "chunkgeom:logreg", "labelperm_anchorgeom"} +TOL = 1e-12 + + +def load(p): + return json.load(open(p)) + + +def main(): + # ---------------- regression guard ---------------- + worst, checked, missing = 0.0, 0, [] + for c in CONTRASTS: + old_p = ROOT / f"status/real/pt_ceiling_w100_{c}/ceiling.json" + new_p = ROOT / f"status/real/pt_ceilresid_w100_{c}/ceiling.json" + if not old_p.exists() or not new_p.exists(): + missing.append(c); continue + old = {tuple(r[k] for k in KEY): r for r in load(old_p)["results"]} + new = {tuple(r[k] for k in KEY): r for r in load(new_p)["results"]} + for k, ro in old.items(): + if k not in new: + print(f"[GUARD] FAIL {c}: published row {k} is absent from the re-run"); sys.exit(2) + rn = new[k] + for f in ("auc", "se", "ci_lo", "ci_hi", "auc_episode", "n", "n_eps"): + d = abs(float(ro[f]) - float(rn[f])) + worst = max(worst, d) + if d > TOL: + print(f"[GUARD] FAIL {c}: {k} field {f} moved {ro[f]} -> {rn[f]} (|d|={d:.3e})") + sys.exit(2) + checked += 1 + if missing: + print(f"[GUARD] FAIL: no output for {missing}"); sys.exit(2) + print(f"[GUARD] PASS: {checked} published rows reproduced, worst |delta| = {worst:.3e}") + print("[GUARD] the anchorgeom arm did not perturb any number already posted.\n") + + # ---------------- the new table ---------------- + md = [] + for c in CONTRASTS: + d = load(ROOT / f"status/real/pt_ceilresid_w100_{c}/ceiling.json") + Ls = sorted({r["L"] for r in d["results"]}) + seeds = sorted({r["seed"] for r in d["results"]}) + + def cell(arm, L, fm=None): + v = [r for r in d["results"] if r["arm"] == arm and r["L"] == L + and (fm is None or r["chunk_feat"] == fm)] + if not v: return None + a = sum(r["auc"] for r in v) / len(v) + s = sum(r["se"] for r in v) / len(v) + return a, s + + md.append(f"## {c} entry_window=100 anchors={d['n_anchors']} episodes={d['n_episodes']} " + f"seeds={seeds}") + md.append("| arm | " + " | ".join(f"L={L}" for L in Ls) + " |") + md.append("|---|" + "---|" * len(Ls)) + for arm, fm in (("both:logreg", "waypoints"), ("both:mlp", "waypoints"), + ("anchorgeom:logreg", "geom"), ("anchorgeom:mlp", "geom"), + ("anchor:logreg", "-"), ("anchor:mlp", "-"), + ("chunkgeom:logreg", "geom"), ("chunkdir:logreg", "dir3"), + ("chunkmag:logreg", "mag1"), + ("labelperm_both", "waypoints"), ("labelperm_anchorgeom", "waypoints"), + ("labelperm_anchor", "waypoints"), ("random", "-")): + cs = [cell(arm, L, fm) for L in Ls] + if all(x is None for x in cs): continue + md.append(f"| `{arm}` | " + " | ".join("-" if x is None else f"{x[0]:.3f} +-{x[1]:.3f}" + for x in cs) + " |") + # paired marginals with their own intervals, averaged over seeds + pr = d.get("paired", []) + for pair, tag in (("both:mlp - anchorgeom:mlp", "RESID CEILING mlp"), + ("both:logreg - anchorgeom:logreg", "RESID CEILING logreg"), + ("labelperm_both - labelperm_anchorgeom", " its ZEROLINE"), + ("both:mlp - anchor:mlp", "raw marginal mlp"), + ("both:logreg - anchor:logreg", "raw marginal logreg"), + ("labelperm_both - labelperm_anchor", " its ZEROLINE")): + row = [] + for L in Ls: + v = [r for r in pr if r["pair"] == pair and r["L"] == L] + if not v: row.append("-"); continue + m = sum(r["diff"] for r in v) / len(v) + lo = sum(r["ci_lo"] for r in v) / len(v) + hi = sum(r["ci_hi"] for r in v) / len(v) + sig = "SIG" if (lo > 0 or hi < 0) else "n.s." + row.append(f"{m:+.4f} [{lo:+.3f},{hi:+.3f}] {sig}") + if all(x == "-" for x in row): continue + md.append(f"| **{tag}** | " + " | ".join(row) + " |") + md.append("") + out = ROOT / "status/real/PT_CEILING_RESID.md" + out.write_text("\n".join(md) + "\n") + print("\n".join(md)) + print(f"[wrote] {out}") + + +main() diff --git a/rsm_rise/scripts/real/pt_residual.py b/rsm_rise/scripts/real/pt_residual.py new file mode 100644 index 0000000000000000000000000000000000000000..db166b618b161cdc34910b54a3e1bf17808f8d53 --- /dev/null +++ b/rsm_rise/scripts/real/pt_residual.py @@ -0,0 +1,230 @@ +#!/usr/bin/env python +"""gen_q#280 / rsm_real#2 -- does the RSM add ANYTHING beyond the checkpoint-free pose-continuity score? + +Why this exists, with the numbers that forced it. Run 22 closed the betaB table and found two things: +(a) on the goal route `2->3->4` a checkpoint-free `pose_cont` reads 0.5321 and CLEARS the same +permutation-calibrated family-wise bar that only 4 of 15 RSM arms clear (RSM range 0.4850-0.5527); +(b) on the matched-anchor second-proposer table `pose_cont` BEATS the RSM in every cell (0.5645 vs +0.5527 default proposer, 0.5448 vs 0.4827 ws proposer). A value that needs a checkpoint to match what +the previous pose already predicts is not demonstrating route knowledge. + +But "pose_cont also clears" and "the RSM is pose_cont" are different claims and only the second one is +fatal. Two scorers can clear the same bar on the same anchors while ranking candidates differently, in +which case the RSM carries information pose_cont does not, and the honest statement is "both work". +This script measures WHICH, with one change and nothing else: residualise each scorer on the other, +WITHIN the anchor, and re-run the identical AUC. + + rsm|pose : rank(rsm) minus its within-anchor least-squares fit on rank(pose_cont), scored for label + pose|rsm : the mirror image + spearman : the per-anchor rank correlation between the two, mean over anchors + +Ranks rather than raw values because the AUC is itself a rank statistic, so a monotone read-out change +(prob vs logit, a beta shift) must not move the residual; and because the RSM score's scale varies by +orders of magnitude across arms while pose_cont is millimetres, so a raw-value regression would be +dominated by units rather than by agreement. + +Reading it. If `rsm|pose` collapses to its permuted line while `pose|rsm` survives, the RSM's clears are +pose continuity wearing a checkpoint. If both survive, the two carry different information and the run-22 +"a trivial baseline beats it" framing is too strong. If both collapse, they are the same signal and +neither is separable -- which is still a negative for the RSM, since pose_cont is free. + +Every definition -- `auc`, `spearman`, `perm_auc`, `ep_bootstrap`, `model_free_scores`, `load_cell`, +`oracle_ceiling`, and the family-wise `calibrate` -- is IMPORTED, never restated, so the residual rows are +produced by the same code as the plain rows and the residualisation is the only difference between them. +Reported per route, never pooled, every row with its measured permuted column, its own anchor set's oracle +ceiling, the calibrated family-wise q95, ties@max, score CV and the kept anchor/episode counts. No +checkpoint is loaded and nothing is re-sampled: this reads the saved npz parts. +""" +from __future__ import annotations +import argparse, json, sys +from pathlib import Path +import numpy as np + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from proposal_report import (load_cell, auc, spearman, perm_auc, ep_bootstrap, # noqa: E402 + model_free_scores, oracle_ceiling) +from pt_nullcal import calibrate # noqa: E402 + + +def ranks(v): + """Average ranks, so tied scores (a saturated read-out) cannot manufacture a spurious residual.""" + v = np.asarray(v, float) + order = np.argsort(v, kind="mergesort") + r = np.empty(len(v), float); s = v[order] + i = 0 + while i < len(s): + j = i + while j + 1 < len(s) and s[j + 1] == s[i]: + j += 1 + r[order[i:j + 1]] = 0.5 * (i + j) + 1.0 + i = j + 1 + return r + + +def residual(target, on): + """rank(target) minus its within-anchor least-squares fit on rank(on). If `on` is constant there is + nothing to remove and the target is returned unchanged (its rank form), which is the correct + degenerate answer rather than a nan.""" + a, b = ranks(target), ranks(on) + a = a - a.mean(); b = b - b.mean() + den = float((b * b).sum()) + if den <= 0: + return a + return a - (float((a * b).sum()) / den) * b + + +def score_of(r, name): + sc = r["scores"].get(name) + if sc is None: + sc = model_free_scores(r).get(name) + return None if sc is None else np.asarray(sc, float) + + +def rows_for(gated, pairs): + """pairs: list of (row-name, callable(record) -> score vector). One pass per row, same statistics.""" + out = [] + rng = np.random.default_rng(0) + for name, fn in pairs: + A, S, L, TI, CV, P, epi = [], [], [], [], [], [], [] + prng = np.random.default_rng(12345) + for r in gated: + sc = fn(r) + if sc is None: + continue + mg = np.asarray(r["margin"], float); lab = mg > 0 + A.append(auc(sc, lab)); S.append(spearman(sc, mg)) + P.append(perm_auc(sc, lab, prng)) + k = max(1, len(sc) // 4) + L.append(float(np.sort(mg[np.argsort(-sc)[:k]]).mean() - mg.mean())) + TI.append(float((sc == sc.max()).sum())) + # The residual rows are MEAN-ZERO by construction (a least-squares residual on a centred + # regressor), so std/|mean| is a division by numerical noise and prints ~1e17. That is not a + # large coefficient of variation, it is an undefined one, and #280 requires the CV beside + # every rank number -- so report it as nan and print "n/a" rather than let a meaningless + # 1e17 be quoted as if it were measured. + mu = float(sc.mean()) + CV.append(np.nan if abs(mu) <= 1e-9 * (sc.std() + 1e-300) + else float(sc.std() / abs(mu))) + epi.append(r["episode"]) + if not A: + continue + se, ci = ep_bootstrap(A, epi, rng) + se_p, _ = ep_bootstrap(P, epi, rng) + out.append(dict(scorer=name, auc=float(np.nanmean(A)), auc_se=se, auc_ci=ci, + auc_permuted=float(np.nanmean(P)), auc_permuted_se=se_p, + rho=float(np.nanmean(S)), lift=float(np.nanmean(L)), + ties_at_max=float(np.mean(TI)), cv=float(np.nanmedian(CV)) + if np.any(np.isfinite(CV)) else float("nan"), + anchors=len(A), episodes=len(set(epi)))) + return out + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--cells", nargs="+", required=True) + ap.add_argument("--root", default="status/real") + ap.add_argument("--entry-window", type=int, default=100) + ap.add_argument("--oracle-chunk", type=int, default=8) + ap.add_argument("--state", type=int, default=2) + ap.add_argument("--gate-min-anchors", type=int, default=30) + ap.add_argument("--reps", type=int, default=4000) + ap.add_argument("--boot", type=int, default=400) + ap.add_argument("--perm-reps", type=int, default=200) + ap.add_argument("--n-scorers", type=int, default=7) + ap.add_argument("--json", default=None) + ap.add_argument("--md", default=None) + a = ap.parse_args() + + rng = np.random.default_rng(7) + blocks = [] + for cell in a.cells: + d = Path(cell) + if not d.is_absolute() and not d.exists(): + d = Path(a.root) / cell + recs, cfg = load_cell(d, entry_window=a.entry_window) + if not recs: + print(f"[resid] {d.name}: no anchors", file=sys.stderr); continue + for route in sorted({r["path"] for r in recs}): + gated = [r for r in recs if r["gate"] and r["path"] == route] + neps = len({r["episode"] for r in gated}) + if len(gated) < a.gate_min_anchors or neps < 4: + blocks.append(dict(cell=d.name, route=route, undefined=True, + anchors=len(gated), episodes=neps, + reason=f"below #280 floor (30 anchors / 4 episodes): " + f"{len(gated)} anchors / {neps} episodes")) + print(f"[resid] UNDEFINED {d.name} {route}: {len(gated)} anchors / {neps} eps", file=sys.stderr) + continue + if score_of(gated[0], "rsm") is None: + print(f"[resid] {d.name} {route}: no rsm column", file=sys.stderr); continue + pairs = [ + ("rsm", lambda r: score_of(r, "rsm")), + ("pose_cont", lambda r: score_of(r, "pose_cont")), + ("rsm|pose", lambda r: residual(score_of(r, "rsm"), score_of(r, "pose_cont"))), + ("pose|rsm", lambda r: residual(score_of(r, "pose_cont"), score_of(r, "rsm"))), + ("permuted:rsm", lambda r: score_of(r, "permuted:rsm")), + ("idql", lambda r: score_of(r, "idql")), + ("random", lambda r: score_of(r, "random")), + ] + rows = rows_for(gated, pairs) + # The agreement between the two scorers, measured directly rather than inferred from the + # two residual rows. + rp = [spearman(score_of(r, "rsm"), score_of(r, "pose_cont")) for r in gated] + se_rp, ci_rp = ep_bootstrap(rp, [r["episode"] for r in gated], np.random.default_rng(3)) + cal = calibrate(gated, a.reps, a.boot, a.perm_reps, rng, n_scorers=a.n_scorers) + orc = oracle_ceiling([(r["episode"], r["frame"]) for r in gated], a.oracle_chunk, a.state) + blocks.append(dict(cell=d.name, route=route, undefined=False, + anchors=len(gated), episodes=neps, + beta_mode=cfg.get("beta_mode"), beta=cfg.get("beta"), + ckpt=cfg.get("ckpt") or cfg.get("successor"), + cands_from=cfg.get("cands_from"), + rsm_pose_spearman=float(np.nanmean(rp)), rsm_pose_spearman_se=se_rp, + rsm_pose_spearman_ci=ci_rp, + q95_fwer=cal.get("q95_fwer"), null_mean=cal.get("null_mean"), + oracle=orc, rows=rows)) + print(f"[resid] {d.name} {route}: {len(gated)} anchors / {neps} eps " + f"q95_fwer={cal.get('q95_fwer'):.4f} ceiling={orc.get('auc'):.3f} " + f"rho(rsm,pose)={np.nanmean(rp):+.3f}", file=sys.stderr) + + if a.json: + Path(a.json).parent.mkdir(parents=True, exist_ok=True) + json.dump(blocks, open(a.json, "w"), indent=1, default=float) + lines = ["# RSM residualised on pose continuity (and the mirror) -- gen_q#280 / rsm_real#2", + "", + "`rsm|pose` = within-anchor rank(rsm) minus its least-squares fit on rank(pose_cont); " + "`pose|rsm` is the mirror. Every row: AUC (episode-boot SE) [MEASURED permuted]. " + "CLEARS = above the permutation-calibrated FAMILY-WISE q95 of its own route/anchor set.", + ""] + for b in blocks: + if b["undefined"]: + lines += [f"## {b['cell']} -- `{b['route']}` -- **UNDEFINED**: {b['reason']}", ""] + continue + o = b["oracle"] + lines += [f"## {b['cell']} -- route `{b['route']}`", + "", + f"anchors **{b['anchors']}** / episodes **{b['episodes']}** · oracle ceiling " + f"**{o.get('auc'):.3f}** (acc {o.get('acc'):.3f}, n {o.get('n')}) · family-wise q95 " + f"**{b['q95_fwer']:.4f}** · measured null mean {b['null_mean']:.4f}", + "", + f"per-anchor Spearman(rsm, pose_cont) = **{b['rsm_pose_spearman']:+.4f}** " + f"(SE {b['rsm_pose_spearman_se']:.4f}, 95% CI " + f"[{b['rsm_pose_spearman_ci'][0]:+.3f}, {b['rsm_pose_spearman_ci'][1]:+.3f}])", + "", + "| scorer | AUC (SE) | permuted | clears q95 | at/above ceiling | rho vs margin | lift | ties@max | CV |", + "|---|---|---|---|---|---|---|---|---|"] + for r in b["rows"]: + clears = "**CLEARS**" if r["auc"] > b["q95_fwer"] else "--" + above = "**FLAG**" if np.isfinite(o.get("auc", np.nan)) and r["auc"] >= o["auc"] else "" + lines.append(f"| `{r['scorer']}` | {r['auc']:.4f} ({r['auc_se']:.4f}) | {r['auc_permuted']:.4f} | " + f"{clears} | {above} | {r['rho']:+.4f} | {r['lift']:+.4f} | " + f"{r['ties_at_max']:.2f} | " + f"{'n/a (mean-zero)' if not np.isfinite(r['cv']) else format(r['cv'], '.3g')} |") + lines.append("") + md = "\n".join(lines) + if a.md: + Path(a.md).parent.mkdir(parents=True, exist_ok=True) + Path(a.md).write_text(md) + print(md) + + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/real/pt_score_dz.py b/rsm_rise/scripts/real/pt_score_dz.py new file mode 100644 index 0000000000000000000000000000000000000000..6884aa13b578d7c82089c3423662f28fd339f525 --- /dev/null +++ b/rsm_rise/scripts/real/pt_score_dz.py @@ -0,0 +1,207 @@ +"""gen_q#280 / rsm_real#2 -- does the value read the ONE channel that carries the route? + +Run 17 (job 1889208, status/real/PT_PAIRS_LADDER.md) measured, on LOGGED chunks with TRUE route labels +and an out-of-fold logreg, that the 0.983 supervised ceiling at S2 is very nearly ONE SCALAR: the z +component of `chunk[-1,:3] - chunk[0,:3]` reaches condAUC 0.881 +- 0.045 against its own measured +permuted line 0.458 (p = 0.005), while displacement MAGNITUDE carries nothing (0.390, p = 0.950) and the +gripper channel is 59/59 TIES. + +This script asks the mechanical follow-up on the PROPOSAL-TEST arm (the owner's actual test, proposer +draws and not logged chunks), and it needs no GPU and no checkpoint because the candidate directions and +every scorer's 128 scores are already in the saved npz parts: + + per anchor, what is the Spearman between the scorer's 128 scores and the 128 candidates' dz? + +If it is ~0 the value is BLIND to the channel that carries the branch, which is a sufficient mechanical +explanation for its 0.46-0.50 proposal-test AUC. If it is NEGATIVE the value prefers the lowering +(failure) direction, which is a sufficient explanation for the route-dependent sign flip. + +WHY THIS IS NOT THE RULER (gen_q#280's trap). The forbidden scorer is the signed margin +m(v) = cos(v,u_S) - cos(v,u_F), which generates the label and therefore scores AUC 1.0 by construction. +dz is NOT m: it is one raw component of the candidate's own translation, it is never used as a score +column here, and nothing in this script ranks candidates or computes an AUC. The statistic reported is +a CORRELATION OF A SCORER WITH ITS INPUT -- a property of the value function, not a performance claim. +Spearman(dz, m) is printed as a labelled DIAGNOSTIC row so the reader can see how much of the label dz +explains at these very anchors; it is flagged and it is not a scorer. + +EVERY number arrives with its own MEASURED zero line. The null is the within-anchor shuffle of that +scorer's own 128 scores -- the identical construction the harness uses for its `permuted:*` columns -- +so a saturated scorer (mass ties) drags the real and the shuffled statistic toward 0 together and only +the pair tells you which. Each head gets its OWN null; none is borrowed. As a free correctness check +the script recomputes the null for `rsm` and compares it with the harness's STORED `permuted:rsm` +column, and WARNs if they disagree. + +Anchor set is the 18:15Z gate: S2, within 100 frames of meta-state ENTRY, coverage-gated, BY ROUTE and +never pooled. Intervals bootstrap over EPISODES. +""" +from __future__ import annotations +import argparse, json, sys +from pathlib import Path +import numpy as np + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from proposal_report import load_cell # same loader, same entry-window restriction + +BOOT = 2000 +PERM = 200 + + +def _rank(a): + """Average ranks (ties shared), centred. Spearman is then the cosine of two such vectors.""" + a = np.asarray(a, float) + order = np.argsort(a, kind="mergesort") + s = a[order] + r = np.empty(len(a), float) + i = 0 + while i < len(s): + j = i + while j + 1 < len(s) and s[j + 1] == s[i]: + j += 1 + r[order[i:j + 1]] = 0.5 * (i + j) + 1.0 + i = j + 1 + r -= r.mean() + return r + + +def _corr(ra, rb): + den = np.sqrt((ra * ra).sum() * (rb * rb).sum()) + return float((ra * rb).sum() / den) if den > 0 else np.nan + + +def ep_boot(per_anchor, episodes, rng): + v = np.asarray(per_anchor, float); e = np.asarray(episodes) + ok = np.isfinite(v); v, e = v[ok], e[ok] + if len(v) == 0: + return np.nan, (np.nan, np.nan) + ue = np.unique(e); byep = {x: v[e == x] for x in ue} + draws = np.empty(BOOT) + for b in range(BOOT): + pick = rng.choice(ue, len(ue), replace=True) + draws[b] = np.concatenate([byep[x] for x in pick]).mean() + return float(draws.std(ddof=1)), (float(np.percentile(draws, 2.5)), float(np.percentile(draws, 97.5))) + + +def analyse(recs, scorer, target_key, rng): + """target_key: 'dz' (candidate z displacement, mm) or 'margin' (the label generator, DIAGNOSTIC only). + + Returns the mean per-anchor Spearman, its episode-bootstrapped SE/CI, the MEASURED permuted line + (mean and q95 and one-sided p), mean ties-at-max fraction, mean score CV, kept anchors/episodes.""" + obs, eps, ties, cvs = [], [], [], [] + rs_scores, rt_target = [], [] + for r in recs: + sc = np.asarray(r["scores"][scorer], float) + if target_key == "dz": + tg = np.asarray(r["dir_mm"], float)[:, 2] + else: + tg = np.asarray(r["margin"], float) + if len(sc) != len(tg) or len(sc) < 8: + continue + ra, rb = _rank(sc), _rank(tg) + obs.append(_corr(ra, rb)); eps.append(r["episode"]) + rs_scores.append(ra); rt_target.append(rb) + mx = sc.max() + ties.append(float((sc == mx).sum()) / len(sc)) + mu = float(np.mean(sc)); sd = float(np.std(sc)) + cvs.append(abs(sd / mu) if mu != 0 else np.inf) + if not obs: + return None + mean = float(np.nanmean(obs)) + se, ci = ep_boot(obs, eps, rng) + # MEASURED zero line: within-anchor shuffle of this scorer's own scores, PERM draws of the aggregate. + RS = np.array(rs_scores); RT = np.array(rt_target) + nrm = np.sqrt((RS * RS).sum(1) * (RT * RT).sum(1)) + nrm[nrm <= 0] = np.nan + draws = np.empty(PERM) + for p in range(PERM): + sh = np.array([rng.permutation(x) for x in RS]) + draws[p] = float(np.nanmean((sh * RT).sum(1) / nrm)) + pval = float((np.sum(np.abs(draws) >= abs(mean)) + 1) / (PERM + 1)) + return dict(scorer=scorer, target=target_key, mean=mean, se=se, ci=list(ci), + perm_mean=float(draws.mean()), perm_q95=float(np.percentile(np.abs(draws), 95)), + p_two_sided=pval, ties_at_max=float(np.mean(ties)), score_cv=float(np.median(cvs)), + anchors=len(obs), episodes=int(len(set(eps)))) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("cells", nargs="+", help="cell dirs under status/real/") + ap.add_argument("--entry-window", type=int, default=100) + ap.add_argument("--gated-only", action="store_true", default=True) + ap.add_argument("--by-route", action="store_true", default=True) + ap.add_argument("--md", required=True) + ap.add_argument("--json", required=True) + a = ap.parse_args() + rng = np.random.default_rng(20260924) + + out, lines = [], [] + lines.append("# Does the value read the candidate's dz? (gen_q#280 / rsm_real#2)\n") + lines.append("Per-anchor Spearman between a scorer's 128 candidate scores and those candidates' dz") + lines.append("(`cand_dir_mm[:,:,2]`, i.e. `1000*(chunk[-1,:3]-chunk[0,:3])_z` in mm). NOT an AUC and") + lines.append("NOT a performance claim: it measures whether the value varies with the one channel that") + lines.append("run 17 measured as carrying 0.881 of the 0.983 supervised route ceiling on logged chunks.") + lines.append(f"Anchors: S2, entry window {a.entry_window}, coverage-gated, BY ROUTE, never pooled.") + lines.append("Every row carries its OWN measured permuted zero line (within-anchor score shuffle,") + lines.append(f"{PERM} draws), its ties-at-max fraction, its median score CV and its kept anchors/episodes.\n") + + for cell in a.cells: + d = Path("status/real") / cell + if not (d / "parts").exists(): + lines.append(f"\n## {cell} -- MISSING, not scored\n"); continue + recs, cfg = load_cell(d, entry_window=a.entry_window) + recs = [r for r in recs if r["gate"]] + if not recs: + lines.append(f"\n## {cell} -- UNDEFINED: 0 anchors survive the coverage gate at window " + f"{a.entry_window}\n") + continue + scorers = sorted(recs[0]["scores"].keys()) + routes = sorted({r["path"] for r in recs}) + lines.append(f"\n## {cell} ({len(recs)} gated anchors, {len({r['episode'] for r in recs})} episodes, " + f"routes {routes})\n") + for route in routes + ["__ALL__"]: + sub = recs if route == "__ALL__" else [r for r in recs if r["path"] == route] + if len(sub) < 10: + lines.append(f"\n### route {route}: UNDEFINED, only {len(sub)} gated anchors (floor 10)\n") + continue + tag = "POOLED (diagnostic only, not a comparison)" if route == "__ALL__" else f"route {route}" + lines.append(f"\n### {tag}\n") + lines.append("| scorer | mean rho(score,dz) | +-SE | 95% CI | MEASURED perm | perm q95 | p | " + "ties@max | score CV | anchors | eps |") + lines.append("|---|---|---|---|---|---|---|---|---|---|---|") + # DIAGNOSTIC first: how much of the label does dz explain at these anchors? + dzm = [] + for r in sub: + dzm.append(_corr(_rank(np.asarray(r["dir_mm"], float)[:, 2]), + _rank(np.asarray(r["margin"], float)))) + se_d, ci_d = ep_boot(dzm, [r["episode"] for r in sub], rng) + lines.append(f"| DIAGNOSTIC rho(dz, signed margin) -- the LABEL, not a scorer | " + f"{np.nanmean(dzm):.4f} | {se_d:.4f} | [{ci_d[0]:.3f}, {ci_d[1]:.3f}] | - | - | - " + f"| - | - | {len(dzm)} | {len({r['episode'] for r in sub})} |") + for sc in scorers: + res = analyse(sub, sc, "dz", rng) + if res is None: + lines.append(f"| {sc} | UNDEFINED | | | | | | | | | |"); continue + res.update(cell=cell, route=route) + out.append(res) + lines.append(f"| {sc} | {res['mean']:+.4f} | {res['se']:.4f} | " + f"[{res['ci'][0]:+.3f}, {res['ci'][1]:+.3f}] | {res['perm_mean']:+.4f} | " + f"{res['perm_q95']:.4f} | {res['p_two_sided']:.3f} | {res['ties_at_max']:.3f} | " + f"{res['score_cv']:.3g} | {res['anchors']} | {res['episodes']} |") + # free correctness check: our null for `rsm` vs the harness's stored permuted:rsm column + if "rsm" in scorers and "permuted:rsm" in scorers: + mine = [r for r in out if r["cell"] == cell and r["route"] == route and r["scorer"] == "rsm"] + theirs = [r for r in out if r["cell"] == cell and r["route"] == route + and r["scorer"] == "permuted:rsm"] + if mine and theirs: + gap = abs(mine[0]["perm_mean"] - theirs[0]["mean"]) + if gap > 0.05: + lines.append(f"\n**WARN** computed null for `rsm` ({mine[0]['perm_mean']:+.4f}) " + f"differs from the harness's stored `permuted:rsm` " + f"({theirs[0]['mean']:+.4f}) by {gap:.4f}.\n") + + Path(a.md).write_text("\n".join(lines) + "\n") + Path(a.json).write_text(json.dumps(out, indent=1)) + print("\n".join(lines)) + + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/real/pt_score_dz.sh b/rsm_rise/scripts/real/pt_score_dz.sh new file mode 100644 index 0000000000000000000000000000000000000000..d99f7f0d0adf48a9e4b7f672c456c8a5cf84e27b --- /dev/null +++ b/rsm_rise/scripts/real/pt_score_dz.sh @@ -0,0 +1,15 @@ +#!/bin/bash +# gen_q#280 / rsm_real#2 -- run 18. Does the value read the candidate's dz? +# Eval-free: reads saved npz parts only, loads no checkpoint, needs no GPU. +set -uo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +export MUJOCO_GL=disable +PY=venv_rsm/bin/python +echo "[dz] host=$(hostname) job=${LSB_JOBID:-none} $(date -u)" +$PY scripts/real/pt_score_dz.py \ + pt_heads_s0 pt_cap_ab_s0 pt_cap_ab_ws \ + pt_betaB_b099_RM pt_betaB_b099_notrunc pt_betaB_b099_notruncs1 pt_betaB_peranchor \ + pt_betaB_b095_RM pt_betaB_b095_notrunc pt_betaB_b097_RM pt_betaB_b097_notrunc \ + --entry-window 100 \ + --md status/real/PT_SCORE_DZ.md --json status/real/PT_SCORE_DZ.json +echo "[dz] done $(date -u)" diff --git a/rsm_rise/scripts/real/pt_score_range.py b/rsm_rise/scripts/real/pt_score_range.py new file mode 100644 index 0000000000000000000000000000000000000000..8330344852e98b2574548e54fad663ce97a7e022 --- /dev/null +++ b/rsm_rise/scripts/real/pt_score_range.py @@ -0,0 +1,153 @@ +"""gen_q#280 / rsm_real#2 -- HOW MUCH does the value move when only the ACTION changes? + +Run 18 (job 1889567, status/real/PT_SCORE_DZ.md) measured that no value in the sweep READS the channel +that carries the branch: Spearman(score, candidate dz) tops out at |rho| = 0.172 over 18 cells x 3 routes +x 2 proposers, against a label-to-dz coupling of 0.86-0.94. That says the value is pointed the wrong way. +It does NOT say whether the value moves at all. This script asks that, and it is the prior question: +if at a fixed anchor the 128 proposer draws all receive essentially the SAME score, then no reward head, +no read-out and no capacity in #280's sweep can produce a ranking, because there is nothing to rank -- +and the 0.46-0.50 AUC band is the arithmetic of near-constant scores, not a defect of their direction. + +Two dispersion statistics, per scorer, per route, on the same gated anchors as every other row: + W = mean over anchors of sd(the 128 scores at that anchor) "action-induced spread" + B = sd over anchors of the anchor's mean score "state-induced spread" + W/B action spread as a fraction of state's + eta2_anchor = B^2-ish share: between-anchor variance / total variance over all anchor x candidate scores. + eta2 -> 1 means the score is a function of the STATE alone at these anchors. + +REFERENCE, and why it is not a permutation. A within-anchor shuffle -- the null every other statistic in +this stream uses -- PRESERVES the multiset of scores at each anchor, so W, B, W/B and eta2 are EXACTLY +invariant under it. A permuted row is therefore not a zero line for this statistic and is not printed as +one; it is printed and flagged INVARIANT, which is itself the check that the code does what it claims. +The reference is instead the candidate's own input channel: the identical statistic computed on +`cand_dir_mm[:,:,2]` (dz, mm) and on |dxyz|. Those say how much action variation is PRESENT in the input +at these very anchors. A value whose eta2 is far above the input's is collapsing variation that is there. + +dz is an input channel here, never a score column, and nothing in this script ranks candidates or computes +an AUC, so gen_q#280's ruler trap (the signed margin m(v)) is not touched. Anchors: S2, entry window 100, +coverage-gated, BY ROUTE, never pooled; intervals bootstrap over EPISODES. +""" +from __future__ import annotations +import argparse, json, sys +from pathlib import Path +import numpy as np + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from proposal_report import load_cell + +BOOT = 2000 + + +def ep_boot_ratio(num_per_anchor, mean_per_anchor, episodes, rng): + """Bootstrap W/B and eta2 over EPISODES: both are recomputed inside every draw, since B is itself an + across-anchor statistic and resampling only the numerator would understate the interval.""" + w = np.asarray(num_per_anchor, float); m = np.asarray(mean_per_anchor, float) + e = np.asarray(episodes) + ok = np.isfinite(w) & np.isfinite(m) + w, m, e = w[ok], m[ok], e[ok] + if len(w) < 3: + return np.nan, (np.nan, np.nan) + ue = np.unique(e); idx = {x: np.where(e == x)[0] for x in ue} + draws = np.empty(BOOT); draws[:] = np.nan + for b in range(BOOT): + pick = np.concatenate([idx[x] for x in rng.choice(ue, len(ue), replace=True)]) + bb = float(np.std(m[pick])) + draws[b] = float(np.mean(w[pick])) / bb if bb > 0 else np.nan + if not np.any(np.isfinite(draws)): + return np.nan, (np.nan, np.nan) + return (float(np.nanstd(draws, ddof=1)), + (float(np.nanpercentile(draws, 2.5)), float(np.nanpercentile(draws, 97.5)))) + + +def dispersion(sub, getvals, rng): + """getvals(rec) -> the 128 values at that anchor (a scorer's scores, or an input channel).""" + W, M, eps, ties = [], [], [], [] + for r in sub: + v = np.asarray(getvals(r), float) + if v.size < 8 or not np.all(np.isfinite(v)): + continue + W.append(float(np.std(v))); M.append(float(np.mean(v))); eps.append(r["episode"]) + ties.append(float((v == v.max()).sum()) / v.size) + if len(W) < 3: + return None + W = np.asarray(W); M = np.asarray(M) + B = float(np.std(M)) + ratio = float(W.mean() / B) if B > 0 else np.inf + # eta2: between-anchor share of the total variance over all anchor x candidate values. + within_var = float(np.mean(W ** 2)) + between_var = B ** 2 + eta2 = between_var / (between_var + within_var) if (between_var + within_var) > 0 else np.nan + se, ci = ep_boot_ratio(W, M, eps, rng) + return dict(W=float(W.mean()), B=B, ratio=ratio, ratio_se=se, ratio_ci=list(ci), eta2=float(eta2), + ties_at_max=float(np.mean(ties)), anchors=len(W), episodes=int(len(set(eps)))) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("cells", nargs="+") + ap.add_argument("--entry-window", type=int, default=100) + ap.add_argument("--md", required=True) + ap.add_argument("--json", required=True) + a = ap.parse_args() + rng = np.random.default_rng(20260924) + + out, lines = [], [] + lines.append("# How much does the value move when only the ACTION changes? (gen_q#280 / rsm_real#2)\n") + lines.append("W = mean over anchors of sd(the 128 candidate scores at that anchor) -- action-induced spread.") + lines.append("B = sd over anchors of the anchor's mean score -- state-induced spread.") + lines.append("eta2 = between-anchor share of the total variance; eta2 -> 1 means the score is a function") + lines.append("of the STATE alone at these anchors and there is nothing for a ranking to read.\n") + lines.append("**There is no permutation zero line for this statistic and none is printed.** A within-anchor") + lines.append("shuffle preserves each anchor's multiset of scores, so W, B, W/B and eta2 are EXACTLY invariant") + lines.append("under it; the `permuted:*` rows are printed and flagged INVARIANT, which is the code's own check.") + lines.append("The reference is the candidate's own INPUT channel (dz in mm, and |dxyz| in mm), which says how") + lines.append("much action variation is present in the input at these very anchors.\n") + lines.append(f"Anchors: S2, entry window {a.entry_window}, coverage-gated, BY ROUTE, never pooled; the ratio's") + lines.append("interval bootstraps over EPISODES with W and B both recomputed inside each draw.\n") + + for cell in a.cells: + d = Path("status/real") / cell + if not (d / "parts").exists(): + lines.append(f"\n## {cell} -- MISSING, not scored\n"); continue + recs, cfg = load_cell(d, entry_window=a.entry_window) + recs = [r for r in recs if r["gate"]] + if not recs: + lines.append(f"\n## {cell} -- UNDEFINED: 0 anchors survive the coverage gate\n"); continue + scorers = sorted(recs[0]["scores"].keys()) + routes = sorted({r["path"] for r in recs}) + lines.append(f"\n## {cell} ({len(recs)} gated anchors, " + f"{len({r['episode'] for r in recs})} episodes, routes {routes})\n") + for route in routes: + sub = [r for r in recs if r["path"] == route] + if len(sub) < 10: + lines.append(f"\n### route {route}: UNDEFINED, only {len(sub)} gated anchors (floor 10)\n") + continue + lines.append(f"\n### route {route}\n") + lines.append("| quantity | W (action spread) | B (state spread) | W/B | +-SE | 95% CI | eta2_anchor " + "| ties@max | anchors | eps |") + lines.append("|---|---|---|---|---|---|---|---|---|---|") + rows = [("INPUT dz (mm) -- reference, not a scorer", + lambda r: np.asarray(r["dir_mm"], float)[:, 2]), + ("INPUT |dxyz| (mm) -- reference, not a scorer", + lambda r: np.linalg.norm(np.asarray(r["dir_mm"], float), axis=1))] + rows += [(sc, (lambda s: (lambda r: r["scores"][s]))(sc)) for sc in scorers] + for name, fn in rows: + res = dispersion(sub, fn, rng) + if res is None: + lines.append(f"| {name} | UNDEFINED (fewer than 3 usable anchors) | | | | | | | | |") + continue + res.update(cell=cell, route=route, quantity=name) + out.append(res) + flag = " *(INVARIANT under the shuffle -- matches its parent by construction)*" \ + if name.startswith("permuted:") else "" + lines.append(f"| {name}{flag} | {res['W']:.4g} | {res['B']:.4g} | {res['ratio']:.4g} | " + f"{res['ratio_se']:.3g} | [{res['ratio_ci'][0]:.3g}, {res['ratio_ci'][1]:.3g}] | " + f"{res['eta2']:.4f} | {res['ties_at_max']:.3f} | {res['anchors']} | " + f"{res['episodes']} |") + Path(a.md).write_text("\n".join(lines) + "\n") + Path(a.json).write_text(json.dumps(out, indent=1)) + print("\n".join(lines)) + + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/real/pt_score_range.sh b/rsm_rise/scripts/real/pt_score_range.sh new file mode 100644 index 0000000000000000000000000000000000000000..8030ee91449556ed7414193963a74783532be650 --- /dev/null +++ b/rsm_rise/scripts/real/pt_score_range.sh @@ -0,0 +1,10 @@ +#!/bin/bash +# gen_q#280 / rsm_real#2 -- action-induced vs state-induced spread of every value in the sweep. +# Eval-free: reads the saved npz parts only (no checkpoint, no GPU). +set -uo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +export MUJOCO_GL=disable +venv_rsm/bin/python scripts/real/pt_score_range.py \ + pt_heads_s0 pt_cap_ab_s0 pt_cap_ab_ws \ + --entry-window 100 \ + --md status/real/PT_SCORE_RANGE.md --json status/real/PT_SCORE_RANGE.json diff --git a/rsm_rise/scripts/real/pt_selftest.sh b/rsm_rise/scripts/real/pt_selftest.sh new file mode 100644 index 0000000000000000000000000000000000000000..62f6f275f4b0e68339389708a87991ec22b4c955 --- /dev/null +++ b/rsm_rise/scripts/real/pt_selftest.sh @@ -0,0 +1,9 @@ +#!/usr/bin/env bash +set -uo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +export MUJOCO_GL=disable +for S in 1.0 1.5 3.0 8.0; do + echo "--- PT_NOISE_SCALE=$S" + PT_NOISE_SCALE=$S /proj/dmfexp/zwhong/rsm_rise/venv_rsm/bin/python \ + scripts/real/pt_proposer_temp.py --selftest || echo "SELFTEST FAILED at scale $S" +done diff --git a/rsm_rise/scripts/real/pt_slot0_exact.py b/rsm_rise/scripts/real/pt_slot0_exact.py new file mode 100644 index 0000000000000000000000000000000000000000..bfc261b0732d6f5e75a31eb0551f2c45657c4466 --- /dev/null +++ b/rsm_rise/scripts/real/pt_slot0_exact.py @@ -0,0 +1,148 @@ +#!/usr/bin/env python +"""gen_q#280 / rsm_real#2 run 21 -- the EXACT slot-0 diagnostic, plus a bank-only contrast that removes +the plausibility channel entirely. + +WHY. Run 20 concluded that the 0.90-1.00 conditional-pairs AUC on logged chunks is the on-manifold +PLAUSIBILITY artefact #280 warns about, on the evidence that the RSM ranks the episode's OWN logged chunk +at ~16.9 of 17 on BOTH label classes -- and so does the beta==gamma negative control. That conclusion was +carried by a NORMAL APPROXIMATION, `1 + 16*Phi((raw-ref)/refsd)`, because only three summaries were stored +per anchor. The stated limit of the diagnostic was exactly this. `pt_pairs_score.py` now retains the full +17-long score vector, so this script counts the rank, the ties and the argmax instead of approximating them. + +THE SECOND STATISTIC, WHICH IS THE POINT. Slot 0 is the anchor's own chunk, so every number that involves +it mixes "is this action good" with "is this the action that actually happened here". Slots 1..16 are the +SHARED bank -- label-balanced, identical at every anchor, and off-manifold at essentially all of them, so +NONE of them is any anchor's own chunk. The contrast + + bank_contrast = mean_{m: bank label 1} V(anchor, m) - mean_{m: bank label 0} V(anchor, m) + +therefore has NO plausibility channel available to it: both sides are equally foreign to the anchor, and +the same 16 chunks are used at every anchor in every route in every cell. If the value ranks goal-route +actions above cook-route actions because it reads the ACTION, this is positive and its size differs by +route. If run 20 is right and the pairs result was plausibility, this sits at zero everywhere, including +in the cells whose slot-0 rank is 16.99. Reported per route, never pooled, with an episode bootstrap. + +A null that is actually valid here: permute the bank's LABELS (which of the 16 are called 1) and recompute. +That leaves the scores untouched and destroys only the label, so unlike `permuted:*` it does not shuffle +slot 0 into the comparison. Quoted beside every bank_contrast row. +""" +from __future__ import annotations +import json, sys, argparse +from pathlib import Path +import numpy as np + +ROOT = Path("/proj/dmfexp/zwhong/rsm_rise") + + +def load(cell): + d = ROOT / "status/real" / cell + out = [] + for p in sorted((d / "parts").glob("ep*.npz")): + z = np.load(p, allow_pickle=True) + m = json.loads(bytes(z["__meta__"]).decode()) + out.append((m, z)) + return out + + +def rt_of(m): + r = m["route"] + return "->".join(str(x) for x in r) if isinstance(r, list) else str(r) + + +def boot_ep(vals, eps, n=2000, seed=0): + """Episode-level bootstrap SE of the mean.""" + rng = np.random.default_rng(seed) + ue = np.unique(eps) + if len(ue) < 2: + return float("nan") + idx = {e: np.flatnonzero(eps == e) for e in ue} + acc = [] + for _ in range(n): + pick = rng.choice(ue, len(ue), replace=True) + acc.append(np.concatenate([vals[idx[e]] for e in pick]).mean()) + return float(np.std(acc)) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--cells", nargs="+", required=True) + ap.add_argument("--mode", default="rsm") + ap.add_argument("--min-parts", type=int, default=98, + help="refuse a cell with fewer episode parts than this. A partially-written cell has " + "its episodes in write order, so its route mix is biased and it is NOT comparable " + "to a complete cell. Skipped loudly with the count, never reduced silently.") + ap.add_argument("--out", default=str(ROOT / "status/real/PT_SLOT0_EXACT.md")) + a = ap.parse_args() + k = a.mode.replace(":", "__") + + L = ["# EXACT slot-0 rank and the bank-only contrast (gen_q#280 / rsm_real#2, run 21)", "", + "Run 20's slot-0 numbers were a normal approximation `1+16*Phi(z)`; these are COUNTED from the", + "retained 17-long score vector. Chance rank **9.0**, chance argmax share **0.0588** (1/17).", + "`ties@max` is the mean number of slots tied at the maximum. Scorer: `" + a.mode + "`.", ""] + T1 = ["| cell | route | mean rank slot0 /17 | slot0 argmax share | ties@max | bank score CV (median) | mean centered | anchors | eps |", + "|---|---|---|---|---|---|---|---|---|"] + T2 = ["| cell | route | bank_contrast | +-SE (ep boot) | label-perm null | null sd | z = bc/null sd | anchors | eps |", + "|---|---|---|---|---|---|---|---|---|"] + skipped = [] + for cell in a.cells: + recs = load(cell) + if not recs: + skipped.append((cell, "no parts")); continue + if len(recs) < a.min_parts: + skipped.append((cell, f"INCOMPLETE -- {len(recs)} of {a.min_parts} episode parts written; " + f"route mix is biased by write order, so it is not comparable to a " + f"complete cell. Not reduced.")); continue + if f"scores__{k}" not in recs[0][1]: + skipped.append((cell, "no retained score vector -- ran under the pre-run-21 scorer")); continue + # bank labels from meta: bank_src rows are [ep, t, label] + blab = np.array([s[2] for s in recs[0][0]["bank"]], int) + by = {} + for m, z in recs: + S = np.asarray(z[f"scores__{k}"], np.float64) # [n_anchors, 17] + by.setdefault(rt_of(m), []).append((S, m["episode"])) + for rt in sorted(by): + S = np.concatenate([b[0] for b in by[rt]], 0) + eps = np.concatenate([np.full(len(b[0]), b[1]) for b in by[rt]]) + n, W = S.shape + s0, bank = S[:, 0], S[:, 1:] + # EXACT rank of slot 0: 1 + (# strictly below) + 0.5*(# tied), midrank convention. + below = (bank < s0[:, None]).sum(1) + tied = (bank == s0[:, None]).sum(1) + rank = 1.0 + below + 0.5 * tied + mx = S.max(1, keepdims=True) + ties_at_max = (S == mx).sum(1) + argmax0 = (S[:, 0] >= mx[:, 0] - 0.0) & (ties_at_max == 1) + centered = s0 - bank.mean(1) + # per-anchor CV of the 16 BANK scores; median over anchors because a per-anchor mean + # can sit near zero and make an individual CV undefined rather than large (see run 23). + bmu, bsd = bank.mean(1), bank.std(1) + cv = np.median(bsd[np.abs(bmu) > 0] / np.abs(bmu[np.abs(bmu) > 0])) if (np.abs(bmu) > 0).any() else float("nan") + T1.append(f"| `{cell}` | `{rt}` | **{rank.mean():.2f}** | {argmax0.mean():.3f} | " + f"{ties_at_max.mean():.2f} | {cv:.4g} | {centered.mean():+.4g} | {n} | {len(np.unique(eps))} |") + # bank-only contrast, no plausibility channel + p, q = blab == 1, blab == 0 + if p.sum() and q.sum(): + bc = bank[:, p].mean(1) - bank[:, q].mean(1) + se = boot_ep(bc, eps) + rng = np.random.default_rng(11) + nulls = [] + for _ in range(500): + perm = rng.permutation(blab) + nulls.append((bank[:, perm == 1].mean(1) - bank[:, perm == 0].mean(1)).mean()) + nsd = float(np.std(nulls)) + zz = (bc.mean() - np.mean(nulls)) / nsd if nsd > 0 else float("nan") + T2.append(f"| `{cell}` | `{rt}` | **{bc.mean():+.5g}** | {se:.5g} | " + f"{np.mean(nulls):+.5g} | {nsd:.5g} | **{zz:+.2f}** | {n} | {len(np.unique(eps))} |") + L += ["## 1. Slot-0 rank, EXACT", ""] + T1 + ["", "## 2. Bank-only contrast (NO plausibility channel)", "", + "Both sides are shared bank chunks, so neither is the anchor's own action. A value that reads the", + "ACTION separates them; a value that only recognises its own on-manifold chunk cannot.", ""] + T2 + if skipped: + L += ["", "## Skipped cells (reported, not silently dropped)", ""] + L += [f"* `{c}` -- {why}" for c, why in skipped] + Path(a.out).write_text("\n".join(L) + "\n") + print("\n".join(L)) + print(f"[slot0exact] wrote {a.out}") + + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/real/pt_slot0_rank.py b/rsm_rise/scripts/real/pt_slot0_rank.py new file mode 100644 index 0000000000000000000000000000000000000000..ee4895c3a56bf695296a9691fe5612b7dcc3b96c --- /dev/null +++ b/rsm_rise/scripts/real/pt_slot0_rank.py @@ -0,0 +1,75 @@ +#!/usr/bin/env python +"""Why `permuted:rsm:centered` sits at 0.22-0.34 and not 0.5, and what the pairs result IS in plain units. + +`permuted:rsm` shuffles the 17-long score vector at each anchor (logged_action_rank.BaselineScorer: +`self.permute = kind.startswith("permuted:")`), and slot 0 -- the TRUE logged chunk -- is INSIDE that +shuffle. `centered = raw - ref = s[0] - mean(s[1:])`. Under a uniform shuffle its per-anchor expectation +is exactly 0 ((17/16)*(s_pi(0) - mean)), so it looks like a null; but if s[0] is a HIGH outlier then all 16 +others sit slightly BELOW the anchor mean, so a shuffled draw is negative with probability 16/17. The +size of that negative scales with how much of an outlier s[0] is -- which is the signal itself. So the row +is anti-biased IN PROPORTION TO THE TRUE EFFECT: it is an inverted signal detector, NOT a zero line. + +This script tests that prediction directly and reports the effect in a unit that needs no null at all: +the RANK of slot 0 among the 17 scores at each anchor, by route. Rank 17/17 means the value put the +episode's own logged chunk above all 16 bank chunks. Chance is 9.0. +""" +from __future__ import annotations +import json, sys +from pathlib import Path +import numpy as np + +ROOT = Path("/proj/dmfexp/zwhong/rsm_rise") + + +def load(cell): + d = ROOT / "status/real" / cell + out = [] + for p in sorted((d / "parts").glob("ep*.npz")): + z = np.load(p, allow_pickle=True) + m = json.loads(bytes(z["__meta__"]).decode()) + out.append((m, z)) + return out + + +def main(): + cells = sys.argv[1:] or ["pp_RM_b099"] + lines = ["# Slot-0 rank: what the pairs result is, in a unit with no null (gen_q#280 / rsm_real#2)", ""] + lines.append("`raw = s[0]` (the episode's OWN logged chunk), `ref = mean(s[1:])` over the SHARED 16-chunk") + lines.append("bank. Below: mean rank of slot 0 among the 17 scores (chance **9.0**, max 17), the share of") + lines.append("anchors where slot 0 is the argmax (chance 1/17 = **0.059**), and the mean `centered` in the") + lines.append("value's own units -- all BY ROUTE, never pooled, with anchors and episodes.") + lines.append("") + lines.append("| cell | route | mean rank of slot0 /17 | slot0 is argmax | mean centered | anchors | eps |") + lines.append("|---|---|---|---|---|---|---|") + for cell in cells: + recs = load(cell) + if not recs: + print(f"[slot0] {cell}: no parts"); continue + modes = recs[0][0]["modes"] + mm = "rsm" if "rsm" in modes else modes[0] + k = mm.replace(":", "__") + by = {} + for m, z in recs: + raw, ref, sd = z[f"raw__{k}"], z[f"ref__{k}"], z[f"refsd__{k}"] + # rank of slot0 among 17 reconstructed from (raw, ref, sd): we only stored summaries, so use + # the z-score of slot0 against the bank as the continuous stand-in and report it honestly. + zs = (raw - ref) / np.maximum(sd, 1e-12) + by.setdefault("->".join(str(x) for x in m["route"]) if isinstance(m["route"], list) else str(m["route"]), []).append((zs, raw - ref, m["episode"])) + for rt in sorted(by): + zs = np.concatenate([b[0] for b in by[rt]]) + ct = np.concatenate([b[1] for b in by[rt]]) + eps = len({b[2] for b in by[rt]}) + # Expected rank of slot0 among 17 iid-normal bank draws, given its z against the bank. + from math import erf, sqrt + phi = np.array([0.5 * (1 + erf(v / sqrt(2))) for v in zs]) + rank = 1 + 16 * phi + lines.append(f"| `{cell}` | `{rt}` | **{rank.mean():.2f}** | {float((zs > 2.5).mean()):.3f} | " + f"{ct.mean():+.4g} | {len(zs)} | {eps} |") + out = ROOT / "status/real/PT_SLOT0_RANK.md" + out.write_text("\n".join(lines) + "\n") + print("\n".join(lines)) + print(f"[slot0] wrote {out}") + + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/real/pt_slot0_rank.sh b/rsm_rise/scripts/real/pt_slot0_rank.sh new file mode 100644 index 0000000000000000000000000000000000000000..e3429091237a35611d75c603a5fbf2eb831bf43e --- /dev/null +++ b/rsm_rise/scripts/real/pt_slot0_rank.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -uo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +export MUJOCO_GL=disable CUDA_VISIBLE_DEVICES="" +exec venv_rsm/bin/python scripts/real/pt_slot0_rank.py \ + pp_RM_b099 pp_RMs1_b099 pp_RMnt_b099 pp_RMnts1_b099 pp_XL_b099 pp_XLnt_b099 pp_RM_peranchor pp_RM_bg_degen pp_IDQLCPU diff --git a/rsm_rise/scripts/real/pt_spread_realized.py b/rsm_rise/scripts/real/pt_spread_realized.py new file mode 100644 index 0000000000000000000000000000000000000000..ef242b7cb706d12e9f38429a28fd53f636ce7004 --- /dev/null +++ b/rsm_rise/scripts/real/pt_spread_realized.py @@ -0,0 +1,90 @@ +#!/usr/bin/env python +"""PROPOSAL_TEST run 46 -- WHAT ANGULAR-SPREAD MULTIPLIER DOES THE NOISE KNOB ACTUALLY DELIVER? + +`pt_spread_required.py` measured what the coverage gate NEEDS, in units of the within-anchor angular +spread K (K_req med 1.75; 62.5 % of anchors at K<=2, 99.3 % at K<=8). That bar is in units of K, not in +units of PT_NOISE_SCALE, and the map between the two has never been measured. This reads it off the +corrected run-45 ladder. + +Per rung, per anchor: theta_i = angle(u_i, ubar) with u_i = unit(cand_dir_mm_i) and ubar = unit(mean u_i). +The realized multiplier of a rung is K_real = median(theta | rung) / median(theta | scale 1.0), matched +ANCHOR BY ANCHOR (same episode, same frame) so a partially-drained rung cannot shift the ratio by covering +a different anchor mix. + +NO RULER and NO COVERAGE NUMBER: `margin`, `gate` and `cands` are never read, only `cand_dir_mm`. This +script cannot see a rung result; it reports the knob's calibration and nothing else. +""" +from __future__ import annotations +import glob, json, os +from pathlib import Path +import numpy as np + +ROOT = "/proj/dmfexp/zwhong/rsm_rise" +PREFIX = os.environ.get("PT_PREFIX", f"{ROOT}/status/real/pt_R45_cov_sn1_knn0p03_") +OUT = os.environ.get("PT_OUT", f"{ROOT}/status/real/pt_r46_spread_realized.json") +# the rung grid, overridable so a re-gridded ladder does not need a second copy of this script +RUNGS = [tuple(x) for x in json.loads(os.environ.get("PT_RUNGS", json.dumps( + [["T10", 1.0], ["T15", 1.5], ["T20", 2.0], ["T25", 2.5], + ["T30", 3.0], ["T40", 4.0], ["T60", 6.0], ["T80", 8.0]])))] + + +def unit(v, axis=-1, eps=1e-12): + n = np.linalg.norm(v, axis=axis, keepdims=True) + return v / np.maximum(n, eps) + + +def thetas(tag): + """-> {(episode, frame): median within-anchor angular deviation in deg}, plus the route.""" + out, route = {}, {} + for f in sorted(glob.glob(f"{PREFIX}{tag}/parts/*.npz")): + z = np.load(f, allow_pickle=True) + m = json.loads(bytes(z["__meta__"]).decode()) + if not m.get("n_anchors", 0) or "cand_dir_mm" not in z.files: + continue + U = unit(np.asarray(z["cand_dir_mm"], np.float64)) + ep, frames = int(m["episode"]), [int(x) for x in m["frames"]] + for ai, fr in enumerate(frames): + u = U[ai] + ubar = unit(u.mean(0)) + th = np.degrees(np.arccos(np.clip(u @ ubar, -1.0, 1.0))) + out[(ep, fr)] = float(np.median(th)) + route[(ep, fr)] = str(m["path"]) + return out, route + + +base, route = thetas("T10") +if not base: + raise SystemExit("[real] scale-1.0 rung has no cache yet -- the multiplier has no denominator, nothing read") +print(f"[real] baseline rung T10 (scale 1.0): {len(base)} anchors, " + f"{len({e for e, _ in base})} episodes, median theta = {np.median(list(base.values())):.3f} deg") + +res = {} +print("[real] === realized angular-spread multiplier, anchors matched to the scale-1.0 rung ===") +print("[real] rung scale matched theta_med(1.0) theta_med(rung) K_real K_real p25/p75") +for tag, s in RUNGS: + if tag == "T10": + continue + cur, _ = thetas(tag) + keys = sorted(set(cur) & set(base)) + if not keys: + print(f"[real] {tag:5s} {s:5.1f} NO MATCHED ANCHORS YET"); continue + b = np.array([base[k] for k in keys]); c = np.array([cur[k] for k in keys]) + r = c / np.maximum(b, 1e-9) + res[tag] = dict(scale=s, matched=len(keys), episodes=len({e for e, _ in keys}), + theta_med_base=float(np.median(b)), theta_med_rung=float(np.median(c)), + k_real=float(np.median(c) / max(np.median(b), 1e-9)), + k_real_per_anchor_med=float(np.median(r)), + k_real_p25=float(np.percentile(r, 25)), k_real_p75=float(np.percentile(r, 75))) + v = res[tag] + print(f"[real] {tag:5s} {s:5.1f} {v['matched']:6d} {v['theta_med_base']:12.3f} " + f"{v['theta_med_rung']:13.3f} {v['k_real']:6.3f} " + f"{v['k_real_p25']:.3f}/{v['k_real_p75']:.3f}") + +res["T10"] = dict(scale=1.0, matched=len(base), episodes=len({e for e, _ in base}), + theta_med_base=float(np.median(list(base.values()))), + theta_med_rung=float(np.median(list(base.values()))), k_real=1.0, + k_real_per_anchor_med=1.0, k_real_p25=1.0, k_real_p75=1.0) +json.dump({"prefix": PREFIX, "rungs": res}, open(OUT, "w"), indent=1) +print(f"[real] -> {OUT}") +print("[real] read this AGAINST the pre-registered requirement curve (pt_r46_spread_required.json): " + "gate pass rate 0.348 at K=1, 0.625 at K=2, 0.859 at K=4, 0.993 at K=8, whole-S2, 1043 anchors/15 eps.") diff --git a/rsm_rise/scripts/real/pt_spread_realized.sh b/rsm_rise/scripts/real/pt_spread_realized.sh new file mode 100644 index 0000000000000000000000000000000000000000..a4ff28d5eb70d236437cc868a01ee6f5dc12a3c2 --- /dev/null +++ b/rsm_rise/scripts/real/pt_spread_realized.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +set -uo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +export MUJOCO_GL=disable +/proj/dmfexp/zwhong/rsm_rise/venv_rsm/bin/python scripts/real/pt_spread_realized.py diff --git a/rsm_rise/scripts/real/pt_spread_realized_r46.sh b/rsm_rise/scripts/real/pt_spread_realized_r46.sh new file mode 100644 index 0000000000000000000000000000000000000000..f679c39fc9a5134cf35fb38063a7671fd80c4ccb --- /dev/null +++ b/rsm_rise/scripts/real/pt_spread_realized_r46.sh @@ -0,0 +1,9 @@ +#!/usr/bin/env bash +# run 46 FINE ladder: same reader, re-gridded via PT_RUNGS / PT_PREFIX. No script duplicated. +set -uo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +export MUJOCO_GL=disable +export PT_PREFIX=/proj/dmfexp/zwhong/rsm_rise/status/real/pt_R46_cov_sn1_knn0p03_ +export PT_OUT=/proj/dmfexp/zwhong/rsm_rise/status/real/pt_r46_spread_realized_fine.json +export PT_RUNGS='[["T10",1.0],["F105",1.05],["F110",1.10],["F115",1.15],["F120",1.20],["F125",1.25],["F130",1.30],["F140",1.40]]' +/proj/dmfexp/zwhong/rsm_rise/venv_rsm/bin/python scripts/real/pt_spread_realized.py diff --git a/rsm_rise/scripts/real/pt_spread_recheck.py b/rsm_rise/scripts/real/pt_spread_recheck.py new file mode 100644 index 0000000000000000000000000000000000000000..cf32d58b5ea7f79024c5ade987af2b772bf38796 --- /dev/null +++ b/rsm_rise/scripts/real/pt_spread_recheck.py @@ -0,0 +1,142 @@ +#!/usr/bin/env python +"""gen_q#280 / rsm_real#2 run 50 -- re-flag every PUBLISHED proposal-test CLEARS mark against the MEASURED +Monte Carlo spread of the read-out. + +Run 49 established that the default read-out is stochastic: proposal_test.py:276 seeds each scorer's RNG by +its index in sorted(scorers), twin_rollout.py:302 hands that to the coin chain, rsm_scorer.py:631 makes it +the torch.Generator. The same checkpoint at a different alphabetical position is a different Monte Carlo +draw. `pt_ro_mcrep` measures that spread directly: 8 rows, identical checkpoint / read-out / cached draws / +anchors / gate, differing only in scorer index. + +This script does NOT re-score anything. It reads the reduce JSONs already on disk and asks one question per +published CLEARS mark: is the clearance bigger than a single unmeasured redraw of the same number? + + margin_fwer = auc - q95_fwer (the family-wise bar the row was flagged against) + margin_perm = auc - auc_permuted (the measured zero line, per #280, never a nominal 0.5) + a mark SURVIVES only if BOTH margins exceed the spread for that row's own group. + +SCOPE, stated because it is the thing that could be got wrong: the mcrep spread is the error bar of the +CHAIN. It applies to scorers that run the chain -- `rsm`, `rsm@...`, `permuted:rsm`. Deterministic scorers +(`idql`, `pose_cont`, `greedy_index`, `greedy`, `bc_ll`) do not resample, so this particular error bar is +not their error bar and their rows are reported N/A rather than given a bar they did not earn. `random` is +stochastic but not through the chain, so it is N/A too. + + usage: pt_spread_recheck.py [cell ...] [--window 100] [--spread status/real/PT_MCSPREAD_w100.json] + [--repsrc ro_mcrep] +""" +import json, sys +from pathlib import Path + +args = list(sys.argv[1:]) + + +def opt(flag, default): + global args + if flag in args: + i = args.index(flag); v = args[i + 1]; del args[i:i + 2]; return v + return default + + +W = opt("--window", "100") +SPREAD_JSON = opt("--spread", None) or f"status/real/PT_MCSPREAD_w{W}.json" +REPSRC = opt("--repsrc", "ro_mcrep") +CELLS = args or ["heads_s0", "cap_ab_s0", "cap_ab_ws"] + +# Cells that carry a published VOID verdict must never be re-flagged into readability. +VOID = {"mlong_s0": "VOID -- run 49 item 1: rsm@M_100k did not reproduce its reference; no rung is readable"} + +CHAIN = lambda s: s == "rsm" or s.startswith("rsm@") or s == "permuted:rsm" or s.startswith("permuted:rsm") + + +def route(g): + return g.split("|", 1)[1].strip() if "|" in g else "POOLED" + + +sp_raw = {} +if Path(SPREAD_JSON).exists(): + sp_raw = json.load(open(SPREAD_JSON)) +# keep only the replicate-source cell's spreads, keyed by route +spread = {} +for k, v in sp_raw.items(): + cell, g = k.split("|", 1) + if cell.strip() == REPSRC: + spread[route(g)] = float(v) + +out = [f"### PUBLISHED CLEARS MARKS, RE-FLAGGED AGAINST THE MEASURED READ-OUT SPREAD (window {W})", "", + f"Spread source `{REPSRC}` ({SPREAD_JSON}). A mark SURVIVES only if BOTH its family-wise margin and " + "its margin over its own measured permuted line exceed the spread for its route. Deterministic " + "scorers are N/A: the chain's error bar is not theirs.", ""] + +if not spread: + out += [f"**NO SPREAD AVAILABLE** -- `{SPREAD_JSON}` is missing or contains no `{REPSRC}` rows. " + "Every published CLEARS mark therefore remains UNVERIFIED against read-out noise. " + "This is reported as UNDEFINED, not as a pass and not as a failure.", ""] +else: + out += ["| route | measured spread |", "|---|---|"] + for r, v in sorted(spread.items()): + out.append(f"| `{r}` | **{v:.4f}** |") + out.append("") + +n_sur = n_within = n_na = n_und = 0 +MARGINS = [] +for cell in CELLS: + if cell in VOID: + out += [f"#### `{cell}` -- SKIPPED: {VOID[cell]}", ""] + continue + wp = Path(f"status/real/PT_WIN_{cell}_w{W}.json") + cp = Path(f"status/real/PT_WINCAL_{cell}_w{W}.json") + if not wp.exists() or not cp.exists(): + out += [f"#### `{cell}` -- MISSING reduce JSON, not re-flagged", ""] + continue + d, cal = json.load(open(wp)), json.load(open(cp)) + out += [f"#### `{cell}`", "", + "| group | scorer | AUC | FWER q95 | margin vs FWER | permuted | margin vs perm | " + "spread | verdict |", "|---|---|---|---|---|---|---|---|---|"] + for g, blk in d.items(): + q = cal.get(g, {}).get("q95_fwer") + if q is None: + out.append(f"| `{g}` | -- | | | | | | | **NO BAR -- not re-flagged** |"); n_und += 1; continue + r_ = route(g) + sv = spread.get(r_) + cov = blk["coverage"] + for row in blk["scorers"]: + s, a = row["scorer"], row["auc"] + if a <= q: + continue # was never a CLEARS mark; nothing to re-flag + p = row["auc_permuted"] + mf, mp = a - q, a - p + if CHAIN(s): + MARGINS.append(min(mf, mp)) + if not CHAIN(s): + v = "N/A -- deterministic, chain spread is not its bar"; n_na += 1 + sv_s = "--" + elif sv is None: + v = f"**UNDEFINED -- no `{REPSRC}` spread for route `{r_}`**"; n_und += 1 + sv_s = "--" + elif mf > sv and mp > sv: + v = "**SURVIVES the spread**"; n_sur += 1 + sv_s = f"{sv:.4f}" + else: + v = "**WITHIN the spread -- NOT an effect**"; n_within += 1 + sv_s = f"{sv:.4f}" + out.append(f"| `{g}` ({cov['gated_anchors']}a/{cov['gated_episodes']}e) | `{s}` | {a:.4f} | " + f"{q:.4f} | {mf:+.4f} | {p:.4f} | {mp:+.4f} | {sv_s} | {v} |") + out.append("") + +# SENSITIVITY: how many marks survive as a function of the spread, so the answer is legible BEFORE the +# spread lands and is not hand-counted afterwards. The binding margin is min(fwer, perm); perm is always +# the larger of the two on these tables, so FWER binds, but the code takes the min rather than assuming it. +if MARGINS: + out += ["", "#### SENSITIVITY -- chain-stochastic CLEARS marks surviving, as a function of the spread", + "", f"{len(MARGINS)} chain-stochastic marks in total. Binding margin is min(vs FWER, vs perm).", + "", "| spread | survive | within (not effects) |", "|---|---|---|"] + for sv in (0.004, 0.008, 0.010, 0.012, 0.014, 0.016, 0.020, 0.030): + k = sum(1 for m in MARGINS if m > sv) + out.append(f"| {sv:.3f} | {k} | {len(MARGINS)-k} |") + +out += ["", f"**Totals across re-flagged CLEARS marks: {n_sur} SURVIVE, {n_within} WITHIN the spread " + f"(not effects), {n_na} N/A (deterministic), {n_und} UNDEFINED (no bar).**"] +txt = "\n".join(out) +print(txt) +Path(f"status/real/PT_SPREAD_RECHECK_w{W}.md").write_text(txt + "\n") +print(f"\n[recheck] wrote status/real/PT_SPREAD_RECHECK_w{W}.md") diff --git a/rsm_rise/scripts/real/pt_spread_required.py b/rsm_rise/scripts/real/pt_spread_required.py new file mode 100644 index 0000000000000000000000000000000000000000..0d485e8982fa7faf4744a1c2ac626cc07758bfaa --- /dev/null +++ b/rsm_rise/scripts/real/pt_spread_required.py @@ -0,0 +1,153 @@ +#!/usr/bin/env python +"""PROPOSAL_TEST run 46 -- HOW MUCH MORE ANGULAR SPREAD WOULD THE COVERAGE GATE NEED? + +The noise-scale ladder (run 45, corrected) asks "does more sampling noise make the gate pass?". That +question has no bar attached to it: the ladder tops out at scale 8.0 and nobody has measured how much +spread the gate actually REQUIRES. This script measures the requirement from the PUBLISHED reference cell +(`pt_cov_sn1_knn0p03`, scale 1.0), so the bar exists BEFORE any corrected rung is read. + +DEFINITION (one number per anchor, `K_req`). Per anchor: + * u_i = unit(cand_dir_mm_i) the 128 candidate directions (THE convention, chunk[-1]-chunk[0]) + * ubar = unit(mean_i u_i) the anchor's mean candidate direction + * theta_i = angle(u_i, ubar) its within-anchor angular deviation + * inflate by K along the SAME great circle: u_i(K) = cos(K*theta_i)*ubar + sin(K*theta_i)*p_i, with + p_i the unit component of u_i perpendicular to ubar (K=1 reproduces u_i exactly). + * m_i(K) = u_i(K).uS - u_i(K).uF the published ruler, re-read from the cell's config.json + * K_req = the smallest K on the grid at which min(#m>0, #m<=0) >= gate_min (16 of 128). + +WHAT THE MODEL ASSUMES, stated because it bounds the answer: spread grows ISOTROPICALLY about a FIXED mean +direction. A sampler knob that also ROTATES the mean toward the boundary would pass at a smaller K, and one +that rotates it away would need more. So K_req is the requirement under "more of the same spread", which is +what a noise-scale knob is supposed to be. The assumption-free companion is printed beside it: + * delta = arcsin(|ubar . unit(uS-uF)|) the angular distance from the mean direction to the m=0 plane + * theta_med = median_i theta_i the candidate cone's half-width + * R = delta / theta_med the same requirement without the slerp model + +THE RULER IS NOT A SCORER HERE. `margin` is the label generator; this script uses it only to locate the +decision boundary, never as a score, and reports no AUC. No value is loaded. Route labels come from the +episode's logged route string, and nothing is pooled across routes. +""" +from __future__ import annotations +import glob, json, os +from pathlib import Path +import numpy as np + +ROOT = "/proj/dmfexp/zwhong/rsm_rise" +CELL = os.environ.get("PT_CELL", f"{ROOT}/status/real/pt_cov_sn1_knn0p03") +GATE_MIN = int(os.environ.get("PT_GATE_MIN", "16")) +OUT = os.environ.get("PT_OUT", f"{ROOT}/status/real/pt_r46_spread_required.json") +KGRID = np.concatenate([np.arange(1.0, 10.001, 0.25), np.arange(10.5, 60.001, 0.5)]) + + +def unit(v, axis=-1, eps=1e-12): + n = np.linalg.norm(v, axis=axis, keepdims=True) + return v / np.maximum(n, eps) + + +# PT_RULER_FROM: read the ruler from another cell's config.json. The ruler (the two measured meta +# directions at S2, job 1881603) is a property of the TEST, not of a cell -- it does not depend on the +# proposer or on a noise scale -- so a rung directory that has no config.json yet (written only when the +# whole cell finishes) is read against the PUBLISHED cell's ruler. That is also what makes a rung's gate +# rate comparable with the requirement curve, which used exactly this ruler. Default unchanged. +RULER_FROM = os.environ.get("PT_RULER_FROM", CELL) +cfg = json.load(open(Path(RULER_FROM) / "config.json")) +if RULER_FROM != CELL: + print(f"[req] RULER borrowed from {RULER_FROM} (rung cells carry no config.json until completion)") +R = cfg["ruler"] +uS = unit(np.asarray(R["u_success"], np.float64)) +uF = unit(np.asarray(R["u_failure"], np.float64)) +w = unit(uS - uF) # normal of the m(v)=0 plane +print(f"[req] cell={CELL}") +print(f"[req] ruler uS={np.round(uS,4).tolist()} uF={np.round(uF,4).tolist()} " + f"angle={R['angle_success_failure_deg']:.1f} deg gate_min={GATE_MIN}") + +rows, dropped_files = [], 0 +for f in sorted(glob.glob(f"{CELL}/parts/*.npz")): + z = np.load(f, allow_pickle=True) + m = json.loads(bytes(z["__meta__"]).decode()) + if not m.get("n_anchors", 0) or "cand_dir_mm" not in z.files: + dropped_files += 1 + continue + V = np.asarray(z["cand_dir_mm"], np.float64) # [A, N, 3] in mm + marg_pub = np.asarray(z["margin"], np.float64) # [A, N] as published (K = 1) + route, ep = str(m["path"]), int(m["episode"]) + U = unit(V) # [A,N,3] + for ai in range(U.shape[0]): + u = U[ai] # [N,3] + n_cand = u.shape[0] + ubar = unit(u.mean(0)) + cth = np.clip(u @ ubar, -1.0, 1.0) + th = np.arccos(cth) # [N] + perp = u - cth[:, None] * ubar[None, :] + nrm = np.linalg.norm(perp, axis=1) + p = np.where(nrm[:, None] > 1e-12, perp / np.maximum(nrm[:, None], 1e-12), 0.0) + # sanity: K = 1 must reproduce the published margin + u1 = np.cos(th)[:, None] * ubar[None, :] + np.sin(th)[:, None] * p + m1 = u1 @ uS - u1 @ uF + err = float(np.max(np.abs(m1 - marg_pub[ai]))) if marg_pub.shape[1] == n_cand else float("nan") + k_req = float("inf") + n_lo = n_hi = -1 + for K in KGRID: + a = np.minimum(K * th, np.pi) + uk = np.cos(a)[:, None] * ubar[None, :] + np.sin(a)[:, None] * p + mk = uk @ uS - uk @ uF + ns = int((mk > 0).sum()) + if min(ns, n_cand - ns) >= GATE_MIN: + k_req, n_lo, n_hi = float(K), ns, n_cand - ns + break + delta = float(np.arcsin(np.clip(abs(float(ubar @ w)), 0.0, 1.0))) + th_med = float(np.median(th)) + ns0 = int((marg_pub[ai] > 0).sum()) if marg_pub.shape[1] == n_cand else -1 + rows.append(dict(episode=ep, route=route, anchor=ai, n_cand=n_cand, + k_req=k_req, n_succ_at_kreq=n_lo, n_fail_at_kreq=n_hi, + delta_deg=float(np.degrees(delta)), theta_med_deg=float(np.degrees(th_med)), + theta_p90_deg=float(np.degrees(np.percentile(th, 90))), + ratio_delta_over_theta=float(delta / max(th_med, 1e-12)), + n_succ_published=ns0, k1_reproduction_maxabs=err)) + +if not rows: + raise SystemExit("[req] no anchors read -- nothing to report") + +R1 = max(r["k1_reproduction_maxabs"] for r in rows) +print(f"[req] K=1 reproduction of the published margin: max|delta| = {R1:.3e} " + f"({'OK' if R1 < 1e-6 else 'MISMATCH -- the slerp model does not reproduce the cell, do not read K_req'})") + +def summarise(sel, name): + if not sel: + print(f"[req] {name}: NO ANCHORS"); return None + k = np.array([r["k_req"] for r in sel]) + fin = np.isfinite(k) + d = np.array([r["delta_deg"] for r in sel]); t = np.array([r["theta_med_deg"] for r in sel]) + rr = np.array([r["ratio_delta_over_theta"] for r in sel]) + eps = sorted({r["episode"] for r in sel}) + s = dict(name=name, anchors=len(sel), episodes=len(eps), + k_req_med=float(np.median(k[fin])) if fin.any() else None, + k_req_q25=float(np.percentile(k[fin], 25)) if fin.any() else None, + k_req_q75=float(np.percentile(k[fin], 75)) if fin.any() else None, + k_req_min=float(k[fin].min()) if fin.any() else None, + frac_unreachable=float((~fin).mean()), + frac_k_le_2=float((k <= 2.0).mean()), frac_k_le_4=float((k <= 4.0).mean()), + frac_k_le_8=float((k <= 8.0).mean()), frac_k_le_20=float((k <= 20.0).mean()), + delta_deg_med=float(np.median(d)), theta_med_deg_med=float(np.median(t)), + ratio_med=float(np.median(rr)), + n_succ_published_med=float(np.median([r["n_succ_published"] for r in sel]))) + print(f"[req] {name}: anchors={s['anchors']} eps={s['episodes']} " + f"K_req med={s['k_req_med']} q25={s['k_req_q25']} q75={s['k_req_q75']} min={s['k_req_min']} " + f"unreachable(K>60)={s['frac_unreachable']:.3f}") + print(f"[req] {name}: frac K<=2 {s['frac_k_le_2']:.3f} | K<=4 {s['frac_k_le_4']:.3f} | " + f"K<=8 {s['frac_k_le_8']:.3f} | K<=20 {s['frac_k_le_20']:.3f} " + f"(K<=8 is the run-45 ladder's top rung)") + print(f"[req] {name}: delta med={s['delta_deg_med']:.2f} deg | theta_med med={s['theta_med_deg_med']:.2f} deg" + f" | ratio med={s['ratio_med']:.2f} | published succ-side med={s['n_succ_published_med']:.0f}/128") + return s + +summ = {"ALL": summarise(rows, "ALL")} +for route in sorted({r["route"] for r in rows}): + summ[route] = summarise([r for r in rows if r["route"] == route], f"route {route}") + +json.dump({"cell": CELL, "gate_min": GATE_MIN, "ruler": R, + "k1_reproduction_maxabs": R1, "dropped_files": dropped_files, + "kgrid": [float(KGRID[0]), float(KGRID[-1])], + "summary": summ, "rows": rows}, open(OUT, "w"), indent=1) +print(f"[req] -> {OUT} ({len(rows)} anchors, {len({r['episode'] for r in rows})} episodes, " + f"{dropped_files} part files with no anchors)") diff --git a/rsm_rise/scripts/real/pt_spread_required.sh b/rsm_rise/scripts/real/pt_spread_required.sh new file mode 100644 index 0000000000000000000000000000000000000000..f36f5b71a843c1addf4bc235202dd61380b85555 --- /dev/null +++ b/rsm_rise/scripts/real/pt_spread_required.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +set -uo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +export MUJOCO_GL=disable +/proj/dmfexp/zwhong/rsm_rise/venv_rsm/bin/python scripts/real/pt_spread_required.py diff --git a/rsm_rise/scripts/real/pt_temp_plaus.sh b/rsm_rise/scripts/real/pt_temp_plaus.sh new file mode 100644 index 0000000000000000000000000000000000000000..2e0146809c95c9559d861469a965eff68f09fb3c --- /dev/null +++ b/rsm_rise/scripts/real/pt_temp_plaus.sh @@ -0,0 +1,15 @@ +#!/bin/bash +# PROPOSAL_TEST run 42 -- the pre-registered PLAUSIBILITY GUARD on the noise-scale ladder. Reference rung +# is scale 1.0. Disqualifiers, both fixed before the wave was submitted: disp > 32.2 mm (2x the logged +# 16.1 mm), or nearest-logged-chunk distance > 3x the scale-1.0 rung's. +set -euo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +export MUJOCO_GL=disable OMP_NUM_THREADS=8 MKL_NUM_THREADS=8 OPENBLAS_NUM_THREADS=8 +exec venv_rsm/bin/python scripts/real/pt_plaus.py \ + --out status/real/pt_temp_plaus \ + --tags pt_cov_sn1_knn0p03 \ + pt_cov_sn1_knn0p03_T10 pt_cov_sn1_knn0p03_T15 pt_cov_sn1_knn0p03_T20 \ + pt_cov_sn1_knn0p03_T25 pt_cov_sn1_knn0p03_T30 pt_cov_sn1_knn0p03_T40 \ + pt_cov_sn1_knn0p03_T60 pt_cov_sn1_knn0p03_T80 \ + --ref-tag pt_cov_sn1_knn0p03_T10 \ + --entry-window 100 --length 8 --donors 128 --rng-seed 90210 --boot 2000 diff --git a/rsm_rise/scripts/real/pt_temp_plaus_r45.sh b/rsm_rise/scripts/real/pt_temp_plaus_r45.sh new file mode 100644 index 0000000000000000000000000000000000000000..58ac922fb2b0ac4167ce15918509195e239d06ef --- /dev/null +++ b/rsm_rise/scripts/real/pt_temp_plaus_r45.sh @@ -0,0 +1,15 @@ +#!/bin/bash +# PROPOSAL_TEST run 42 -- the pre-registered PLAUSIBILITY GUARD on the noise-scale ladder. Reference rung +# is scale 1.0. Disqualifiers, both fixed before the wave was submitted: disp > 32.2 mm (2x the logged +# 16.1 mm), or nearest-logged-chunk distance > 3x the scale-1.0 rung's. +set -euo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +export MUJOCO_GL=disable OMP_NUM_THREADS=8 MKL_NUM_THREADS=8 OPENBLAS_NUM_THREADS=8 +exec venv_rsm/bin/python scripts/real/pt_plaus.py \ + --out status/real/pt_R45_temp_plaus \ + --tags pt_cov_sn1_knn0p03 \ + pt_R45_cov_sn1_knn0p03_T10 pt_R45_cov_sn1_knn0p03_T15 pt_R45_cov_sn1_knn0p03_T20 \ + pt_R45_cov_sn1_knn0p03_T25 pt_R45_cov_sn1_knn0p03_T30 pt_R45_cov_sn1_knn0p03_T40 \ + pt_R45_cov_sn1_knn0p03_T60 pt_R45_cov_sn1_knn0p03_T80 \ + --ref-tag pt_R45_cov_sn1_knn0p03_T10 \ + --entry-window 100 --length 8 --donors 128 --rng-seed 90210 --boot 2000 diff --git a/rsm_rise/scripts/real/pt_temp_reduce.sh b/rsm_rise/scripts/real/pt_temp_reduce.sh new file mode 100644 index 0000000000000000000000000000000000000000..e142c56244cf7be93546e4d8a60d5768b5480037 --- /dev/null +++ b/rsm_rise/scripts/real/pt_temp_reduce.sh @@ -0,0 +1,17 @@ +#!/bin/bash +# PROPOSAL_TEST run 42 -- the coverage reading of the noise-scale ladder. Instrument: the ground-truth +# route-label destiny model of run 41 (`pt_proposer_destiny.py`, IMPORTED/RUN UNEDITED), because the +# published coverage gate's nearest-centroid direction proxy was measured BELOW CHANCE at S2 (18:15Z). +# NO AUC is computed on proposer draws. The scale-1.0 rung is the REPRODUCTION GUARD against the published +# cell `pt_cov_sn1_knn0p03`, which is included in the same run so the two sit on the same anchors. +set -euo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +export MUJOCO_GL=disable OMP_NUM_THREADS=1 MKL_NUM_THREADS=1 OPENBLAS_NUM_THREADS=1 +exec venv_rsm/bin/python scripts/real/pt_proposer_destiny.py \ + --out status/real/pt_temp_destiny_w100_goal_vs_cook \ + --tags pt_cov_sn1_knn0p03 \ + pt_cov_sn1_knn0p03_T10 pt_cov_sn1_knn0p03_T15 pt_cov_sn1_knn0p03_T20 \ + pt_cov_sn1_knn0p03_T25 pt_cov_sn1_knn0p03_T30 pt_cov_sn1_knn0p03_T40 \ + pt_cov_sn1_knn0p03_T60 pt_cov_sn1_knn0p03_T80 \ + --entry-window 100 --lengths 8 --seeds 0 1 2 --models logreg mlp \ + --donors 128 --min-side 16 --min-anchors 30 --min-eps 4 --boot 2000 --repro-guard 1 diff --git a/rsm_rise/scripts/real/pt_temp_reduce_r45.sh b/rsm_rise/scripts/real/pt_temp_reduce_r45.sh new file mode 100644 index 0000000000000000000000000000000000000000..a5ede64d7969acebdddb22ab9df4408af97dcd0f --- /dev/null +++ b/rsm_rise/scripts/real/pt_temp_reduce_r45.sh @@ -0,0 +1,17 @@ +#!/bin/bash +# PROPOSAL_TEST run 42 -- the coverage reading of the noise-scale ladder. Instrument: the ground-truth +# route-label destiny model of run 41 (`pt_proposer_destiny.py`, IMPORTED/RUN UNEDITED), because the +# published coverage gate's nearest-centroid direction proxy was measured BELOW CHANCE at S2 (18:15Z). +# NO AUC is computed on proposer draws. The scale-1.0 rung is the REPRODUCTION GUARD against the published +# cell `pt_cov_sn1_knn0p03`, which is included in the same run so the two sit on the same anchors. +set -euo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +export MUJOCO_GL=disable OMP_NUM_THREADS=1 MKL_NUM_THREADS=1 OPENBLAS_NUM_THREADS=1 +exec venv_rsm/bin/python scripts/real/pt_proposer_destiny.py \ + --out status/real/pt_R45_temp_destiny_w100_goal_vs_cook \ + --tags pt_cov_sn1_knn0p03 \ + pt_R45_cov_sn1_knn0p03_T10 pt_R45_cov_sn1_knn0p03_T15 pt_R45_cov_sn1_knn0p03_T20 \ + pt_R45_cov_sn1_knn0p03_T25 pt_R45_cov_sn1_knn0p03_T30 pt_R45_cov_sn1_knn0p03_T40 \ + pt_R45_cov_sn1_knn0p03_T60 pt_R45_cov_sn1_knn0p03_T80 \ + --entry-window 100 --lengths 8 --seeds 0 1 2 --models logreg mlp \ + --donors 128 --min-side 16 --min-anchors 30 --min-eps 4 --boot 2000 --repro-guard 1 diff --git a/rsm_rise/scripts/real/pt_temp_repro.py b/rsm_rise/scripts/real/pt_temp_repro.py new file mode 100644 index 0000000000000000000000000000000000000000..9a9eb63ee9cd94b0f7e0ef6526c034c94556b3cc --- /dev/null +++ b/rsm_rise/scripts/real/pt_temp_repro.py @@ -0,0 +1,42 @@ +#!/usr/bin/env python +"""PROPOSAL_TEST run 42 -- the BIT-EXACT reproduction guard of the noise-scale ladder. + +The scale-1.0 rung installs no wrapper at all (`pt_proposer_temp.py` only wraps the generator when +`PT_NOISE_SCALE != 1.0`), so its `cands` must equal the published cell `pt_cov_sn1_knn0p03`'s EXACTLY. +`|delta| = 0` in float32 is the bar, not a tolerance. If this fails, every rung of run 42 is VOID. +""" +import glob, json, sys +from pathlib import Path +import numpy as np + +ROOT = "/proj/dmfexp/zwhong/rsm_rise" +A, B = sys.argv[1], sys.argv[2] +wa = worst = 0.0 +n_anch = n_ep = 0 +bad = [] +for fa in sorted(glob.glob(f"{ROOT}/status/real/{A}/parts/*.npz")): + name = Path(fa).name + fb = f"{ROOT}/status/real/{B}/parts/{name}" + if not Path(fb).exists(): + bad.append(f"{name}: MISSING in {B}"); continue + za, zb = np.load(fa, allow_pickle=True), np.load(fb, allow_pickle=True) + ma = json.loads(bytes(za["__meta__"]).decode()) + if not ma.get("n_anchors", 0): + continue + if "cands" not in za.files or "cands" not in zb.files: + bad.append(f"{name}: no `cands` in one side"); continue + ca, cb = np.asarray(za["cands"]), np.asarray(zb["cands"]) + if ca.shape != cb.shape: + bad.append(f"{name}: shape {ca.shape} vs {cb.shape}"); continue + d = float(np.abs(ca.astype(np.float64) - cb.astype(np.float64)).max()) + worst = max(worst, d) + n_anch += ca.shape[0]; n_ep += 1 + if d != 0.0: + bad.append(f"{name}: max|delta| = {d:.6e}") +print(f"[repro] {A} vs {B}: compared {n_anch} anchors across {n_ep} episodes, " + f"worst max|delta| on `cands` = {worst:.6e}") +for b in bad[:20]: + print(f"[repro] PROBLEM {b}") +ok = (not bad) and worst == 0.0 and n_anch > 0 +print(f"[repro] BIT-EXACT REPRODUCTION GUARD {'PASSES' if ok else 'FAILS -- every run-42 rung is VOID'}") +sys.exit(0 if ok else 4) diff --git a/rsm_rise/scripts/real/pt_temp_repro.sh b/rsm_rise/scripts/real/pt_temp_repro.sh new file mode 100644 index 0000000000000000000000000000000000000000..9ff3519903ab7e5ad500cf835132222b45548c86 --- /dev/null +++ b/rsm_rise/scripts/real/pt_temp_repro.sh @@ -0,0 +1,11 @@ +#!/usr/bin/env bash +# PROPOSAL_TEST run 43 -- runner for the run-42 bit-exact reproduction guard. +set -uo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +export MUJOCO_GL=disable +P=/proj/dmfexp/zwhong/rsm_rise/venv_rsm/bin/python +echo "[repro-run] start $(date)" +$P scripts/real/pt_temp_repro.py pt_cov_sn1_knn0p03_T10 pt_cov_sn1_knn0p03 +rc=$? +echo "[repro-run] exit=$rc $(date)" +exit $rc diff --git a/rsm_rise/scripts/real/pt_temp_repro_diag.py b/rsm_rise/scripts/real/pt_temp_repro_diag.py new file mode 100644 index 0000000000000000000000000000000000000000..d8eaab3669ce91a652b5388e7215af80bf114177 --- /dev/null +++ b/rsm_rise/scripts/real/pt_temp_repro_diag.py @@ -0,0 +1,75 @@ +#!/usr/bin/env python +"""PROPOSAL_TEST run 43 -- DIAGNOSTIC for the run-42 reproduction-guard FAILURE. + +The guard (pt_temp_repro.py) reported worst max|delta| = 6.08e-02 on `cands` between the scale-1.0 rung +`pt_cov_sn1_knn0p03_T10` and the published cell `pt_cov_sn1_knn0p03`, which VOIDS every run-42 rung as +pre-registered. This script does NOT reinterpret the guard. It asks only WHY, by separating the two +hypotheses that have different consequences: + + H_num : same RNG stream, numerical / hardware divergence amplified by the flow solver. + Signature -> delta concentrated near 0 with a thin tail; per-anchor candidate SETS still + pair up elementwise; correlation ~1. + H_seed : a different underlying draw stream (sharding, seed or ordering differs). + Signature -> delta of the same order as the candidate spread itself everywhere; median delta + comparable to max; no elementwise pairing. + +It also reports the delta IN THE UNITS THE LADDER IS MEASURED IN (mm of displacement), because a delta +that is large in raw absolute-pose units may be irrelevant to a displacement statistic, and vice versa. +NO rung is read as a result here and no coverage number is produced. +""" +import glob, json +from pathlib import Path +import numpy as np + +ROOT = "/proj/dmfexp/zwhong/rsm_rise" +A, B = "pt_cov_sn1_knn0p03_T10", "pt_cov_sn1_knn0p03" + +rows = [] +for fa in sorted(glob.glob(f"{ROOT}/status/real/{A}/parts/*.npz")): + name = Path(fa).name + fb = f"{ROOT}/status/real/{B}/parts/{name}" + if not Path(fb).exists(): + continue + za, zb = np.load(fa, allow_pickle=True), np.load(fb, allow_pickle=True) + ma = json.loads(bytes(za["__meta__"]).decode()) + if not ma.get("n_anchors", 0) or "cands" not in za.files or "cands" not in zb.files: + continue + ca = np.asarray(za["cands"]).astype(np.float64) + cb = np.asarray(zb["cands"]).astype(np.float64) + if ca.shape != cb.shape: + print(f"[diag] {name}: SHAPE MISMATCH {ca.shape} vs {cb.shape}") + continue + d = np.abs(ca - cb) + # displacement direction statistic the ladder actually uses: chunk[-1,:3] - chunk[0,:3] + def disp(c): + return c[..., -1, :3] - c[..., 0, :3] + da, db = disp(ca), disp(cb) + dd = np.linalg.norm(da - db, axis=-1) * 1000.0 + rows.append(dict(name=name, n_anchor=ca.shape[0], shape=str(ca.shape), + d_med=float(np.median(d)), d_p99=float(np.percentile(d, 99)), + d_max=float(d.max()), d_mean=float(d.mean()), + corr=float(np.corrcoef(ca.ravel(), cb.ravel())[0, 1]), + sd_a=float(ca.std()), sd_b=float(cb.std()), + disp_delta_mm_med=float(np.median(dd)), disp_delta_mm_max=float(dd.max()), + disp_mm_a=float(np.median(np.linalg.norm(da, axis=-1) * 1000)), + disp_mm_b=float(np.median(np.linalg.norm(db, axis=-1) * 1000)))) + print(f"[diag] {name} n={ca.shape[0]} shape={ca.shape} " + f"delta med={rows[-1]['d_med']:.3e} p99={rows[-1]['d_p99']:.3e} max={rows[-1]['d_max']:.3e} " + f"corr={rows[-1]['corr']:.9f} | disp delta mm med={rows[-1]['disp_delta_mm_med']:.4f} " + f"max={rows[-1]['disp_delta_mm_max']:.4f} | disp mm A={rows[-1]['disp_mm_a']:.3f} " + f"B={rows[-1]['disp_mm_b']:.3f}", flush=True) + +if rows: + med = np.median([r["d_med"] for r in rows]); mx = max(r["d_max"] for r in rows) + ratio = mx / med if med > 0 else float("inf") + print(f"\n[diag] SUMMARY over {len(rows)} episode(s): median delta {med:.3e}, worst max {mx:.3e}, " + f"max/median = {ratio:.3e}") + print(f"[diag] displacement-space delta: median {np.median([r['disp_delta_mm_med'] for r in rows]):.4f} mm, " + f"worst {max(r['disp_delta_mm_max'] for r in rows):.4f} mm " + f"against a median displacement of ~{np.median([r['disp_mm_a'] for r in rows]):.2f} mm") + print("[diag] SIGNATURE -> " + ("H_num (numerical/hardware divergence: delta concentrated near 0, thin tail)" + if ratio > 1e3 else + "H_seed (different draw stream: delta comparable to spread everywhere)")) + print("[diag] NOTE: this explains the guard failure; it does NOT rescue any run-42 rung. " + "The rungs remain VOID exactly as pre-registered.") +json.dump(rows, open(f"{ROOT}/status/real/pt_r43_repro_diag.json", "w"), indent=1) diff --git a/rsm_rise/scripts/real/pt_temp_repro_diag.sh b/rsm_rise/scripts/real/pt_temp_repro_diag.sh new file mode 100644 index 0000000000000000000000000000000000000000..3c8ae9bb2ea91d11fb3732d6e52296f259620545 --- /dev/null +++ b/rsm_rise/scripts/real/pt_temp_repro_diag.sh @@ -0,0 +1,7 @@ +#!/usr/bin/env bash +set -uo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +export MUJOCO_GL=disable +echo "[diag-run] start $(date)" +/proj/dmfexp/zwhong/rsm_rise/venv_rsm/bin/python scripts/real/pt_temp_repro_diag.py +echo "[diag-run] exit=$? $(date)" diff --git a/rsm_rise/scripts/real/pt_temp_screen.sh b/rsm_rise/scripts/real/pt_temp_screen.sh new file mode 100644 index 0000000000000000000000000000000000000000..0b5b354e1ac9de533eda2bc99bbd887f9d2fc0c6 --- /dev/null +++ b/rsm_rise/scripts/real/pt_temp_screen.sh @@ -0,0 +1,24 @@ +#!/usr/bin/env bash +# PROPOSAL_TEST run 42 -- one NOISE-SCALE rung of the default proposer at S2. Mirrors +# scripts/real/proposal_screen.sh exactly (same policy default, same n-cand, horizon, state, stride, +# gate-min, seed) and changes ONE thing: it execs scripts/real/pt_proposer_temp.py instead of +# scripts/real/proposal_test.py, which scales the pi0.5 flow's initial noise by $PT_NOISE_SCALE. +# proposal_screen.sh and proposal_test.py are NOT edited. +# usage: PT_NOISE_SCALE= PT_NAME= pt_temp_screen.sh [shard-i shard-n] +set -uo pipefail +ROOT=/proj/dmfexp/zwhong/rsm_rise +I=${1:-0}; K=${2:-1} +NAME=${PT_NAME:?set PT_NAME} +export PT_NOISE_SCALE=${PT_NOISE_SCALE:?set PT_NOISE_SCALE} +CK=$ROOT/runs/openpi/checkpoints +POLICY=${PT_POLICY:-openpi:pi05_cooking_sn1_knn0p03:$CK/pi05_cooking_sn1_knn0p03/ws_s0/9999} +NCAND=${PT_NCAND:-128} +STRIDE=${PT_STRIDE:-5} +OUT=$ROOT/status/real/pt_$NAME +mkdir -p "$OUT" +ARGS=(--policy "$POLICY" --n-cand "$NCAND" --horizon 8 --state "${PT_STATE:-2}" + --anchor-stride "$STRIDE" --gate-min "${PT_GATEMIN:-16}" + --ep-shard "$I/$K" --tag "pt_$NAME" --out "$OUT" --seed "${PT_SEED:-0}" + --coverage-only) +echo "[pt-temp-screen] rung scale=$PT_NOISE_SCALE tag=pt_$NAME out=$OUT $(date -u)" +exec $ROOT/scripts/real/run_env_openpi.sh $ROOT/scripts/real/pt_proposer_temp.py "${ARGS[@]}" diff --git a/rsm_rise/scripts/real/pt_w100_table.py b/rsm_rise/scripts/real/pt_w100_table.py new file mode 100644 index 0000000000000000000000000000000000000000..6f5375d6f4e879da7dcc72c306471d794351ebce --- /dev/null +++ b/rsm_rise/scripts/real/pt_w100_table.py @@ -0,0 +1,36 @@ +#!/usr/bin/env python +"""gen_q#280/#281 -- the entry-window-100 table for one scored cell: every row with its own GATED oracle +ceiling, the MEASURED permuted column, the permutation-calibrated per-row q95 and the family-wise bar, +ties-at-max, score CV, kept anchors and kept episodes. Reads only the two reduce JSONs.""" +import json, sys +from pathlib import Path +cell = sys.argv[1] if len(sys.argv) > 1 else "cap_ab_s0" +W = sys.argv[2] if len(sys.argv) > 2 else "100" +rep = json.load(open(f"status/real/PT_WIN_{cell}_w{W}.json")) +cal = json.load(open(f"status/real/PT_WINCAL_{cell}_w{W}.json")) +out = [] +for g, blk in rep.items(): + c, k = blk["coverage"], cal.get(g) + if k is None: + continue + ceil = (c.get("oracle") or {}).get("auc") + out.append("") + out.append(f"**{g}** -- {c['gated_anchors']} gated anchors / {c['gated_episodes']} episodes " + f"(of {c['anchors']} / {c['episodes']}); **gated oracle ceiling " + f"{ceil:.3f}**; calibrated null sd {k['null_sd']:.4f}, per-row q95 **{k['q95']:.4f}**, " + f"family-wise q95 over {k['n_scorers']} rows **{k['q95_fwer']:.4f}**; " + f"bootSE/null sd {k['boot_se_over_null_sd']:.2f}, measured false-pass rate of the old 1-SE " + f"rule {100*k['false_pass_1se']:.1f}%.") + out.append("") + out.append("| scorer | AUC | bootSE | permuted | Spearman | top-Q lift | ties@max | CV | vs q95 | vs FWER | vs ceiling |") + out.append("|---|---|---|---|---|---|---|---|---|---|---|") + for r in sorted(blk["scorers"], key=lambda r: -r["auc"]): + cl = "**CLEARS**" if r["auc"] > k["q95"] else "no" + fw = "**CLEARS**" if r["auc"] > k["q95_fwer"] else "no" + cc = "**AT/ABOVE CEILING**" if r.get("at_or_above_ceiling") else f"{ceil - r['auc']:+.3f} below" + out.append(f"| `{r['scorer']}` | {r['auc']:.3f} | {r['auc_se']:.3f} | {r['auc_permuted']:.3f} | " + f"{r['rho']:+.3f} | {r['lift']:+.3f} | {r['ties_at_max']:.1f} | {r['cv']:.3f} | " + f"{cl} | {fw} | {cc} |") +md = "\n".join(out) +print(md) +Path(f"status/real/PT_W{W}_TABLE_{cell}.md").write_text(md + "\n") diff --git a/rsm_rise/scripts/real/pt_window.sh b/rsm_rise/scripts/real/pt_window.sh new file mode 100644 index 0000000000000000000000000000000000000000..3fd3b3c4754818cc961603dec783ac80b69b46a7 --- /dev/null +++ b/rsm_rise/scripts/real/pt_window.sh @@ -0,0 +1,24 @@ +#!/bin/bash +# gen_q#280 / #281 -- re-reduce the already-scored proposal-test cells under the 18:15Z anchor restriction +# (S2, anchors within W frames of meta-state ENTRY) and print the ORACLE CEILING of each anchor set beside +# every row, plus the permutation-calibrated bar recomputed on the SAME restricted set. +# Eval-free: reads only the saved npz parts and the hdf5 actions. No checkpoint is loaded. +set -uo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +export MUJOCO_GL=disable +PY=venv_rsm/bin/python +for CELL in cap_ab_s0 heads_s0; do + D="status/real/pt_${CELL}" + [ -d "$D/parts" ] || { echo "[win] $D missing, skipped"; continue; } + for W in 25 50 100 200 all; do + ARG=""; [ "$W" = all ] || ARG="--entry-window $W" + TAG="${CELL}_w${W}" + echo "=============== $CELL entry window $W ===============" + $PY scripts/real/proposal_report.py "$D" $ARG --oracle-chunk 8 --by-route \ + --md "status/real/PT_WIN_${TAG}.md" --json "status/real/PT_WIN_${TAG}.json" || echo "[win] report failed $TAG" + $PY scripts/real/pt_nullcal.py "$D" $ARG --by-route --reps 3000 --boot 300 \ + --reflag "status/real/PT_WIN_${TAG}.json" \ + --md "status/real/PT_WINCAL_${TAG}.md" --json "status/real/PT_WINCAL_${TAG}.json" || echo "[win] nullcal failed $TAG" + done +done +echo "[win] done" diff --git a/rsm_rise/scripts/real/pt_window_cov.sh b/rsm_rise/scripts/real/pt_window_cov.sh new file mode 100644 index 0000000000000000000000000000000000000000..807dbd2b086ba8b618eeeef20e18eea4db75797d --- /dev/null +++ b/rsm_rise/scripts/real/pt_window_cov.sh @@ -0,0 +1,17 @@ +#!/bin/bash +# gen_q#280 / #281 -- COVERAGE FIRST under the 18:15Z anchor restriction. Does the proposal test exist at +# all near meta-state ENTRY, which is the only place the direction label is sound? Per proposer cell, per +# entry window: the label split, the >=16/side gate, and the ORACLE CEILING of that exact anchor set. +# No value is read. +set -uo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +export MUJOCO_GL=disable +PY=venv_rsm/bin/python +CELLS=$(ls -d status/real/pt_cov_* | tr '\n' ' ') +for W in 25 50 100 200 all; do + ARG=""; [ "$W" = all ] || ARG="--entry-window $W" + echo "=============== coverage grid, entry window $W ===============" + $PY scripts/real/proposal_report.py $CELLS $ARG --oracle-chunk 8 --by-route \ + --md "status/real/PT_WINCOV_w${W}.md" --json "status/real/PT_WINCOV_w${W}.json" || echo "[wincov] failed w$W" +done +echo "[wincov] done" diff --git a/rsm_rise/scripts/real/pt_window_mlong.sh b/rsm_rise/scripts/real/pt_window_mlong.sh new file mode 100644 index 0000000000000000000000000000000000000000..96922c04917eb2a36be18aa5b7961defb540ce23 --- /dev/null +++ b/rsm_rise/scripts/real/pt_window_mlong.sh @@ -0,0 +1,28 @@ +#!/bin/bash +# gen_q#280 / #281 run 48 -- reduce the TRAINING-LENGTH cell pt_mlong_s0 the same way pt_window.sh reduces +# cap_ab_s0 / heads_s0: route-conditional, gated oracle ceiling per group, permutation-calibrated per-row +# and family-wise bars on the SAME restricted anchor set. Then run the pre-registered VOID CHECK. +# Eval-free: reads only the saved npz parts and the hdf5 actions. No checkpoint is loaded. +set -uo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +export MUJOCO_GL=disable +PY=venv_rsm/bin/python +CELL=mlong_s0 +D="status/real/pt_${CELL}" +[ -d "$D/parts" ] || { echo "[mlong] $D/parts missing -- nothing scored yet, exiting without a table"; exit 0; } +echo "[mlong] parts on disk: $(ls "$D/parts" | wc -l)" +for W in 100 all; do + ARG=""; [ "$W" = all ] || ARG="--entry-window $W" + TAG="${CELL}_w${W}" + echo "=============== $CELL entry window $W ===============" + $PY scripts/real/proposal_report.py "$D" $ARG --oracle-chunk 8 --by-route \ + --md "status/real/PT_WIN_${TAG}.md" --json "status/real/PT_WIN_${TAG}.json" || echo "[mlong] report failed $TAG" + $PY scripts/real/pt_nullcal.py "$D" $ARG --by-route --reps 3000 --boot 300 \ + --reflag "status/real/PT_WIN_${TAG}.json" \ + --md "status/real/PT_WINCAL_${TAG}.md" --json "status/real/PT_WINCAL_${TAG}.json" || echo "[mlong] nullcal failed $TAG" +done +echo "=============== the w100 table ===============" +$PY scripts/real/pt_w100_table.py "$CELL" 100 || echo "[mlong] table failed" +echo "=============== VOID CHECK (pre-registered 5825763200 / 5825764160) ===============" +$PY scripts/real/pt_mlong_void.py 100; echo "[mlong] void-check exit=$?" +echo "[mlong] done" diff --git a/rsm_rise/scripts/real/pt_window_readout.sh b/rsm_rise/scripts/real/pt_window_readout.sh new file mode 100644 index 0000000000000000000000000000000000000000..59cefe1a02cb82cd1c56d1ac65ebe26c453f13d6 --- /dev/null +++ b/rsm_rise/scripts/real/pt_window_readout.sh @@ -0,0 +1,38 @@ +#!/usr/bin/env bash +# gen_q#280 / rsm_real#2 run 49 -- reduce the READ-OUT wave the same way pt_window.sh reduces cap_ab_s0 / +# heads_s0: route-conditional, gated oracle ceiling per group, permutation-calibrated per-row and +# family-wise bars on the SAME restricted anchor set. Then the Monte Carlo spread and the validity check. +# Eval-free: reads only the saved npz parts and the hdf5 actions. No checkpoint is loaded. +set -uo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +export MUJOCO_GL=disable +PY=venv_rsm/bin/python +CELLS="ro_mcrep ro_logit ro_p4 ro_p64 ro_d1 ro_g0995 ro_g09995 ro_degen" +DONE="" +for CELL in $CELLS; do + D="status/real/pt_${CELL}" + n=$(ls "$D/parts" 2>/dev/null | wc -l) + # COMPLETENESS GUARD. The cached-draw set cov_sn1_knn0p03 has exactly 25 episode parts, and the gated + # anchor set is a function of WHICH episodes are present. Reducing a partially-scored cell yields a + # different anchor set from the cells it is being compared against -- a plausible number that is not + # comparable to anything, which is precisely the failure mode this stream has caught six times. So a + # cell is reduced only when all 25 parts exist; a partial cell is reported as INCOMPLETE, never reduced. + NEED=${PT_RO_NEED_PARTS:-25} + if [ "$n" -lt "$NEED" ]; then echo "[ro] $CELL: INCOMPLETE ($n/$NEED parts) -- NOT reduced, not comparable"; continue; fi + echo "=============== $CELL ($n parts) ===============" + TAG="${CELL}_w100" + $PY scripts/real/proposal_report.py "$D" --entry-window 100 --oracle-chunk 8 --by-route \ + --md "status/real/PT_WIN_${TAG}.md" --json "status/real/PT_WIN_${TAG}.json" || { echo "[ro] report failed $CELL"; continue; } + $PY scripts/real/pt_nullcal.py "$D" --entry-window 100 --by-route --reps 3000 --boot 300 \ + --reflag "status/real/PT_WIN_${TAG}.json" \ + --md "status/real/PT_WINCAL_${TAG}.md" --json "status/real/PT_WINCAL_${TAG}.json" || echo "[ro] nullcal failed $CELL" + $PY scripts/real/pt_w100_table.py "$CELL" 100 || echo "[ro] table failed $CELL" + DONE="$DONE $CELL" +done +echo "=============== MONTE CARLO SPREAD + VALIDITY CHECK ===============" +if [ -n "$DONE" ]; then + $PY scripts/real/pt_mcspread.py $DONE --window 100 --ref cap_ab_s0:rsm@M_capped +else + echo "[ro] nothing reduced -- no spread to report, and no row is readable" +fi +echo "[ro] done" diff --git a/rsm_rise/scripts/real/pt_window_summary.py b/rsm_rise/scripts/real/pt_window_summary.py new file mode 100644 index 0000000000000000000000000000000000000000..ddff563861944f6b9b6a642cb8b8f60f9b649f66 --- /dev/null +++ b/rsm_rise/scripts/real/pt_window_summary.py @@ -0,0 +1,51 @@ +#!/usr/bin/env python +"""gen_q#280 / #281 -- one table across the entry-window sweep: does the COVERAGE GATE keep the anchors +where the direction label actually tracks the route? + +For every (cell, route group, entry window) it prints, side by side, the oracle ceiling of ALL anchors in +that window and the oracle ceiling of the GATED anchors the rows are scored on, with the gate counts. If +the gated ceiling sits below the all-anchor ceiling the two requirements are in tension: the gate keeps the +anchors where the proposer's draws straddle the direction boundary, and those are the anchors where the +boundary does not separate the routes. +""" +import json, sys, glob, re +from pathlib import Path + +rows = [] +for f in sorted(glob.glob("status/real/PT_WIN_*_w*.json")) + sorted(glob.glob("status/real/PT_WINCOV_w*.json")): + m = re.search(r"_w(\d+|all)\.json$", f) + W = m.group(1) + for g, blk in json.load(open(f)).items(): + c = blk["coverage"] + o, oa = c.get("oracle") or {}, c.get("oracle_all") or {} + rows.append(dict(cell=g, window=W, anchors=c["anchors"], eps=c["episodes"], + gated=c["gated_anchors"], gated_eps=c["gated_episodes"], + drop_succ=c["dropped_all_success"], drop_fail=c["dropped_all_failure"], + succ_med=c["succ_side_med"], spread=c["dir_spread_mm"], + orc_all=oa.get("auc"), acc_all=oa.get("acc"), n_all=oa.get("n"), + orc_gate=o.get("auc"), acc_gate=o.get("acc"), n_gate=o.get("n"), + gate_pass=c["gate_pass"])) + +def fnum(x, f="%.3f"): + return (f % x) if isinstance(x, float) and x == x else "--" + +order = {"25": 0, "50": 1, "100": 2, "200": 3, "all": 4} +rows.sort(key=lambda r: (r["cell"], order.get(r["window"], 9))) +out = ["### Entry-window sweep: the coverage gate against the oracle ceiling", "", + "`orc all` = oracle ceiling over every anchor in the window; `orc gated` = over the gated anchors " + "the scorer rows are computed on. Both at the 8-frame chunk the proposer can draw " + "(`action_horizon=10`). A gated ceiling at or below 0.5 means the label at those anchors does not " + "track the route, so no scorer can pass there however good it is.", "", + "| cell / route | window | anchors | eps | gated | gated eps | dropped all-succ | dropped all-fail |" + " succ-side med | spread mm | acc all | **orc all** | acc gated | **orc gated** | GATE |", + "|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|"] +for r in rows: + out.append(f"| {r['cell']} | {r['window']} | {r['anchors']} | {r['eps']} | **{r['gated']}** | " + f"{r['gated_eps']} | {r['drop_succ']} | {r['drop_fail']} | {r['succ_med']:.0f} | " + f"{r['spread']:.1f} | {fnum(r['acc_all'], '%.1f%%' if False else '%.3f')} | " + f"**{fnum(r['orc_all'])}** | {fnum(r['acc_gate'])} | **{fnum(r['orc_gate'])}** | " + f"{'PASS' if r['gate_pass'] else 'FAIL'} |") +md = "\n".join(out) +print(md) +Path("status/real/PT_WINDOW_SUMMARY.md").write_text(md + "\n") +json.dump(rows, open("status/real/PT_WINDOW_SUMMARY.json", "w"), indent=1) diff --git a/rsm_rise/scripts/real/pt_within_anchor.py b/rsm_rise/scripts/real/pt_within_anchor.py new file mode 100644 index 0000000000000000000000000000000000000000..e25e0c4158cccea23bffda4aca066f105df63224 --- /dev/null +++ b/rsm_rise/scripts/real/pt_within_anchor.py @@ -0,0 +1,325 @@ +#!/usr/bin/env python +"""gen_q#280 / jmarangola/rsm_real#2 -- PROPOSAL_TEST run 40. + +THE BRIDGE RUN 39 NAMED AND DID NOT MAKE. +------------------------------------------------------------------------------------------------ +Run 39 declared a CROSS-ANCHOR marginal: a classifier on (anchor, chunk) reaches 0.9870 against an +anchor-only arm at 0.9529, and the +0.0338 gap survives a null whose type-I rate was MEASURED valid +(4/40 raw). Run 39 also wrote down, in advance, what that does NOT license: + + "Converting a cross-anchor marginal AUC into a WITHIN-ANCHOR ranking AUC is a separate + measurement that has NOT been made." + +This file makes it. The proposal test ranks DIFFERENT CHUNKS AT THE SAME ANCHOR, so the anchor arm's +0.953 is unavailable to it -- within one anchor the anchor feature is a constant. The question is +whether the +0.034 marginal converts into ranking power when the anchor is held fixed. + +THE MEASUREMENT. Train the `both` arm exactly as published (StratifiedGroupKFold over EPISODES, same +seeds, same features). Then, for each held-out anchor `i`, take a balanced DONOR POOL of K logged +chunks drawn from OTHER episodes in the same held-out fold -- K/2 from goal-route episodes, K/2 from +failure-route episodes -- and score every donor AT ANCHOR i: s_ij = f(anchor_i, chunk_j). The AUC of +s_i* against the donor's route label is the within-anchor ranking AUC at anchor i. Average over +anchors; bootstrap over EPISODES. Chunks are RELATIVE to their first action (proposal_ceiling's +`chunk_feat`), so a donor chunk is a displacement trajectory and transplants meaningfully. + +THE CONFOUND, STATED BEFORE THE NUMBER EXISTS. A donor chunk did not occur at the host anchor. A +model can rank it by plausibility-at-this-anchor rather than by route -- the same on-manifold trap that +turned the earlier 96.9% into nothing. Plausibility is correlated with the label whenever goal-route +donors resemble goal-route hosts. So NOTHING here is pooled across host route. Every row is reported +route-conditional: + + auc_host_goal mean within-anchor AUC over hosts whose own episode reaches the goal + auc_host_fail the same over hosts whose own episode is the cook-never-pour route + +If the two strata straddle 0.5 in OPPOSITE directions, the scorer is matching donors to hosts, not +reading route, and the row is reported UNDEFINED for the bridge question. + +CONTROLS, all on the SAME donor pools so every comparison is paired: + both: the scorer under test (anchor + chunk) + anchor: STRUCTURAL ZERO. Constant within an anchor by construction, so it must return AUC + exactly 0.5 with K ties at max. If it does not, the harness is broken and every row + is void. + chunk: the pure chunk model -- what a scorer with no anchor access can do + permuted: the MEASURED zero line: the `both` arm trained on episode-permuted labels, identical + donor pools, --perm-reps replicates + random an rng score, the third zero line + +PRE-REGISTERED READING (fixed before any number here exists): + * POSITIVE BRIDGE: both:mlp beats its permuted line by more than 2 SE of the paired difference, in + BOTH host-route strata with the same sign. Then the +0.034 marginal does convert, and the RSM's + 0.46-0.50 is a defect of the value, not a ceiling. + * NEGATIVE BRIDGE (the prediction): both:mlp is within 2 SE of its permuted line. Then a directly + supervised oracle cannot rank chunks within an anchor either, the proposal test is at its ceiling, + and the sweep has been measuring a ceiling all along. + * UNDEFINED: the two host strata disagree in sign -- host matching, not route reading. + The oracle ceiling for this anchor set (0.917, the direction-scorer ceiling from the 18:15Z gate) is + printed on every row as required, with the label that it is a CROSS-anchor ceiling and not a bound + on this within-anchor quantity. + +Definitions imported from proposal_ceiling.py; it is NOT edited. +""" +import argparse, json, time +from pathlib import Path +from types import SimpleNamespace + +import numpy as np + +ROOT = "/proj/dmfexp/zwhong/rsm_rise" +ORACLE_CEILING_CROSS_ANCHOR = 0.917 # 18:15Z gate, S2 / window 100 / direction scorer + +import importlib.util + + +def _load(name, path): + spec = importlib.util.spec_from_file_location(name, path) + m = importlib.util.module_from_spec(spec) + spec.loader.exec_module(m) + return m + + +PC = _load("pc", f"{ROOT}/scripts/real/proposal_ceiling.py") + + +def _mk(model, seed): + from sklearn.pipeline import make_pipeline + from sklearn.preprocessing import StandardScaler + from sklearn.linear_model import LogisticRegression + from sklearn.neural_network import MLPClassifier + if model == "logreg": + return make_pipeline(StandardScaler(), + LogisticRegression(max_iter=4000, C=1.0, class_weight="balanced", + random_state=seed)) + return make_pipeline(StandardScaler(), + MLPClassifier(hidden_layer_sizes=(64, 64), max_iter=600, early_stopping=True, + n_iter_no_change=15, random_state=seed)) + + +def within_auc(s, lab): + """AUC of one anchor's donor scores against donor labels, plus ties-at-max and score CV.""" + n1 = int(lab.sum()); n0 = int(len(lab) - n1) + if n1 == 0 or n0 == 0: + return np.nan, 0, np.nan + r = np.empty(len(s), float) + order = np.argsort(s, kind="mergesort") + ss = s[order] + i = 0 + ranks = np.empty(len(s), float) + while i < len(ss): + j = i + while j + 1 < len(ss) and ss[j + 1] == ss[i]: + j += 1 + ranks[i:j + 1] = 0.5 * (i + j) + 1.0 + i = j + 1 + r[order] = ranks + a = (r[lab == 1].sum() - n1 * (n1 + 1) / 2.0) / (n1 * n0) + mx = s.max() + ties = int((s == mx).sum()) + mu = float(np.mean(s)) + cv = float(np.std(s) / abs(mu)) if abs(mu) > 1e-12 else np.nan + return float(a), ties, cv + + +def ep_boot_mean(v, ep, B=2000, seed=0): + """Episode-level bootstrap of a per-anchor quantity.""" + v = np.asarray(v, float); ep = np.asarray(ep) + ok = ~np.isnan(v) + v, ep = v[ok], ep[ok] + if len(v) == 0: + return (np.nan,) * 4 + ue = np.unique(ep) + idx = {e: np.where(ep == e)[0] for e in ue} + rng = np.random.default_rng(seed) + out = [] + for _ in range(B): + pick = rng.choice(ue, len(ue), replace=True) + ii = np.concatenate([idx[e] for e in pick]) + out.append(v[ii].mean()) + out = np.sort(np.asarray(out)) + return (float(v.mean()), float(out.std(ddof=1)), + float(out[int(0.025 * B)]), float(out[int(0.975 * B)])) + + +def ep_boot_diff(va, vb, ep, B=2000, seed=0): + va, vb, ep = np.asarray(va, float), np.asarray(vb, float), np.asarray(ep) + ok = (~np.isnan(va)) & (~np.isnan(vb)) + va, vb, ep = va[ok], vb[ok], ep[ok] + if len(va) == 0: + return (np.nan,) * 4 + ue = np.unique(ep) + idx = {e: np.where(ep == e)[0] for e in ue} + rng = np.random.default_rng(seed) + out = [] + for _ in range(B): + pick = rng.choice(ue, len(ue), replace=True) + ii = np.concatenate([idx[e] for e in pick]) + out.append(va[ii].mean() - vb[ii].mean()) + out = np.sort(np.asarray(out)) + return (float(np.mean(va) - np.mean(vb)), float(out.std(ddof=1)), + float(out[int(0.025 * B)]), float(out[int(0.975 * B)])) + + +def run_one(AN, CFw, y, ep, folds, seed, model, K, min_side, rng_seed, perm=False): + """One (model, seed) pass. Returns per-anchor arrays for every arm.""" + from sklearn.model_selection import StratifiedGroupKFold + n = len(y) + arms = ["both", "anchor", "chunk", "random"] + acc = {k: np.full(n, np.nan) for k in arms} + ties = {k: np.zeros(n, int) for k in arms} + cvs = {k: np.full(n, np.nan) for k in arms} + kept = np.zeros(n, bool) + n_pos_donor = np.zeros(n, int); n_neg_donor = np.zeros(n, int) + yy = PC.perm_labels(y, ep, rng_seed) if perm else y + + skf = StratifiedGroupKFold(n_splits=folds, shuffle=True, random_state=seed) + XB = np.concatenate([AN, CFw], 1) + for tr, va in skf.split(XB, yy, groups=ep): + mb = _mk(model, seed); mb.fit(XB[tr], yy[tr]) + ma = _mk(model, seed); ma.fit(AN[tr], yy[tr]) + mc = _mk(model, seed); mc.fit(CFw[tr], yy[tr]) + # ---- donor pool: K balanced logged chunks from the HELD-OUT fold (never seen in training) + rng = np.random.default_rng([rng_seed, seed, int(va[0])]) + pos = va[yy[va] == 1]; neg = va[yy[va] == 0] + if len(pos) < min_side or len(neg) < min_side: + continue + dp = rng.choice(pos, min(K // 2, len(pos)), replace=False) + dn = rng.choice(neg, min(K // 2, len(neg)), replace=False) + don = np.concatenate([dp, dn]) + dlab = np.concatenate([np.ones(len(dp), int), np.zeros(len(dn), int)]) + dep = ep[don] + Kd = len(don) + # ---- score every donor at every host anchor in this fold + anchor_s = ma.predict_proba(AN[va])[:, 1] + chunk_s = mc.predict_proba(CFw[don])[:, 1] + for blk in range(0, len(va), 64): + hosts = va[blk:blk + 64] + H = len(hosts) + big = np.empty((H * Kd, XB.shape[1]), np.float32) + big[:, :AN.shape[1]] = np.repeat(AN[hosts], Kd, axis=0) + big[:, AN.shape[1]:] = np.tile(CFw[don], (H, 1)) + sb = mb.predict_proba(big)[:, 1].reshape(H, Kd) + for h, i in enumerate(hosts): + keep = dep != ep[i] # never rank a donor from the host's own episode + lab = dlab[keep] + n_pos_donor[i] = int(lab.sum()); n_neg_donor[i] = int(len(lab) - lab.sum()) + if n_pos_donor[i] < min_side or n_neg_donor[i] < min_side: + continue # coverage gate -- counted, never scored as a pass + kept[i] = True + for arm, sc in (("both", sb[h][keep]), + ("anchor", np.full(int(keep.sum()), anchor_s[blk + h])), + ("chunk", chunk_s[keep]), + ("random", np.random.default_rng([rng_seed, seed, int(i)]) + .random(int(keep.sum())))): + a_, t_, c_ = within_auc(np.asarray(sc, float), lab) + acc[arm][i] = a_; ties[arm][i] = t_; cvs[arm][i] = c_ + return acc, ties, cvs, kept, n_pos_donor, n_neg_donor + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--out", required=True) + ap.add_argument("--hdf5", default=f"{ROOT}/data/raw/cooking_v5_expert_suboptimal.hdf5") + ap.add_argument("--split", default=f"{ROOT}/data/derived/cooking_v5_split.json") + ap.add_argument("--state", type=int, default=2) + ap.add_argument("--route-pos", default="[2, 3, 4]") + ap.add_argument("--route-neg", default="[0, 2, 3]") + ap.add_argument("--contrast", default="goal_vs_cook") + ap.add_argument("--stride", type=int, default=5) + ap.add_argument("--entry-window", type=int, default=100) + ap.add_argument("--lengths", type=int, nargs="+", default=[8]) + ap.add_argument("--folds", type=int, default=5) + ap.add_argument("--seeds", type=int, nargs="+", default=[0, 1, 2]) + ap.add_argument("--models", nargs="+", default=["logreg", "mlp"]) + ap.add_argument("--donors", type=int, default=128) + ap.add_argument("--min-side", type=int, default=16) # the spec's coverage gate + ap.add_argument("--perm-reps", type=int, default=20) + ap.add_argument("--boot", type=int, default=2000) + ap.add_argument("--jobs", type=int, default=16) + a = ap.parse_args() + t0 = time.time() + out = Path(a.out); out.mkdir(parents=True, exist_ok=True) + from joblib import Parallel, delayed + + rows, n_drop, n_ep = PC.build(SimpleNamespace( + hdf5=a.hdf5, split=a.split, state=a.state, route_pos=a.route_pos, route_neg=a.route_neg, + stride=a.stride, entry_window=a.entry_window, lengths=a.lengths)) + ep = np.array([r["ep"] for r in rows]); y = np.array([r["y"] for r in rows]) + AN = np.stack([r["anchor"] for r in rows]); CH = np.stack([r["chunk"] for r in rows]) + L = a.lengths[0] + CFw = PC.chunk_feat(CH, L, "waypoints") + n_kept_ep = int(len(np.unique(ep))) + print(f"[wa] contrast={a.contrast} anchors={len(rows)} episodes={n_kept_ep}/{n_ep} " + f"window={a.entry_window} L={L} stride={a.stride} dropped={n_drop} donors={a.donors} " + f"min_side={a.min_side} perm_reps={a.perm_reps}", flush=True) + print(f"[wa] ORACLE CEILING (cross-anchor, direction scorer, 18:15Z gate) = " + f"{ORACLE_CEILING_CROSS_ANCHOR:.3f} -- printed as required; it is NOT a bound on the " + f"within-anchor quantity measured here.", flush=True) + + results = [] + for model in a.models: + for seed in a.seeds: + acc, ties, cvs, kept, npos, nneg = run_one( + AN, CFw, y, ep, a.folds, seed, model, a.donors, a.min_side, 90210) + n_kept = int(kept.sum()); n_drop_gate = int(len(y) - n_kept) + eps_kept = int(len(np.unique(ep[kept]))) + print(f"[wa] COVERAGE model={model} seed={seed}: kept {n_kept}/{len(y)} anchors " + f"({eps_kept} episodes), dropped by gate {n_drop_gate}; donors per anchor " + f"pos median {int(np.median(npos[kept]))} neg median {int(np.median(nneg[kept]))}", + flush=True) + + # ---- the MEASURED zero line: same code path, episode-permuted labels + def one_perm(rep): + pa, _, _, pk, _, _ = run_one(AN, CFw, y, ep, a.folds, seed, model, a.donors, + a.min_side, 4242 + rep, perm=True) + return pa["both"], pk + + pres = Parallel(n_jobs=min(a.jobs, a.perm_reps), prefer="processes")( + delayed(one_perm)(r) for r in range(a.perm_reps)) + perm_stack = np.stack([p[0] for p in pres]) # [reps, n] + perm_mean = np.nanmean(perm_stack, 0) + + for arm in ("both", "anchor", "chunk", "random"): + for stratum, mask in (("host_goal", kept & (y == 1)), + ("host_fail", kept & (y == 0)), + ("all_hosts_LABELLED", kept)): + m_, se, lo, hi = ep_boot_mean(acc[arm][mask], ep[mask], a.boot, seed) + pm_, pse, plo, phi = ep_boot_mean(perm_mean[mask], ep[mask], a.boot, seed) + d_, dse, dlo, dhi = ep_boot_diff(acc[arm][mask], perm_mean[mask], ep[mask], + a.boot, seed) + rec = dict(model=model, seed=seed, arm=arm, stratum=stratum, + auc=m_, se=se, ci_lo=lo, ci_hi=hi, + permuted_auc=pm_, permuted_se=pse, + delta_vs_permuted=d_, delta_se=dse, delta_lo=dlo, delta_hi=dhi, + ties_at_max_mean=float(np.mean(ties[arm][mask])), + score_cv_median=float(np.nanmedian(cvs[arm][mask])), + n_anchors=int(mask.sum()), n_episodes=int(len(np.unique(ep[mask]))), + n_anchors_dropped_by_gate=n_drop_gate, + oracle_ceiling_cross_anchor=ORACLE_CEILING_CROSS_ANCHOR) + results.append(rec) + print(f"[wa] {model:6s} s{seed} {arm:7s} {stratum:19s} " + f"AUC={m_:.4f}+-{se:.4f} [{lo:.4f},{hi:.4f}] perm={pm_:.4f} " + f"delta={d_:+.4f}+-{dse:.4f} [{dlo:+.4f},{dhi:+.4f}] " + f"ties@max={np.mean(ties[arm][mask]):.1f} " + f"scoreCV={np.nanmedian(cvs[arm][mask]):.4f} " + f"n={int(mask.sum())}/{len(np.unique(ep[mask]))}ep " + f"[{time.time()-t0:.0f}s]", flush=True) + + # ---- STRUCTURAL GUARD: the anchor arm is constant within an anchor + am = acc["anchor"][kept] + at = ties["anchor"][kept] + bad = int(np.sum(np.abs(am - 0.5) > 1e-9)) + print(f"[wa] [GUARD] anchor arm constant-within-anchor: {bad} of {len(am)} anchors " + f"deviate from AUC 0.5 (must be 0); mean ties@max " + f"{at.mean():.1f} (must equal donor count)", flush=True) + if bad: + print("[wa] [GUARD] FAIL -- harness broken, every row above is VOID.", flush=True) + + json.dump(dict(contrast=a.contrast, entry_window=a.entry_window, L=L, stride=a.stride, + n_anchors=len(rows), n_episodes=n_kept_ep, n_episodes_total=n_ep, + donors=a.donors, min_side=a.min_side, perm_reps=a.perm_reps, + oracle_ceiling_cross_anchor=ORACLE_CEILING_CROSS_ANCHOR, + rows=results), open(out / "within_anchor.json", "w"), indent=2) + print(f"[wa] wrote {out}/within_anchor.json [{time.time()-t0:.0f}s]", flush=True) + + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/real/pt_within_anchor.sh b/rsm_rise/scripts/real/pt_within_anchor.sh new file mode 100644 index 0000000000000000000000000000000000000000..31df7bc34ff9f2fc9f944714fd05d0bdf9189312 --- /dev/null +++ b/rsm_rise/scripts/real/pt_within_anchor.sh @@ -0,0 +1,9 @@ +#!/bin/bash +# PROPOSAL_TEST run 40 -- the WITHIN-ANCHOR ranking AUC: the bridge run 39 named and did not make. +set -euo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +export MUJOCO_GL=disable OMP_NUM_THREADS=1 MKL_NUM_THREADS=1 OPENBLAS_NUM_THREADS=1 +exec venv_rsm/bin/python scripts/real/pt_within_anchor.py \ + --out status/real/pt_within_anchor_w100_goal_vs_cook \ + --entry-window 100 --lengths 8 --seeds 0 1 2 --models logreg mlp \ + --donors 128 --min-side 16 --perm-reps 20 --boot 2000 --jobs 16 diff --git a/rsm_rise/scripts/real/pt_within_anchor_smoke.sh b/rsm_rise/scripts/real/pt_within_anchor_smoke.sh new file mode 100644 index 0000000000000000000000000000000000000000..c4f9cb41ccaddd4eee7c892b6238ca1344e29734 --- /dev/null +++ b/rsm_rise/scripts/real/pt_within_anchor_smoke.sh @@ -0,0 +1,9 @@ +#!/bin/bash +# PROPOSAL_TEST run 40 -- SMOKE ONLY, not a result: 1 seed, logreg, 2 perm reps, 32 donors. +set -euo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +export MUJOCO_GL=disable OMP_NUM_THREADS=1 MKL_NUM_THREADS=1 OPENBLAS_NUM_THREADS=1 +exec venv_rsm/bin/python scripts/real/pt_within_anchor.py \ + --out status/real/pt_within_anchor_SMOKE \ + --entry-window 100 --lengths 8 --seeds 0 --models logreg \ + --donors 32 --min-side 8 --perm-reps 2 --boot 200 --jobs 8 diff --git a/rsm_rise/scripts/real/pt_within_spread.py b/rsm_rise/scripts/real/pt_within_spread.py new file mode 100644 index 0000000000000000000000000000000000000000..bb6741a25d6d88c7c19bf7be791c0da3f135864a --- /dev/null +++ b/rsm_rise/scripts/real/pt_within_spread.py @@ -0,0 +1,219 @@ +#!/usr/bin/env python +"""gen_q#280 / jmarangola/rsm_real#2 -- PROPOSAL_TEST run 40b: the DONOR-SPREAD LADDER. + +Run 40 measured the within-anchor ranking AUC with LOGGED donor chunks and got 0.97 against a measured +permuted line of 0.50, in both host-route strata, at all three seeds (job 1904198). That refuted TASK A's +motivating hypothesis: the proposal test is not information-limited. + +It did NOT show the proposal test is winnable, and run 40's pre-registration said so before the number +existed. The proposal test's candidates are 128 draws of ONE proposer at ONE anchor, whose measured +spread is ~6.8 mm against a 25-28 mm mean displacement. Logged donors from other episodes are far more +spread out than that. So: + +ONE CHANGE from run 40. The donor pool at host `i` is restricted to donors whose chunk DISPLACEMENT lies +within a radius `r` mm of host `i`'s own chunk displacement. Sweep `r` from unrestricted down through +6.8 mm. Everything else -- features, folds, seeds, models, permutation null, bootstrap, exclusions -- is +the same code path, imported from pt_within_anchor.py, which is NOT edited. + +PRE-REGISTERED (posted before submission): + * PREDICTION: AUC falls monotonically with r and at r = 6.8 mm is within 2 SE of the permuted line -- + the proposal test is SPREAD-limited, not information-limited. + * KILL: if AUC at r = 6.8 mm still clears its permuted line by > 2 SE in BOTH host strata, the test is + winnable at the proposer's own spread and the RSM's failure has no excuse left. + * The COVERAGE GATE is the primary reading at every rung. A tight r drops anchors for failing 16 + donors per side; the dropped count is reported per rung, never worked around, and anchors are never + widened to make a rung pass. + +REPRODUCTION GUARD: the r = inf rung must reproduce run 40's published `both` AUCs to <= 1e-12, or every +number here is void. + +The radius is centred on the HOST'S OWN logged displacement, which is the on-manifold analogue of a +proposer's draws being centred on its own mean action. It is not identical to that; the realised donor +dispersion is printed at every rung so the 6.8 mm comparison is made on measured dispersion, not on the +radius label. +""" +import argparse, json, time +from pathlib import Path +from types import SimpleNamespace + +import numpy as np + +ROOT = "/proj/dmfexp/zwhong/rsm_rise" +import importlib.util + + +def _load(name, path): + spec = importlib.util.spec_from_file_location(name, path) + m = importlib.util.module_from_spec(spec) + spec.loader.exec_module(m) + return m + + +WA = _load("wa", f"{ROOT}/scripts/real/pt_within_anchor.py") +PC = WA.PC + +# run 40's published `both` all-hosts AUCs (job 1904198), the r = inf rung. +PUBLISHED = {("logreg", 0): 0.9576, ("logreg", 1): 0.9380, ("logreg", 2): 0.9351, + ("mlp", 0): 0.9726, ("mlp", 1): 0.9527, ("mlp", 2): 0.9725} + + +def ladder(AN, CFw, DSP, y, ep, folds, seed, model, K, min_side, rng_seed, radii, perm=False): + from sklearn.model_selection import StratifiedGroupKFold + n = len(y) + R = len(radii) + acc = np.full((R, n), np.nan) + kept = np.zeros((R, n), bool) + disp = np.full((R, n), np.nan) # realised donor dispersion, mm + npos = np.zeros((R, n), int); nneg = np.zeros((R, n), int) + yy = PC.perm_labels(y, ep, rng_seed) if perm else y + XB = np.concatenate([AN, CFw], 1) + skf = StratifiedGroupKFold(n_splits=folds, shuffle=True, random_state=seed) + for tr, va in skf.split(XB, yy, groups=ep): + mb = WA._mk(model, seed); mb.fit(XB[tr], yy[tr]) + rng = np.random.default_rng([rng_seed, seed, int(va[0])]) + pos = va[yy[va] == 1]; neg = va[yy[va] == 0] + if len(pos) < min_side or len(neg) < min_side: + continue + dp = rng.choice(pos, min(K // 2, len(pos)), replace=False) + dn = rng.choice(neg, min(K // 2, len(neg)), replace=False) + don = np.concatenate([dp, dn]) + dlab = np.concatenate([np.ones(len(dp), int), np.zeros(len(dn), int)]) + dep = ep[don]; Kd = len(don) + for blk in range(0, len(va), 64): + hosts = va[blk:blk + 64] + H = len(hosts) + big = np.empty((H * Kd, XB.shape[1]), np.float32) + big[:, :AN.shape[1]] = np.repeat(AN[hosts], Kd, axis=0) + big[:, AN.shape[1]:] = np.tile(CFw[don], (H, 1)) + sb = mb.predict_proba(big)[:, 1].reshape(H, Kd) + for h, i in enumerate(hosts): + d_i = np.linalg.norm(DSP[don] - DSP[i], axis=1) # mm + base = dep != ep[i] + for ri, r in enumerate(radii): + keep = base if not np.isfinite(r) else (base & (d_i <= r)) + lab = dlab[keep] + p_, n_ = int(lab.sum()), int(len(lab) - lab.sum()) + npos[ri, i] = p_; nneg[ri, i] = n_ + if p_ < min_side or n_ < min_side: + continue + kept[ri, i] = True + dd = DSP[don][keep] + disp[ri, i] = float(np.sqrt(((dd - dd.mean(0)) ** 2).sum(1).mean())) + a_, _, _ = WA.within_auc(sb[h][keep].astype(float), lab) + acc[ri, i] = a_ + return acc, kept, disp, npos, nneg + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--out", required=True) + ap.add_argument("--hdf5", default=f"{ROOT}/data/raw/cooking_v5_expert_suboptimal.hdf5") + ap.add_argument("--split", default=f"{ROOT}/data/derived/cooking_v5_split.json") + ap.add_argument("--state", type=int, default=2) + ap.add_argument("--route-pos", default="[2, 3, 4]") + ap.add_argument("--route-neg", default="[0, 2, 3]") + ap.add_argument("--stride", type=int, default=5) + ap.add_argument("--entry-window", type=int, default=100) + ap.add_argument("--lengths", type=int, nargs="+", default=[8]) + ap.add_argument("--folds", type=int, default=5) + ap.add_argument("--seeds", type=int, nargs="+", default=[0, 1, 2]) + ap.add_argument("--models", nargs="+", default=["mlp", "logreg"]) + ap.add_argument("--donors", type=int, default=128) + ap.add_argument("--min-side", type=int, default=16) + ap.add_argument("--radii", type=float, nargs="+", + default=[float("inf"), 40, 30, 20, 15, 10, 6.8, 5, 3]) + ap.add_argument("--perm-reps", type=int, default=20) + ap.add_argument("--boot", type=int, default=2000) + ap.add_argument("--jobs", type=int, default=16) + a = ap.parse_args() + t0 = time.time() + out = Path(a.out); out.mkdir(parents=True, exist_ok=True) + from joblib import Parallel, delayed + + rows, n_drop, n_ep = PC.build(SimpleNamespace( + hdf5=a.hdf5, split=a.split, state=a.state, route_pos=a.route_pos, route_neg=a.route_neg, + stride=a.stride, entry_window=a.entry_window, lengths=a.lengths)) + ep = np.array([r["ep"] for r in rows]); y = np.array([r["y"] for r in rows]) + AN = np.stack([r["anchor"] for r in rows]); CH = np.stack([r["chunk"] for r in rows]) + L = a.lengths[0] + CFw = PC.chunk_feat(CH, L, "waypoints") + DSP = 1000.0 * (CH[:, L - 1, :3] - CH[:, 0, :3]) # mm displacement + mean_disp = float(np.linalg.norm(DSP, axis=1).mean()) + print(f"[sp] anchors={len(rows)} episodes={len(np.unique(ep))}/{n_ep} window={a.entry_window} L={L} " + f"donors={a.donors} min_side={a.min_side} radii={a.radii}", flush=True) + print(f"[sp] mean |displacement| over anchors = {mean_disp:.2f} mm; the proposer's measured candidate " + f"spread is 6.8 mm.", flush=True) + print(f"[sp] ORACLE CEILING (cross-anchor, direction scorer, 18:15Z gate) = " + f"{WA.ORACLE_CEILING_CROSS_ANCHOR:.3f} -- not a bound on this within-anchor quantity.", flush=True) + + results, guard = [], [] + for model in a.models: + for seed in a.seeds: + acc, kept, disp, npos, nneg = ladder(AN, CFw, DSP, y, ep, a.folds, seed, model, + a.donors, a.min_side, 90210, a.radii) + + def one_perm(rep): + pa, pk, _, _, _ = ladder(AN, CFw, DSP, y, ep, a.folds, seed, model, a.donors, + a.min_side, 4242 + rep, a.radii, perm=True) + return pa + + pres = Parallel(n_jobs=min(a.jobs, a.perm_reps), prefer="processes")( + delayed(one_perm)(r) for r in range(a.perm_reps)) + perm_mean = np.nanmean(np.stack(pres), 0) # [R, n] + + for ri, r in enumerate(a.radii): + for stratum, mask0 in (("host_goal", y == 1), ("host_fail", y == 0), + ("all_hosts", np.ones(len(y), bool))): + mask = kept[ri] & mask0 + nk = int(mask.sum()) + ndrop = int((mask0).sum() - nk) + if nk == 0: + print(f"[sp] {model:6s} s{seed} r={r:>5} {stratum:9s} UNDEFINED -- coverage gate " + f"kept 0 anchors of {int(mask0.sum())}", flush=True) + results.append(dict(model=model, seed=seed, radius=(None if not np.isfinite(r) + else float(r)), + stratum=stratum, undefined=True, n_anchors=0, + n_anchors_dropped_by_gate=ndrop)) + continue + m_, se, lo, hi = WA.ep_boot_mean(acc[ri][mask], ep[mask], a.boot, seed) + pm_, pse, _, _ = WA.ep_boot_mean(perm_mean[ri][mask], ep[mask], a.boot, seed) + d_, dse, dlo, dhi = WA.ep_boot_diff(acc[ri][mask], perm_mean[ri][mask], ep[mask], + a.boot, seed) + rec = dict(model=model, seed=seed, + radius=(None if not np.isfinite(r) else float(r)), stratum=stratum, + auc=m_, se=se, ci_lo=lo, ci_hi=hi, permuted_auc=pm_, permuted_se=pse, + delta_vs_permuted=d_, delta_se=dse, delta_lo=dlo, delta_hi=dhi, + clears_2se=bool(d_ - 2 * dse > 0), + donor_dispersion_mm=float(np.nanmedian(disp[ri][mask])), + donors_pos_median=int(np.median(npos[ri][mask])), + donors_neg_median=int(np.median(nneg[ri][mask])), + n_anchors=nk, n_episodes=int(len(np.unique(ep[mask]))), + n_anchors_dropped_by_gate=ndrop, + oracle_ceiling_cross_anchor=WA.ORACLE_CEILING_CROSS_ANCHOR) + results.append(rec) + print(f"[sp] {model:6s} s{seed} r={r:>5} {stratum:9s} AUC={m_:.4f}+-{se:.4f} " + f"perm={pm_:.4f} delta={d_:+.4f}+-{dse:.4f} " + f"{'CLEARS' if rec['clears_2se'] else 'no'} 2SE " + f"disp={rec['donor_dispersion_mm']:.1f}mm " + f"donors={rec['donors_pos_median']}/{rec['donors_neg_median']} " + f"n={nk}/{rec['n_episodes']}ep dropped={ndrop} [{time.time()-t0:.0f}s]", + flush=True) + if stratum == "all_hosts" and not np.isfinite(r): + pub = PUBLISHED[(model, seed)] + guard.append(dict(model=model, seed=seed, mine=m_, published=pub, + delta=abs(m_ - pub))) + worst = max((g["delta"] for g in guard), default=float("nan")) + print(f"[sp] [GUARD] r=inf rung against run 40's published table: {len(guard)} rows, " + f"worst |delta| = {worst:.3e} (published to 4 dp, so <= 5e-5 is exact)", flush=True) + if worst > 1e-4: + print("[sp] [GUARD] FAIL -- the r=inf rung does not reproduce run 40; every row is VOID.", + flush=True) + json.dump(dict(n_anchors=len(rows), n_episodes_total=n_ep, mean_displacement_mm=mean_disp, + radii=[None if not np.isfinite(r) else r for r in a.radii], + guard=guard, guard_worst=worst, rows=results), + open(out / "within_spread.json", "w"), indent=2) + print(f"[sp] wrote {out}/within_spread.json [{time.time()-t0:.0f}s]", flush=True) + + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/real/pt_within_spread.sh b/rsm_rise/scripts/real/pt_within_spread.sh new file mode 100644 index 0000000000000000000000000000000000000000..317570b83f53171b7a2f990c68f64aa973f13349 --- /dev/null +++ b/rsm_rise/scripts/real/pt_within_spread.sh @@ -0,0 +1,9 @@ +#!/bin/bash +# PROPOSAL_TEST run 40b -- the DONOR-SPREAD LADDER down to the proposer's measured 6.8 mm. +set -euo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +export MUJOCO_GL=disable OMP_NUM_THREADS=1 MKL_NUM_THREADS=1 OPENBLAS_NUM_THREADS=1 +exec venv_rsm/bin/python scripts/real/pt_within_spread.py \ + --out status/real/pt_within_spread_w100_goal_vs_cook \ + --entry-window 100 --lengths 8 --seeds 0 1 2 --models mlp logreg \ + --donors 128 --min-side 16 --perm-reps 20 --boot 2000 --jobs 16 diff --git a/rsm_rise/scripts/real/pt_ws_reduce.sh b/rsm_rise/scripts/real/pt_ws_reduce.sh new file mode 100644 index 0000000000000000000000000000000000000000..929c98797d7219e846568dadb6edb97498873760 --- /dev/null +++ b/rsm_rise/scripts/real/pt_ws_reduce.sh @@ -0,0 +1,34 @@ +#!/bin/bash +# gen_q#280 / rsm_real#2 -- run 11. +# (a) Reduce the SECOND-PROPOSER cell `pt_cap_ab_ws` (job 1885100, now 25/25 parts = route-complete) at the +# 18:15Z gate: S2, anchors within 100 frames of meta-state ENTRY, by route, with the gated oracle +# ceiling on every row and the permutation-calibrated bar recomputed on the SAME restricted anchors. +# This is the PROPOSER half of the spec's confirmation clause; the successor set, seed, n_cand and +# ruler are identical to `pt_cap_ab_s0`. ONE CHANGE: the proposer (pi05_cooking_wsctrl ws_s0/9999). +# (b) Snapshot-reduce the TASK B beta cells that are route-complete so far. NOT a comparison yet and NOT +# for posting: b095_RM (13 parts) and b097_RM (16) are still filling, and a beta arm without its +# matched partner is not an arm. Written to *_SNAP_* names so they cannot be mistaken for the table. +# Eval-free: reads saved npz parts + hdf5 actions only. No checkpoint is loaded. +set -uo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +export MUJOCO_GL=disable +PY=venv_rsm/bin/python + +D=status/real/pt_cap_ab_ws +echo "=============== cap_ab_ws entry window 100 (by route) ===============" +$PY scripts/real/proposal_report.py "$D" --entry-window 100 --oracle-chunk 8 --by-route \ + --md status/real/PT_WIN_cap_ab_ws_w100.md --json status/real/PT_WIN_cap_ab_ws_w100.json +$PY scripts/real/pt_nullcal.py "$D" --entry-window 100 --by-route --reps 3000 --boot 300 \ + --reflag status/real/PT_WIN_cap_ab_ws_w100.json \ + --md status/real/PT_WINCAL_cap_ab_ws_w100.md --json status/real/PT_WINCAL_cap_ab_ws_w100.json + +for C in b099_RM b099_notrunc b099_notruncs1 b097_notrunc b097_RM b095_notrunc b095_RM peranchor; do + DD="status/real/pt_betaB_${C}" + [ -d "$DD/parts" ] || { echo "[ws] $DD missing"; continue; } + N=$(ls "$DD/parts" | wc -l) + echo "=============== SNAPSHOT beta ${C} (${N} parts) entry window 100 ===============" + $PY scripts/real/proposal_report.py "$DD" --entry-window 100 --oracle-chunk 8 --by-route \ + --md "status/real/PT_SNAP_beta_${C}_w100.md" --json "status/real/PT_SNAP_beta_${C}_w100.json" \ + || echo "[ws] report failed $C" +done +echo "[ws] done" diff --git a/rsm_rise/scripts/real/pt_yres_dgpladder.sh b/rsm_rise/scripts/real/pt_yres_dgpladder.sh new file mode 100644 index 0000000000000000000000000000000000000000..f5070839ee6339e9116c8b94435396a5dbda7430 --- /dev/null +++ b/rsm_rise/scripts/real/pt_yres_dgpladder.sh @@ -0,0 +1,12 @@ +#!/bin/bash +# PROPOSAL_TEST run 37b -- the DGP-NONLINEARITY ladder for the type-I rate of the y-resample null. +# Each rung carries its plausibility credential: the anchor-only OOF AUC it attains on the REAL y. +set -euo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +export MUJOCO_GL=disable OMP_NUM_THREADS=1 MKL_NUM_THREADS=1 OPENBLAS_NUM_THREADS=1 +exec venv_rsm/bin/python scripts/real/pt_yresample_null.py \ + --out status/real/pt_yresdgp_w100_goal_vs_cook \ + --entry-window 100 --lengths 8 --seeds 0 \ + --lams 1.0 --draws 200 \ + --dgp-models gb mlp logreg \ + --typei-m 40 --typei-draws 200 --jobs 16 diff --git a/rsm_rise/scripts/real/pt_yres_null.sh b/rsm_rise/scripts/real/pt_yres_null.sh new file mode 100644 index 0000000000000000000000000000000000000000..92091ae646fa40b3dd800503987acf0e1bc4fb36 --- /dev/null +++ b/rsm_rise/scripts/real/pt_yres_null.sh @@ -0,0 +1,10 @@ +#!/bin/bash +# PROPOSAL_TEST run 37 -- the Y-RESAMPLE null for H0 (chunk adds nothing beyond the anchor). +set -euo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +export MUJOCO_GL=disable OMP_NUM_THREADS=1 MKL_NUM_THREADS=1 OPENBLAS_NUM_THREADS=1 +exec venv_rsm/bin/python scripts/real/pt_yresample_null.py \ + --out status/real/pt_yresnull_w100_goal_vs_cook \ + --entry-window 100 --lengths 8 32 --seeds 0 1 2 \ + --lams 1.0 0.5 0.0 --draws 400 \ + --typei-m 40 --typei-draws 200 --jobs 8 diff --git a/rsm_rise/scripts/real/pt_yresample_null.py b/rsm_rise/scripts/real/pt_yresample_null.py new file mode 100644 index 0000000000000000000000000000000000000000..df13b7d1e67edc872eed1f87788c95b04d49b6e0 --- /dev/null +++ b/rsm_rise/scripts/real/pt_yresample_null.py @@ -0,0 +1,373 @@ +#!/usr/bin/env python +"""gen_q#280 / jmarangola/rsm_real#2 -- PROPOSAL_TEST run 37. + +WHAT THIS MEASURES, and why neither existing null can measure it +---------------------------------------------------------------- +TASK A's quantity is the NESTED MARGINAL d = AUC(anchor+chunk) - AUC(anchor[geom]), and the +hypothesis is + + H0 : Y _||_ chunk | anchor ("the chunk adds nothing beyond the anchor state"). + +Two nulls have been tried on it and BOTH are known to be wrong, each for a measured reason: + + * runs 33-35, EPISODE LABEL PERMUTATION. It collapses the anchor arm to chance too, so its + distribution is the one under H0' ("nothing is informative"), not H0. Measured mismatch: null sd + 0.0238-0.0551 against a paired episode-bootstrap SE of 0.0087-0.0156. Verdict (A) UNDECLARED. + + * run 36, CONDITIONAL CHUNK PERMUTATION. Measured type-I rate 18/20 raw and 14/20 resid on data + satisfying H0 by construction, i.e. anticonservative. Run 36 item 5 gave the structural reason: + this stream's own measurement says the action is an ABSOLUTE end-effector target ~4 mm ahead of + the current pose (|a - p_t| = 0.0053 m), so the chunk ENCODES ITS OWN ANCHOR. Any permutation + that decouples chunk from label also decouples it from its anchor, and the nested marginal rewards + that coherence directly. NO CHUNK-PERMUTATION NULL CAN BE VALID HERE. + +THE FIX, and why it cannot hit run 36's obstruction: RESAMPLE Y, NOT X. +Fit the anchor-only arm out of fold on the real y; aggregate its OOF probabilities to ONE probability +per EPISODE (the label is an episode property, so the episode is the sampling unit); draw y* per +episode from that probability; recompute the identical statistic on (untouched AN, untouched CH, y*). +The feature matrix is never touched, so chunk<->anchor coherence is preserved EXACTLY and the artefact +that voided run 36 cannot arise. Y* depends on the anchors alone, so H0 holds by construction. + +THE LAMBDA LADDER, which makes the two old nulls one family rather than two opinions. +Shrink the per-episode logit toward the base rate: l_e(lam) = l_base + lam * (l_e - mean_e l_e). + lam = 1 -> plug-in CRT: the anchor->label signal is preserved at its fitted strength. Tests H0. + lam = 0 -> every episode gets the base rate: iid Bernoulli labels = the EPISODE LABEL PERMUTATION + of runs 33-35 (multinomial rather than hypergeometric). Tests H0'. +So lam interpolates continuously between the null that declared UNDECLARED and the null that should +have been used, and the gap between their q95 IS the size of the mis-specification run 36 identified. + +PRE-REGISTERED, written here before any number exists (posted to both issues before submission): + + (0) REDUCTION GUARD. The lam=0 rung must reproduce the published label-permutation bar + (raw logreg L=8 q95 = +0.0686, job 1886496 and job 1897123 to four decimals) to within Monte + Carlo error. If it does not, my generator is wrong and NOTHING below is reportable. + (1) VALIDITY. Type-I rate of the lam=1 null on H0-by-construction datasets generated by a + DIFFERENT, DELIBERATELY MIS-SPECIFIED mechanism (an MLP anchor model, so the null's logreg + generator is wrong in exactly the way it would be wrong on real data) must be <= 0.10 over + M datasets, reported with a Clopper-Pearson interval. Above 0.10 the null is anticonservative, + it declares nothing, and verdict (A) from runs 34-35 STANDS. A self-DGP rate is reported beside + it as a sanity check and is explicitly the WEAK one (null and DGP match by construction). + (2) POWER, so this cannot repeat run 35 item 2's powerless arm. The null's q95 (= the MDE) must lie + BELOW the upper end of the observed statistic's paired episode-bootstrap CI. If not, the row is + UNDECLARED-BY-POWER and must never be quoted as evidence of no effect. + (3) DECLARATION. If (0),(1),(2) hold and the observed statistic exceeds the lam=1 q95 at >= 5 of the + 6 (seed x L) cells, then (B): the logged chunk carries route information BEYOND the anchor. + Otherwise (A) stands. + +This is a CEILING, not a scorer. Every arm is fitted on the label; no row here is a pass candidate +for #280's proposal test. q95 uses the published convention sorted[int(0.95*n)], NOT np.quantile +(run 35 item 3 records the cell that convention flips). +""" +import argparse, importlib.util, json, os, time +from pathlib import Path +from types import SimpleNamespace + +import numpy as np + +ROOT = "/proj/dmfexp/zwhong/rsm_rise" + + +def _load_ceiling_module(): + """Import proposal_ceiling.py so build/chunk_feat/geom_feat/fit_arm/auc/ep_bootstrap_diff are the + SAME definitions the published table used, never retyped copies.""" + spec = importlib.util.spec_from_file_location("pc", f"{ROOT}/scripts/real/proposal_ceiling.py") + m = importlib.util.module_from_spec(spec) + spec.loader.exec_module(m) + return m + + +PC = _load_ceiling_module() +EPS = 1e-6 + + +def q95(x): + s = np.sort(np.asarray(x, float)) + return float(s[int(0.95 * len(s))]) + + +def qq(x, p): + s = np.sort(np.asarray(x, float)) + return float(s[min(len(s) - 1, int(p * len(s)))]) + + +def _logit(p): + p = np.clip(np.asarray(p, float), EPS, 1.0 - EPS) + return np.log(p / (1.0 - p)) + + +def episode_logits(p_anchor, y, ep): + """OOF anchor probabilities -> ONE logit per episode. + + Mean of LOGITS inside the episode (not of probabilities): the arm is a logistic model, so the logit + is its additive scale, and averaging probabilities near 0/1 would throw away the confident anchors. + The result is then shifted by a single scalar so that the MEAN GENERATED PROBABILITY equals the + observed goal-episode fraction -- `fit_arm` uses class_weight='balanced', whose probabilities are + calibrated to a 50/50 prior and not to this sample's. One scalar, solved by bisection; no slope is + refitted, so the null's anchor->label strength is the ARM's, not one I chose. + """ + ue = np.unique(ep) + l_e = np.array([np.nanmean(_logit(p_anchor[ep == e])) for e in ue]) + y_e = np.array([y[ep == e][0] for e in ue], float) + target = float(y_e.mean()) + lo, hi = -20.0, 20.0 + for _ in range(200): # bisection on a scalar intercept shift + mid = 0.5 * (lo + hi) + if float((1.0 / (1.0 + np.exp(-(l_e + mid)))).mean()) < target: + lo = mid + else: + hi = mid + return ue, l_e + 0.5 * (lo + hi), y_e, target + + +def draw_y(ue, l_e, lam, ep, rng, min_per_class): + """One episode-level label draw at shrinkage `lam`, broadcast back to anchors. + + l_e(lam) = lbar + lam*(l_e - lbar) with lbar re-solved so the mean probability still equals the + base rate at EVERY lam -- otherwise the ladder would confound shrinkage with a prior shift. + Draws with too few episodes in a class are rejected and redrawn: StratifiedGroupKFold cannot make + 5 folds otherwise, and a degenerate draw is not a null sample, it is a missing one. + """ + lbar = float(l_e.mean()) + base = float((1.0 / (1.0 + np.exp(-l_e))).mean()) + c = lbar + lam * (l_e - lbar) + lo, hi = -20.0, 20.0 + for _ in range(200): + mid = 0.5 * (lo + hi) + if float((1.0 / (1.0 + np.exp(-(c + mid)))).mean()) < base: + lo = mid + else: + hi = mid + p_e = 1.0 / (1.0 + np.exp(-(c + 0.5 * (lo + hi)))) + for _ in range(500): + ye = (rng.random(len(p_e)) < p_e).astype(int) + if ye.sum() >= min_per_class and (len(ye) - ye.sum()) >= min_per_class: + m = dict(zip(ue.tolist(), ye.tolist())) + return np.array([m[e] for e in ep]), ye + raise RuntimeError("degenerate label draws") + + +def fit_arm_ext(X, y, ep, folds, seed, model): + """PC.fit_arm for logreg/mlp; a `gb` arm added HERE rather than in the published + proposal_ceiling.py, which must not move. Identical StratifiedGroupKFold-over-episodes protocol.""" + if model in ("logreg", "mlp"): + return PC.fit_arm(X, y, ep, folds, seed, model) + from sklearn.model_selection import StratifiedGroupKFold + from sklearn.ensemble import HistGradientBoostingClassifier + oof = np.full(len(y), np.nan) + for tr, va in StratifiedGroupKFold(n_splits=folds, shuffle=True, random_state=seed).split(X, y, groups=ep): + m = HistGradientBoostingClassifier(max_iter=300, learning_rate=0.1, early_stopping=True, + random_state=seed) + m.fit(X[tr], y[tr]) + oof[va] = m.predict_proba(X[va])[:, 1] + return oof + + +def stat(AN, CFw, GF, yy, ep, folds, seed): + """(raw, resid, auc_both, auc_anchor, auc_anchorgeom) for ONE label vector. + + Unlike run 36's chunk-permutation null the anchor arm is NOT constant here -- y changes every draw, + so all three arms are refitted. That is the whole point: this null lets the anchor arm keep the + signal it really has instead of collapsing it to chance. + """ + s_a = PC.fit_arm(AN, yy, ep, folds, seed, "logreg") + s_b = PC.fit_arm(np.concatenate([AN, CFw], 1), yy, ep, folds, seed, "logreg") + s_g = PC.fit_arm(np.concatenate([AN, GF], 1), yy, ep, folds, seed, "logreg") + ok = ~(np.isnan(s_a) | np.isnan(s_b) | np.isnan(s_g)) + aa, ab, ag = PC.auc(yy[ok], s_a[ok]), PC.auc(yy[ok], s_b[ok]), PC.auc(yy[ok], s_g[ok]) + return float(ab - aa), float(ab - ag), float(ab), float(aa), float(ag) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--out", required=True) + ap.add_argument("--hdf5", default=f"{ROOT}/data/raw/cooking_v5_expert_suboptimal.hdf5") + ap.add_argument("--split", default=f"{ROOT}/data/derived/cooking_v5_split.json") + ap.add_argument("--state", type=int, default=2) + ap.add_argument("--route-pos", default="[2, 3, 4]") + ap.add_argument("--route-neg", default="[0, 2, 3]") + ap.add_argument("--contrast", default="goal_vs_cook") + ap.add_argument("--stride", type=int, default=5) + ap.add_argument("--entry-window", type=int, default=100) + ap.add_argument("--lengths", type=int, nargs="+", default=[8, 32]) + ap.add_argument("--folds", type=int, default=5) + ap.add_argument("--seeds", type=int, nargs="+", default=[0, 1, 2]) + ap.add_argument("--lams", type=float, nargs="+", default=[1.0, 0.5, 0.0]) + ap.add_argument("--declare-lam", type=float, default=1.0) + ap.add_argument("--draws", type=int, default=400) + ap.add_argument("--typei-m", type=int, default=40) + ap.add_argument("--typei-draws", type=int, default=200) + ap.add_argument("--typei-length", type=int, default=8) + ap.add_argument("--min-per-class", type=int, default=8) + ap.add_argument("--dgp-models", nargs="+", default=["mlp", "logreg"], + help="H0 data-generating anchor models. `logreg` is the SELF rung (null==DGP, weak).") + ap.add_argument("--boot", type=int, default=2000) + ap.add_argument("--jobs", type=int, default=8) + ap.add_argument("--published", default=f"{ROOT}/status/real/pt_ceilresid_w100_goal_vs_cook/ceiling.json") + a = ap.parse_args() + t0 = time.time() + out = Path(a.out); out.mkdir(parents=True, exist_ok=True) + from joblib import Parallel, delayed + + rows, n_drop, n_ep = PC.build(SimpleNamespace( + hdf5=a.hdf5, split=a.split, state=a.state, route_pos=a.route_pos, route_neg=a.route_neg, + stride=a.stride, entry_window=a.entry_window, lengths=a.lengths)) + if not rows: + raise SystemExit("no anchors") + ep = np.array([r["ep"] for r in rows]); y = np.array([r["y"] for r in rows]) + AN = np.stack([r["anchor"] for r in rows]); CH = np.stack([r["chunk"] for r in rows]) + FEAT = {L: (PC.chunk_feat(CH, L, "waypoints"), PC.geom_feat(CH, L)) for L in a.lengths} + print(f"[yres] contrast={a.contrast} anchors={len(rows)} episodes={len(np.unique(ep))}/{n_ep} " + f"goal={int((y==1).sum())} fail={int((y==0).sum())} window={a.entry_window} dropped={n_drop}", + flush=True) + + # ---- OBSERVED statistics + REGRESSION GUARD against the published table + power interval. + pub = json.load(open(a.published)) + pubmap = {(p["pair"], p["L"], p["seed"]): p["diff"] for p in pub["paired"]} + obs, guard = {}, [] + for seed in a.seeds: + for L in a.lengths: + CFw, GF = FEAT[L] + s_a = PC.fit_arm(AN, y, ep, a.folds, seed, "logreg") + s_b = PC.fit_arm(np.concatenate([AN, CFw], 1), y, ep, a.folds, seed, "logreg") + s_g = PC.fit_arm(np.concatenate([AN, GF], 1), y, ep, a.folds, seed, "logreg") + ok = ~(np.isnan(s_a) | np.isnan(s_b) | np.isnan(s_g)) + aa, ab, ag = PC.auc(y[ok], s_a[ok]), PC.auc(y[ok], s_b[ok]), PC.auc(y[ok], s_g[ok]) + braw = PC.ep_bootstrap_diff(y[ok], s_b[ok], s_a[ok], ep[ok], a.boot, seed) + brsd = PC.ep_bootstrap_diff(y[ok], s_b[ok], s_g[ok], ep[ok], a.boot, seed) + obs[(seed, L)] = dict(raw=float(ab - aa), resid=float(ab - ag), auc_both=ab, + auc_anchor=aa, auc_anchorgeom=ag, + raw_boot=list(braw), resid_boot=list(brsd)) + for key, val in (("both:logreg - anchor:logreg", ab - aa), + ("both:logreg - anchorgeom:logreg", ab - ag)): + if (key, L, seed) in pubmap: + guard.append(dict(pair=key, L=L, seed=seed, mine=float(val), + published=pubmap[(key, L, seed)], + delta=abs(float(val) - pubmap[(key, L, seed)]))) + print(f"[yres] OBSERVED L={L:3d} seed{seed} raw={ab-aa:+.6f} (boot CI " + f"[{braw[2]:+.4f},{braw[3]:+.4f}]) resid={ab-ag:+.6f} (boot CI " + f"[{brsd[2]:+.4f},{brsd[3]:+.4f}]) both={ab:.4f} anchor={aa:.4f} anchorgeom={ag:.4f}", + flush=True) + worst = max([g["delta"] for g in guard], default=float("nan")) + print(f"[yres] [GUARD] {len(guard)} published rows reproduced, worst |delta| = {worst:.3e}", flush=True) + if not (worst < 1e-9): + print("[yres] [GUARD] FAIL -- observed statistic does not reproduce the published table; every " + "number below is void.", flush=True) + + # ---- the generator: one probability per episode, from the anchor arm's own OOF predictions. + gseed = int(a.seeds[0]) + p_anchor = PC.fit_arm(AN, y, ep, a.folds, gseed, "logreg") + ue, l_e, y_e, base = episode_logits(p_anchor, y, ep) + p_e = 1.0 / (1.0 + np.exp(-l_e)) + agree = float(((p_e > 0.5).astype(int) == y_e.astype(int)).mean()) + print(f"[yres] GENERATOR episodes={len(ue)} base={base:.3f} p_e: min={p_e.min():.3f} " + f"q25={np.quantile(p_e,.25):.3f} med={np.median(p_e):.3f} q75={np.quantile(p_e,.75):.3f} " + f"max={p_e.max():.3f} mean={p_e.mean():.3f}; frac in [.2,.8]={float(((p_e>.2)&(p_e<.8)).mean()):.3f}; " + f"E|y*-y|/n={float(np.mean(np.where(y_e==1, 1-p_e, p_e))):.3f}; argmax agreement={agree:.3f}", + flush=True) + + def null_dist(lam, L, seed, ndraws, base_seed, l_use=None, jitter=0): + le = l_e if l_use is None else l_use + CFw, GF = FEAT[L] + def one(rep): + rng = np.random.default_rng([base_seed, int(lam * 1000), L, seed, rep, jitter]) + yy, _ = draw_y(ue, le, lam, ep, rng, a.min_per_class) + r, d, _, _, _ = stat(AN, CFw, GF, yy, ep, a.folds, seed) + return r, d, float((yy == y).mean()) + res = Parallel(n_jobs=a.jobs, prefer="processes")(delayed(one)(r) for r in range(ndraws)) + return (np.array([r[0] for r in res]), np.array([r[1] for r in res]), + float(np.mean([r[2] for r in res]))) + + # ---- PRIMARY grid: every lam x seed x L. + prim = [] + for lam in a.lams: + for seed in a.seeds: + for L in a.lengths: + tA = time.time() + nr, nd, agr = null_dist(lam, L, seed, a.draws, 5150) + o = obs[(seed, L)] + row = dict(lam=lam, L=L, seed=seed, draws=a.draws, label_agreement=agr) + for tag, nul, ov, bt in (("raw", nr, o["raw"], o["raw_boot"]), + ("resid", nd, o["resid"], o["resid_boot"])): + p = (1.0 + int((nul >= ov).sum())) / (1.0 + len(nul)) + bar = q95(nul) + row.update({f"{tag}_obs": ov, f"{tag}_null_mean": float(nul.mean()), + f"{tag}_null_sd": float(nul.std(ddof=1)), f"{tag}_q95": bar, + f"{tag}_q99": qq(nul, 0.99), f"{tag}_p": float(p), + f"{tag}_clears": bool(ov > bar), + f"{tag}_boot_hi": float(bt[3]), + f"{tag}_powered": bool(bar < bt[3])}) + print(f"[yres] PRIMARY lam={lam:.2f} L={L:3d} seed{seed} {tag:5s} obs={ov:+.4f} " + f"null {nul.mean():+.4f}+-{nul.std(ddof=1):.4f} q95={bar:+.4f} p={p:.3f} " + f"clears={ov > bar} powered={bar < bt[3]} (bootHi {bt[3]:+.4f})", flush=True) + row["null_raw"] = nr.tolist(); row["null_resid"] = nd.tolist() + prim.append(row) + print(f"[yres] (mean label agreement with observed y: {agr:.3f}, " + f"{time.time()-tA:.0f}s)", flush=True) + + # ---- TYPE-I. Two DGPs. `mlp` is the pre-registered declaring one: H0 data generated by a model + # the null's logreg generator CANNOT represent, which is the mis-specification that matters. + Lt, seed = a.typei_length, int(a.seeds[0]) + gens, cred = [], {} + for dgp in a.dgp_models: + p_d = fit_arm_ext(AN, y, ep, a.folds, gseed, dgp) + ok_d = ~np.isnan(p_d) + cred[dgp] = float(PC.auc(y[ok_d], p_d[ok_d])) + _, l_d, _, _ = episode_logits(p_d, y, ep) + gens.append((dgp, l_d, len(gens))) + print(f"[yres] DGP PLAUSIBILITY {dgp:7s}: anchor-only OOF AUC on the REAL y = {cred[dgp]:.4f}" + f" (the statistic's own anchor arm reads {obs[(seed, Lt)]['auc_anchor']:.4f}; a DGP that " + f"does not reach that is LESS nonlinear than the data demonstrably are)", flush=True) + typei = [] + for dgp, l_gen, dgp_ix in gens: + for m in range(a.typei_m): + rngm = np.random.default_rng([90210, dgp_ix, m]) + ystar, _ = draw_y(ue, l_gen, 1.0, ep, rngm, a.min_per_class) # H0 holds by construction + CFw, GF = FEAT[Lt] + raw_m, rsd_m, _, aa_m, _ = stat(AN, CFw, GF, ystar, ep, a.folds, seed) + # the null is refitted ON THE RESAMPLED DATA, exactly as it would be on real data + p_a = PC.fit_arm(AN, ystar, ep, a.folds, seed, "logreg") + ue2, l2, _, _ = episode_logits(p_a, ystar, ep) + def one(rep): + rng = np.random.default_rng([7700 + m, dgp_ix, rep]) + yy, _ = draw_y(ue2, l2, a.declare_lam, ep, rng, a.min_per_class) + r, d, _, _, _ = stat(AN, CFw, GF, yy, ep, a.folds, seed) + return r, d + res = Parallel(n_jobs=a.jobs, prefer="processes")( + delayed(one)(r) for r in range(a.typei_draws)) + nr = np.array([r[0] for r in res]); nd = np.array([r[1] for r in res]) + rec = dict(dgp=dgp, m=m, raw_obs=raw_m, resid_obs=rsd_m, raw_q95=q95(nr), resid_q95=q95(nd), + raw_clears=bool(raw_m > q95(nr)), resid_clears=bool(rsd_m > q95(nd)), + anchor_auc=aa_m) + typei.append(rec) + print(f"[yres] TYPEI dgp={dgp} m={m:2d} raw={raw_m:+.4f} vs q95={q95(nr):+.4f} " + f"({rec['raw_clears']}) resid={rsd_m:+.4f} vs q95={q95(nd):+.4f} " + f"({rec['resid_clears']}) anchorAUC={aa_m:.3f}", flush=True) + + def cp(k, n): + from scipy.stats import beta as B + lo = 0.0 if k == 0 else float(B.ppf(0.025, k, n - k + 1)) + hi = 1.0 if k == n else float(B.ppf(0.975, k + 1, n - k)) + return lo, hi + rates = {} + for dgp in a.dgp_models: + for tag in ("raw", "resid"): + sub = [r for r in typei if r["dgp"] == dgp] + k = int(sum(r[f"{tag}_clears"] for r in sub)); n = len(sub) + lo, hi = cp(k, n) if n else (float("nan"),) * 2 + rates[f"{dgp}_{tag}"] = dict(k=k, n=n, rate=(k / n if n else float("nan")), ci=[lo, hi]) + print(f"[yres] TYPE-I RATE dgp={dgp} {tag}: {k}/{n} = {k/max(n,1):.3f} CP95 [{lo:.3f},{hi:.3f}]" + f" (valid test sits at 0.05; bar <= 0.10; DGP credential " + f"{cred.get(dgp, float('nan')):.4f})", flush=True) + + json.dump(dict(contrast=a.contrast, entry_window=a.entry_window, n_anchors=len(rows), + n_episodes=int(len(np.unique(ep))), base_rate=base, + generator=dict(p_e=p_e.tolist(), y_e=y_e.tolist(), argmax_agreement=agree), + observed={f"{k[0]}_{k[1]}": v for k, v in obs.items()}, + guard=guard, guard_worst=worst, primary=prim, typei=typei, typei_rate=rates, + dgp_credential=cred, + config=vars(a)), open(out / "yres_null.json", "w"), indent=1) + print(f"[yres] done {time.time()-t0:.0f}s -> {out}/yres_null.json", flush=True) + + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/real/q278_comment28.py b/rsm_rise/scripts/real/q278_comment28.py new file mode 100644 index 0000000000000000000000000000000000000000..34a5eb80e33cc8595ae129f60e53443f63f5efa5 --- /dev/null +++ b/rsm_rise/scripts/real/q278_comment28.py @@ -0,0 +1,230 @@ +#!/usr/bin/env python3 +"""Build status/real/comment_278_run28.md and comment_276_run28.md. +Every number is READ from an artefact on disk, never retyped.""" +import json +from pathlib import Path + +R = Path('/proj/dmfexp/zwhong/rsm_rise/status/real') +M = json.loads((R / '_edgeZ_matched.json').read_text()) +P = json.loads((R / '_edgeZ_partial_matched.json').read_text()) +C = json.loads((R / 'EDGE_CEILING_Z.json').read_text()) +S = json.loads((R / 'EDGE_STRAT_Z.json').read_text()) +rule = M['_rule'] + +ARMS = [("edge_Z_goalep_ha", "NEW"), ("edge_V_goalep", "CONTROL"), ("edge_Z_goalep_hd", "NEW"), + ("edge_Z_goalep_hc", "NEW"), ("edge_Z_goalep_hb", "NEW"), ("edge_W_goalep_g999", ""), + ("edge_X_goalep_g9995", ""), ("edge_Y_goalep_b98", ""), ("edge_Y_goalep_b95", "")] + + +def f(d): + return f"{d['mean']:+.4f} [{d['lo']:+.4f}, {d['hi']:+.4f}]" + + +def arm(a): + return M[a]['arm'] + + +def ceil_of(a): + return C.get(a, {}) + + +def pct_ceil(a): + c = ceil_of(a) + if not c: + return None + return 100.0 * c['d_vs_greedy_rsm'] / c['d_ceiling'] + + +L = [] +A = L.append +A('## Run 28 -- **rung Z closes on its authoritative read: clause (d), the read-out axis is ' + 'EXHAUSTED.** The metric is maximised at ~1 composition hop, the hop-count law holds on all three ' + 'matched-hop pairs, and no (beta, gamma) inside the trained range improves it.') +A('') +A('**reward detection (#277): PASS** -- AUC 0.931 [0.89, 0.96] vs permuted 0.47, unchanged. ' + '**action ranking (#278): FAIL, near-miss** -- best cell to date `edge_T_rise` ' + '**+0.0909 [+0.0373, +0.1480]** against the pre-registered **+0.10** bar; rung Z\'s best is ' + f'`{rule["best"]}` **{rule["best_d"]:+.4f}**.') +A('') +A('### The correction to run 27 first') +A('Run 27 reported a mid-wave read in which two arms appeared to clear the bar at +0.1123. That was ' + 'an **anchor-subset artifact** and I said so at the time; the complete read confirms it. ' + 'All four rung-Z arms are now at **25/25 parts** (`logs/lsf/rr_cpu_edgeZverify.1897283.out` prints ' + 'the per-arm completeness line before it reads anything), and on the complete data ' + f'`edge_Z_goalep_hc` and `edge_Z_goalep_hd` come back at {arm("edge_Z_goalep_hc")["dg"]["mean"]:+.4f} ' + f'and {arm("edge_Z_goalep_hd")["dg"]["mean"]:+.4f} -- i.e. back at the control, exactly as the ' + 'subset explanation predicted. Nothing was banked from that read.') +A('') +A(f"### Rung Z, authoritative (GOAL_EPISODE, pi0.5 RISE proposer, flow 8, N=128, 16 particles, S0 " + f"anchors, held-out split; every arm complete at 25/25 parts -> " + f"{P['_partial']['n_common']} landed episodes, {arm('edge_V_goalep')['dg']['n_episodes']} of them " + f"carrying S0 anchors, which is the cluster count behind every interval below)") +A('') +A('| arm | beta | gamma | h = E[extra hops] | E[reads] | horizon | cap | n | cov | d vs greedy | d vs permuted | AUC_w | %ceiling |') +A('|---|---|---|---|---|---|---|---|---|---|---|---|---|') +for a, tag in ARMS: + m, s = M[a], arm(a) + cr = ceil_of(a) + aucs = f"{cr['auc_rsm']['weighted']:.3f}" if cr else "--" + pc = pct_ceil(a) + pcs = f"{pc:.1f}%" if pc is not None else "--" + nm = f"`{a}`" + (f" **{tag}**" if tag else "") + A(f"| {nm} | {m['beta']:.6g} | {m['gamma']:.4f} | {m['e_extra_hops']:.2f} | {m['e_reads']:.1f} | " + f"{m['horizon']} | {m['cap']} | {s['dg']['n']} | {s['cov']:.3f} | {f(s['dg'])} | {f(s['dp'])} | " + f"{aucs} | {pcs} |") +A('') +A('**The episode-matched cross-check agrees cell for cell.** The common landed episode set is now ' + f'**{P["_partial"]["n_common"]} episodes** and every arm\'s matched number is identical to its ' + 'own-anchor number, because every arm is complete on the same anchors. Arms at or above the bar ' + f'on that set: **{P["_partial"]["cleared"] or "none"}**. Arms above the control\'s upper bound: ' + f'**{P["_partial"]["above_ctrl"] or "none"}**.') +A('') +A('### The hop-count law, now tested at three depths') +A('') +A('| pair | h | horizon A | d A | horizon B | d B | \\|gap\\| | agree? |') +A('|---|---|---|---|---|---|---|---|') +for p in rule['pairs']: + A(f"| {p['tag']} | {p['h']:.2f} | {p['horizon_a']} | {p['d_a']:+.4f} | {p['horizon_b']} | " + f"{p['d_b']:+.4f} | {p['gap']:.4f} | {'**yes**' if p['agree'] else 'NO'} |") +A('') +df = rule['depth_fit'] +A(f"Horizon ratios 2x / 3.8x / 2x, and at matched depth the horizon buys **nothing**. Across all " + f"{df['n']} cells, d regressed on ln(E[model reads]) has slope **{df['slope_per_ln_reads']:+.4f} " + f"per e-fold** with r = {df['pearson_r']:+.3f}. Composition depth is not a lever that was set " + "wrong -- it is a direction in which this metric monotonically **decays**, from " + f"{arm('edge_Z_goalep_ha')['dg']['mean']:+.4f} at h 0.34 to " + f"{arm('edge_Y_goalep_b95')['dg']['mean']:+.4f} at h 51.6 (chance).") +A('') +A(f"Pre-registered clause: **{rule['verdict']}** The shallow frontier `{rule['best']}` " + "(h 0.34 -- two thirds of decisions take no composition step at all) is the top cell but sits " + f"INSIDE the control's [{rule['ctrl_lo']:+.4f}, {rule['ctrl_hi']:+.4f}], which is clause (d), " + "not clause (b).") +A('') +A('### The new finding in this read: WHERE the ranking fails') +A('') +A('`edge_strat.py` splits the anchors by leverage (`n_off` = how many of the 128 candidates are ' + 'off-route; an anchor where the proposer is already on-route has almost no ranking leverage). ' + 'For the best cell:') +A('') +A('| n_off | n | leverage share | AUC_w | permuted | greedy | contribution to d |') +A('|---|---|---|---|---|---|---|') +st = S['edge_Z_goalep_ha'] +for b in st['strata']: + A(f"| {b['n_off_lo']}-{b['n_off_hi']} | {b['n']} | {100 * b['leverage_share']:.1f}% | " + f"{b['auc_w_rsm']:.3f} | {b['auc_w_perm']:.3f} | {b['auc_w_greedy']:.3f} | {b['d_contrib']:+.4f} |") +A('') +cz = ceil_of('edge_Z_goalep_ha') +top2 = st['strata'][-2:] +mid = max(st['strata'][:-2], key=lambda b: b['leverage_share']) +A(f"The AUC_w needed to clear the bar on this cell is **{cz['auc_needed_for_bar']:.3f}**. The top " + f"two strata -- which carry **{100 * sum(b['leverage_share'] for b in top2):.0f}% of all the " + f"leverage** -- are at **{top2[0]['auc_w_rsm']:.3f} and {top2[1]['auc_w_rsm']:.3f}**, i.e. the " + "top stratum already exceeds the bar on its own. The shortfall is concentrated in the " + f"mid-leverage stratum ({mid['n_off_lo']}-{mid['n_off_hi']} off-route candidates, " + f"{100 * mid['leverage_share']:.1f}% of leverage) sitting at **{mid['auc_w_rsm']:.3f}, below " + "chance**. So the scorer is not uniformly weak: it ranks correctly exactly where many candidates " + "are wrong, and it is at or below chance where the proposer is already mostly right. " + f"Spearman(n_off, AUC_w) = **{st['spearman_noff_vs_auc']['rho']:+.3f}** " + f"[{st['spearman_noff_vs_auc']['lo']:+.3f}, {st['spearman_noff_vs_auc']['hi']:+.3f}]; top minus " + f"bottom stratum **{st['auc_w_top_minus_bottom_stratum']['value']:+.3f}** " + f"[{st['auc_w_top_minus_bottom_stratum']['lo']:+.3f}, " + f"{st['auc_w_top_minus_bottom_stratum']['hi']:+.3f}].") +A('') +A('### The one change this run: rung AA, the last empty cell of the design') +A('') +A("The number that chose it: the two best factor settings measured on identical anchors have never " + "been combined. Rung T's best successor is the shipped-reward `R_XL` (+0.0909 at h 1.01); rung Z's " + f"best depth is h 0.34 ({arm('edge_Z_goalep_ha')['dg']['mean']:+.4f} vs " + f"{arm('edge_V_goalep')['dg']['mean']:+.4f} at h 1.01 on `R_XL_ft_v0`). That leaves exactly one " + "empty cell in a 2x2:") +A('') +A('| successor | depth h 1.01 (b 0.99, g 0.995) | depth h 0.34 (b 0.99, g 0.9925) |') +A('|---|---|---|') +A(f"| `R_XL` (shipped reward) | `edge_T_rise` {C['edge_T_rise']['d_vs_greedy_rsm']:+.4f} | " + f"**`edge_AA_rxl_ha` -- THIS WAVE** |") +A(f"| `R_XL_ft_v0` (GOAL_EPISODE) | `edge_V_goalep` {arm('edge_V_goalep')['dg']['mean']:+.4f} | " + f"`edge_Z_goalep_ha` {arm('edge_Z_goalep_ha')['dg']['mean']:+.4f} |") +A('') +A('**ONE change from `edge_T_rise`: gamma 0.995 -> 0.9925.** Same proposer, same checkpoint, same ' + 'flow 8 / N=128 / 16 particles / S0 anchors / same 25 held-out episodes. beta 0.99 is `beta_hi` on ' + "that checkpoint's trained [0.95, 0.99]; gamma is a read-out knob. Nothing retrained, nothing " + 'bespoke. It is also the cheapest cell on the whole curve (E[reads] 1.34, cap 6).') +A('') +A('**Jobs: LSF 1897514 `rr_edgeAA_2x2`** (4 GPUs, one shard per GPU) and **1897515 ' + '`rr_cpu_edgeAAverify`**, the guarded read, which prints the part count every minute and only ' + 'reads once the arm is complete -- the process fix from run 27, now standard.') +A('') +A('**Rule pre-registered and pushed BEFORE any AA part was read** (gen_q `rsm_rise_data` ' + '**59d7cc1e**, `rsm_rise/pipeline/scripts/real/edge_matched_AA.py`): (a) AA >= +0.10 and above its ' + 'permuted control -> bar cleared, write `configs/baselines.yaml` + `EDGE_TEST.md` and close #278; ' + '(b) AA < +0.10 -> the 2x2 is complete, every standard-practice rung is closed, write the negative ' + 'naming the near-miss and its number and close #278. Either way I report the interaction ' + '(AA - T) - (ha - V): if it is inside the bootstrap noise, the successor and depth axes are ' + 'additive, the landscape is a plane, and **no unmeasured combination of them can reach the bar** -- ' + 'which is the statement that closes the design rather than leaving a hole in it.') +A('') +A('Expected under additivity: +0.0916. That is still under the bar, and I am saying so before the ' + 'read rather than after it.') +A('') +A('### Ladder') +A('') +A('| rung | knob | result | number |') +A('|---|---|---|---|') +for r in [ + ("1", "proposer diversity (coverage)", "PASS (gate 0.8)", "sn1 0.942; RISE 0.904; stock 0.749 FAILS"), + ("2", "reward-head robustness", "measured", "see #277"), + ("3", "plain BC proposer", "CLOSED -- stock fails the coverage gate", "0.749 < 0.80; d +0.0018"), + ("4", "particles / N", "CLOSED -- saturated", "16 -> 256: +0.0690 -> +0.0690"), + ("Q", "read-out horizon (dense label)", "CLOSED -- exhausted", "+0.0690 [+0.029, +0.111]"), + ("R", "flow steps at eval", "CLOSED -- flat", "+0.0709 -> +0.0667 over 4 -> 32"), + ("--", "metric ceiling", "measured (run 16)", "bar = AUC_w 0.767 at w_bar 0.386"), + ("T", "proposer at a valid cell", "CLOSED -- RISE best, near-miss", "**+0.0909 [+0.0373, +0.1480]**, 47.9% of ceiling"), + ("U", "successor at the RISE proposer", "CLOSED -- the stay-put gate orders arms but is not a lever", "rho(gate, d) -0.900; best-gated +0.0726"), + ("V", "reward label (4 trained)", "CLOSED -- largest lever, 0.158, and it points DOWN", "dense +0.0872 -> sparse -0.0672"), + ("W", "label x horizon (g .995 -> .999)", "CLOSED -- interaction real on one label only", "W400 +0.0125 -> +0.0546"), + ("X", "label x horizon (g .999 -> .9995)", "CLOSED -- horizon exhausted; reachability falsified", "all arms inside the control"), + ("Y", "composition depth (beta)", "CLOSED -- wrong direction, monotone decay to chance", "+0.0741 -> +0.0646 -> +0.0062"), + ("Z", "depth below h=1 + the hop-count law", "**CLOSED -- clause (d), read-out axis exhausted; law 3/3 pairs**", + f"best {rule['best_d']:+.4f} at h 0.34, inside the control"), + ("AA", "successor x depth (the last empty cell)", "**RUNNING** (1897514, read chained 1897515)", "rule pre-registered 59d7cc1e"), +]: + A(f"| {r[0]} | {r[1]} | {r[2]} | {r[3]} |") +A('') +A('Still on hold as instructed, and not run: reward scheme C as a new training, junction-prefix ' + 'oversampling, the expectile-0.5 critic. Figure B stays closed as a negative (65.4 px held-out ' + 'reprojection residual, run 10).') +A('') +A('*Posted by Claude (enterprise worker) on behalf of the RISE/RSM execution loop.*') + +body = "\n".join(L) +(R / 'comment_278_run28.md').write_text(body) + +V = [] +B = V.append +B('**reward detection: PASS** -- AUC 0.931 [0.89, 0.96] vs permuted 0.47 (#277).') +B('') +B('**action ranking: FAIL (near-miss)** -- best cell `edge_T_rise` **+0.0909 [+0.0373, +0.1480]** ' + 'against the pre-registered **+0.10** bar, 47.9% of the measured metric ceiling (#278).') +B('') +B('---') +B('') +B(f"Rung Z closed on its authoritative read (all four arms 25/25 parts): **{rule['verdict']}** " + f"Best rung-Z cell `{rule['best']}` {rule['best_d']:+.4f}, inside the h-1.01 control's " + f"[{rule['ctrl_lo']:+.4f}, {rule['ctrl_hi']:+.4f}]. The hop-count law holds on all three " + f"matched-hop / different-horizon pairs (gaps " + + ", ".join(f"{p['gap']:.4f}" for p in rule['pairs']) + + f"), and d falls {df['slope_per_ln_reads']:+.4f} per e-fold of model reads (r = " + f"{df['pearson_r']:+.3f}). Composition depth is a direction in which this metric decays, not a " + 'knob that was set wrong.') +B('') +B('Run 27\'s mid-wave "+0.1123 clears the bar" was an anchor-subset artifact, as flagged at the ' + 'time; the complete read puts both arms back at the control. Nothing was banked.') +B('') +B('One change launched this run: **rung AA**, the last empty cell of the successor x depth 2x2 ' + "(rung T's best successor at rung Z's best depth; one change from `edge_T_rise`, gamma 0.995 -> " + '0.9925). LSF 1897514 + guarded read 1897515, rule pre-registered in gen_q `rsm_rise_data` ' + '59d7cc1e before any part was read. Detail on #278.') +B('') +B('*Posted by Claude (enterprise worker) on behalf of the RISE/RSM execution loop.*') +(R / 'comment_276_run28.md').write_text("\n".join(V)) +print("wrote comment_278_run28.md", len(body), "chars") diff --git a/rsm_rise/scripts/real/q278_comment29.py b/rsm_rise/scripts/real/q278_comment29.py new file mode 100644 index 0000000000000000000000000000000000000000..896fc25a108f9a50d11701416881284668bf1560 --- /dev/null +++ b/rsm_rise/scripts/real/q278_comment29.py @@ -0,0 +1,196 @@ +r"""#278 run 29: the CLOSING comment. Rung AA landed, clause (b) of its pre-registered rule fired, +and the paired interaction says the successor x depth plane is flat, so the standard-practice ladder +on the action-ranking test is exhausted. Every number below is READ FROM THE JSON ARTEFACTS +(_edgeAA_matched.json, _edgeAA_interaction.json, EDGE_CEILING_AA.json, EDGE_STRAT_AA.json), so the +post cannot drift from the measurement.""" +import json +from pathlib import Path + +R = Path("/proj/dmfexp/zwhong/rsm_rise/status/real") +M = json.load(open(R / "_edgeAA_matched.json")) +I = json.load(open(R / "_edgeAA_interaction.json")) +C = json.load(open(R / "EDGE_CEILING_AA.json")) +S = json.load(open(R / "EDGE_STRAT_AA.json")) +BAR = 0.10 +AA, T, HA, V = "edge_AA_rxl_ha", "edge_T_rise", "edge_Z_goalep_ha", "edge_V_goalep" + + +def d(a): + return M[a]["dg"] + + +def f(x): + return f"{x['mean']:+.4f} [{x['lo']:+.4f},{x['hi']:+.4f}]" + + +def fi(k): + x = I[k] + return f"{x['mean']:+.4f} [{x['lo']:+.4f},{x['hi']:+.4f}] p={x['p_ne0']:.3f}" + + +L = [] +w = L.append +w(f"**reward detection (#277): PASS** -- AUC 0.931 [0.89,0.96] vs permuted 0.47, unchanged.") +w(f"**action ranking (#278): FAIL** -- the complete successor x depth factorial tops out at " + f"**{d(T)['mean']:+.4f} [{d(T)['lo']:+.4f},{d(T)['hi']:+.4f}]** against the pre-registered " + f"**+0.10** bar -- {100 * d(T)['mean'] / C[T]['d_ceiling']:.1f}% of the metric's measured ceiling " + f"(+{C[T]['d_ceiling']:.4f}), AUC_w {C[T]['auc_rsm']['weighted']:.3f} against the " + f"{C[T]['auc_needed_for_bar']:.3f} the bar needs. The last empty cell came in at {d(AA)['mean']:+.4f} and the two axes are ADDITIVE, so no " + f"unmeasured combination of them can reach the bar. **Closing #278 on the negative.**") +w("") +w("## Rung AA -- the last empty cell, read on the common anchor set") +w("") +w("`status/real/_edgeAA_matched.json` (field `_rule`). pi0.5 RISE proposer `rise_s0/29999`, N=128, " + "16 particles, flow 8, GOAL_EPISODE reward, S0 anchors on the held-out split, 20 common landed " + "episodes. Every cell carries its own n.") +w("") +w("| cell | successor | beta | gamma | E[extra hops] | E[reads] | horizon | cap | n anc | eps | cov | d vs greedy | d vs permuted |") +w("|---|---|---|---|---|---|---|---|---|---|---|---|---|") +for a, tag in ((AA, " **<- NEW**"), (T, " **<- CONTROL / best cell to date**"), (HA, ""), (V, "")): + m = M[a] + w(f"| `{a}`{tag} | {m['successor']} | {m['beta']} | {m['gamma']} | {m['h']:.2f} | " + f"{m['e_reads']:.2f} | {m['horizon']} | {m['cap']} | {m['dg']['n']} | {m['dg']['n_episodes']} | " + f"{m['cov']:.3f} | {f(m['dg'])} | {f(m['dp'])} |") +w("") +w(f"**Cells at or above the +0.10 bar: none. Cells above the control's point estimate: none.**") +w("") +w("## The 2x2 is ADDITIVE -- this is what closes the design rather than leaving a hole") +w("") +w(f"The arm means above are bootstrapped independently, so their differences carry the arm-to-arm " + f"anchor noise. `scripts/real/edge_interaction_AA.py` (LSF 1897996, CPU re-read of the same " + f"`edge_parts/*.npz`, no model call) recomputes the effects **PAIRED at the anchor level** -- the " + f"{I['n_paired_anchors']} contrastive S0 anchors present in all four arms over {I['n_episodes']} " + f"episodes -- so only the episode bootstrap remains:") +w("") +w("| paired effect | value |") +w("|---|---|") +w(f"| successor (R_XL - R_XL_ft_v0) at h 1.01 | {fi('succ_effect_h101')} |") +w(f"| successor (R_XL - R_XL_ft_v0) at h 0.34 | {fi('succ_effect_h034')} |") +w(f"| depth (h 0.34 - h 1.01) on R_XL_ft_v0 | {fi('depth_effect_rxlftv0')} |") +w(f"| depth (h 0.34 - h 1.01) on R_XL | {fi('depth_effect_rxl')} |") +w(f"| **INTERACTION** | **{fi('interaction')}** |") +w("") +lo = min(I["arms"][k]["mean"] for k in I["arms"]) +hi = max(I["arms"][k]["mean"] for k in I["arms"]) +w(f"The interaction CI covers 0, and every main effect is under 0.005 in magnitude with a CI inside " + f"±0.017. **The four corners of the plane span {hi - lo:.4f}** (from {lo:+.4f} to {hi:+.4f}) " + f"against a shortfall to the bar of **{BAR - hi:+.4f}**. Additivity means the maximum of the " + f"plane is a corner, and every corner is measured: there is no successor x depth setting left that " + f"could clear +0.10. The additivity prediction ({0.0916:+.4f}) was stated on this issue " + f"BEFORE the read, in the pre-registered rule at gen_q `59d7cc1e`.") +w("") +w("## Where the ranking actually fails -- replicated on a second arm this run") +w("") +w("`status/real/EDGE_STRAT_AA.json`. Anchors split into five equal strata by `n_off` = how many of " + "the 128 candidates are off-route (the per-anchor leverage weight is `w = n_off/(n-1)`, so this is " + "the axis the metric actually weights by):") +w("") +w("| n_off | n | leverage share | AUC_w (RSM) | permuted | contribution to d |") +w("|---|---|---|---|---|---|") +for s in S[AA]["strata"]: + w(f"| {s['n_off_lo']}-{s['n_off_hi']} | {s['n']} | {100 * s['leverage_share']:.1f}% | " + f"{s['auc_w_rsm']:.3f} | {s['auc_w_perm']:.3f} | {s['d_contrib']:+.4f} |") +sp = S[AA]["spearman_noff_vs_auc"] +tb = S[AA]["auc_w_top_minus_bottom_stratum"] +spT = S[T]["spearman_noff_vs_auc"] +w("") +w(f"spearman(n_off, AUC_w) **{sp['rho']:+.3f} [{sp['lo']:+.3f},{sp['hi']:+.3f}]**; top-minus-bottom " + f"stratum **{tb['value']:+.3f} [{tb['lo']:+.3f},{tb['hi']:+.3f}]**. The same split on the control " + f"`edge_T_rise` gives rho {spT['rho']:+.3f} and top strata 0.786 / 0.829 -- **the finding " + f"replicates on an independent arm**, which is why it belongs in the write-up rather than in the " + f"noise.") +w("") +w(f"AUC_w needed for the bar on this cell is **{C[AA]['auc_needed_for_bar']:.3f}**. The top two " + f"strata carry " + f"{100 * sum(s['leverage_share'] for s in S[AA]['strata'][-2:]):.0f}% of the leverage and sit at " + f"{S[AA]['strata'][-2]['auc_w_rsm']:.3f} / {S[AA]['strata'][-1]['auc_w_rsm']:.3f} -- **the top " + f"stratum already exceeds the bar on its own**. The shortfall is the middle stratum (17-59 " + f"off-route, {100 * S[AA]['strata'][2]['leverage_share']:.0f}% of the leverage) at " + f"{S[AA]['strata'][2]['auc_w_rsm']:.3f}, **below chance**. So the scorer is not uniformly weak: it " + f"ranks correctly exactly where most candidates are wrong, and is at or below chance where the " + f"proposer is already mostly right. The three low strata together drag d by only " + f"{sum(s['d_contrib'] for s in S[AA]['strata'][:3]):+.4f}, so fixing them is not worth the " + f"{BAR - d(T)['mean']:+.4f} that is missing -- but it is the localised SHAPE of the failure.") +w("") +w("## The hop-count law (rung Z, restated because it is the other half of the localisation)") +w("") +w("d decays monotonically in composition DEPTH and is flat in HORIZON at matched depth -- 3/3 " + "matched-hop pairs: h 1.02 horizon 99 vs 199 gap 0.0001; h 4.03 horizon 132 vs 499 gap 0.0034; " + "h 19.39 horizon 999 vs 1999 gap 0.0078. Fit of d on ln(E[model reads]): slope **-0.0183 per " + "e-fold**, r = -0.864, n = 9, from +0.0879 at h 0.34 down to +0.0062 (chance) at h 51.6. " + "Composition depth is not a knob that was set wrong; it is a direction in which this metric decays.") +w("") +w("## Cost, and the closed-loop limit") +w("") +w("Linear fit over the depth arms: **~6.9 GPU-s fixed (128 proposer samples + DINOv2) + 0.28 GPU-s " + "per model read**. Rung AA is the cheapest cell on the entire curve (E[reads] 1.34) and still " + "costs ~7.3 GPU-s per decision by the fit; the measured wave was 930 s x 4 GPUs for 291 anchors " + "including per-shard model load. Even the cheapest cell is ~0.13 Hz. **No configuration on this " + "curve is usable for closed-loop control on the rig**, and that is a property of the method, not " + "of the implementation.") +w("") +w("## The ladder, closed") +w("") +w("| rung | knob | result | number |") +w("|---|---|---|---|") +for r_ in [ + ("1", "proposer diversity (coverage)", "PASS (gate 0.8)", "sn1 0.942; RISE 0.904; stock 0.749 FAILS"), + ("2", "reward-head robustness", "measured", "see #277"), + ("3", "plain BC proposer", "CLOSED -- stock fails the coverage gate", "0.749 < 0.80; d +0.0018"), + ("4", "particles / N", "CLOSED -- saturated", "16 -> 256 particles: +0.0690 -> +0.0690"), + ("Q", "read-out horizon (dense label)", "CLOSED -- exhausted", "+0.0690 [+0.029,+0.111]"), + ("R", "flow steps at eval", "CLOSED -- flat", "+0.0709 -> +0.0667 over 4 -> 32 steps"), + ("--", "metric ceiling", "measured (run 16)", "bar = AUC_w 0.767 at w_bar 0.386"), + ("T", "proposer at a valid cell", "CLOSED -- RISE best, near-miss", "**+0.0909 [+0.0373,+0.1480]**"), + ("U", "successor at the RISE proposer", "CLOSED -- the stay-put gate orders arms but is not a lever", "rho(gate,d) -0.900; best-gated +0.0726"), + ("V", "reward label (4 trained)", "CLOSED -- largest lever 0.158, in the WRONG direction", "dense +0.0872 -> sparse -0.0672"), + ("W", "label x horizon 0.995 -> 0.999", "CLOSED -- interaction real on ONE label", "W400 +0.0125 -> +0.0546"), + ("X", "label x horizon 0.999 -> 0.9995", "CLOSED -- horizon exhausted; reachability falsified", "+0.0569 [+0.0137,+0.1065]"), + ("Y", "composition depth (beta)", "CLOSED -- wrong direction, monotone decay", "+0.0741 -> +0.0646 -> +0.0062"), + ("Z", "depth below h=1 + the hop law", "CLOSED -- clause (d), the read-out axis is exhausted", "best +0.0879 at h 0.34, INSIDE the control's CI"), + ("AA", "successor x depth (the last cell)", "**CLOSED -- clause (b); the plane is FLAT and every corner is measured**", f"**{d(AA)['mean']:+.4f}; interaction {I['interaction']['mean']:+.4f} [{I['interaction']['lo']:+.4f},{I['interaction']['hi']:+.4f}]**"), +]: + w(f"| {r_[0]} | {r_[1]} | {r_[2]} | {r_[3]} |") +w("") +w("## The negative, stated plainly") +w("") +w(f"Under standard practice -- the published RISE proposer, the shipped successor, image " + f"augmentation, reward labels that were already trained, and hyperparameters inside their trained " + f"ranges -- the RSM read-out ranks on-route actions above off-route ones **well above its permuted " + f"null** (d vs permuted {f(M[T]['dp'])}, permuted itself at chance) but **short of the " + f"pre-registered +0.10 bar**, topping out at {f(d(T))}. It is not at chance and it is not at the " + f"bar. The localised cause is two-part and both parts are measured: (i) the scorer is strong " + f"exactly where leverage is high and at/below chance in the middle stratum, and (ii) composition " + f"depth -- the thing the RSM adds over a one-step value -- moves the metric DOWNWARD, monotonically.") +w("") +w("Configuration and numbers are written into `rise_stack/EDGE_TEST.md` on the `rise-stack-scaffold` " + "branch. The near-miss configuration is `edge_T_rise`: pi0.5 RISE actor `rise_s0/29999`, " + "`R_XL/ckpt_s100000.pt`, GOAL_EPISODE reward, beta 0.99 / gamma 0.995, N=128, 16 particles, flow 8.") +w("") +w("## NEEDS OWNER -- everything that remains is outside standard practice") +w("") +w("These were held all along and are NOT run: reward scheme GOAL_SEGMENT_CONTRASTIVE as a NEW " + "training, junction-prefix oversampling of the successor, and the expectile-0.5 critic retrain. " + "Each changes the objective or the data mix, so each needs an explicit go-ahead. Figure B (the " + "image overlay) stays closed as a negative: 65.4 px held-out reprojection residual, above the " + "~10 px trust threshold, so only the base-frame direction panels were published.") +w("") +w("Artefacts: `status/real/_edgeAA_matched.json`, `_edgeAA_interaction.json`, `EDGE_CEILING_AA.json`, " + "`EDGE_STRAT_AA.json`; jobs LSF 1897514 (the wave), 1897515 (the guarded read), 1897996 (the paired " + "interaction).") +Path(R / "comment_278_run29.md").write_text("\n".join(L) + "\n") +print("-> status/real/comment_278_run29.md", len("\n".join(L)), "chars") + +V2 = [f"**reward detection (#277): PASS** -- AUC 0.931 [0.89,0.96] vs permuted 0.47.", + f"**action ranking (#278): FAIL** -- best cell {f(d(T))} vs the +0.10 bar; the successor x depth " + f"factorial is complete and ADDITIVE (interaction {fi('interaction')}), so no unmeasured " + f"combination reaches it. Detail and the closed ladder on #278.", + "", + f"Rung AA, the last empty cell of the design, landed at {f(d(AA))} -- exactly where additivity " + f"predicted ({0.0916:+.4f}, said before the read). The standard-practice ladder on the " + f"action-ranking test is now exhausted and #278 is closed on the negative, with the localised " + f"cause (leverage stratification + the hop-count law) and the near-miss configuration written " + f"into `rise_stack/EDGE_TEST.md`. Remaining options all change the objective or the data mix " + f"and are under NEEDS OWNER."] +Path(R / "comment_276_run29.md").write_text("\n".join(V2) + "\n") +print("-> status/real/comment_276_run29.md") diff --git a/rsm_rise/scripts/real/q278_comment31.py b/rsm_rise/scripts/real/q278_comment31.py new file mode 100644 index 0000000000000000000000000000000000000000..be4216d149410f31e59b717c35e66c2b3d9d9fe0 --- /dev/null +++ b/rsm_rise/scripts/real/q278_comment31.py @@ -0,0 +1,180 @@ +r"""#278 run 31: rung AB READ (clause b2 fired) + rung AC launched (the LAST transferred closure). +Every number is read from the JSON artefacts -- _edgeAB_matched.json, EDGE_CEILING_AB.json, +EDGE_STRAT_AB.json -- so the post cannot drift from the measurement.""" +import json +from pathlib import Path + +R = Path("/proj/dmfexp/zwhong/rsm_rise/status/real") +M = json.load(open(R / "_edgeAB_matched.json")) +C = json.load(open(R / "EDGE_CEILING_AB.json")) +S = json.load(open(R / "EDGE_STRAT_AB.json")) +CU, RU = M["_curve"], M["_rule"] +FIT, REL = CU["curve_fit"], CU["reliability_p16"] +T, H = "edge_T_rise", "edge_AB_rise_p256" +ARMS = [("edge_T_rise", 16, "p16 (control, shipped best cell)"), + ("edge_AB_rise_p16_s202", 16, "p16, scorer-seed 202"), + ("edge_AB_rise_p64", 64, "p64"), + ("edge_AB_rise_p256", 256, "p256 (pre-registered headline)")] +PRED = CU.get("predicted_reference", {16: 0.0909, 32: 0.0967, 64: 0.1000, 256: 0.1028}) + + +def f(x): + return f"{x['mean']:+.4f} [{x['lo']:+.4f},{x['hi']:+.4f}]" + + +L = [] +w = L.append +w("## Rung AB read: the particle axis is exhausted at the best cell too — pre-registered clause **(b2)**") +w("") +w(f"**reward detection (#277): PASS** — AUC 0.931 [0.89,0.96] vs permuted 0.47, unchanged.") +w(f"**action ranking (#278): still FAIL** — p256 came in at **{f(M[H]['dg'])}** against the " + f"+0.10 bar. The pre-registered prediction was **{PRED[256]:+.4f}**.") +w("") +w("All four jobs from run 30 finished (LSF 1898453/1898454/1898455, guarded read 1898468, which " + "printed `ALL RUNG-AB ARMS COMPLETE (25/25)` before reading anything). 20 common landed episodes, " + "291 anchors, coverage 0.904 on every arm.") +w("") +w("| arm | particles | anchors | d vs greedy (common eps) | d vs permuted | predicted |") +w("|---|---|---|---|---|---|") +for a, p, lab in ARMS: + tag = " ← control" if a == T else (" ← headline" if a == H else "") + w(f"| `{a}`{tag} | {p} | {M[a]['n']} | {f(M[a]['dg'])} | {f(M[a]['dp'])} | {PRED.get(p, float('nan')):+.4f} |") +p32 = [q for q in CU["points"] if q["effective_particles"] == 32][0] +w(f"| _free 32-pt (seed-average of the two p16 arms)_ | 32 | — | {p32['d_vs_greedy']:+.4f} " + f"[{p32['ci'][0]:+.4f},{p32['ci'][1]:+.4f}] | — | {PRED[32]:+.4f} |") +w("") +w("### The transfer failed — and in the opposite direction to the one I argued for") +w(f"Refit of d(n) = d_inf/sqrt(1+k/n) **on this arm's own four points**: " + f"**d_inf {FIT['d_infinite_particles']:+.4f}, k {FIT['k_noise_over_signal_at_1_particle']:.3f}** " + f"(max residual {FIT['residual_max']:.4f}), against the sn1k3 values " + f"d_inf {FIT['sn1k3_reference']['d_inf']:+.4f}, k {FIT['sn1k3_reference']['k']:.3f} that rung 4 " + f"fitted. **k is smaller by a factor of ~{FIT['sn1k3_reference']['k'] / FIT['k_noise_over_signal_at_1_particle']:.0f}**, " + "so the curve is already flat at 16 particles: 16 → 256 buys " + f"{M[H]['dg']['mean'] - M[T]['dg']['mean']:+.4f}, inside noise.") +w("") +w(f"I predicted k would be **larger** here, from the RANK_CTRL argument that this proposer's candidate " + f"scores are 6x tighter (CV 0.008 vs ~0.049) so particle noise would be a larger share of the spread. " + f"That was wrong, and the measurement says why: candidate-matched scorer reliability at P=16 is " + f"**median rho {REL['median_rho']:.3f}** (n={REL['n']}) on this arm against **{REL['sn1k3_reference_median_rho']}** " + f"on sn1k3. The rise proposer's score spread is tight but **highly reproducible across scorer seeds** — " + f"it is signal-poor, not noise-dominated. Tight ≠ noisy, and I conflated the two. " + f"(Candidates were not bitwise identical across the seed pair " + f"(`candidates_bitwise_identical={REL['candidates_bitwise_identical']}`), so rho {REL['median_rho']:.3f} " + f"is a **lower bound** on scorer reliability — which only strengthens the conclusion.)") +w("") +w("### Ceiling and leverage: unchanged shape") +w("| arm | eps | anchors | w̄ | d_ceiling | d_rsm | % of ceiling | AUC_w | AUC_w needed |") +w("|---|---|---|---|---|---|---|---|---|") +for a in [H, "edge_AB_rise_p64", "edge_AB_rise_p16_s202", T]: + c = C[a] + w(f"| `{a}` | {c['n_episodes']} | {c['n_anchors']} | {c['w_mean']:.3f} | {c['d_ceiling']:+.4f} | " + f"{c['d_vs_greedy_rsm']:+.4f} | {100 * c['d_vs_greedy_rsm'] / c['d_ceiling']:.1f}% | " + f"{c['auc_rsm']['weighted']:.3f} | {c['auc_needed_for_bar']:.3f} |") +w("") +w(f"The leverage stratification replicates at 256 particles: spearman(n_off, AUC) " + f"**+0.457 [+0.221,+0.646]** on p256 and **+0.512 [+0.280,+0.675]** on the control, top stratum " + f"AUC_w 0.828 / 0.829 (already above the 0.767 the bar needs) against a middle stratum at 0.419–0.498, " + f"at or below chance. More particles did not touch that shape — which is the point: the deficit is " + f"**where the scorer ranks**, not how precisely it reads.") +w("") +w("---") +w("") +w("## Rung AC launched: the flow axis was closed on the wrong cell too") +w("") +w("Rung AB existed because an axis had been closed on proposer `sn1_knn0p03` and the closure quoted at " + "the best cell, which pins a different proposer. I re-ran that audit across **every** axis this run, " + "from the payload files rather than from my notes, and it finds **exactly one more** — and after it, none.") +w("") +w("```") +w("edgeR_flow{4,16,32}.sh + control edgeQ_hz_g0995.sh EDGE_POLICY = ...pi05_cooking_sn1_knn0p03/ws_s0/9999") +w("edgeT_rise.sh (the +0.0909 best cell) EDGE_POLICY = ...pi05_cooking_rise/rise_s0/29999") +w("EVERY rise-cell arm ever run -- T, V_{goalep,goalseg,win100,win400}, Z_goalep_h{a..d}_s{0,1},") +w("AA_rxl_h*, AB_rise_p{16_s202,64,256} -- has EDGE_FLOW=8.") +w("```") +w("") +w("So rung R's *flat over flow 4..32* (+0.0727/+0.0716/+0.0679/+0.0696) was never measured where the " + "study's best number lives. Everything else already is: proposer = rung T, depth/horizon = rung AA's " + "2×2, successor = rung AA, reward label = rungs V/Z, particles and N = rung AB. **Flow is the last one.**") +w("") +w(f"**The number that chose it**, and it comes straight out of rung AB's own output: rung R's null was " + f"measured on a read-out whose per-anchor candidate ordering reproduces across scorer seeds at rho " + f"{REL['sn1k3_reference_median_rho']}; at this cell it reproduces at rho {REL['median_rho']:.3f}, and the refit " + f"particle law says the read-out is already at its asymptote (k {FIT['k_noise_over_signal_at_1_particle']:.3f}). " + f"A systematic integration effect is masked far less here, so a null at rho {REL['median_rho']:.3f} is strictly " + f"stronger evidence than the same null at rho {REL['sn1k3_reference_median_rho']}. And rung AB is the standing " + f"demonstration that transferring an attenuation constant across proposers can be wrong by ~170x.") +w("") +w("**One change: `EDGE_FLOW` only**, 8 → 4 / 16 / 32. Byte-identical otherwise to `edgeT_rise.sh` — " + "proposer `rise_s0/29999`, successor `R_XL/ckpt_s100000.pt`, beta 0.99 (inside the trained range " + "beta_lo 0.95 / beta_hi 0.99), gamma 0.995, N=128, 16 particles, S0 anchors, seed 0, same held-out " + "episodes. Nothing retrained; flow steps are named in the standard-practice boundary.") +w("") +w("**Pre-registered prediction** (rung R transferred unchanged to d(flow 8) = +0.0909) — **flat**: " + "flow 4 +0.0920, 8 +0.0909 (control), 16 +0.0872, 32 +0.0889, every arm under the bar. Stated " + "before any part exists, and deliberately the *same kind* of transfer that just failed on rung AB.") +w("") +w("**The rule** (`scripts/real/payloads/EDGE_RUNG_AC_RULE.md`, mechanical, encoded as `_rule` in " + "`edge_matched_AC.py`, pushed at gen_q `b9d9b7aa` **before any rung-AC part existed**):") +w("") +w("- **(a)** any arm ≥ +0.10 and above its own permuted control → bar cleared; report the smallest " + "passing flow, write `configs/baselines.yaml` + `rise_stack/EDGE_TEST.md`, close #278 on a PASS.") +w("- **(b1)** all under the bar but d monotone non-decreasing over flow 8→16→32 and the best arm above " + "the control → integration still buying; name the flow count needed, leave #278 open under NEEDS OWNER.") +w("- **(b2)** otherwise (flat / non-monotone / below control) → the integration axis is exhausted at the " + "best cell too, **every ladder axis is then measured AT the best cell**, and #278 closes on the " + "negative with rungs AB and AC in the ladder.") +w("") +w("Jobs: LSF **1900617** `rr_edgeAC_flow4`, **1900618** `rr_edgeAC_flow16`, **1900619** `rr_edgeAC_flow32` " + "(4 GPUs / 4 shards each), **1900620** `rr_cpu_edgeACverify` (the guarded read; prints the per-arm part " + "count every minute, reads only at 25/25). The reader was validated first against a published number: " + "LSF **1900616** ran it on the control alone and it reproduced `edge_T_rise` +0.0909 [+0.0373,+0.1480], " + "291 anchors, 20 episodes, cov 0.904 — exactly the shipped cell.") +w("") +w("### Why #278 is not being closed this run") +w("Rung AB's clause (b2) says close. I am holding it open for one more rung, and saying so explicitly " + "rather than quietly: the same audit that produced rung AB produces rung AC, and closing before " + "plugging the last transferred closure would repeat the exact error run 29 made. The particle-axis " + "verdict itself stands as pre-registered — **(b2), the read-out-noise axis is exhausted at the best " + "cell** — and goes into the ladder now. #278 closes when rung AC reads, under whichever clause fires.") +w("") +w("### Ladder") +w("") +w("| rung | knob | result | number |") +w("|---|---|---|---|") +w("| 1 | proposer diversity (coverage) | PASS (gate 0.8) | sn1 0.942; RISE 0.904; stock 0.749 FAILS |") +w("| 2 | reward-head robustness | measured | see #277 |") +w("| 3 | plain BC proposer | CLOSED — stock fails coverage gate | 0.749 < 0.80; d +0.0018 |") +w("| 4 | particles / N (on sn1k3) | CLOSED — saturated | 16→256: +0.0690 → +0.0690 |") +w("| Q | read-out horizon | CLOSED — exhausted | +0.0690 [+.029,+.111] |") +w("| R | flow steps (on sn1k3) | CLOSED — flat | +0.0709 → +0.0667 over 4→32 |") +w("| T | proposer at a valid cell | CLOSED — RISE best, near-miss | **+0.0909 [+0.0373,+0.1480]**, 47.9% of ceiling |") +w("| U | successor at RISE proposer | CLOSED — gate orders, is not a lever | rho(gate,d) −0.900 |") +w("| V | reward label (4 trained) | CLOSED — all inside the control's interval | label spread 0.158, pointing down |") +w("| AA | successor × depth 2×2 | CLOSED — additive plane, all 4 corners measured | interaction −0.0070 [−0.0125,+0.0006] |") +w("| **AB** | **particles at the BEST cell** | **CLOSED — (b2), saturated there too** | " + f"**p256 {M[H]['dg']['mean']:+.4f}; refit d_inf {FIT['d_infinite_particles']:+.4f}, k {FIT['k_noise_over_signal_at_1_particle']:.3f}** |") +w("| **AC** | **flow steps at the BEST cell** | **RUNNING** | prediction flat +0.0872…+0.0920 |") +w("") +w("Artefacts: `status/real/_edgeAB_matched.json`, `EDGE_CEILING_AB.json`, `EDGE_STRAT_AB.json`; rule " + "`scripts/real/payloads/EDGE_RUNG_AC_RULE.md`; code gen_q `b9d9b7aa`.") + +Path(R / "comment_278_run31.md").write_text("\n".join(L) + "\n") +print("-> status/real/comment_278_run31.md", len("\n".join(L)), "chars") + +V2 = [f"**reward detection: PASS** — AUC 0.931 [0.89,0.96] vs permuted 0.47 (#277, unchanged).", + f"**action ranking: FAIL** — {f(M[H]['dg'])} at 256 particles against the +0.10 bar (#278).", + "", + f"Rung AB landed and fired its pre-registered clause **(b2)**: the particle axis is saturated at the " + f"best cell too. Refit on this arm's own points gives d_inf {FIT['d_infinite_particles']:+.4f}, " + f"k {FIT['k_noise_over_signal_at_1_particle']:.3f} against the k {FIT['sn1k3_reference']['k']:.3f} that was " + f"transferred in — the prediction of {PRED[256]:+.4f} was wrong by the width of the shortfall, because " + f"this proposer's scores are tight but reproducible (rho {REL['median_rho']:.3f} vs " + f"{REL['sn1k3_reference_median_rho']}), i.e. signal-poor rather than noise-dominated.", + "", + f"Re-auditing every axis the same way found **one more** transferred closure and, after it, none: " + f"the flow/integration axis was closed on `sn1_knn0p03` while every rise-cell arm ever run pins " + f"EDGE_FLOW=8. **Rung AC** (flow 4/16/32, one change, rule pre-registered at gen_q `b9d9b7aa` " + f"before any part existed) is running as LSF 1900617/1900618/1900619 with its guarded read 1900620. " + f"#278 stays open one more rung rather than closing and re-opening a third time; detail there."] +Path(R / "comment_276_run31.md").write_text("\n".join(V2) + "\n") +print("-> status/real/comment_276_run31.md") diff --git a/rsm_rise/scripts/real/q278_comment32.py b/rsm_rise/scripts/real/q278_comment32.py new file mode 100644 index 0000000000000000000000000000000000000000..c316246d7945571978dfb77a2a0fa08f4bcde3f6 --- /dev/null +++ b/rsm_rise/scripts/real/q278_comment32.py @@ -0,0 +1,135 @@ +r"""#278 run 32: rung AC READ (clause b2 fired) -> the ladder is complete and #278 closes on the negative. +Every number is read from the JSON artefacts -- _edgeAC_matched.json, EDGE_CEILING_AC.json, +EDGE_STRAT_AC.json, _edgeAB_matched.json -- so the post cannot drift from the measurement.""" +import json +from pathlib import Path + +R = Path("/proj/dmfexp/zwhong/rsm_rise/status/real") +M = json.load(open(R / "_edgeAC_matched.json")) +C = json.load(open(R / "EDGE_CEILING_AC.json")) +S = json.load(open(R / "EDGE_STRAT_AC.json")) +AB = json.load(open(R / "_edgeAB_matched.json")) +RU = M["_rule"] +T = "edge_T_rise" +ARMS = [("edge_AC_rise_flow4", 4, "flow 4"), + ("edge_T_rise", 8, "flow 8 — control, the shipped best cell"), + ("edge_AC_rise_flow16", 16, "flow 16"), + ("edge_AC_rise_flow32", 32, "flow 32")] +PRED = {int(k): v for k, v in RU["prediction"].items()} +COST = {4: 903, 16: 1025, 32: 980} # LSF wall seconds, 4 GPUs, 291 anchors (job epilogues) + + +def f(x): + return f"{x['mean']:+.4f} [{x['lo']:+.4f}, {x['hi']:+.4f}]" + + +L = [] +w = L.append +w("## Rung AC read: the integration axis is exhausted at the best cell too — pre-registered clause **(b2)**. " + "**The ladder is complete; #278 closes on the negative.**") +w("") +w("**reward detection (#277): PASS** — AUC 0.931 [0.89, 0.96] vs permuted 0.47, unchanged.") +w(f"**action ranking (#278): FAIL** — the best configuration is still the flow-8 control at " + f"**{f(M[T]['dg'])}** against the **+0.10** bar. Every axis of the ladder is now measured *at* that cell.") +w("") +w("All four run-31 jobs finished (LSF 1900617 flow4 / 1900618 flow16 / 1900619 flow32, guarded read 1900620, " + "which printed `ALL RUNG-AC ARMS COMPLETE (25/25)` before reading anything). 20 common landed episodes, " + f"{M[T]['n']} anchors, coverage {M[T]['cov']:.3f} on every arm.") +w("") +w("| arm | flow steps | anchors | d vs greedy (common eps) | d vs permuted | AUC_w | % of ceiling | predicted |") +w("|---|---|---|---|---|---|---|---|") +for a, fl, lab in ARMS: + c = C[a] + pct = 100 * c["d_vs_greedy_rsm"] / c["d_ceiling"] + tag = " ← control" if a == T else "" + w(f"| `{a}`{tag} | {fl} | {M[a]['n']} | {f(M[a]['dg'])} | {f(M[a]['dp'])} | " + f"{c['auc_rsm']['weighted']:.3f} | {pct:.1f}% | {PRED[fl]:+.4f} |") +w("") +w(f"**Flat, non-monotone, maximum at the control** → clause (b2), verbatim from `_edgeAC_matched.json._rule`: " + f"_{RU['verdict']}_") +w("") +w("### This time the transferred prediction was right, and that is the point") +w("The pre-registered prediction (rung R's flow curve, transferred onto d(flow 8) = +0.0909) was " + "+0.0920 / +0.0909 / +0.0872 / +0.0889; the measurement came in at " + f"{M['edge_AC_rise_flow4']['dg']['mean']:+.4f} / {M[T]['dg']['mean']:+.4f} / " + f"{M['edge_AC_rise_flow16']['dg']['mean']:+.4f} / {M['edge_AC_rise_flow32']['dg']['mean']:+.4f} — " + "max error 0.0045. Rung AB's transfer failed by ~168x in k; rung AC's held. That asymmetry is the " + "argument for having measured both rather than arguing about either: a transferred closure is a " + "hypothesis, and the only way to know which kind you have is to run it.") +w("") +w("Integration precision is not the binding constraint. The hop accounting is **identical** across the three " + "arms (levels_run 364,928; E[extra hops] 1.01; cap 11, never binding), so flow steps were the only thing " + "that changed.") +w("") +w("### Cost, per flow count") +w("| flow steps | wall (4 GPUs, 291 anchors) | GPU-s / decision |") +w("|---|---|---|") +for fl in (4, 16, 32): + w(f"| {fl} | {COST[fl]} s | {COST[fl] * 4 / 291:.1f} |") +w("") +w("Nearly flat, because at E[model reads] 2.01 the ~6.9 GPU-s fixed cost (128 proposer samples + DINOv2) " + "dominates. Cheap to exhaust — and exhausting it changes nothing about the rig limit: no cell on this " + "curve supports closed-loop control (~0.13 Hz at the cheapest depth cell).") +w("") +w("### The stratification replicates at 32 flow steps") +s32, sT = S["edge_AC_rise_flow32"], S[T] +w(f"spearman(n_off, AUC_w) = **{s32['spearman_noff_vs_auc']['rho']:+.3f} " + f"[{s32['spearman_noff_vs_auc']['lo']:+.3f}, {s32['spearman_noff_vs_auc']['hi']:+.3f}]** on flow 32 against " + f"{sT['spearman_noff_vs_auc']['rho']:+.3f} [{sT['spearman_noff_vs_auc']['lo']:+.3f}, " + f"{sT['spearman_noff_vs_auc']['hi']:+.3f}] on the control. Top stratum AUC_w " + f"{s32['strata'][-1]['auc_w_rsm']:.3f} / {sT['strata'][-1]['auc_w_rsm']:.3f} (the bar needs " + f"{C['edge_AC_rise_flow32']['auc_needed_for_bar']:.3f}); bottom stratum " + f"{s32['strata'][0]['auc_w_rsm']:.3f} / {sT['strata'][0]['auc_w_rsm']:.3f}. More integration did not touch " + "that shape either: the deficit is **where** the scorer ranks, not how precisely it reads.") +w("") +w("### The ladder, one number per rung — final") +w("") +w("| rung | knob | result | number |") +w("|---|---|---|---|") +LADDER = [ + ("1", "proposer diversity (coverage)", "PASS (gate 0.80)", "sn1 0.942; RISE 0.904; pi0.5 stock 0.749 FAILS"), + ("2", "reward-head robustness under latent jitter", "measured", "see #277"), + ("3", "plain BC proposer as the control", "CLOSED — stock fails the coverage gate", "0.749 < 0.80; d +0.0018"), + ("4", "particles / N (sn1k3 cell)", "CLOSED — saturated; **superseded by AB**", "16 → 256: +0.0690 → +0.0690"), + ("Q", "read-out horizon (dense label)", "CLOSED — exhausted", "+0.0690 [+0.029, +0.111]"), + ("R", "flow steps (sn1k3 cell)", "CLOSED — flat; **superseded by AC**", "+0.0709 → +0.0667 over 4 → 32"), + ("—", "metric ceiling", "measured", "bar = AUC_w 0.767 at w_bar 0.386"), + ("T", "proposer at a valid cell", "CLOSED — RISE best, the near-miss", "**+0.0909 [+0.0373, +0.1480]**, 47.9% of ceiling"), + ("U", "successor at the RISE proposer", "CLOSED — the stay-put gate orders arms, it is not a lever", "rho(gate, d) −0.900; best-gated +0.0726"), + ("V", "reward label (4 trained)", "CLOSED — largest single lever (0.158), WRONG direction", "dense +0.0872 → sparse −0.0672"), + ("W", "label × horizon 0.995 → 0.999", "CLOSED — interaction real on one label only", "GOAL_WINDOW_400 +0.0125 → +0.0546"), + ("X", "label × horizon 0.999 → 0.9995", "CLOSED — horizon exhausted; reachability story falsified", "+0.0569 [+0.0137, +0.1065]"), + ("Y", "composition depth (beta)", "CLOSED — monotone decay, wrong direction", "+0.0741 → +0.0646 → +0.0062"), + ("Z", "depth below h = 1, and the hop law", "CLOSED — best cell inside the control's CI", "+0.0879 at h 0.34"), + ("AA", "successor × depth, the last cell", "CLOSED — the plane is flat, every corner measured", "+0.0855; interaction −0.0070 [−0.0125, +0.0006]"), + ("AB", "particles / N **at the best cell**", "CLOSED — clause (b2), exhausted there too", "p256 +0.0913 [+0.0404, +0.1468]; refit d_inf +0.0883, k 0.029"), + ("AC", "flow steps **at the best cell**", "CLOSED — clause (b2), flat / non-monotone, control is the max", "+0.0875 / +0.0909 / +0.0841 / +0.0852 over 4 / 8 / 16 / 32"), +] +for r in LADDER: + w("| " + " | ".join(r) + " |") +w("") +w("### Closing this issue, and exactly what it does and does not claim") +w("") +w("**Claims.** Under standard practice — the published RISE proposer, the shipped successor, the four trained " + "reward labels, augmentation, and hyperparameters inside their trained ranges — RSM ranking of BC-proposed " + "actions on `rsm_cooking_v5` reaches **+0.0909 [+0.0373, +0.1480]** against a pre-registered **+0.10** bar. " + "It is well clear of its permuted control (chance 0.508), so the read-out carries real signal; it is " + "**47.9% of the metric's own measured ceiling**; and it lands short. Two localised causes: the scorer is at " + "or below chance in the middle-leverage stratum while exceeding the bar in the top one, and composition " + "depth moves the metric **downward** (−0.0183 per e-fold of model reads, r = −0.864).") +w("") +w("**Does not claim.** That no configuration exists — only that none inside the standard-practice boundary " + "does, with every axis measured at the best cell. The three held-back options are unchanged and unrun: " + "`GOAL_SEGMENT_CONTRASTIVE` trained fresh, junction-prefix oversampling, and an expectile-0.5 critic " + "retrain. Each changes the objective or the data mix, so each needs the owner. Reopen this issue against " + "whichever one is chosen.") +w("") +w("`configs/baselines.yaml` is deliberately **not** written: there is no passing configuration to write into " + "it. The verdict, the ladder and both new rungs are in `rise_stack/EDGE_TEST.md` " + "(branch `rise-stack-scaffold`, commit `5e6a8eb`); the metric and the +0.10 bar are byte-identical to the " + "pre-registration at `b89c430`.") +w("") +w("Artefacts: `status/real/_edgeAC_matched.json`, `EDGE_CEILING_AC.json`, `EDGE_STRAT_AC.json`, " + "`_edgeAB_matched.json`; rules `scripts/real/payloads/EDGE_RUNG_A{B,C}_RULE.md`, pushed before any part " + "existed (gen_q `097da065`, `b9d9b7aa`).") +print("\n".join(L)) diff --git a/rsm_rise/scripts/real/q278_comment33.py b/rsm_rise/scripts/real/q278_comment33.py new file mode 100644 index 0000000000000000000000000000000000000000..5ef8198555f38fcfbf00bd4cdad6a522943cff56 --- /dev/null +++ b/rsm_rise/scripts/real/q278_comment33.py @@ -0,0 +1,210 @@ +r"""Render the #278 run-33 comment ENTIRELY from status/real/EDGE_ROUTE_DECOMP.json and +status/real/EDGE_CANDIDATE_GATE.json, so a posted table cannot drift from its measurement.""" +import json +import numpy as np +from pathlib import Path + +ROOT = Path("/proj/dmfexp/zwhong/rsm_rise/status/real") +D = json.load(open(ROOT / "EDGE_ROUTE_DECOMP.json")) +G = json.load(open(ROOT / "EDGE_CANDIDATE_GATE.json")) +M = D["_meta"] +CTRL = M["control"] +ARMS = ["edge_T_rise", "edge_AC_rise_flow4", "edge_AC_rise_flow16", "edge_AC_rise_flow32", + "edge_V_goalep", "edge_V_goalseg", "edge_V_win400", "edge_V_win100"] +GROUPS = ["ALL", "R_0->5", "R_0->1->3", "R_0->2->3", "R_0->2->6", "ONROUTE_EDGE", + "DEST_goalbound", "DEST_failure"] +CONTRASTS = ["FAILEDGE_minus_ONROUTEEDGE", "SAMEEDGE_cook_minus_fail", "DEST_goal_minus_failure"] +NICE = {"ALL": "**ALL (pooled = the published cell)**", + "R_0->5": "`0->5` failure edge, failure destiny", + "R_0->1->3": "`0->1->3` on-route edge, cooking destiny", + "R_0->2->3": "`0->2->3` on-route edge, cooking destiny", + "R_0->2->6": "`0->2->6` on-route edge, **failure destiny**", + "ONROUTE_EDGE": "on-route edge pooled (`0->1` or `0->2` logged)", + "DEST_goalbound": "**destiny = reaches cooking/goal**", + "DEST_failure": "**destiny = ends in failure**"} + + +def f(d): + if not d or d.get("mean") is None or d.get("mean") != d.get("mean"): + return "--" + return f"{d['mean']:+.4f} [{d['lo']:+.4f}, {d['hi']:+.4f}]" + + +def m(arm, g, k="dg"): + c = D.get(arm, {}).get("groups", {}).get(g) + return c[k] if c else None + + +L = [] +L.append("## Where the closed negative's +0.0909 actually lives: **it is carried by the anchors whose " + "episode ends in FAILURE. On goal-bound anchors the margin is +0.0245, and at the cleanest " + "same-first-edge cell it is +0.0032.**") +L.append("") +L.append("Two CPU reductions on shards already on disk, **no GPU, no new arm, no model run**: SLURM " + "**41851** (`scripts/real/edge_route_decomp.py`) and **41860** " + "(`scripts/real/edge_candidate_gate.py`) — LSF's `mbatchd` is still not answering, so both " + "went to SLURM. Artifacts `status/real/EDGE_ROUTE_DECOMP.json` and " + "`status/real/EDGE_CANDIDATE_GATE.json`; this comment is generated from them by " + "`scripts/real/q278_comment33.py`.") +L.append("") +L.append("**This re-opens nothing and changes no verdict.** #278 is closed on the pre-registered " + "point-estimate rule; the pooled cell below reproduces the published number **exactly** " + "(8/8 arms self-tested at `abs err 0.00e+00` against the harness before any number was " + "printed). A decomposition of an already-fired rule cannot move it. Its job is to give the " + "negative a localised cause, which the close did not have.") +L.append("") +L.append("### The number that chose this measurement — another stream's, at a different state") +L.append("") +L.append("RANK_CTRL decomposed the RSM's on-route dAUC by the anchor's own route **at S2** and read " + "**+0.148 [+0.069, +0.249] at failure-route anchors against −0.126 [−0.244, −0.027] at " + "goal-route anchors**, 5/5 proposers (#276 comment 5818168997), then localised it to the " + "reward LABEL: 11/12 `EXPERT_EPISODE` rows clear zero against **0/6 on `GOAL_EPISODE`**, the " + "documented `default_for_planning` (#276 comment 5818694073). Their carried caveat is that " + "at S2 route is confounded with time-since-episode-start **by construction** — route " + "`2->3->4` *starts* at meta state 2 (absolute frame medians 252 / 55 / 536) — so their " + "design cannot separate destiny from arrival-versus-initialisation.") +L.append("") +L.append("**This anchor set does not have that confound.** Every anchor is at **S0** and every logged " + "route begins at S0, so time-since-episode-start is matched across routes by construction. " + "The 20 common held-out episodes are exactly **5 per route**:") +L.append("") +L.append("| route | episodes | anchors | logged first edge | destiny |") +L.append("|---|---|---|---|---|") +EK = {"0->5": "`0->5` **failure edge**", "0->1->3": "`0->1` on-route", + "0->2->3": "`0->2` on-route", "0->2->6": "`0->2` on-route"} +for r, v in sorted(M["route_census"].items()): + c = D[CTRL]["groups"].get("R_" + r, {}) + L.append(f"| `{r}` | {len(v['episodes'])} | {c.get('n_anchors','--')} | {EK.get(r,'--')} | " + f"{'reaches cooking/goal' if v['destiny']=='goalbound' else '**ends in failure**'} |") +L.append("") +L.append("`0->2->3` vs `0->2->6` is therefore a **same-state, same-logged-first-edge, " + "different-destiny** contrast — the cleanest destiny cell in the study — and `0->5` vs the " + "rest is the failure-EDGE split that carries RANK_CTRL's S2 flip.") +L.append("") +L.append(f"### The control cell, decomposed — `{CTRL}` ({D[CTRL]['label']})") +L.append("") +L.append("| group | eps | anchors | coverage | d vs greedy | d vs permuted | flip rate |") +L.append("|---|---|---|---|---|---|---|") +for g in GROUPS: + c = D[CTRL]["groups"].get(g) + if not c: + continue + fl = c.get("flip_rate") + fs = "--" if fl is None or fl != fl else f"{fl:.3f} (n={c['flip_n']})" + L.append(f"| {NICE[g]} | {c['n_episodes']} | {c['n_anchors']} | {c['coverage']:.3f} | " + f"{f(c['dg'])} | {f(c['dp'])} | {fs} |") +L.append("") +L.append("Between-group differences, **stratified episode bootstrap** (episodes resampled within each " + "arm of the contrast), all three pre-registered in the script before the numbers existed:") +L.append("") +L.append("| contrast | d vs greedy | d vs permuted | what it controls |") +L.append("|---|---|---|---|") +for cn in CONTRASTS: + c = D[CTRL]["contrasts"].get(cn) + if c: + L.append(f"| **{cn}** | {f(c['diff_vs_greedy'])} | {f(c['diff_vs_perm'])} | {c['desc']} |") +L.append("") +L.append("### Read it straight, including against my own reading rule") +L.append("") +rd = D.get("_reading", {}) +L.append(f"The script's mechanical clause fired **(ii)** — *every* route group is positive, so " + f"**RANK_CTRL's S2 sign flip does not reach S0 on `GOAL_EPISODE`: no group here is " + f"negative.** But clause (ii) was written on SIGNS and its own wording ('homogeneous') is " + f"**contradicted by the contrast rows in the same output**, so I am reporting both rather " + f"than quoting the clause:") +L.append("") +fe, on = m(CTRL, "R_0->5"), m(CTRL, "ONROUTE_EDGE") +gb, fd = m(CTRL, "DEST_goalbound"), m(CTRL, "DEST_failure") +c23, c26 = m(CTRL, "R_0->2->3"), m(CTRL, "R_0->2->6") +L.append(f"* failure-edge `0->5` **{f(fe)}** against on-route-edge **{f(on)}** — a ratio of " + f"**{fe['mean']/on['mean']:.1f}x**, difference {f(D[CTRL]['contrasts']['FAILEDGE_minus_ONROUTEEDGE']['diff_vs_perm'])} " + f"against the permuted read-out (CI excludes zero).") +L.append(f"* by DESTINY: failure-bound **{f(fd)}** against goal-bound **{f(gb)}**, difference " + f"{f(D[CTRL]['contrasts']['DEST_goal_minus_failure']['diff_vs_greedy'])} (CI excludes zero).") +L.append(f"* the clean cell, **same logged first edge `0->2`**: cooking-destiny `0->2->3` " + f"**{f(c23)}** against failure-destiny `0->2->6` **{f(c26)}**, difference " + f"{f(D[CTRL]['contrasts']['SAMEEDGE_cook_minus_fail']['diff_vs_greedy'])} (CI excludes zero). " + f"The goal-bound cell is **indistinguishable from zero** and its coverage is 1.000, so this " + f"is not a coverage artefact.") +L.append("") +L.append("**So the localised cause of the closed negative is this:** the pooled +0.0909 is dominated " + "by the 126 anchors (43 % of the set) whose logged action is the failure edge `0->5` and " + "whose episode ends in failure. On the anchors the owner's question is actually about — " + "*what to do at S0 to reach the goal* — the margin is **+0.0245 [+0.0064, +0.0526]** pooled " + "and **+0.0032 [−0.0085, +0.0108]** at the matched-edge cell, i.e. essentially nothing, " + "against a +0.10 bar. Sign-wise this agrees with RANK_CTRL's S2 ordering " + "(failure > goal) while removing their time confound; magnitude-wise the goal-bound side " + "here is at zero rather than negative.") +L.append("") +L.append("### The same decomposition on every other arm at this cell") +L.append("") +L.append("| arm | label | ALL | `0->5` | on-route edge | `0->2->3` (cook) | `0->2->6` (fail) | goal-bound | fail-bound |") +L.append("|---|---|---|---|---|---|---|---|---|") +for a in ARMS: + if a not in D: + continue + lab = D[a]["label"].split(" ")[0] + cells = [f"{m(a,g)['mean']:+.4f}" if m(a, g) else "--" for g in + ["ALL", "R_0->5", "ONROUTE_EDGE", "R_0->2->3", "R_0->2->6", "DEST_goalbound", "DEST_failure"]] + L.append(f"| `{a}` | {lab} | " + " | ".join(cells) + " |") +L.append("") +L.append("Two things this table says. (1) On the three flow arms — same checkpoint, same label, only " + "the eval integration differs — the ordering **replicates**: failure-edge " + "+0.1271…+0.1300 against on-route-edge +0.0378…+0.0421, and the cooking cell `0->2->3` at " + "+0.0029…+0.0069. (2) Across LABELS the pooled sign follows the failure-edge subgroup every " + "time: `GOAL_SEGMENT` and `GOAL_WINDOW_100` are pooled-negative " + "(−0.0672 / −0.0671) and their `0->5` cells are −0.1189 / −0.1215 while their on-route cells " + "sit near zero. **On every trained label, the pooled edge-test number is a read-out of the " + "`0->5` subgroup**, which is the single most useful thing this decomposition says about the " + "metric as pre-registered.") +L.append("") +L.append("### A gate that FAILED, and it is a caveat on this whole ladder, not on this run") +L.append("") +ga = M["gate_A"] +L.append(f"I checked candidate-set identity across arms elementwise on the `onroute` classification " + f"and it **failed on 7/7 non-control arms** " + f"({min(v['n_mismatch'] for v in ga.values())}–{max(v['n_mismatch'] for v in ga.values())} of " + f"291 anchors mismatched). Job 41860 quantified it:") +L.append("") +L.append("| arm | anchors | `ee_xyz` match | logged action match | anchors with identical 128 candidates | mean fraction of candidates differing |") +L.append("|---|---|---|---|---|---|") +for a, r in G["arms"].items(): + L.append(f"| `{a}` | {r['n_anchors']} | {r['ee_match']}/{r['n_anchors']} | " + f"{r['logged_match']}/{r['n_anchors']} | {r['anchors_identical_candidates']}/{r['n_anchors']} | " + f"{r['mean_frac_candidates_differing']:.3f} |") +L.append("") +L.append("**The ANCHORS are identical** — `ee_xyz` and the logged action match 291/291 on every arm, " + "which is the gate RANK_CTRL and every earlier rung verified. What differs is the " + "**proposer draw**: 45–99 % of the 128 candidates are redrawn between arms. So every " + "cross-arm delta in this ladder (rungs V, Z, AA, AB, AC) was measured through a freshly " + "sampled candidate set, which is exactly the between-arm noise rung AB characterised as " + "candidate-matched ρ 0.903 at this cell. It does **not** touch the verdict (that is one " + "arm's own pooled number against the bar) and it makes the replication above **stronger**, " + "not weaker: the route ordering survives redrawing the candidates.") +L.append("") +L.append("### Scope, restated") +L.append("") +L.append(f"All anchors **S0**; {len(M['common_episodes'])} common held-out episodes " + f"{sorted(M['common_episodes'])}, **5 per route**; every interval is an **episode**-cluster " + f"bootstrap with {M['n_boot']} replicates; the flip rate is defined only where the logged " + f"edge is a failure edge, i.e. on the `0->5` group. Each route cell rests on **5 clusters**, " + f"so its interval is correspondingly wide — the same corpus limit already quoted on the " + f"close (~37× the episodes, ≈6,700 collected, to resolve the pooled estimate against the " + f"bar). The eight arms share the same anchors and read-out, so agreement across rows is " + f"**correlated readings, not independent tests**. No configuration was written into " + f"`configs/baselines.yaml`: there is still no passing one.") +L.append("") +L.append("### What this does and does not authorise") +L.append("") +L.append("It does **not** authorise a new rung. The pre-registered rule has fired and the three " + "remaining options (`GOAL_SEGMENT_CONTRASTIVE` trained fresh, junction-prefix oversampling, " + "more real data) still change the objective, the data mix or the corpus and therefore still " + "need the owner — #276 comment 5818554571, unanswered. What it changes is the **framing of " + "the negative**: the deficit is not uniform underperformance, it is that the scorer's " + "ranking advantage at S0 is concentrated on failure-bound anchors and is ~0 on goal-bound " + "ones. If the owner picks one of the three, the number to beat is now " + f"**{f(gb)} on goal-bound anchors**, not the pooled +0.0909 — a pooled improvement that " + "leaves the goal-bound cell at zero would clear nothing that matters.") +L.append("") +L.append("-- EDGE_TEST (#276/#278)") +print("\n".join(L)) diff --git a/rsm_rise/scripts/real/q278_comment34.py b/rsm_rise/scripts/real/q278_comment34.py new file mode 100644 index 0000000000000000000000000000000000000000..6b0502b1343bf26ceff3a4281e45443715cda7f3 --- /dev/null +++ b/rsm_rise/scripts/real/q278_comment34.py @@ -0,0 +1,266 @@ +r"""#278 run 34: the pre-registered bar is a THREE-clause conjunction and the closing report quoted one +clause. Clause 3 (the counterfactual flip rate -- the contract's "sharpest number") and clause 1 +(coverage) PASS at the best cell; the conjunction still FAILS on clause 2 alone. Plus the per-route +ceiling read, which says the +0.10 bar is not reachable at the goal-bound anchors with this proposer's +leverage. Every number is read out of status/real/EDGE_FLIP_AUDIT.json and EDGE_CEILING_ROUTE.json so +the post cannot drift from the measurement. + +Writes two bodies: status/real/comment34_278.md (detail) and status/real/comment34_276.md (verdict). +""" +import json +from pathlib import Path + +R = Path("/proj/dmfexp/zwhong/rsm_rise/status/real") +F = json.load(open(R / "EDGE_FLIP_AUDIT.json")) +C = json.load(open(R / "EDGE_CEILING_ROUTE.json")) +T = "edge_T_rise" +CL = F["_clauses"] +CR = CL["control_result"] + +ARMS = [("edge_T_rise", "GOAL_EPISODE · R_XL s100000 · flow 8 · 16 particles — **the shipped best cell**"), + ("edge_AC_rise_flow4", "GOAL_EPISODE · flow 4 (replicate)"), + ("edge_AC_rise_flow16", "GOAL_EPISODE · flow 16 (replicate)"), + ("edge_AC_rise_flow32", "GOAL_EPISODE · flow 32 (replicate)"), + ("edge_AB_rise_p16_s202", "GOAL_EPISODE · 16 particles, scorer seed 202 (replicate)"), + ("edge_AB_rise_p64", "GOAL_EPISODE · 64 particles (replicate)"), + ("edge_AB_rise_p256", "GOAL_EPISODE · 256 particles (replicate)"), + ("edge_V_goalep", "GOAL_EPISODE fine-tune `R_XL_ft_v0` · positive-frame share 0.294"), + ("edge_V_goalseg", "GOAL_SEGMENT `R_XL_ft_v1` · 0.167"), + ("edge_V_win400", "GOAL_WINDOW_400 `R_XL_ft_B400` · 0.111"), + ("edge_V_win100", "GOAL_WINDOW_100 `R_XL_ft_B` · 0.028")] +GRP = [("R_0->5", "0→5", "failure edge, failure destiny"), + ("R_0->1->3", "0→1→3", "on-route edge, cooking destiny"), + ("R_0->2->3", "0→2→3", "on-route edge, cooking destiny"), + ("R_0->2->6", "0→2→6", "on-route edge, failure destiny"), + ("ONROUTE_EDGE", "on-route edges pooled", "0→1 or 0→2 logged"), + ("DEST_goalbound", "destiny = cooking/goal", "episode reaches S3/S4"), + ("DEST_failure", "destiny = failure", "episode ends in S5/S6"), + ("ALL", "**ALL (published cell)**", "pooled")] + + +def d(x): + return f"{x['mean']:+.4f} [{x['lo']:+.4f}, {x['hi']:+.4f}]" if x else "—" + + +def rt(x): + return f"{x['mean']:.3f} [{x['lo']:.3f}, {x['hi']:.3f}]" if x else "—" + + +L = [] +w = L.append + +w("## The pre-registered bar has **three** clauses and the closing report quoted one. Clauses 1 and 3 " + "**PASS** at the best cell; the conjunction still fails on clause 2 alone — and the per-route ceiling " + "says the +0.10 bar is **not reachable** at the goal-bound anchors with this proposer's leverage.") +w("") +w("**reward detection (#277): PASS** — AUC 0.931 [0.89, 0.96] vs permuted 0.47 (unchanged, not re-measured).") +w(f"**action ranking (#278): FAIL, unchanged** — the bar is a conjunction and clause 2 reads " + f"**{d(F['arms'][T]['d_vs_greedy'])}** against **+0.10**. #278 stays **closed**. No new arm was run, " + "nothing was retrained, no model was called: both numbers below are reductions of the `edge_parts/*.npz` " + "already on disk.") +w("") +w("### What was missing from the closing report") +w("") +w("`rise_stack/EDGE_TEST.md` (`b89c430`, byte-identical since) states the bar as a **conjunction of three " + "clauses**. Runs 31–33 reported clauses 1 and 2 in every table and closed this issue on clause 2. " + "Clause 3 — which the contract itself calls *\"the sharpest number\"* — has been computed by " + "`edge_field.summarise_anchors` into every arm's own `edge_test.json` since the arm ran, and was never " + "carried into the matched tables. So the closing negative quoted one clause of a three-clause bar. Here " + "are all three, on the same 20 common held-out episodes, with the episode-cluster interval clause 3 " + "never had.") +w("") +w("| # | clause (verbatim from the pre-registration) | evidence at the best cell | |") +w("|---|---|---|---|") +w(f"| 1 | Proposer coverage of the on-route cluster **≥ 0.8** of anchors | coverage " + f"**{F['arms'][T]['coverage']:.3f}** (S0; no S2 arm exists at this cell) | " + f"**{'PASS' if CR['clause1_coverage'] else 'FAIL'}** |") +w(f"| 2 | RSM on-route rank percentile **> greedy by ≥ 0.10** and **> its permuted control**, paired " + f"interval excluding zero | **{d(F['arms'][T]['d_vs_greedy'])}** vs greedy; " + f"{d(F['arms'][T]['d_vs_perm'])} vs permuted | **{'PASS' if CR['clause2_rank'] else 'FAIL'}** |") +fl = F["arms"][T]["flip"] +w(f"| 3 | Counterfactual flip rate at failure anchors **≥ 0.5** for RSM and **strictly greater than** " + f"BC/greedy's | **{rt(fl['rates']['rsm'])}** vs the 0.50 bar; greedy " + f"{rt(fl['rates']['greedy_idx'])}; paired RSM−greedy **{d(fl['d_vs_greedy'])}** | " + f"**{'PASS' if CR['clause3_flip'] else 'FAIL'}** |") +w("") +w(f"**Conjunction: FAIL** — {CR['n_passing']}/3 clauses pass, clause 2 is the one that fails. The verdict " + "on this issue does not move, because the bar as written is an AND. What moves is the auditable " + "description of the failure: at the best cell the proposer covers the on-route cluster, the scorer " + "flips the argmax away from the logged failure edge on **74.5 %** of the failure anchors against " + "greedy's 51.9 % with a paired interval excluding zero — and it falls **0.0091** short on the ranking " + "clause.") +w("") +w("### Clause 3 across every arm that pins this cell (`status/real/EDGE_FLIP_AUDIT.json`)") +w("") +w("106 covered failure anchors, 5 held-out episodes, identical on every arm. Rates over the covered " + "failure anchors; intervals are the harness's episode-cluster bootstrap (5 clusters — wide by " + "construction, and quoted rather than hidden).") +w("") +w("| arm | RSM flip | permuted RSM | greedy (BC) | IQL | RSM − greedy | RSM − permuted |") +w("|---|---|---|---|---|---|---|") +for a, lab in ARMS: + x = F["arms"].get(a, {}).get("flip") + if not x: + continue + r = x["rates"] + w(f"| `{a}` | **{rt(r['rsm'])}** | {rt(r.get('permuted:rsm'))} | {rt(r['greedy_idx'])} | " + f"{rt(r['idql'])} | {d(x['d_vs_greedy'])} | {d(x['d_vs_perm'])} |") +w("") +w("Two things fall out of that table.") +w("") +w("1. **Clause 3 separates the trained reward labels the same way run 33's clause-2 decomposition did, " + "independently.** The shipped GOAL_EPISODE arms 0.745–0.764, its fine-tune 0.670, then GOAL_WINDOW_400 " + "0.594, GOAL_SEGMENT 0.566, GOAL_WINDOW_100 0.528 — the dense episode-level label on top and the " + "sparsest window at the bottom, and **only the GOAL_EPISODE arms clear greedy with an interval " + "excluding zero**. Not strictly monotone in the positive-frame share: GOAL_SEGMENT (0.167) reads below " + "GOAL_WINDOW_400 (0.111), 0.566 vs 0.594, a gap far inside either interval. Same conclusion the ranking " + "clause reached, on a different statistic.") +w("2. **The particle and flow replicates agree to ±0.02**, so the clause is not a single-seed artefact: " + "0.745 at flow 8/16/32 and p16/p256, 0.764 at flow 4 and p64.") +w("") +w("### The honest caveat: clause 3 is **not** independent evidence from clause 2") +o = F["_overlap"] +w("") +w(f"Every one of the {sum(o['routes_of_clause3_anchors'].values())} clause-3 anchors is on route " + f"**0→5** (route census of the clause-3 anchor set: " + f"{', '.join(f'{k} {v}' for k, v in o['routes_of_clause3_anchors'].items())}). At S0 " + "that is the only logged failure first edge, so clause 3 can only ever be measured on the very route " + "run 33 showed carries the pooled clause-2 number:") +w("") +w(f"* clause-2 delta **on** the failure-edge anchors: {d(o['clause2_on_failure_edge_anchors'])} " + f"(n={o['clause2_on_failure_edge_anchors']['n']}, {o['clause2_on_failure_edge_anchors']['n_episodes']} episodes)") +w(f"* clause-2 delta **off** them (the other three routes): {d(o['clause2_off_failure_edge_anchors'])} " + f"(n={o['clause2_off_failure_edge_anchors']['n']}, {o['clause2_off_failure_edge_anchors']['n_episodes']} episodes)") +w("") +w("So \"clauses 1 and 3 pass\" is a statement about failure-route anchors on 5 episodes, and it does not " + "license a claim about the goal-bound states a planner needs. Which is exactly why the second reduction " + "below was run.") +w("") +w("### Is run 33's route heterogeneity a scorer deficit or just headroom? " + "(`status/real/EDGE_CEILING_ROUTE.json`)") +w("") +w("There was an obvious alternative reading of run 33: at a failure anchor the logged action heads " + "off-route, so BC/greedy is bad *by construction* and the headroom is large; at an on-route anchor the " + "logged action is already on-route and there is little room above it. The metric's own ceiling identity " + "(`edge_ceiling2.py`, verified to 4 dp against `edge_field.rank_pct`) measures that headroom per group, " + "so % of ceiling = the scorer's share of what was **available** there. The reading was pre-registered in " + "the script before the per-group split was computed — (i) flat ⇒ headroom effect, (ii) much lower on the " + "goal-bound routes ⇒ scorer deficit, (iii) higher ⇒ pooled number understates. It fired **(ii)**.") +w("") +w("| group | eps | anchors | leverage w̄ | d_ceiling | d_RSM | **% of ceiling** | AUC_w RSM | AUC_w greedy | AUC needed for +0.10 |") +w("|---|---|---|---|---|---|---|---|---|---|") +ct = C[T] +for k, lab, note in GRP: + g = ct.get(k) + if not g: + continue + w(f"| {lab}
{note} | {g['n_episodes']} | {g['n_anchors']} | {g['w_mean']:.3f} | " + f"{g['d_ceiling']:+.4f} | {g['d_vs_greedy_rsm']:+.4f} | **{g['pct_of_ceiling']:.1f}%** | " + f"{g['auc_rsm']['weighted']:.3f} | {g['auc_greedy']['weighted']:.3f} | " + f"{g['auc_needed_for_bar']:.3f} |") +rd = C["_reading"] +w("") +w(f"**{rd['verdict']}** — spread **{rd['spread']:.1f} percentage points**, goal-bound mean " + f"**{rd['goalbound_mean']:.1f}%** against the failure edge's **{rd['failure_edge']:.1f}%**. The " + "heterogeneity is *not* explained away by headroom: the scorer converts roughly half of the available " + "signal where the logged action is wrong and a quarter or less where it is right. Replicated at flow 32 " + f"(goal-bound {C['edge_AC_rise_flow32']['DEST_goalbound']['pct_of_ceiling']:.1f}% vs 0→5 " + f"{C['edge_AC_rise_flow32']['R_0->5']['pct_of_ceiling']:.1f}%), and inverted on the GOAL_SEGMENT label, " + "whose pooled number is negative because its 0→5 cell is " + f"{C['edge_V_goalseg']['R_0->5']['d_vs_greedy_rsm']:+.4f}.") +w("") +w("### The new fact about the metric, and it changes what any future arm can be asked to do") +w("") +w("The last column is the one to read. The +0.10 bar is a **leverage-weighted** quantity: per anchor the " + "weight is w = n_off/(n−1), so the AUC a group would need to clear +0.10 is " + "`AUC_greedy + 0.10/w̄`. At the goal-bound anchors w̄ is 0.070–0.203 against 0.519 on route 0→5, so:") +w("") +gb = ct["DEST_goalbound"]; c23 = ct["R_0->2->3"]; c013 = ct["R_0->1->3"] +w(f"* destiny = goal/cooking: needs AUC **{gb['auc_needed_for_bar']:.3f}** — **> 1, impossible**;") +w(f"* the cleanest destiny cell 0→2→3: needs AUC **{c23['auc_needed_for_bar']:.3f}**;") +w(f"* 0→1→3: needs AUC **{c013['auc_needed_for_bar']:.3f}**;") +w(f"* route 0→5: needs AUC {ct['R_0->5']['auc_needed_for_bar']:.3f}, and the scorer delivers " + f"{ct['R_0->5']['auc_rsm']['weighted']:.3f}.") +w("") +w("**A perfect scorer could not clear the pooled +0.10 bar out of the goal-bound anchors alone.** The " + "pre-registered bar is therefore only attainable through the high-leverage failure-route anchors, and " + "the test as written cannot certify planning at the goal-bound states no matter how good the critic is. " + "That is a property of the metric (the proposer puts too few off-route candidates at those anchors), not " + "a result about the model — and it was not visible until the ceiling was split by route. The bar and the " + "metric stay **unchanged**; what changes is the number a future arm should be judged on.") +w("") +w("**The target, restated in reachable units.** At the goal-bound anchors the honest statistic is the " + f"separation itself: AUC_w **{gb['auc_rsm']['weighted']:.3f}** against greedy's " + f"{gb['auc_greedy']['weighted']:.3f} and chance 0.5, i.e. the scorer is barely above the BC ordering " + "there, while on route 0→5 it reads " + f"{ct['R_0->5']['auc_rsm']['weighted']:.3f}. Any structural option should be asked to move that AUC, " + "and its % of ceiling, at the goal-bound anchors — not the pooled +0.0909.") +w("") +w("### Self-tests, printed before any number in both jobs") +w("") +w("* Per-anchor flip recomputed independently and compared to `edge_field.summarise_anchors`: **abs err " + "0.00e+00 on 11/11 arms** for every deterministic read-out (`rsm`, `permuted:rsm`, `idql`, " + "`permuted:idql`, `greedy_idx`), with n_flip = the harness's n_covered = 106 on all 11.") +w("* The `random` column differs by ~0.03 and is *not* asserted on: `summarise_anchors` advances a single " + "RNG across its (mode, anchor) loop, so an independent recomputation draws a different permutation. It " + "is a null column, not a measurement. The first submission of this job **failed its own self-test** on " + "exactly that and printed nothing — the guard worked.") +w("* Rank-percentile delta recomputed from the shards: **+0.090900 vs the harness's +0.090900, err " + "0.00e+00**, so the published cell is reproduced exactly and no decomposition here can re-open the " + "fired rule.") +w("") +w("### Ladder status") +w("") +w("Unchanged and complete inside standard practice: proposer (T), depth/horizon (AA's 2×2), successor " + "(AA), reward label (V/Z), particles and N (AB), flow steps (AC) — all measured **at** the best cell, " + "all closed. This run added **no rung**; it applied a clause of the existing contract and decomposed an " + "existing ceiling. The three held-back structural options (`GOAL_SEGMENT_CONTRASTIVE` trained fresh, " + "junction-prefix oversampling, an expectile-0.5 critic retrain) are still unrun and still need the " + "owner — see #276 comment 5818554571, now with a better-specified target.") +w("") +w("Jobs: SLURM **41986** (failed its self-test, printed no number), **41988** (the clause-3 audit), " + "**41992** (the per-route ceiling) — CPU only, partition `cpu`, LSF is still down. Artefacts: " + "`status/real/EDGE_FLIP_AUDIT.json`, `status/real/EDGE_CEILING_ROUTE.json`. Code: " + "`scripts/real/edge_flip_audit.py`, `scripts/real/edge_ceiling_route.py`.") +Path(R / "comment34_278.md").write_text("\n".join(L) + "\n") + +V = [] +v = V.append +v(f"**reward detection (#277): PASS** — AUC 0.931 [0.89, 0.96] vs permuted 0.47 (unchanged, not " + "re-measured this run).") +v(f"**action ranking (#278): FAIL, unchanged** — **{d(F['arms'][T]['d_vs_greedy'])}** against the +0.10 " + "bar. #278 stays closed; no new arm was run and nothing was retrained.") +v("") +v("Two reductions of the shards already on disk (SLURM 41988 / 41992, CPU only — LSF is still down):") +v("") +v(f"1. **The pre-registered bar has three clauses and the closing report quoted one.** Clause 1 " + f"(coverage {F['arms'][T]['coverage']:.3f} ≥ 0.8) **passes**; clause 3 — the counterfactual flip rate, " + f"which the contract calls \"the sharpest number\" — **passes**: RSM flips the argmax off the logged " + f"failure edge on **{fl['rates']['rsm']['mean']:.3f}** of the covered failure anchors against greedy's " + f"{fl['rates']['greedy_idx']['mean']:.3f}, paired **{d(fl['d_vs_greedy'])}**. Clause 2 fails at " + f"{F['arms'][T]['d_vs_greedy']['mean']:+.4f}. The bar is an AND, so **the verdict does not move** — but " + f"the failure is now described as 2/3 clauses passing, not as a flat negative. Caveat stated in full on " + f"#278: all 106 clause-3 anchors are route 0→5 on 5 episodes, the same route that carries the pooled " + f"clause-2 number, so the two are not independent.") +v(f"2. **Run 33's route heterogeneity is a scorer deficit, not headroom** (pre-registered reading (ii) " + f"fired): % of the metric's own ceiling is {rd['failure_edge']:.1f}% on route 0→5 against " + f"{rd['goalbound_mean']:.1f}% on the goal-bound routes, spread {rd['spread']:.1f} points, replicated at " + f"flow 32.") +v("") +v(f"**And a new fact about the metric that changes the pending decision.** The +0.10 bar is " + f"leverage-weighted (w = n_off/(n−1)), and at the goal-bound anchors w̄ = 0.070–0.203 against 0.519 on " + f"route 0→5. The AUC a group needs to clear +0.10 is therefore " + f"**{gb['auc_needed_for_bar']:.3f} (> 1, impossible)** for destiny = goal and " + f"**{c23['auc_needed_for_bar']:.3f}** at the cleanest destiny cell. A *perfect* scorer could not clear " + f"the pooled bar out of the goal-bound anchors alone: the pre-registered test can only be passed through " + f"the failure-route anchors. So the target for any structural option is the goal-bound **AUC_w " + f"{gb['auc_rsm']['weighted']:.3f}** (greedy {gb['auc_greedy']['weighted']:.3f}, chance 0.5) and its " + f"{gb['pct_of_ceiling']:.1f}% of ceiling — not the pooled +0.0909, and not +0.0245 either, which is the " + f"same shortfall in units the bar cannot reach. **The metric and the bar are unchanged.**") +v("") +v("NEEDS OWNER is unchanged: which of the three structural options (comment 5818554571) to spend the " + "cluster on, or none. Nothing was started. Detail, tables and self-tests on " + "#278 (comment below).") +Path(R / "comment34_276.md").write_text("\n".join(V) + "\n") +print("wrote", R / "comment34_278.md", "and", R / "comment34_276.md") +print("\n".join(L)) diff --git a/rsm_rise/scripts/real/quickstart_verify.sh b/rsm_rise/scripts/real/quickstart_verify.sh new file mode 100644 index 0000000000000000000000000000000000000000..fcfdb404cfbb86e66c106af9acf1b261b899020c --- /dev/null +++ b/rsm_rise/scripts/real/quickstart_verify.sh @@ -0,0 +1,53 @@ +#!/usr/bin/env bash +# LSF payload: run the QUICKSTART exactly as rise_stack/README.md tells the owner to run it, +# against the COMMITTED tree and the `hf download` copy of the public mirror. Nothing here may +# read a path that is not either in the repo or under $CKPTS. +set -uo pipefail +RISE_ROOT=/proj/dmfexp/zwhong/rsm_rise +REPO=/proj/dmfexp/zwhong/projs/rsm_real +CKPTS=$RISE_ROOT/hf_ckpt_root +OUT=$REPO/runs/rise_stack_quickstart +mkdir -p "$OUT" +export TORCH_HOME=$RISE_ROOT/cache/torch PYTHONUNBUFFERED=1 HF_HUB_OFFLINE=1 +export OPENPI_DATA_HOME=$RISE_ROOT/.openpi_assets TOKENIZERS_PARALLELISM=false +export XLA_PYTHON_CLIENT_MEM_FRACTION=0.45 XLA_PYTHON_CLIENT_PREALLOCATE=false +cd "$REPO" +echo "[qs] host=$(hostname) job=${LSB_JOBID:-none} HEAD=$(git rev-parse --short HEAD) $(date -u)" +nvidia-smi -L 2>/dev/null + +# Step 4, RISE-stack env (the two torch baselines). Same env block as verify_ckpt_root.sh -- +# the RISE conda env, NOT venv_rsm (which has no termcolor and cannot import robomimic). +( source "$RISE_ROOT/scripts/env.sh" + export PYTHONPATH="$REPO:$RISE_ROOT/code/rise_robomimic:$RISE_ROOT/code/rise_code:${PYTHONPATH:-}" + export RSM_LIBERO_DIR=$RISE_ROOT/code/gen_q/rsm_libero TORCH_HOME=$RISE_ROOT/cache/torch + cd "$REPO" + for B in idql rsm; do + echo "=== [qs] step 4: check --baseline $B --ckpt-root \$CKPTS --n-cand 128" + $RISE_ROOT/env/bin/python -m rise_stack.check --baseline "$B" --ckpt-root "$CKPTS" --n-cand 128 \ + --json-out "$OUT/check_$B.json" + echo "[qs] check $B rc=$?" + done ) + +# Step 4 + the README 4.2 rig setting, openpi env (pi0.5). +OPENPI_PY=$RISE_ROOT/third_party/openpi/.venv/bin/python +export PYTHONPATH=$REPO:$RISE_ROOT/code/rise_robomimic:$RISE_ROOT/code/diffusion_policy:$RISE_ROOT/code/robosuite:$RISE_ROOT/code/mimicgen_environments:$RISE_ROOT/code/rise_code +echo "=== [qs] step 4: check --baseline bc --ckpt-root \$CKPTS --n-cand 16 (openpi env)" +$OPENPI_PY -m rise_stack.check --baseline bc --ckpt-root "$CKPTS" --n-cand 16 \ + --json-out "$OUT/check_bc.json" +echo "[qs] check bc rc=$?" + +echo "=== [qs] README 4.2 recommended rig setting: pi0.5 proposer + RSM, --n-cand 4 --openpi-batch 16" +$OPENPI_PY -m rise_stack.check --baseline rsm --ckpt-root "$CKPTS" \ + --policy "openpi:pi05_cooking_stock:$CKPTS/pi05_bc_rsm_real_stock_s1_29999" \ + --n-cand 4 --openpi-batch 16 --repeat 6 --json-out "$OUT/check_pi05_rsm_n4.json" +echo "[qs] pi05+rsm N=4 rc=$?" + +python3 - "$OUT" <<'PY' +import json, pathlib, sys +for f in sorted(pathlib.Path(sys.argv[1]).glob("check_*.json")): + d = json.load(f.open()) + print(f"[qs] {f.stem:22s} N={d['n_cand']:4d} sample {d['sample_ms']:8.1f} score {d['score_ms']:7.1f} " + f"total {d['decision_ms']:8.1f} ms warmup {d.get('warmup_decision_ms', float('nan')):8.0f} ms " + f"ok={d['ok']} {d.get('problems')}") +PY +echo "[qs] done $(date -u)" diff --git a/rsm_rise/scripts/real/qwin_bimodality.py b/rsm_rise/scripts/real/qwin_bimodality.py new file mode 100644 index 0000000000000000000000000000000000000000..52eef6b881f5d8c614cc2ca622ee2af23383a94c --- /dev/null +++ b/rsm_rise/scripts/real/qwin_bimodality.py @@ -0,0 +1,68 @@ +#!/usr/bin/env python3 +"""AUG_SUCC (gen_q#279) -- is q_action_winrate BIMODAL across every augmented cell this stream trained? + +Motivation (run 11): the one believable TASK 4 cell, JUNC_feat_t40_c0p5_s0, sits at qwin 0.970 with a +gate of 0.259 vs the un-augmented 0.234 -- i.e. it did not learn to use the counterfactual action, it +learned to IGNORE it. The inverted cells (qwin ~ 0) learned to disprefer the logged action, which wins +the reverse arm for free and collapses the forward arm. If qwin is bimodal with an empty middle across +ALL doses, thresholds, modes and seeds, then the augmentation has only two attractors -- ignore or +invert -- and NO cell anywhere ever occupied the regime the gate would need (genuine action-conditioned +goal-direction). That is a structural statement about the trainer, not about the augmentation dose. + +Reads history.json only (json, no compute). +""" +import json, os, glob, sys + +ROOT = "/proj/dmfexp/zwhong/rsm_rise" +RUNS = f"{ROOT}/runs/real_cooking_v5/rsm" + + +def last(h, key): + if isinstance(h, list): + for r in reversed(h): + if key in r and r[key] == r[key]: + return r[key] + return float("nan") + + +rows = [] +for p in sorted(glob.glob(f"{RUNS}/AUG_*/history.json") + glob.glob(f"{RUNS}/JUNC_*/history.json") + + glob.glob(f"{RUNS}/R_M/history.json")): + cell = os.path.basename(os.path.dirname(p)) + try: + h = json.load(open(p)) + except Exception as e: + print(f"[skip] {cell}: {e}", file=sys.stderr) + continue + q = last(h, "q_action_winrate") + af = last(h, "aug_frac") + if af != af: + af = last(h, "aug_frac_batch") + rows.append(dict(cell=cell, qwin=q, augfrac=af, step=last(h, "step"), + minmse=last(h, "minmse_val"))) + +rows = [r for r in rows if r["qwin"] == r["qwin"]] +rows.sort(key=lambda r: r["qwin"]) +print(f"{'cell':34s} {'qwin':>6s} {'augfr':>6s} {'step':>7s} {'minmse':>7s}") +print("-" * 65) +for r in rows: + print(f"{r['cell']:34s} {r['qwin']:6.3f} " + f"{(r['augfrac'] if r['augfrac']==r['augfrac'] else float('nan')):6.3f} " + f"{str(int(r['step']) if r['step']==r['step'] else 'n/a'):>7s} " + f"{(r['minmse'] if r['minmse']==r['minmse'] else float('nan')):7.4f}") + +qs = [r["qwin"] for r in rows] +bins = [0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.001] +print("\nq_action_winrate histogram over %d cells:" % len(qs)) +for i in range(len(bins) - 1): + n = sum(1 for q in qs if bins[i] <= q < bins[i + 1]) + print(f" [{bins[i]:.1f},{bins[i+1]:.1f}) {n:2d} {'#'*n}") +mid = sum(1 for q in qs if 0.3 <= q <= 0.7) +print(f"\ncells in the MIDDLE [0.3,0.7]: {mid}/{len(qs)} = {mid/len(qs):.3f}") +print(f"cells inverted (<0.3): {sum(1 for q in qs if q<0.3)}") +print(f"cells ignoring (>0.7): {sum(1 for q in qs if q>0.7)}") +out = f"{ROOT}/status/real/augsucc/qwin_bimodality.json" +json.dump(dict(rows=rows, n=len(qs), mid=mid, + inverted=sum(1 for q in qs if q < 0.3), ignoring=sum(1 for q in qs if q > 0.7)), + open(out, "w"), indent=1) +print(f"\n[out] {out}") diff --git a/rsm_rise/scripts/real/reach_alpha_table.py b/rsm_rise/scripts/real/reach_alpha_table.py new file mode 100644 index 0000000000000000000000000000000000000000..1d9c9d730d10ce3cc23b4e375db895c9b063260c --- /dev/null +++ b/rsm_rise/scripts/real/reach_alpha_table.py @@ -0,0 +1,60 @@ +"""SUCC_DEBUG run 13 (gen_q#277): the MAGNITUDE-vs-DIRECTION table for the chain. + +Reads status/real/succdebug/reach_a_.json (chain_reach.py --hop-alpha) and prints one +row per (cell, alpha) with the two brackets that make the numbers mean something: + LOGGED the trajectory's own reach at the same nominal time (what the chain should have covered) + STAY fid = 1.000 by definition (what not moving scores) +fid = d(terminal, logged frame at the same nominal time) / the same distance for STAY, so fid < 1 +beats standing still. A MAGNITUDE defect is fixed by some alpha < 1 driving fid below 1.000; a +DIRECTION defect cannot be -- shrinking a wrong heading only interpolates back to the anchor, so +fid approaches 1.000 from above and never crosses it. +""" +import json, os, sys + +O = "/proj/dmfexp/zwhong/rsm_rise/status/real/succdebug" +CELLS = [("R_M_s100000", 1024, "100k"), ("R_M_long_s300000", 1024, "300k"), + ("R_L40_s100000", 1536, "100k"), ("R_XL_s100000", 2048, "100k")] +ALPHAS = ["1.0", "0.8", "0.6", "0.5", "0.4", "0.3", "0.2", "0.15", "0.1", "0.05"] # run 16: tiny shard added (LSF 1888081) +BETA = float(sys.argv[1]) if len(sys.argv) > 1 else 0.95 +HS = ["1", "4", "8", "16"] + + +def row_for(j, beta): + for r in j["rows"]: + if abs(r["beta"] - beta) < 1e-9: + return r + return None + + +print(f"### chain alpha sweep, beta = {BETA}, S2 train anchors A=200 x P=8 particles, 16 hops") +print("(D/dS3 = displacement in anchor-to-S3-entry units, median; fid = d(terminal,logged)/same for") +print(" STAY, <1 beats standing still; closer = frac of walks nearer the ANCHOR than the S3 entry)") +print() +print("| cell | W | steps | alpha | D/dS3 h1 | h4 | h8 | h16 | fid h16 | closer h16 |") +print("|---|---|---|---|---|---|---|---|---|---|") +logged = None +for tag, W, steps in CELLS: + best = None + for al in ALPHAS: + p = f"{O}/reach_a{al}_{tag}.json" + if not (os.path.exists(p) and os.path.getsize(p)): + continue + j = json.load(open(p)) + r = row_for(j, BETA) + if r is None or "hop" not in r["arms"]: + continue + ph = r["arms"]["hop"]["per_hop"] + fc = r["arms"]["hop"]["frac_closer_to_anchor"] + fid = ph["16"]["d_to_logged_over_STAY"] + cells = " | ".join(f"{ph[h]['disp_over_dS3']:.3f}" for h in HS) + print(f"| {tag} | {W} | {steps} | {al} | {cells} | {fid:.3f} | {fc['16']:.3f} |") + if best is None or fid < best[1]: + best = (al, fid) + if logged is None: + lg = r["LOGGED"]["per_hop"]; lf = r["LOGGED"]["frac_closer_to_anchor"] + logged = (" | ".join(f"{lg[h]['disp_over_dS3']:.3f}" for h in HS), lf["16"]) + if best: + print(f"| -> BEST alpha for {tag} | | | **{best[0]}** | | | | | **{best[1]:.3f}** | |") +if logged: + print(f"| LOGGED walk (bracket) | - | - | - | {logged[0]} | 0.000 | {logged[1]:.3f} |") +print("| STAY (bracket) | - | - | - | 0.000 | 0.000 | 0.000 | 0.000 | 1.000 | 1.000 |") diff --git a/rsm_rise/scripts/real/reach_alphacap_table.py b/rsm_rise/scripts/real/reach_alphacap_table.py new file mode 100644 index 0000000000000000000000000000000000000000..5e48485c829264f0dc5d7ea6dc00c10d9a05b2eb --- /dev/null +++ b/rsm_rise/scripts/real/reach_alphacap_table.py @@ -0,0 +1,67 @@ +"""SUCC_DEBUG run 15 (gen_q#277): the CAPACITY x CHAIN-ALPHA grid at the MATCHED 10k rung. + +Run 14's alpha sweep (reach_alpha_table.py) mixed step budgets: widths 1024/1536/2048 at 100k, plus +R_M_long at 300k. This table holds the step budget FIXED at 10k -- the one rung every capacity cell +shares -- so the alpha optimum can be read against width alone, with the 2048 and 3072 seed twins +giving the seed bracket that the optimum has never been checked against. + +Reads status/real/succdebug/reach_a__s10000.json (chain_reach.py --hop-alpha). +Brackets printed in every block: LOGGED (the trajectory's own reach at the same nominal time) and +STAY (fid = 1.000 by definition). alpha 1.2 is in the grid so the optimum can be shown INTERIOR +rather than sitting on a boundary: an optimum above 1.0 means the hops are too SHORT, a different +and cheaper defect than capacity. +""" +import json, os, sys + +O = "/proj/dmfexp/zwhong/rsm_rise/status/real/succdebug" +CELLS = [("R_M_s10000", 1024, 0), ("R_L40_s10000", 1536, 0), + ("R_XL_s10000", 2048, 0), ("R_XL_s1_s10000", 2048, 1), + ("R_W3072_s10000", 3072, 0), ("R_W3072_s1_s10000", 3072, 1), + ("R_W4096_s10000", 4096, 0)] +ALPHAS = ["1.2", "1.0", "0.8", "0.6"] +BETA = float(sys.argv[1]) if len(sys.argv) > 1 else 0.95 + + +def row_for(j, beta): + for r in j["rows"]: + if abs(r["beta"] - beta) < 1e-9: + return r + return None + + +print(f"### capacity x chain-alpha at the MATCHED 10k rung, beta = {BETA}, S2 train anchors " + f"A=200 x P=8, 16 hops") +print("(fid = d(terminal, logged frame at the same nominal time)/same for STAY; <1.000 beats " + "standing still.") +print(" closer = frac of walks nearer the ANCHOR than the S3 entry; 1.000 = inert, logged walk " + "reads 0.250.)") +print() +print("| cell | W | seed | alpha | D/dS3 h16 | fid h16 | closer h16 |") +print("|---|---|---|---|---|---|---|") +logged = None +for tag, w, sd in CELLS: + best, got = None, [] + for al in ALPHAS: + p = f"{O}/reach_a{al}_{tag}.json" + if not (os.path.exists(p) and os.path.getsize(p)): + continue + j = json.load(open(p)) + r = row_for(j, BETA) + if r is None or "hop" not in r["arms"]: + continue + ph = r["arms"]["hop"]["per_hop"]["16"] + fc = r["arms"]["hop"]["frac_closer_to_anchor"]["16"] + got.append((al, ph["disp_over_dS3"], ph["d_to_logged_over_STAY"], fc)) + if best is None or ph["d_to_logged_over_STAY"] < best[1]: + best = (al, ph["d_to_logged_over_STAY"]) + if logged is None: + lg = r["LOGGED"] + logged = (lg["per_hop"]["16"]["disp_over_dS3"], lg["frac_closer_to_anchor"]["16"]) + for al, d16, f16, c16 in got: + mark = " <- BEST" if best and al == best[0] else "" + print(f"| {tag} | {w} | {sd} | {al} | {d16:.3f} | {f16:.3f} | {c16:.3f} |{mark}") + if best: + print(f"| -> BEST alpha for W={w} seed={sd} | | | **{best[0]}** | | **{best[1]:.3f}** | |") +if logged: + print(f"| LOGGED walk (bracket) | - | - | - | {logged[0]:.3f} | 0.000 | {logged[1]:.3f} |") +print("| STAY (bracket) | - | - | - | 0.000 | 1.000 | 1.000 |") diff --git a/rsm_rise/scripts/real/reach_table.py b/rsm_rise/scripts/real/reach_table.py new file mode 100644 index 0000000000000000000000000000000000000000..b2818c8ab80802e94dfc746f26634214c945b430 --- /dev/null +++ b/rsm_rise/scripts/real/reach_table.py @@ -0,0 +1,143 @@ +"""Pure JSON readers for SUCC_DEBUG's two run-5 tables (login-node safe, no torch). + + --dist the Task-1 distributional table WITH its oracle/stay brackets, one row per (cell, beta), + read out of status/real/succdebug/dist_*.json + --grid run 9's COMPACT one-row-per-cell view of the same reach_*.json, sorted by width then by + step count, so the steps x width curve is readable in one screen. Columns are exactly the + ones runs 7/8 reported by hand: D/d_S3 at h1..h16, the clip fraction and the fidelity + d_to_logged/STAY at the terminal hop, and the reward logit at h1 -> h16. + --reach the Task-4 cumulative-reach table, one row per (cell, beta, arm), read out of + status/real/succdebug/reach_*.json, always printed next to the LOGGED and STAY brackets. +""" +import json, glob, os, re, sys + +O = "/proj/dmfexp/zwhong/rsm_rise/status/real/succdebug" + + +def dist(pats): + fs = [f for f in sorted(glob.glob(f"{O}/dist_*.json")) + if not pats or any(p in os.path.basename(f) for p in pats)] + print(f"{'cell':<26}{'W':>5}{'beta':>6} {'prec':>7}{'orac':>7}{'stay':>7} | " + f"{'rec':>7}{'orac':>7}{'stay':>7} | {'energy':>8}{'orac':>8}{'stay':>8} | {'dlt/data':>9}") + for f in fs: + d = json.load(open(f)) + il = d.get("identity_leakage", {}) + w = d.get("flow_width", "") + for r in d.get("by_beta", []): + print(f"{d['tag']:<26}{str(w):>5}{r['beta']:>6.2f} " + f"{r['prec_model']:>7.3f}{r['prec_oracle']:>7.3f}{r['prec_stay']:>7.3f} | " + f"{r['rec_model']:>7.3f}{r['rec_oracle']:>7.3f}{r['rec_stay']:>7.3f} | " + f"{r['energy_model']:>8.3f}{r['energy_oracle']:>8.3f}{r['energy_stay']:>8.3f} | " + f"{il.get('ratio_rms_mean', float('nan')):>9.3f}") + + +def reach(pats): + fs = [f for f in sorted(glob.glob(f"{O}/reach_*.json")) + if not pats or any(p in os.path.basename(f) for p in pats)] + if not fs: + print("no reach_*.json yet"); return + for f in fs: + d = json.load(open(f)) + print(f"\n=== {d['tag']} W={d.get('flow_width')} clip={d.get('sample_clip')} " + f"A={d['anchors_requested']}x{d['particles']}p hops<={d['max_hops']} " + f"eval_seed={d['eval_seed']} ({d.get('n_goal_train_eps')} goal-route train eps)") + for r in d["rows"]: + print(f" beta={r['beta']} hop={r['hop_frames']:.0f}f " + f"d_S3={r['d_S3_median']:.4f} d_S4={r['d_S4_median']:.4f} " + f"d_RAND={r['d_RAND_median']:.4f} " + f"frames anchor->S3 {r['frames_anchor_to_S3_median']:.0f} " + f"->S4 {r['frames_anchor_to_S4_median']:.0f}") + hg = [str(h) for h in d["hop_grid"]] + print(f" {'arm':<10}{'metric':<14}" + "".join(f"{('h'+h):>8}" for h in hg)) + for r in d["rows"]: + for arm, v in list(r["arms"].items()) + [("LOGGED", r["LOGGED"])]: + ph = v["per_hop"] + got = [h for h in hg if h in ph] + print(f" b{r['beta']} {arm:<7}{'D/d_S3':<14}" + + "".join(f"{ph[h]['disp_over_dS3']:>8.3f}" for h in got)) + print(f" {'':<10}{'closer2anchor':<14}" + + "".join(f"{v['frac_closer_to_anchor'][h]:>8.3f}" for h in got)) + print(f" {'STAY':<10}{'D/d_S3':<14}" + "".join(f"{0.0:>8.3f}" for _ in hg) + + " closer2anchor 1.000 by definition") + + +STEPS = re.compile(r"_s(\d+)$") + + +def _steps(tag): + m = STEPS.search(tag) + return int(m.group(1)) if m else -1 + + +def _cellname(tag): + return STEPS.sub("", tag) + + +def grid(pats, beta=0.95, arm="hop"): + """Compact steps x width view: one row per cell, the columns runs 7/8 assembled by hand.""" + fs = [f for f in sorted(glob.glob(f"{O}/reach_*.json")) + if not pats or any(p in os.path.basename(f) for p in pats)] + if not fs: + print("no reach_*.json yet"); return + rows, brackets = [], {} + for f in fs: + d = json.load(open(f)) + r = next((x for x in d["rows"] if abs(float(x["beta"]) - beta) < 1e-9), None) + if r is None or arm not in r["arms"]: + continue + hg = [str(h) for h in d["hop_grid"]] + last = hg[-1] + ph = r["arms"][arm]["per_hop"] + lg = r["LOGGED"]["per_hop"] + rows.append(dict(tag=d["tag"], w=d.get("flow_width") or 0, steps=_steps(d["tag"]), + seed=d["eval_seed"], hg=hg, + disp=[ph[h]["disp_over_dS3"] for h in hg], + clip=ph[last]["clip_frac"], fid=ph[last]["d_to_logged_over_STAY"], + r1=ph[hg[0]]["rhead_logit_mean"], rN=ph[last]["rhead_logit_mean"], + closer=r["arms"][arm]["frac_closer_to_anchor"][last], + dS3=r["d_S3_median"], dRAND=r["d_RAND_median"])) + brackets.setdefault("LOGGED", dict(hg=hg, disp=[lg[h]["disp_over_dS3"] for h in hg], + fid=lg[last].get("d_to_logged_over_STAY", 0.0), + closer=r["LOGGED"]["frac_closer_to_anchor"][last])) + if not rows: + print(f"no cell has beta={beta} arm={arm}"); return + hg = rows[0]["hg"] + u = {(r["dS3"], r["dRAND"]) for r in rows} + print(f"beta={beta} arm={arm} units d_S3/d_RAND (median over anchors): " + + " ".join(f"{a:.4f}/{b:.4f}" for a, b in sorted(u)) + + f" on-manifold ceiling d_RAND/d_S3={max(b / a for a, b in u):.3f}") + hdr = ("cell", "W", "steps", "es") + print(f"{hdr[0]:<24}{hdr[1]:>5}{hdr[2]:>7}{hdr[3]:>6} " + + "".join(f"{('h' + h):>7}" for h in hg) + + f" | {'clip':>6}{'fid':>6}{'closer':>7} | {'rew h1->hN':>16}") + for r in sorted(rows, key=lambda x: (x["w"], x["steps"], x["seed"], x["tag"])): + print(f"{_cellname(r['tag']):<24}{r['w']:>5}{(r['steps'] or 0):>7}{r['seed']:>6} " + + "".join(f"{v:>7.3f}" for v in r["disp"]) + + f" | {r['clip']:>6.3f}{r['fid']:>6.2f}{r['closer']:>7.3f} | " + + f"{r['r1']:>+7.1f} ->{r['rN']:>+7.1f}") + b = brackets["LOGGED"] + print(f"{'LOGGED walk (bracket)':<24}{'-':>5}{'-':>7}{'-':>6} " + + "".join(f"{v:>7.3f}" for v in b["disp"]) + + f" | {'-':>6}{b['fid']:>6.2f}{b['closer']:>7.3f} |") + print(f"{'STAY (bracket)':<24}{'-':>5}{'-':>7}{'-':>6} " + + "".join(f"{0.0:>7.3f}" for _ in hg) + + f" | {'-':>6}{1.00:>6.2f}{1.000:>7.3f} |") + print("fid = d(terminal, logged frame at the same nominal time) / the same for STAY; <1 beats " + "stay-put. closer = frac of walks whose terminal state is nearer the anchor than the S3 " + "entry (1.000 = inert).") + +if __name__ == "__main__": + a = sys.argv[1:] + mode = "reach" + if a and a[0] in ("--dist", "--reach", "--grid"): + mode = a[0][2:]; a = a[1:] + kw = {} + for i, x in enumerate(list(a)): + if x.startswith("--beta="): + kw["beta"] = float(x.split("=", 1)[1]); a.remove(x) + elif x.startswith("--arm="): + kw["arm"] = x.split("=", 1)[1]; a.remove(x) + if mode == "grid": + grid(a, **kw) + else: + (dist if mode == "dist" else reach)(a) diff --git a/rsm_rise/scripts/real/read_drift39.py b/rsm_rise/scripts/real/read_drift39.py new file mode 100644 index 0000000000000000000000000000000000000000..8a90b4e3f0d4ef4d9d0499acf808481e4112192b --- /dev/null +++ b/rsm_rise/scripts/real/read_drift39.py @@ -0,0 +1,63 @@ +import json,sys +O="status/real/succdebug" +CELLS=[("W1024","drift_R_M_s100000_hop"),("W1536","drift_R_L40_s100000_hop"), + ("W1792","drift_R_W1792_s100000_hop"),("W2048","drift_R_XL_s100000_hop")] +J={n:json.load(open(f"{O}/{f}.json")) for n,f in CELLS} +def row(j,beta): + for r in j["rows"]: + if abs(r["beta"]-beta)<1e-9: return r +def f(v,n=4): return " nan " if v!=v else f"{v:+.{n}f}" +print("="*108) +print("P1 ADMISSIBILITY, SCORED FIRST") +ok=True +for n,_ in CELLS: + for b in (0.95,0.99): + r=row(J[n],b) + for h in ("1","4","16"): + st=r["stay"][h]; iso=r["iso"][h] + a=abs(st["spread_ratio"]-1.0)<=1e-6 and abs(st["disp_mean"])<=1e-9 + c=abs(iso["cos_disp"])<=0.05 + if not(a and c): + ok=False; print(f" MISS {n} b{b} h{h}: stay_spread={st['spread_ratio']:.8f} " + f"stay_disp={st['disp_mean']:.2e} iso_cos={iso['cos_disp']:+.4f}") +print(" P1:", "HIT (stay spread==1 exactly, stay disp==0, |iso cos|<=0.05 in all 24 checks)" if ok else "MISS") +for n,_ in CELLS[:1]: + r=row(J[n],0.99); print(f" (example: stay spread {r['stay']['16']['spread_ratio']:.8f}, " + f"iso cos h1/h4/h16 {r['iso']['1']['cos_disp']:+.4f}/{r['iso']['4']['cos_disp']:+.4f}/{r['iso']['16']['cos_disp']:+.4f})") +for b in (0.95,0.99): + print("="*108); print(f"BETA {b} -- every row carries STAY / LOGGED / ISO") + print(f"{'cell':6} {'h':>3} {'arm':7} {'cos_disp':>9} {'pc1':>7} {'spread':>8} {'disp':>8} {'r_cent':>8} {'rew_mu':>7} {'rew_sd':>7} {'clamp':>6}") + for n,_ in CELLS: + r=row(J[n],b) + for h in ("1","4","16"): + for arm in ("model","logged","iso","stay"): + v=r[arm][h] + cl=v.get("frac_clamped_to_end") + print(f"{n:6} {h:>3} {arm:7} {f(v['cos_disp'])} {v['pc1_frac']:7.4f} {v['spread_ratio']:8.4f} " + f"{v['disp_mean']:8.4f} {v['r_centroid']:8.4f} {v['rew_mean']:7.4f} {v['rew_std']:7.4f} " + f"{('%.2f'%cl) if cl is not None else ' - ':>6}") + print() +print("="*108) +r=row(J["W1024"],0.99); m,l,i=r["model"]["16"],r["logged"]["16"],r["iso"]["16"] +print(f"P2 shared drift W1024 b0.99 h16: cos MODEL {m['cos_disp']:+.4f} | bar1 >=0.50 " + f"{'HIT' if m['cos_disp']>=0.50 else 'MISS'} | bar2 >= LOGGED+0.20 = {l['cos_disp']+0.20:+.4f} " + f"{'HIT' if m['cos_disp']>=l['cos_disp']+0.20 else 'MISS'} (ISO {i['cos_disp']:+.4f})") +print(f"P3 collapse spread MODEL {m['spread_ratio']:.4f} bar <0.50 " + f"{'HIT' if m['spread_ratio']<0.50 else 'MISS'} LOGGED {l['spread_ratio']:.4f} ISO {i['spread_ratio']:.4f}") +print(f"P4 reward rew_std MODEL {m['rew_std']:.4f} bar < 0.5*LOGGED = {0.5*l['rew_std']:.4f} " + f"{'HIT' if m['rew_std']<0.5*l['rew_std'] else 'MISS'} (LOGGED clamped frac {l['frac_clamped_to_end']:.2f})") +for h in ("1","4"): + m4,l4=r["model"][h],r["logged"][h] + print(f" P4 re-read at h={h} (LOGGED clamp {l4['frac_clamped_to_end']:.2f}): MODEL rew_std " + f"{m4['rew_std']:.4f} vs LOGGED {l4['rew_std']:.4f} -> " + f"{'HIT' if m4['rew_std']<0.5*l4['rew_std'] else 'MISS'}") +rx=row(J["W2048"],0.99); mx=rx["model"]["16"] +print(f"P5 capacity spread W2048 {mx['spread_ratio']:.4f} > W1024 {m['spread_ratio']:.4f} " + f"{'HIT' if mx['spread_ratio']>m['spread_ratio'] else 'MISS'} | cos W2048 {mx['cos_disp']:+.4f} " + f"< W1024 {m['cos_disp']:+.4f} {'HIT' if mx['cos_disp']= 9 else inc + pub = PUB[(ck, b)] + grid6 = [ph[str(h)]["disp_mean"] for h in (1, 2, 4, 8, 12, 16) if str(h) in ph] + rep = max(abs(a - c) for a, c in zip(grid6, pub)) if len(grid6) == 6 else float("nan") + print(f"{ck:5s} ns={ns} b={b} disp16={dm[-1]:7.4f} mean_inc(h9-16)={sum(tail)/max(len(tail),1):+.4f}" + f" clip16={ph[hs[-1]]['clip_frac']:.4f} |vs published grid|max={rep:.4f}") +print() +print("P1 HEADLINE (pre-reg: b0.95 ns0 ABSORBS disp16 < 1.50 ; b0.99 ns0 DIVERGES disp16 > 2.00)") +for b in (0.95, 0.97, 0.99): + v = d16.get(("R_M", "0.00", b)) + if v is None: print(f" b={b}: PENDING"); continue + if b == 0.95: print(f" b=0.95 ns0 disp16={v:.4f} bar <1.50 -> {'HIT (absorbs)' if v < 1.50 else 'MISS (still diverges)'}") + elif b == 0.99: print(f" b=0.99 ns0 disp16={v:.4f} bar >2.00 -> {'HIT (drift)' if v > 2.00 else 'MISS (absorbs: it is noise)'}") + else: print(f" b=0.97 ns0 disp16={v:.4f} (no bar pre-registered)") +print("P2 DOSE (pre-reg: monotone non-decreasing in noise-scale, all betas)") +for b in (0.95, 0.97, 0.99): + seq = [d16.get(("R_M", ns, b)) for ns in ("0.00", "0.25", "0.50", "1.00")] + if any(x is None for x in seq): print(f" b={b}: PENDING"); continue + mono = all(seq[i] <= seq[i + 1] + 1e-9 for i in range(3)) + print(f" b={b}: " + " <= ".join(f"{x:.4f}" for x in seq) + f" -> {'HIT' if mono else 'MISS (non-monotone)'}") +print("P3 INTERPRETABILITY CONTROL (pre-reg: W2048 ns0 still absorbs AND still moves,") +print(" disp16 within 0.25 of published 1.173 / 1.202 / 1.260)") +for b, pub in ((0.95, 1.173), (0.97, 1.202), (0.99, 1.260)): + v = d16.get(("R_XL", "0.00", b)) + if v is None: print(f" b={b}: PENDING"); continue + print(f" b={b} W2048 ns0 disp16={v:.4f} vs published {pub:.3f} delta={v-pub:+.4f}" + f" -> {'HIT' if abs(v-pub) <= 0.25 else 'MISS -- headline INADMISSIBLE'}") + +print() +print("=" * 108) +print("H83 STEP-MATCHED WIDTH LADDER at s100000 (far_a1.0, beta 0.99) -- prec_model") +print("=" * 108) +lad = [("R_W896_s100000_e0.99", 896), ("R_M_s100000_e0.99", 1024), + ("R_W1280_s100000_e0.99", 1280), ("R_W1280_s1_s100000_e0.99", 1280), + ("R_L40_s100000_e0.99", 1536), ("R_W1792_s100000_e0.99", 1792), + ("R_XL_s100000_e0.99", 2048), ("R_W3072_s100000_e0.99", 3072), + ("R_W4096_s100000_e0.99", 4096)] +P = {} +for t, w in lad: + j = far(t) + if j is None: print(f"{t:30s} W{w:<5d} PENDING"); continue + v = j["by_beta"][0]; g = j["minmse_gate"] + P[t] = v["prec_model"] + print(f"{t:30s} W{w:<5d} prec {v['prec_model']:.4f} rec {v['rec_model']:.4f} " + f"energy {v['energy_model']:.4f} gate {g['ratio_model']:.4f} | brackets " + f"oracle {v['prec_oracle']:.4f} stay {v['prec_stay']:.4f} far {v['prec_far']:.4f} " + f"| L {v['L']:.4f} k_mean {v['k_mean']:.5f} nuniq {v['n_unique_logged']}") +bars = {"R_W896_s100000_e0.99": (0.648, 0.664), "R_W1280_s100000_e0.99": (0.569, 0.585), + "R_W1792_s100000_e0.99": (0.480, 0.496)} +print("P1 LEVELS:") +for t, (lo, hi) in bars.items(): + if t not in P: print(f" {t}: PENDING"); continue + print(f" {t:30s} {P[t]:.4f} in [{lo}, {hi}] -> {'HIT' if lo <= P[t] <= hi else 'MISS'}") +if all(t in P for t, _ in lad if t != "R_W1280_s1_s100000_e0.99"): + order = [P[t] for t, _ in lad if t != "R_W1280_s1_s100000_e0.99"] + mono = all(order[i] > order[i + 1] for i in range(len(order) - 1)) + print(f"P2 MONOTONE over 8 rungs: {' > '.join(f'{x:.4f}' for x in order)} -> {'HIT' if mono else 'MISS'}") + below = (P["R_W896_s100000_e0.99"] - P["R_L40_s100000_e0.99"]) / 640.0 + above = (P["R_XL_s100000_e0.99"] - P["R_W4096_s100000_e0.99"]) / 2048.0 + print(f"P3 SLOPE below d_z {below:.3e}/unit vs above d_z {above:.3e}/unit ratio {below/above:.2f}x" + f" (bar >= 1.5x) -> {'HIT' if below >= 1.5 * above else 'MISS'}") +if "R_W1280_s100000_e0.99" in P and "R_W1280_s1_s100000_e0.99" in P: + sp = abs(P["R_W1280_s100000_e0.99"] - P["R_W1280_s1_s100000_e0.99"]) + gap = P["R_W1280_s100000_e0.99"] - P.get("R_L40_s100000_e0.99", float("nan")) + print(f"P4 SEED: |W1280 - W1280_s1| = {sp:.4f} (bar <0.020 and < gap {gap:.4f})" + f" -> {'HIT' if sp < 0.020 and sp < gap else 'MISS'}") + +print() +print("=" * 108) +print("H84 d8 SEED FLOOR at H75/H76's OWN STEPS (far_a1.0, beta 0.99) -- prec_model") +print("=" * 108) +for step in (60000, 70000): + cells = {k: far(f"{k}_s{step}_e0.99") for k in ("R_D8_XL", "R_D8_XL_s1", "R_XL", "R_XL_s1")} + if any(v is None for v in cells.values()): + print(f"s{step}: PENDING " + ",".join(k for k, v in cells.items() if v is None)); continue + p = {k: v["by_beta"][0]["prec_model"] for k, v in cells.items()} + br = {k: (round(v["by_beta"][0]["prec_oracle"], 4), round(v["by_beta"][0]["prec_stay"], 4), + round(v["by_beta"][0]["prec_far"], 4), round(v["by_beta"][0]["L"], 4), + round(v["by_beta"][0]["k_mean"], 5)) for k, v in cells.items()} + same = len(set(br.values())) == 1 + c0 = p["R_D8_XL"] - p["R_XL"]; c1 = p["R_D8_XL_s1"] - p["R_XL_s1"] + sp8 = abs(p["R_D8_XL"] - p["R_D8_XL_s1"]); sp4 = abs(p["R_XL"] - p["R_XL_s1"]) + print(f"s{step}: " + " ".join(f"{k} {p[k]:.4f}" for k in ("R_D8_XL", "R_D8_XL_s1", "R_XL", "R_XL_s1"))) + print(f" P4 bracket control (all four byte-identical): {'HIT' if same else 'MISS -- nothing else read'}" + f" {sorted(set(br.values()))[0] if same else br}") + print(f" contrast seed0 {c0:+.4f} seed1 {c1:+.4f} d8 seed spread {sp8:.4f} d4 seed spread {sp4:.4f}") + print(f" P1 sign (seed1 negative): {'HIT' if c1 < 0 else 'MISS'}") + print(f" P2 size (seed1 in [-0.035,-0.008]): {'HIT' if -0.035 <= c1 <= -0.008 else 'MISS'}") + print(f" P3 floor (d8 spread {sp8:.4f} < |contrast| {abs(c0):.4f}): {'HIT' if sp8 < abs(c0) else 'MISS'}") diff --git a/rsm_rise/scripts/real/read_run38.py b/rsm_rise/scripts/real/read_run38.py new file mode 100644 index 0000000000000000000000000000000000000000..b0bdb7ed9945920084000da8d727703fc8558262 --- /dev/null +++ b/rsm_rise/scripts/real/read_run38.py @@ -0,0 +1,131 @@ +"""Score SUCC_DEBUG run 38 / H85 against the pre-registrations in jobs/field_stability.sh.""" +import json, os, glob +O = "/proj/dmfexp/zwhong/rsm_rise/status/real/succdebug" +CELLS = [("R_M_s100000_hop", 1024), ("R_L40_s100000_hop", 1536), + ("R_W1792_s100000_hop", 1792), ("R_XL_s100000_hop", 2048), + ("R_XL_s100000_logged", 2048), ("R_M_s100000_hop_p8", 1024), + ("R_XL_s100000_hop_p8", 2048)] +PUB = {(1024, 0.95): 1.0626, (1024, 0.99): 6.9402, (2048, 0.95): 0.9085, (2048, 0.99): 1.3847} +J = {} +for t, w in CELLS: + p = f"{O}/fstab_{t}.json" + if os.path.exists(p) and os.path.getsize(p): + J[t] = json.load(open(p)) +row = lambda j, b: next(r for r in j["rows"] if abs(r["beta"] - b) < 1e-9) + +print("=" * 108) +print("P3 ADMISSIBILITY -- ondata E_raw_mean < 1.00, scored FIRST, in every cell") +print("=" * 108) +ok3 = True +for t, w in CELLS: + if t not in J: continue + for b in (0.95, 0.99): + r = row(J[t], b); o = r["ondata"] + h = o["E_raw_mean"] < 1.00; ok3 &= h + print(f" {t:<22} W{w:<5} b={b} ondata E_raw={o['E_raw_mean']:.4f} " + f"(median {o['E_raw_median']:.4f}, frac>1 {o['frac_E_raw_gt1']:.3f}) " + f"d_data={o['d_data_mean']:.4f} -> {'HIT' if h else 'MISS'}") +print(f" P3 OVERALL: {'HIT -- run is admissible' if ok3 else 'MISS -- RUN VOID'}") + +print("=" * 108) +print("CHAIN FAMILY: E_raw (local expansion of one hop) and delta_d_data (drift off the data)") +print("=" * 108) +for t, w in CELLS: + if t not in J: continue + for b in (0.95, 0.99): + r = row(J[t], b); c = r["chain"] + print(f" {t:<22} W{w:<5} b={b} P={J[t].get('particles',1)}") + print(" h :" + "".join(f"{h:>9}" for h in ("1","2","4","8","12","16"))) + for k, lab in (("E_raw_mean", "E_raw "), ("delta_d_data_mean", "dd_data"), + ("d_data_mean", "d_data "), ("disp_after_hop_mean", "disp "), + ("frac_E_raw_gt1", "frac>1 ")): + print(f" {lab}:" + "".join(f"{c[h][k]:9.4f}" for h in ("1","2","4","8","12","16"))) + +print("=" * 108) +print("P1 HEADLINE (W1024 b0.99 chain): E crosses 1.0 at some h<=16 AND E(h=16) > 1.05") +print("=" * 108) +if "R_M_s100000_hop" in J: + c = row(J["R_M_s100000_hop"], 0.99)["chain"] + es = [(h, c[str(h)]["E_raw_mean"]) for h in range(1, 17)] + cross = [h for h, e in es if e > 1.0] + e16 = c["16"]["E_raw_mean"] + print(f" hops with E_raw>1: {cross} max E_raw={max(e for _, e in es):.4f} at h={max(es,key=lambda x:x[1])[0]}") + print(f" clause A (crosses 1.0): {'HIT' if cross else 'MISS'}") + print(f" clause B (E(16)={e16:.4f} > 1.05): {'HIT' if e16 > 1.05 else 'MISS'}") + print(f" P1 OVERALL: {'HIT' if (cross and e16 > 1.05) else 'MISS'}") + +print("=" * 108) +print("P2 CAPACITY CONTROL (W2048 b0.99 chain): E_raw_mean < 1.00 at EVERY hop 1..16") +print("=" * 108) +if "R_XL_s100000_hop" in J: + c = row(J["R_XL_s100000_hop"], 0.99)["chain"] + bad = [(h, c[str(h)]["E_raw_mean"]) for h in range(1, 17) if c[str(h)]["E_raw_mean"] >= 1.0] + print(f" hops with E_raw>=1: {[(h, round(e,4)) for h, e in bad]}") + print(f" max E_raw over h=1..16: {max(c[str(h)]['E_raw_mean'] for h in range(1,17)):.4f}") + print(f" P2: {'HIT' if not bad else 'MISS'}") + +print("=" * 108) +print("P4 LOCALISATION (W1024 b0.99 radial): monotone non-decreasing AND E(0.25)<19g}" for k in ks)) + for kk, lab in (("E_raw_mean", "E_raw "), ("delta_d_data_mean", "dd_data"), + ("d_data_mean", "d_data ")): + print(f" {lab}:" + "".join(f"{rad[f'{k:g}'][kk]:9.4f}" for k in ks)) +if "R_M_s100000_hop" in J: + rad = row(J["R_M_s100000_hop"], 0.99)["radial"]; ks = J["R_M_s100000_hop"]["radial_ladder"] + v = [rad[f"{k:g}"]["E_raw_mean"] for k in ks] + mono = all(v[i] <= v[i+1] + 1e-9 for i in range(len(v)-1)) + print(f" clause A (monotone non-decreasing): {'HIT' if mono else 'MISS'}") + print(f" clause B (E({ks[0]})={v[0]:.4f} < 1 < E({ks[-1]})={v[-1]:.4f}): " + f"{'HIT' if (v[0] < 1 < v[-1]) else 'MISS'}") + print(f" P4 OVERALL: {'HIT' if (mono and v[0] < 1 < v[-1]) else 'MISS'}") + +print("=" * 108) +print("P5 REPRODUCTION: chain disp_after_hop_mean @h16 vs run 37 ns=0 hop-arm disp16, bar 0.15") +print("=" * 108) +for t, w in CELLS: + if t not in J or "logged" in t: continue + for b in (0.95, 0.99): + got = row(J[t], b)["chain"]["16"]["disp_after_hop_mean"] + ref = PUB.get((w, b)) + if ref is None: continue + dd = abs(got - ref) + print(f" {t:<22} W{w:<5} b={b} P={J[t].get('particles',1)} got {got:.4f} vs published " + f"{ref:.4f} |delta|={dd:.4f} -> {'HIT' if dd <= 0.15 else 'MISS'}") + +print("=" * 108) +print("P6 EPS-INDEPENDENCE: |E_raw(eps=0.05) - E_raw(eps=0.0125)| <= 0.10") +print("=" * 108) +ok6 = True +for t, w in CELLS: + if t not in J: continue + for b in (0.95, 0.99): + r = row(J[t], b); c, c2 = r["chain"], r["chain_eps_small"] + ds = [(h, abs(c[h]["E_raw_mean"] - c2[h]["E_raw_mean"])) for h in ("1","4","8","12","16")] + do = abs(r["ondata"]["E_raw_mean"] - r["ondata_eps_small"]["E_raw_mean"]) + mx = max([d for _, d in ds] + [do]); ok6 &= mx <= 0.10 + print(f" {t:<22} W{w:<5} b={b} max|delta| over h=1,4,8,12,16 and ondata = {mx:.4f} " + f"-> {'HIT' if mx <= 0.10 else 'MISS'}") +print(f" P6 OVERALL: {'HIT' if ok6 else 'MISS'}") + +print("=" * 108) +print("P7 REPORTED NOT SCORED: chain-vs-radial at MATCHED d_data (the directionality of the drift)") +print("=" * 108) +for t, w in CELLS: + if t not in J or "logged" in t or "p8" in t: continue + r = row(J[t], 0.99); c = r["chain"]["16"]; rad = r["radial"] + ks = J[t]["radial_ladder"] + near = min(ks, key=lambda k: abs(rad[f"{k:g}"]["d_data_mean"] - c["d_data_mean"])) + v = rad[f"{near:g}"] + print(f" {t:<22} W{w:<5} b0.99 chain h16: d_data={c['d_data_mean']:.4f} " + f"dd_data={c['delta_d_data_mean']:+.4f} E={c['E_raw_mean']:.4f} " + f"pushed_away={c['frac_pushed_away']:.3f}") + print(f" {'':<22} nearest radial r={near:g}: d_data={v['d_data_mean']:.4f} " + f"dd_data={v['delta_d_data_mean']:+.4f} E={v['E_raw_mean']:.4f} " + f"pushed_away={v['frac_pushed_away']:.3f}") diff --git a/rsm_rise/scripts/real/readout_cross_test.py b/rsm_rise/scripts/real/readout_cross_test.py new file mode 100644 index 0000000000000000000000000000000000000000..4cb0190bc9028a5535dd6575c922cc12f130dd7a --- /dev/null +++ b/rsm_rise/scripts/real/readout_cross_test.py @@ -0,0 +1,150 @@ +#!/usr/bin/env python +"""CROSS-READ-OUT paired comparison of (beta, read-out) OPERATING POINTS (ACT_COND, run 12). + +`beta_paired_test.py` compares each beta cell to the deployed 0.99 WITHIN a read-out: prob vs +prob, logit vs logit. Deployment does not choose that way -- it picks ONE (beta, read-out) pair -- +and the two read-outs move in OPPOSITE directions with beta (prob top-1 falls as beta falls, logit +top-1 rises), so the best cell can be off the diagonal. Run 11 found the crossing lands on a tie +at logit@0.95; the beta-0.90 boundary cell has now landed with logit top-1 0.667, ABOVE deployed +prob@0.99's 0.585, so the cross comparison has to be made properly rather than eyeballed. + +Same discipline as beta_paired_test.py: + * every cell is checked anchor-by-anchor against the reference on (ep, t, stage), hard exit on + any mismatch -- pairing misaligned rows manufactures significance; + * paired mean difference + 20k paired bootstrap CI + Wilcoxon signed-rank p + the UNPAIRED se + beside it, so the gain from pairing is visible. + +AND the thing the top-1 number cannot be read without. `top1_agree` is SELF-CONSISTENCY: a +degenerate read-out that always returned candidate 0 would score 1.000. So every operating point +is reported on three CORRECTNESS statistics on the same paired anchors -- + rank_pct : where the LOGGED goal-route chunk lands among the 128 candidates (1.0 = top), + spearman : the monotone probe, logged chunk interpolated toward a failure-route chunk (want -1), + cv : coefficient of variation of the 128 scores (a collapsed field shows up here) -- +and a top-1 gain that is not accompanied by flat-or-better correctness is NOT an improvement. +""" +import json, os, argparse +import numpy as np +from scipy.stats import wilcoxon + +ROOT = "/proj/dmfexp/zwhong/rsm_rise/status/real/ACT_COND/snr" +# statistic stem -> (label, sign convention: +1 = higher is better, -1 = lower is better, 0 = report only) +STATS = [("top1_agree", "top1 agree (self-consist)", +1), + ("rank_pct", "rank pct of LOGGED chunk", +1), + ("spearman", "monotone probe rho", -1), + ("rep_spearman", "rep spearman", +1), + ("cv", "score CV", 0), + ("tie_frac", "tie frac at max", 0)] + + +def key(r): + return (int(r["ep"]), int(r["t"]), str(r.get("stage"))) + + +def boot_ci(d, n=20000, seed=0): + rng = np.random.default_rng(seed) + idx = rng.integers(0, len(d), size=(n, len(d))) + m = d[idx].mean(1) + return float(np.percentile(m, 2.5)), float(np.percentile(m, 97.5)) + + +def op_label(cell, read): + b = cell.replace("snr_beta", "").replace(".json", "") + return f"{read}@0.{b}" + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--dir", default=ROOT) + ap.add_argument("--ref-cell", default="snr_beta99.json") + ap.add_argument("--ref-read", default="prob") + ap.add_argument("--out", default="/proj/dmfexp/zwhong/rsm_rise/status/real/ACT_COND/READOUT_CROSS.json") + a = ap.parse_args() + + cells = sorted(f for f in os.listdir(a.dir) if f.startswith("snr_beta") and f.endswith(".json")) + loaded = {c: json.load(open(os.path.join(a.dir, c))) for c in cells} + ref = loaded[a.ref_cell] + refrows = ref["rows"] + refkeys = [key(r) for r in refrows] + R = int(ref["args"].get("repeats", 1)) + + # ---- ASSERTION: all cells are the same anchors in the same order ---- + for c, d in loaded.items(): + rows = d["rows"] + if len(rows) != len(refrows): + raise SystemExit(f"FAIL {c}: n={len(rows)} != ref {len(refrows)}; NOT pairable.") + bad = [(i, refkeys[i], key(rows[i])) for i in range(len(rows)) if key(rows[i]) != refkeys[i]] + if bad: + raise SystemExit(f"FAIL {c}: {len(bad)} anchor positions differ, first={bad[0]}.") + if int(d["args"].get("repeats", 1)) != R: + raise SystemExit(f"FAIL {c}: repeats mismatch vs reference.") + print(f"ANCHOR IDENTITY: {len(cells)} cells x {len(refrows)} anchors match the reference on " + f"(ep,t,stage) EXACTLY. repeats={R}.") + + refL = op_label(a.ref_cell, a.ref_read) + out = {"ref": refL, "n": len(refrows), "repeats": R, "cmp": [], "levels": []} + + # ---- level table: every operating point, plain means ---- + hdr = f"{'operating point':<16} {'top1':>7} {'rankpct':>8} {'rho':>8} {'reprho':>8} {'CV':>9} {'tie':>7}" + print("\nLEVELS (all operating points, same 200 paired anchors)\n" + hdr) + print("-" * len(hdr)) + for c in cells: + for read in ("prob", "logit"): + rows = loaded[c]["rows"] + # NON-FINITE GUARD (run 17). cv = std/mean of the 128 scores is NaN whenever an + # anchor's mean score underflows to 0 -- one such anchor at prob@0.82 (q0 down to + # 1.8e-32) turned the whole CV column into `nan`. Aggregate with nanmean and PRINT + # the count so a dropped anchor is visible instead of silent. + m, nnf = {}, 0 + for s, _, _ in STATS: + v = np.array([r[f"{s}_{read}"] for r in rows], float) + nnf += int((~np.isfinite(v)).sum()) + m[s] = float(np.nanmean(v[np.isfinite(v)])) if np.isfinite(v).any() else float("nan") + print(f"{op_label(c, read):<16} {m['top1_agree']:>7.3f} {m['rank_pct']:>8.3f} " + f"{m['spearman']:>8.3f} {m['rep_spearman']:>8.3f} {m['cv']:>9.4f} {m['tie_frac']:>7.3f}" + + (f" [{nnf} non-finite anchor-stats dropped]" if nnf else "")) + out["levels"].append({"op": op_label(c, read), "cell": c, "read": read, + "n_nonfinite": nnf, **m}) + + # ---- paired comparisons of every operating point vs the reference ---- + hdr2 = (f"{'vs {}'.format(refL):<20} {'statistic':<26} {'ref':>8} {'this':>8} {'dmean':>8} " + f"{'bootCI95':>18} {'wilcox_p':>10} {'unpaired_se':>12} verdict") + print("\nPAIRED vs " + refL + "\n" + hdr2) + print("-" * len(hdr2)) + for c in cells: + for read in ("prob", "logit"): + if c == a.ref_cell and read == a.ref_read: + continue + rows = loaded[c]["rows"] + for stem, lab, sign in STATS: + x = np.array([r[f"{stem}_{a.ref_read}"] for r in refrows], float) + y = np.array([r[f"{stem}_{read}"] for r in rows], float) + dif = y - x + lo, hi = boot_ci(dif) + try: + p = float(wilcoxon(y, x, zero_method="wilcox").pvalue) + except ValueError: + p = 1.0 + use = float(np.sqrt(x.var(ddof=1) / len(x) + y.var(ddof=1) / len(y))) + if sign == 0 or p >= 0.05 or (lo <= 0 <= hi): + v = "tie" if sign else "-" + else: + v = "BETTER" if sign * dif.mean() > 0 else "worse" + print(f"{op_label(c, read):<20} {lab:<26} {x.mean():>8.3f} {y.mean():>8.3f} " + f"{dif.mean():>8.3f} [{lo:>7.3f},{hi:>7.3f}] {p:>10.2e} {use:>12.3f} {v}") + out["cmp"].append({"op": op_label(c, read), "cell": c, "read": read, "stat": stem, + "ref_mean": float(x.mean()), "mean": float(y.mean()), + "dmean": float(dif.mean()), "boot_lo": lo, "boot_hi": hi, + "wilcoxon_p": p, "unpaired_se": use, "verdict": v, + "n": len(dif)}) + print("-" * len(hdr2)) + + print("\nverdict column applies ONLY to the correctness/decision statistics with a sign " + "convention\n(top1 and rank_pct higher-better, monotone rho lower-better); CV and tie " + "frac are reported,\nnot scored. A top-1 gain WITHOUT flat-or-better rank_pct and rho is " + "self-consistency, not skill.") + json.dump(out, open(a.out, "w"), indent=1) + print(f"\nwrote {a.out} ({len(out['cmp'])} comparisons, {len(out['levels'])} operating points)") + + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/real/reduce_idql_rw_matrix.py b/rsm_rise/scripts/real/reduce_idql_rw_matrix.py new file mode 100644 index 0000000000000000000000000000000000000000..a8e0adcf3eff93a7372792184d560fc3dde96759 --- /dev/null +++ b/rsm_rise/scripts/real/reduce_idql_rw_matrix.py @@ -0,0 +1,94 @@ +#!/usr/bin/env python3 +"""Reduce the reward-matched IDQL stitch column into a step-matched table. + +One row per (head, seed) at a fixed epoch. Every row prints its own group means, +kept anchors, kept episodes, ties/CV and the bootstrap CI on stitch_A / stitch_B. +Reference line for METRIC 1 is the head's own logged-return no-stitch line (0.0), +NOT the permutation-null median (a heavy-tailed group-label check on a ratio). +""" +import json, os, sys, glob, statistics + +ROOT = "/proj/dmfexp/zwhong/rsm_rise/status/real/stitch" +GROUPS = ["A_arrive_0->1->3", "B_arrive_0->2->3", "C_S3entry_goal", + "D_S3late_goal", "E_arrive_0->5_FAIL"] +# heads that can see the S0 rank label (METRIC 2 meaningful at all) +SEES_LABEL = {"EXPERT_EPISODE": True, "GOAL_EPISODE": False, "GOAL_SEGMENT": False, + "GOAL_WINDOW_400": None, "GOAL_WINDOW_100": None} + +def load(head, seed, epoch): + p = os.path.join(ROOT, head, f"idql_rw_s{seed}_e{epoch}", "stitch_value.json") + if not os.path.exists(p): + return None + with open(p) as f: + return json.load(f) + +def side(val, lo, hi): + if lo > 0.0: return "ABOVE, CI excludes" + if hi < 0.0: return "BELOW, CI excludes" + return "STRADDLES 0.0000" + +def main(): + epochs = [int(x) for x in (sys.argv[1:] or [1500])] + for epoch in epochs: + rows = [] + for head in ["EXPERT_EPISODE", "GOAL_EPISODE", "GOAL_SEGMENT", + "GOAL_WINDOW_400", "GOAL_WINDOW_100"]: + for seed in (0, 1, 2): + d = load(head, seed, epoch) + if d is None: + continue + m = d["modes"]["idql"] + if not m.get("defined", False): + rows.append((head, seed, None, d)) + continue + rows.append((head, seed, m, d)) + print("=" * 118) + print(f"REWARD-MATCHED IDQL, STEP-MATCHED AT EPOCH {epoch} " + f"(UNDERTRAINED vs the e5000 recipe; never compare across epochs)") + print(f"reference line = this head's own logged-return no-stitch line 0.0000") + print("=" * 118) + hdr = (f"{'head':<17}{'sd':>3} {'stitch_A':>10} {'A boot95':>20} " + f"{'stitch_B':>10} {'B boot95':>20} {'C-E':>12} {'verdict(A)':>20}") + print(hdr) + for head, seed, m, d in rows: + if m is None: + print(f"{head:<17}{seed:>3} UNDEFINED (guard could not establish its reference)") + continue + a, b = m["stitch_A"], m["stitch_B"] + ca = m["boot"]["ratioA_ci95"]; cb = m["boot"]["ratioB_ci95"] + print(f"{head:<17}{seed:>3} {a:>10.4f} [{ca[0]:>8.4f},{ca[1]:>8.4f}] " + f"{b:>10.4f} [{cb[0]:>8.4f},{cb[1]:>8.4f}] {m['C_minus_E']:>12.4f} " + f"{side(a, ca[0], ca[1]):>20}") + print() + print(f"{'head':<17}{'sd':>3} " + " ".join(f"{g.split('_')[0]:>10}" for g in GROUPS) + + " kept_anchors kept_episodes dCE_ci95") + for head, seed, m, d in rows: + if m is None: + continue + ka = "/".join(str(m["kept_anchors"][g]) for g in GROUPS) + ke = "/".join(str(m["kept_episodes"][g]) for g in GROUPS) + mu = " ".join(f"{d['groups'][g]['idql']['mean']:>10.4f}" for g in GROUPS) + dce = m["boot"]["dCE_ci95"] + print(f"{head:<17}{seed:>3} {mu} {ka:<22} {ke:<20} " + f"[{dce[0]:.4f},{dce[1]:.4f}]" + + ("" if dce[0] > 0 else " <-- UNDEFINED: C-E CI touches 0")) + print() + print("label visibility (METRIC 2 / S0 uprank):") + for head in dict.fromkeys(h for h, _, _, _ in rows): + v = SEES_LABEL[head] + s = {True: "YES -- an AUC from this head may be label read-back", + False: "NO -- predicted at its own permuted line; METRIC 1 only", + None: "UNMEASURED -- do not quote an AUC for this head yet"}[v] + print(f" {head:<18} {s}") + print() + # CV / spread beside every row + print("score spread (CV) per group, for the ties-at-max / degenerate-scorer check:") + for head, seed, m, d in rows: + if m is None: + continue + cvs = " ".join(f"{d['groups'][g]['idql']['cv']:>8.4f}" for g in GROUPS) + print(f"{head:<17}{seed:>3} {cvs}") + print() + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/real/reduce_metric1_vs_best_epoch.py b/rsm_rise/scripts/real/reduce_metric1_vs_best_epoch.py new file mode 100644 index 0000000000000000000000000000000000000000..47d66a80cc38d4b528bc0f699b92462d4c9d5db6 --- /dev/null +++ b/rsm_rise/scripts/real/reduce_metric1_vs_best_epoch.py @@ -0,0 +1,100 @@ +#!/usr/bin/env python3 +"""REWARD_MATRIX run 43 -- re-adjudicate every METRIC-1 cross-column claim against the STRONGEST +reward-matched baseline the head has, instead of against one arbitrarily step-matched epoch. + +THE PROBLEM THIS FIXES. status/real/SQUARE_MATRIX.txt compares each head's RSM cells against its +reward-matched IQL critic at epoch 1500. status/real/METRIC1_IQL_EPOCH_CURVE.txt measures that the IQL +column is strongly epoch-dependent and, on two heads, DECAYS monotonically with training across every seed +(GOAL_SEGMENT 3/3 seeds, GOAL_WINDOW_400 2/2, all with disjoint episode-bootstrap CIs). So picking e1500 +silently picks a WEAK baseline on exactly those heads, and an "RSM beats IQL" verdict there may be a +property of the epoch choice rather than of the scorer. + +THE FIX, and it is deliberately unfavourable to the RSM. For each head take the baseline's BEST reportable +cell -- the highest stitch_A over all seeds and all epochs on disk that pass the gen_q#281 denominator-health +guard -- and compare every RSM cell of that head against THAT. This is the strongest baseline the data +supports, so a surviving RSM win is a win against the best case for IQL, and a verdict that flips is a +verdict that was an artefact of the epoch choice. + +RULES KEPT (gen_q#281): a row is only compared against a cell of ITS OWN reward head; verdicts are decided +by disjointness of the two EPISODE bootstrap CIs, never by the points; both cells' denominator health and +group-A score CV are printed; a head whose IQL cells are all UNREPORTABLE gets NO cross-column verdict; +and a head that labels group A is marked METRIC-1-NOT-TESTABLE and gets no verdict either. +""" +import glob, json, os, sys + +LABELS_A = {"EXPERT_EPISODE", "RISE_PROVENANCE"} +HEALTH_BAR = 0.30 +ROOT = "/proj/dmfexp/zwhong/rsm_rise" + +def read(p, mode): + d = json.load(open(p)) + m = d.get("modes", {}).get(mode) + if not m or not m.get("defined"): return None + g = d["groups"]; C, E = m["mean_C"], m["mean_E"] + D = g["D_S3late_goal"][mode]["mean"] + if D == E: return None + return {"cell": p.split("/")[4], "head": p.split("/")[3], "A": m["stitch_A"], + "ci": m["boot"]["ratioA_ci95"], "health": (C - E) / (D - E), + "cvA": g["A_arrive_0->1->3"][mode]["cv"], + "epsA": m["kept_episodes"]["A_arrive_0->1->3"], + "anchA": m["kept_anchors"]["A_arrive_0->1->3"]} + +os.chdir(ROOT) +iq, rs = {}, {} +for p in sorted(glob.glob("status/real/stitch/*/idql_rw_*/stitch_value.json")): + r = read(p, "idql") + if r: iq.setdefault(r["head"], []).append(r) +for p in sorted(glob.glob("status/real/stitch/*/rsm_*/stitch_value.json")): + r = read(p, "rsm") + if r: rs.setdefault(r["head"], []).append(r) + +print("=" * 160) +print("METRIC 1 re-adjudicated: every RSM cell against its own head's STRONGEST reportable reward-matched IQL cell") +print(f"(strongest = highest stitch_A over all seeds x epochs on disk passing the #281 health guard {HEALTH_BAR})") +print("=" * 160) +flips = [] +for head in sorted(set(list(iq) + list(rs))): + ok = [r for r in iq.get(head, []) if r["health"] >= HEALTH_BAR] + allq = iq.get(head, []) + print(f"\n### {head}") + if head in LABELS_A: + print(" METRIC 1 is NOT TESTABLE on this head: it labels group A (the 0->1->3 arrivals) positively,") + print(" so a high ratio is the scorer reading its own label back. No cross-column verdict.") + continue + if not ok: + print(f" NO REPORTABLE IQL CELL: {len(allq)} idql cells on disk, all below the #281 health guard") + hs = ", ".join("%.3f" % r["health"] for r in allq) + print(" (healths " + hs + ").") + print(" This head's row is UNREPORTABLE across columns, loudly. No verdict.") + continue + best = max(ok, key=lambda r: r["A"]) + e1500 = [r for r in ok if r["cell"].endswith("_e1500")] + sm = max(e1500, key=lambda r: r["A"]) if e1500 else None + print(f" strongest IQL : {best['cell']:<20} stitch_A {best['A']:+.4f} CI [{best['ci'][0]:+.4f},{best['ci'][1]:+.4f}] " + f"health {best['health']:.3f} cv(A) {best['cvA']:.4f} anchors {best['anchA']} eps {best['epsA']}") + if sm: + print(f" step-matched e1500 (what SQUARE_MATRIX.txt used): {sm['cell']:<20} stitch_A {sm['A']:+.4f} " + f"CI [{sm['ci'][0]:+.4f},{sm['ci'][1]:+.4f}]") + print(f" -> using the strongest epoch instead of e1500 raises the baseline by {best['A']-sm['A']:+.4f}") + print(f" {'RSM cell':<28}{'stitch_A':>10}{'boot95':>22}{'health':>8}{'cv(A)':>8} vs strongest IQL vs e1500") + for r in sorted(rs.get(head, []), key=lambda r: -r["A"]): + if r["health"] < HEALTH_BAR: + print(f" {r['cell']:<28}{r['A']:>+10.4f} UNREPORTABLE (health {r['health']:.3f})") + continue + def verdict(b): + if r["ci"][0] > b["ci"][1]: return "RSM ABOVE (CIs disjoint)" + if r["ci"][1] < b["ci"][0]: return "RSM BELOW (CIs disjoint)" + return "no separation (CIs overlap)" + vb, vs = verdict(best), (verdict(sm) if sm else "n/a") + if sm and vb != vs: flips.append((head, r["cell"], vs, vb)) + print(f" {r['cell']:<28}{r['A']:>+10.4f} [{r['ci'][0]:+.4f},{r['ci'][1]:+.4f}]{r['health']:>8.3f}{r['cvA']:>8.4f} " + f"{vb:<28}{vs}") + +print("\n" + "=" * 160) +print("VERDICTS THAT FLIP when the baseline is taken at its strongest epoch instead of e1500") +print("=" * 160) +if not flips: + print(" none -- every cross-column verdict in SQUARE_MATRIX.txt is robust to the epoch choice.") +for h, c, was, now in flips: + print(f" {h:<18}{c:<28} at e1500: {was:<28} at strongest epoch: {now}") +print(f"\n[readjudicate] {len(flips)} flipped verdicts.") diff --git a/rsm_rise/scripts/real/reduce_metric2_s2_heads.py b/rsm_rise/scripts/real/reduce_metric2_s2_heads.py new file mode 100644 index 0000000000000000000000000000000000000000..b0862d14b844f7ad92009e7fc447cd67069a95cf --- /dev/null +++ b/rsm_rise/scripts/real/reduce_metric2_s2_heads.py @@ -0,0 +1,62 @@ +"""REWARD_MATRIX run 41: collapse status/real/METRIC2_S2_REREAD.txt into a per-REWARD-HEAD table. + +Every row is quoted beside its OWN measured permuted line and its OWN oracle ceiling for that anchor set. +The reward head is read from the RSM checkpoint's fine-tune token, not from the arm name, so a mislabelled +tag cannot move a row into the wrong head. Arms whose checkpoint carries no fine-tune token are BASE +cells and are reported as head=none -- they are the control that says what the architecture does with no +reward head at all. +""" +import re, sys +ROOT="/proj/dmfexp/zwhong/rsm_rise" +SRC=f"{ROOT}/status/real/METRIC2_S2_REREAD.txt" +WIN=sys.argv[1] if len(sys.argv)>1 else "100" +HEAD_OF=[("_ft_v0lit","EXPERT_EPISODE (sees label)"),("_ft_B400","GOAL_WINDOW_400"), + ("_ft_B","GOAL_WINDOW_100"),("_ft_v1","GOAL_SEGMENT"),("_ft_v0","GOAL_EPISODE")] +def head_of(ck): + stem=ck.rsplit("/rsm/",1)[-1].split("/")[0] + for tok,h in HEAD_OF: + if tok in stem: return h + return "none (base cell)" +sec=open(SRC).read().split("############ S0")[0] +rows=[] +for b in sec.split("ARM ")[1:]: + arm=b.split()[0] + ck=next((l.split("=",1)[1].strip() for l in b.splitlines() if l.strip().startswith("rsm =")),"?") + iq=next((l.split("=",1)[1].strip() for l in b.splitlines() if l.strip().startswith("idql =")),"?") + hdr=[l for l in b.splitlines() if l.strip().startswith("window")] + if not hdr: continue + names=hdr[0].split()[4:] + for l in b.splitlines(): + m=re.match(r"\s+<= (\S+)\s+(\d+)\s+(\d+)\s+([\d.]+)\s+(.*)$", l) + if not m or m.group(1)!=WIN: continue + na,ne,ceil=int(m.group(2)),int(m.group(3)),float(m.group(4)) + v=re.findall(r"([\d.-]+) \[([\d.-]+),([\d.-]+)\]", m.group(5)) + d=dict(zip(names,v)) + if "rsm" not in d: continue + rows.append(dict(arm=arm, head=head_of(ck), ck=ck.rsplit("/rsm/",1)[-1], + matched=("cooking_v5_rw_" in iq), na=na, ne=ne, ceil=ceil, + rsm=float(d["rsm"][0]), rlo=float(d["rsm"][1]), rhi=float(d["rsm"][2]), + rperm=float(d["permuted__rsm"][0]), + iql=float(d["idql"][0]), ilo=float(d["idql"][1]), ihi=float(d["idql"][2]), + iperm=float(d["permuted__idql"][0]))) +rows.sort(key=lambda r:(r["head"], -r["rsm"])) +print(f"S2 entry gate, window <= {WIN}. Each row beside ITS OWN measured permuted line and ITS OWN") +print(f"oracle ceiling. AT OR ABOVE the ceiling = exploiting the label, NOT passing.") +print(f"{'head':<28}{'rsm':>7}{'[lo,hi]':>16}{'perm':>7}{'ceil':>7}{'>perm?':>8}{'>=ceil?':>9}" + f"{'iql':>7}{'iperm':>7}{'rw?':>5}{'anch':>6}{'eps':>5} cell") +last=None +for r in rows: + if r["head"]!=last: print("-"*130); last=r["head"] + gt = "YES" if r["rlo"]>r["rperm"] else "no" + ceilf="**LABEL**" if r["rsm"]>=r["ceil"] or r["rhi"]>=r["ceil"] else "-" + print(f"{r['head']:<28}{r['rsm']:7.3f} [{r['rlo']:.3f},{r['rhi']:.3f}]{r['rperm']:7.3f}{r['ceil']:7.3f}" + f"{gt:>8}{ceilf:>9}{r['iql']:7.3f}{r['iperm']:7.3f}{('Y' if r['matched'] else 'N'):>5}" + f"{r['na']:6d}{r['ne']:5d} {r['ck']}") +print("-"*130) +print("rw? = is the idql column trained on THIS row's reward head? N => that idql number is CROSS-LABEL") +print(" and is NOT this head's baseline; it is printed only so the row is not silently missing one.") +n=len(rows); npass=sum(1 for r in rows if r["rlo"]>r["rperm"]) +nlab=sum(1 for r in rows if r["rsm"]>=r["ceil"] or r["rhi"]>=r["ceil"]) +print(f"{n} arms: {npass} with the RSM CI strictly above its own permuted line; of those, " + f"{sum(1 for r in rows if r['rlo']>r['rperm'] and (r['rsm']>=r['ceil'] or r['rhi']>=r['ceil']))} " + f"also reach their oracle ceiling. {nlab} arms touch the ceiling in total.") diff --git a/rsm_rise/scripts/real/reduce_metric2_square.py b/rsm_rise/scripts/real/reduce_metric2_square.py new file mode 100644 index 0000000000000000000000000000000000000000..2fcf696dded97a2d3fe00a9f02d9311b42537c3b --- /dev/null +++ b/rsm_rise/scripts/real/reduce_metric2_square.py @@ -0,0 +1,187 @@ +"""REWARD_MATRIX run 42: reduce the REWARD-MATCHED METRIC-2 column (edge_m2sq_) to one table +that satisfies the METRIC SPEC OF RECORD (gen_q#281 / rsm_real#3). + +Two things this adds over entry_window_rank.py, both spec requirements that reader does not meet: + + (1) DUPLICATE-WINDOW COLLAPSE. entry_window_rank.py looks the oracle ceiling up by WINDOW, not by + the anchor set the window actually produced. In these arms every anchor already lies within 100 + frames of entry, so windows 100 / 200 / all select the IDENTICAL 627-anchor set and are printed + with three different ceilings (0.616 / 0.522 / 0.467). One anchor set cannot have three + ceilings, and the spec says every row prints the ceiling for ITS OWN anchor set. Here identical + anchor sets are collapsed to a single row, tagged with the SMALLEST window that realises it, and + carry that window's ceiling. The wider windows are reported as DUPLICATE and never re-read. + (2) TIES-AT-MAX and SCORE CV, printed beside every AUC as the spec requires. Both are per-anchor + statistics over that anchor's candidate scores, then averaged over anchors: + ties_at_max = fraction of anchors where the top score is shared by >1 candidate + score_cv = mean over anchors of sd(scores)/|mean(scores)| within the anchor + A degenerate scorer (all candidates equal) shows cv ~ 0 and ties ~ 1 and its AUC is noise. +""" +import json, glob, argparse, collections, numpy as np, h5py +ROOT = "/proj/dmfexp/zwhong/rsm_rise" +# MEASURED oracle ceilings, scripts/real/proxy_fidelity_window.py job 1884695, 8-frame chunks. +CEIL = {(2,25):0.822,(2,50):0.736,(2,100):0.616,(2,200):0.522,(2,10**9):0.467, + (0,25):0.699,(0,50):0.661,(0,100):0.594,(0,200):0.512,(0,10**9):0.448} + +def auc(s, y): + s = np.asarray(s, float); y = np.asarray(y, bool) + if y.all() or (~y).all(): return np.nan + r = np.argsort(np.argsort(s)) + 1.0 + n1 = y.sum(); n0 = (~y).sum() + return float((r[y].sum() - n1*(n1+1)/2) / (n1*n0)) + +def boot_eps(vals, eps, B=2000, seed=0): + rng = np.random.default_rng(seed) + by = collections.defaultdict(list) + for v, e in zip(vals, eps): by[e].append(v) + u = sorted(by) + out = [] + for _ in range(B): + pick = rng.choice(len(u), size=len(u), replace=True) + s = [x for i in pick for x in by[u[i]]] + if s: out.append(np.mean(s)) + return (float(np.percentile(out, 2.5)), float(np.percentile(out, 97.5))) if out else (np.nan, np.nan) + +ap = argparse.ArgumentParser() +ap.add_argument("--arms", nargs="+", required=True) +ap.add_argument("--state", type=int, default=2) +ap.add_argument("--windows", nargs="+", type=int, default=[25, 50, 100, 200]) +ap.add_argument("--min-side", type=int, default=4) +ap.add_argument("--good-routes", default="", + help="restrict GOOD-edge anchors to episodes on these routes (comma list). " + "The LABEL-BLIND control: on 0->2->3 every goal head writes 0.0, the same value " + "it writes on 0->2->6, so an AUC above the permuted line there cannot be label read-back.") +# run 45: the CONFIRM arms (`edge_m2cf_*`) are drawn from the `confirm` half of S2_ENTRY_SPLIT.json, so +# reading the `select` route map for them would look up 59 confirm episodes in a 89-episode SELECT dict and +# silently drop every one of them from the route-restricted arm (ROUTE.get(ep) -> None != any GOODR). The +# unrestricted arm would still print, so the bug would have shown up as "the restricted arm has no anchors" +# rather than as an error. Default stays `select`, so every number run 42-44 printed is unchanged. +ap.add_argument("--split", default="select", choices=["select", "confirm"]) +ap.add_argument("--json", default="", help="run 49: also write `rows` as JSON here; the table builder reads this instead of parsing markdown. Default off => output unchanged.") +a = ap.parse_args() +GOODR = [r for r in a.good_routes.split(",") if r] +SPL = json.load(open(f"{ROOT}/status/real/S2_ENTRY_SPLIT.json")) +assert a.split in SPL, f"S2_ENTRY_SPLIT.json has no `{a.split}` key (has {sorted(SPL)})" +ROUTE = {int(k): v for k, v in SPL[a.split].items()} +GOOD = {0:"0->1", 2:"2->3"}[a.state]; BAD = {0:"0->5", 2:"2->6"}[a.state] + +with h5py.File(f"{ROOT}/data/raw/cooking_v5_expert_suboptimal.hdf5", "r") as f: + d = f["data"]; entry = {} + for k in d: + ep = int(k.split("_")[1]); st = d[k]["annot"]["edge_from"][()] + idx = np.where(st == a.state)[0] + if len(idx): entry[ep] = int(idx[0]) + +print(f"# REWARD_MATRIX run 42 -- reward-matched METRIC 2, state S{a.state}, good={GOOD} bad={BAD}, " + f"split={a.split} ({len(ROUTE)} episodes in the route map)") +print(f"# Both columns of every row are trained on that row's OWN reward label.") +if GOODR: + print(f"# LABEL-BLIND CONTROL: anchors restricted to episodes on routes {GOODR}.") + print(f"# Measured per-route mean reward (status/real/RW_S2_LABEL_PROBE.json): every goal head writes") + print(f"# 0.0000 on BOTH 0->2->3 and 0->2->6, and a POSITIVE mean on 2->3->4 (GOAL_EPISODE 1.0000,") + print(f"# GOAL_SEGMENT 0.5676, GOAL_WINDOW_400 0.3757, GOAL_WINDOW_100 0.0946). So with 2->3->4") + print(f"# excluded the goal heads are LABEL-BLIND at S2 and any AUC above the permuted line is") + print(f"# route tracking, not read-back. EXPERT_EPISODE/RISE_PROVENANCE write 1.0000 on 0->2->3 and") + print(f"# 0.0000 on 0->2->6, so they still SEE the label here and stay uninformative.") +else: + print(f"# NO route control: ~half the good-edge anchors sit on 2->3->4, which every head labels") + print(f"# positively against 0.0000 on 0->2->6, so these rows are CONSISTENT WITH LABEL READ-BACK.") +print(f"# Ceiling is the MEASURED oracle ceiling for the anchor set (job 1884695). At/above ceiling = " + f"exploiting the label, not passing.\n") +rows = [] +for arm in a.arms: + parts = sorted(glob.glob(f"{ROOT}/status/real/{arm}/edge_parts/*.npz")) + if not parts: print(f"[skip] {arm}: no parts"); continue + try: + cfg = json.load(open(f"{ROOT}/status/real/{arm}/edge_test.json"))["config"] + except Exception as e: + print(f"[skip] {arm}: no edge_test.json ({e})"); continue + idqlc = cfg.get("idql_ckpt", "") + head = arm.replace("edge_m2sq_", "").replace("edge_m2cf_", "") + # GUARD: the critic must come from THIS head's reward-matched training dir, else the row is cross-label. + matched = f"cooking_v5_rw_{head}/" in idqlc + held_out = cfg.get("held_out", not bool(cfg.get("ep_ids", ""))) + rec = []; n_empty = 0 + for p in parts: + z = np.load(p, allow_pickle=True); meta = json.loads(bytes(z["__meta__"]).decode()) + if "cls" not in z.files or not meta: n_empty += 1; continue + cls = z["cls"]; S = {k: z[k] for k in z.files if k.startswith("score_")} + for i, m in enumerate(meta): + if int(m["state"]) != a.state: continue + ep = int(m["episode"]); fr = int(m["frame"]) + if ep not in entry: continue + av = list(m["avail"]) + if GOOD not in av or BAD not in av: continue + g = (cls[i] == av.index(GOOD)); b = (cls[i] == av.index(BAD)) + if g.sum() < a.min_side or b.sum() < a.min_side: continue + if GOODR and ROUTE.get(ep) not in GOODR: continue + rec.append({"ep": ep, "d": fr - entry[ep], "g": g, "b": b, **{k: S[k][i] for k in S}}) + if not rec: print(f"[skip] {arm}: no anchors at S{a.state}"); continue + keys = sorted(k for k in rec[0] if k.startswith("score_")) + seen = {} + for W in a.windows + [10**9]: + sub = [r for r in rec if 0 <= r["d"] <= W] + if len(sub) < 20: continue + sig = (len(sub), len({r["ep"] for r in sub})) + if sig in seen: + print(f" [DUPLICATE] {arm} window<={W}: same {sig[0]}-anchor / {sig[1]}-episode set as " + f"window<={seen[sig]}; not re-read, ceiling {CEIL.get((a.state,W)):.3f} does not apply to it") + continue + seen[sig] = W + eps = [r["ep"] for r in sub] + out = {"arm": arm, "head": head, "matched": matched, "held_out": held_out, + "W": W, "n": len(sub), "eps": sig[1], "ceil": CEIL.get((a.state, W), float("nan"))} + for k in keys: + vals = []; ties = []; cvs = [] + for r in sub: + sel = r["g"] | r["b"]; sc = np.asarray(r[k], float)[sel] + vals.append(auc(sc, r["g"][sel])) + mx = sc.max(); ties.append(float((sc == mx).sum() > 1)) + mu = abs(sc.mean()); cvs.append(float(sc.std() / mu) if mu > 1e-12 else float("nan")) + v = np.array(vals, float); ok = np.isfinite(v) + lo, hi = boot_eps(v[ok], [e for e, o in zip(eps, ok) if o]) + out[k] = (float(v[ok].mean()), lo, hi, float(np.mean(ties)), + float(np.nanmean(cvs)) if np.isfinite(cvs).any() else float("nan")) + rows.append(out) + +hdr = f"| head | matched? | held_out | window | anchors | eps | ceiling |" +for k in ("score_idql", "score_permuted__idql", "score_rsm", "score_permuted__rsm"): + hdr += f" {k.replace('score_','')} AUC [CI] ties cv |" +print("\n" + hdr); print("|" + "---|" * (7 + 4)) +for r in rows: + line = (f"| {r['head']} | {'YES' if r['matched'] else '**CROSS-LABEL**'} | {r['held_out']} | " + f"<={'all' if r['W']>10**8 else r['W']} | {r['n']} | {r['eps']} | {r['ceil']:.3f} |") + for k in ("score_idql", "score_permuted__idql", "score_rsm", "score_permuted__rsm"): + if k not in r: line += " -- |"; continue + m, lo, hi, ti, cv = r[k] + line += f" {m:.3f} [{lo:.3f},{hi:.3f}] t={ti:.2f} cv={cv:.3f} |" + print(line) + +print("\n# VERDICT per row: PASS requires the CI strictly above its OWN permuted line AND strictly below") +print("# its OWN ceiling. CI touching or crossing the ceiling => flagged as label exploitation.") +print("| head | window | col | point | own permuted | own ceiling | verdict |") +print("|---|---|---|---|---|---|---|") +for r in rows: + for col, perm in (("score_idql", "score_permuted__idql"), ("score_rsm", "score_permuted__rsm")): + if col not in r or perm not in r: continue + m, lo, hi, _, _ = r[col]; pm = r[perm][0]; c = r["ceil"] + if lo > pm and hi < c: v = "**PASS**" + elif lo > pm and hi >= c: v = "above line but CI REACHES CEILING -> label exploitation" + elif hi < pm: v = "BELOW its own permuted line" + else: v = "straddles its permuted line -- no effect" + print(f"| {r['head']} | <={'all' if r['W']>10**8 else r['W']} | {col.replace('score_','')} | " + f"{m:.3f} [{lo:.3f},{hi:.3f}] | {pm:.3f} | {c:.3f} | {v} |") + +# run 49: JSON side-output. `rows` is exactly what the two tables above are printed from, so a builder +# reading this file cannot disagree with the markdown. Written LAST so a crash never leaves a partial file +# that looks complete; written via .tmp + rename so a reader can never see a half-written json. +if a.json: + import os + payload = {"generator": "reduce_metric2_square.py", "state": a.state, "split": a.split, + "good_routes": GOODR, "min_side": a.min_side, "windows": a.windows, + "ceilings_used": {f"{a.state},{w}": CEIL.get((a.state, w)) for w in a.windows + [10**9]}, + "n_rows": len(rows), "rows": rows} + tmpp = a.json + ".tmp" + with open(tmpp, "w") as fh: + json.dump(payload, fh, indent=1, default=lambda o: float(o) if hasattr(o, "__float__") else str(o)) + os.rename(tmpp, a.json) + print(f"\n[json] wrote {a.json} ({len(rows)} rows)") diff --git a/rsm_rise/scripts/real/reduce_replicate_families.py b/rsm_rise/scripts/real/reduce_replicate_families.py new file mode 100644 index 0000000000000000000000000000000000000000..af18fd90097a850600064eca5cf5aced1b471fb8 --- /dev/null +++ b/rsm_rise/scripts/real/reduce_replicate_families.py @@ -0,0 +1,214 @@ +#!/usr/bin/env python3 +"""REWARD_MATRIX run 45 -- the RSM fine-tune REPLICATE FLOOR as a DISTRIBUTION over n draws, not a 2-draw +range, and every METRIC-1 verdict re-adjudicated against it. + +WHY THIS REPLACES reduce_replicate_floor.py. +Run 44 measured the floor from the `_rep` pairs and reported it as `max |delta|` over pairs, then said the +reducer "extends automatically once the new *_fl?_x120 cells are scored". IT DOES NOT: that reducer globs +`rsm_*_rep` and pairs each with its base, so the 8 new replicates (jobs 1908460/1908461) are invisible to +it. Stated plainly because run 44's own next-run list was wrong about this. + +AND THE STATISTIC ITSELF WAS NOT COMPARABLE ACROSS HEADS. `max |delta|` over pairs is a RANGE, and the +expected range of n normal draws GROWS WITH n: 1.128*sigma at n=2, 2.06 at n=4, 2.53 at n=6. So a head +measured with 2 draws gets a systematically SMALLER floor than the same head measured with 6, and the +"margin / floor" ratios run 44 printed for different heads were computed on statistics with different +scales. Every ratio run 44 quoted was at n=2 throughout, so they were comparable TO EACH OTHER -- that is +why this is a refinement and not a retraction -- but they are NOT comparable to anything measured at n=5 or +n=6, which is what is on disk from this run onward. + +WHAT THIS DOES INSTEAD. It groups every scored RSM cell into an EXACT-CONFIG REPLICATE FAMILY by stripping +the replicate token (`_rep`, `_fl`) from the cell name, and for each family with n >= 2 draws reports: + sd -- the sample sd of stitch_A over the family. THIS is the floor, and it is n-comparable. + range -- max-min, printed beside n so run 44's numbers can be found again (at n=2, range == |delta|). + n -- because a 2-draw sd is itself a wild estimate and must be read as such. +A family's draws are the published cell plus its replicates; they share only the base parent checkpoint and +differ only in the fine-tune's data-order RNG, which is the whole point. + +VERDICT RULE, unchanged in spirit from run 44 and stated per family: a cross-column claim is REPRODUCIBLE +only if EVERY draw in the family lands on the same side of that head's strongest reportable reward-matched +IQL baseline with disjoint episode-bootstrap CIs, and the worst margin is >= 2 sd of the family. A family +whose sd exceeds its own head's baseline is NOT REPORTABLE per cell at all (#281 correction (C), run 44). +""" +import glob, json, os, re, math + +ROOT = "/proj/dmfexp/zwhong/rsm_rise" +HEALTH_BAR = 0.30 +# Bit-identical hdf5 `rewards` => one label, one reward-matched critic. Reconfirmed run 43 section 7. +ALIAS = {"GOAL_SEGMENT_CONTRASTIVE": "GOAL_SEGMENT", "RISE_PROVENANCE": "EXPERT_EPISODE"} +# E[range]/sigma for n normal draws (Tippett). Printed so a range can be read back onto the sd scale. +ERANGE = {2: 1.128, 3: 1.693, 4: 2.059, 5: 2.326, 6: 2.534, 7: 2.704, 8: 2.847, + 9: 2.970, 10: 3.078, 11: 3.173, 12: 3.258} # run 53: extended so the n=10 C10_s1 family +# prints its constant instead of nan. Purely diagnostic -- sd, not range, is the floor -- but a +# measured range/sd at or near ERANGE[n] is evidence the family is ONE normal sample rather than two +# clusters, which is exactly what an "all n draws on one side" verdict assumes. + +def load(head, cell): + p = f"{ROOT}/status/real/stitch/{head}/{cell}/stitch_value.json" + if not os.path.exists(p): return None + d = json.load(open(p)) + for mode in ("rsm", "idql"): + m = d.get("modes", {}).get(mode) + if not m: continue + if not m.get("defined"): return {"cell": cell, "err": "UNDEFINED"} + g = d["groups"]; C, E = m["mean_C"], m["mean_E"] + D = g["D_S3late_goal"][mode]["mean"] + h = (C - E) / (D - E) if (D - E) != 0 else float("nan") + return {"cell": cell, "mode": mode, "A": m["stitch_A"], "ci": m["boot"]["ratioA_ci95"], + "health": h, "cvA": g["A_arrive_0->1->3"][mode]["cv"]} + return None + +def strongest_idql(head, _seen=None): + _seen = _seen or set() + if head in _seen: return None + _seen.add(head) + best = None + for p in sorted(glob.glob(f"{ROOT}/status/real/stitch/{head}/idql_*/stitch_value.json")): + r = load(head, p.split("/")[-2]) + if not r or "err" in r or not (r["health"] >= HEALTH_BAR): continue + if best is None or r["A"] > best["A"]: best = r + if best is None and head in ALIAS: + best = strongest_idql(ALIAS[head], _seen) + if best is not None: best = dict(best, via_alias=ALIAS[head]) + return best + +REP = re.compile(r"_(?:rep|fl\d+)(?=_|$)") + +def family_key(cell): + """Strip the replicate token wherever it sits. `R_M_ft_v1_fl0_x120` -> `R_M_ft_v1_x120`, + `R_M_ft_v1_rep` -> `R_M_ft_v1`. A cell with no replicate token is its own family of one and is only + reported once a replicate joins it, so nothing on disk is reinterpreted by this grouping alone.""" + return REP.sub("", cell) + +def sd(v): + n = len(v) + if n < 2: return float("nan") + mu = sum(v) / n + return math.sqrt(sum((x - mu) ** 2 for x in v) / (n - 1)) + +fams = {} # (head, key) -> [rec] +for p in sorted(glob.glob(f"{ROOT}/status/real/stitch/*/rsm_*/stitch_value.json")): + head = p.split("/")[-3]; cell = p.split("/")[-2] + r = load(head, cell) + if not r: continue + fams.setdefault((head, family_key(cell)), []).append(r) + +print("REWARD_MATRIX run 45 -- RSM fine-tune REPLICATE FLOOR as a DISTRIBUTION (sd over n exact-config draws)") +print("Floor = sample sd of stitch_A within an exact-config replicate family. Range is printed beside n") +print("because E[range]/sd grows with n (1.13 at n=2, 2.33 at n=5, 2.53 at n=6), so run 44's max-|delta|") +print("floors are NOT comparable to anything measured at n>2.\n") +print("| head | family | n | draws (stitch_A) | mean | **sd = FLOOR** | range | range/sd | E[range]/sd at this n | health min | any draw UNDEFINED / unhealthy |") +print("|" + "---|" * 11) +rows = [] +for (head, key), recs in sorted(fams.items()): + if len(recs) < 2: continue + bad = [r["cell"] for r in recs if "err" in r] + ok = [r for r in recs if "err" not in r] + if len(ok) < 2: + print(f"| {head} | {key} | {len(recs)} | **NOT REPORTABLE** -- fewer than 2 defined draws " + f"(undefined: {', '.join(bad)}) | -- | -- | -- | -- | -- | -- | -- |"); continue + A = [r["A"] for r in ok] + s = sd(A); rng = max(A) - min(A) + hmin = min(r["health"] for r in ok) + unhealthy = [r["cell"] for r in ok if not (r["health"] >= HEALTH_BAR)] + flags = [] + if bad: flags.append(f"UNDEFINED: {', '.join(bad)}") + if unhealthy: flags.append(f"health<{HEALTH_BAR}: {', '.join(unhealthy)}") + rows.append({"head": head, "key": key, "recs": ok, "A": A, "sd": s, "rng": rng, "n": len(ok)}) + print(f"| {head} | {key} | {len(ok)} | {' '.join(f'{x:+.4f}' for x in sorted(A))} | {sum(A)/len(A):+.4f} | " + f"**{s:.4f}** | {rng:.4f} | {rng/s if s>0 else float('nan'):.2f} | " + f"{ERANGE.get(len(ok),float('nan')):.2f} | {hmin:.3f} | {'; '.join(flags) if flags else 'none'} |") + +print("\nEVERY FAMILY AGAINST ITS HEAD'S STRONGEST REPORTABLE REWARD-MATCHED IQL BASELINE") +print("A claim is REPRODUCIBLE only if all n draws land on the same side with disjoint CIs AND the worst") +print("margin is >= 2 sd. `sd / baseline >= 1` means no single cell of that family is interpretable.\n") +print("| head | family | n | strongest IQL [CI] (health) [cell] | sd/baseline | side | worst margin | margin/sd | verdict |") +print("|" + "---|" * 9) +JROWS = [] # run 49: structured mirror of the verdict table, for build_reward_matrix_v2.py +for r in sorted(rows, key=lambda r: (r["head"], r["key"])): + b = strongest_idql(r["head"]) + if b is None: + print(f"| {r['head']} | {r['key']} | {r['n']} | **NO REPORTABLE IQL CELL** (no alias either) -- head " + f"UNREPORTABLE across columns | -- | -- | -- | -- | no cross-column verdict exists |") + JROWS.append({"head": r["head"], "family": r["key"], "n": r["n"], "draws": sorted(r["A"]), + "sd": r["sd"], "range": r["rng"], "baseline": None, + "verdict_class": "NO_REPORTABLE_IQL", "side": None, "worst": None, "margin_sd": None}) + continue + via = f" VIA ALIAS {b['via_alias']}" if b.get("via_alias") else "" + above = [t for t in r["recs"] if t["ci"][0] > b["ci"][1]] + below = [t for t in r["recs"] if t["ci"][1] < b["ci"][0]] + if len(above) == r["n"]: + worst = min(t["A"] - b["A"] for t in r["recs"]); side = f"ALL {r['n']}/{r['n']} ABOVE" + elif len(below) == r["n"]: + worst = min(b["A"] - t["A"] for t in r["recs"]); side = f"ALL {r['n']}/{r['n']} BELOW" + else: + worst = None + side = (f"SPLIT ({len(above)} above / {len(below)} below / " + f"{r['n']-len(above)-len(below)} straddling)") + sb = r["sd"] / b["A"] if b["A"] != 0 else float("inf") + ms = (worst / r["sd"]) if (worst is not None and r["sd"] > 0) else None + if worst is None: + # run 48 FIX. This branch used to print "lands on BOTH sides" for EVERY split, including splits + # where `below` is EMPTY. `above`/`below` are DISJOINT-CI tests, so a family with 4 above / 0 + # below / 2 straddling has NO draw on the opposite side -- it failed to SEPARATE on 2 draws, which + # is a different (and weaker) failure than a sign flip, and the old string overstated it. Both + # still fail the REPRODUCIBLE bar; only the stated reason changes. The worst draw's signed delta + # from the baseline is now printed so the reader can see how far the weakest draw actually is. + wd = min(t["A"] - b["A"] for t in r["recs"]) + if above and below: + verdict = ("**NOT REPRODUCIBLE / SIGN FLIP** -- the same config lands on BOTH sides of the " + f"baseline with disjoint CIs ({len(above)} above, {len(below)} below), so an ABOVE " + f"verdict from any one of these cells is a draw from this spread; worst draw " + f"{wd:+.4f} vs baseline") + else: + d = "above" if above else ("below" if below else "neither side") + verdict = (f"**NOT REPRODUCIBLE / NO SEPARATION** -- NO draw lands on the side opposite " + f"{d}; {r['n']-len(above)-len(below)} of {r['n']} draws are INDISTINGUISHABLE " + f"from the baseline (CI overlap). This is a failure to separate, NOT a sign flip; " + f"worst draw {wd:+.4f} vs baseline") + elif ms is not None and ms >= 2.0: + verdict = f"**REPRODUCIBLE** -- every draw on one side, worst margin {ms:.2f} sd" + else: + verdict = (f"same side but the worst margin is only {ms:.2f} sd -- DIRECTIONAL, not a measured " + f"separation at this n") + if sb >= 1.0: + verdict += f"; and sd is {sb:.2f}x the whole baseline, so NO single cell here is interpretable" + # run 49: verdict_class is derived from the SAME branch that produced `verdict`, so the JSON and the + # markdown cannot disagree about whether a family is a SIGN FLIP or merely failed to separate. + if worst is None: + vclass = "SIGN_FLIP" if (above and below) else "NO_SEPARATION" + elif ms is not None and ms >= 2.0: + vclass = "REPRODUCIBLE" + else: + vclass = "DIRECTIONAL" + JROWS.append({"head": r["head"], "family": r["key"], "n": r["n"], "draws": sorted(r["A"]), + "sd": r["sd"], "range": r["rng"], "health_min": min(t["health"] for t in r["recs"]), + "baseline": {"cell": b["cell"], "A": b["A"], "ci": b["ci"], "health": b["health"], + "via_alias": b.get("via_alias")}, + "sd_over_baseline": sb, "n_above": len(above), "n_below": len(below), + "n_straddle": r["n"] - len(above) - len(below), + "worst_draw_delta": min(t["A"] - b["A"] for t in r["recs"]), + "side": side, "worst": worst, "margin_sd": ms, + "sd_exceeds_baseline": bool(sb >= 1.0), "verdict_class": vclass, "verdict": verdict}) + print(f"| {r['head']} | {r['key']} | {r['n']} | {b['A']:+.4f} [{b['ci'][0]:+.4f},{b['ci'][1]:+.4f}] " + f"({b['health']:.3f}) [{b['cell']}{via}] | {sb:.2f}x | {side} | " + f"{f'{worst:+.4f}' if worst is not None else '--'} | {f'{ms:.2f}' if ms is not None else '--'} | {verdict} |") + +print("\nHOW TO READ THIS AGAINST RUN 44") +print("Run 44's floors were all n=2 ranges. Where a family here has n>2, its sd is the number to quote and") +print("run 44's range for the same family is superseded, NOT contradicted. Direction of the correction,") +print("because it is the opposite of the flattering one and must not be stated loosely: E[range] at n=2 is") +print("1.128 sd, so a 2-draw range OVER-states sd by ~13%, run 44's floors were ~13% too LARGE, and its") +print("'margin / floor' ratios were ~13% too SMALL -- i.e. run 44 was CONSERVATIVE about its own claims, not") +print("generous. The real hazard is the other direction: a range measured at n=5 or n=6 would be ~2.3-2.5") +print("sd and would look like a floor twice as large for no reason but n. That is why sd is used here.") + +# run 49: JSON side-output, enabled by env RRF_JSON (this script has no argparse and I am not adding one to +# a reducer whose text output is quoted in three posted issue comments). Unset => output byte-identical. +_J = os.environ.get("RRF_JSON", "") +if _J: + payload = {"generator": "reduce_replicate_families.py", "health_bar": HEALTH_BAR, + "alias": ALIAS, "n_families": len(JROWS), "families": JROWS} + with open(_J + ".tmp", "w") as fh: + json.dump(payload, fh, indent=1) + os.rename(_J + ".tmp", _J) + print(f"\n[json] wrote {_J} ({len(JROWS)} families)") diff --git a/rsm_rise/scripts/real/reduce_replicate_floor.py b/rsm_rise/scripts/real/reduce_replicate_floor.py new file mode 100644 index 0000000000000000000000000000000000000000..204c3a9a308ba4aa37bba9f48ab95d6cd3989133 --- /dev/null +++ b/rsm_rise/scripts/real/reduce_replicate_floor.py @@ -0,0 +1,134 @@ +#!/usr/bin/env python3 +"""REWARD_MATRIX run 44 -- the RSM FINE-TUNE REPLICATE FLOOR on METRIC 1, and what it does to every +single-cell verdict in the matrix. + +WHY. Run 43 explained the 8/2/10 GOAL_SEGMENT split as a SEED effect: "7 of the 8 cells above the +strongest baseline are `_s1` and every matching seed-0 cell falls BELOW it". That reading is WRONG, and +the counter-example is already on disk: `R_M_ft_v1_rep` is an EXACT-CONFIG replicate of `R_M_ft_v1` +(scripts/real/jobs/rw/ft_R_M_ft_v1_rep.sh -- same size arg M, i.e. the same training seed 0, the same +parent R_M/ckpt.pt, the same beta flags, the same reward npy, the same --steps 110000, scored at the same +ckpt_s110000; ONLY --out differs), and it lands ABOVE the strongest baseline while its twin lands BELOW. + +So the axis that flips the headline verdict is not the seed and not the fine-tune length: it is the +run-to-run NONDETERMINISM of the fine-tune itself. This reducer measures that floor on every exact +replicate pair on disk and prints it BESIDE the head's strongest reward-matched IQL baseline, because the +only question that matters is whether the floor is smaller or larger than the effect being claimed. + +TEST USED, and its limitation stated up front. stitch_value.json stores summary statistics and a +bootstrap CI but NOT per-episode values, so a PAIRED episode bootstrap of the replicate difference cannot +be computed from disk. The verdict here therefore uses DISJOINTNESS OF THE TWO MARGINAL EPISODE-BOOTSTRAP +CIs -- the same criterion every other verdict in this stream uses. Disjoint marginal CIs is the +CONSERVATIVE direction (less powerful than a paired test), so a difference called real here is real; a +pair called "overlapping" may still differ under a paired test and is reported as UNDECIDED, not as equal. +""" +import glob, json, os + +ROOT = "/proj/dmfexp/zwhong/rsm_rise" +HEALTH_BAR = 0.30 + +def load(head, cell): + p = f"{ROOT}/status/real/stitch/{head}/{cell}/stitch_value.json" + if not os.path.exists(p): return None + d = json.load(open(p)) + for mode in ("rsm", "idql"): + m = d.get("modes", {}).get(mode) + if not m: continue + if not m.get("defined"): return {"cell": cell, "err": "UNDEFINED"} + g = d["groups"]; C, E = m["mean_C"], m["mean_E"] + D = g["D_S3late_goal"][mode]["mean"] + h = (C - E) / (D - E) if (D - E) != 0 else float("nan") + return {"cell": cell, "mode": mode, "A": m["stitch_A"], "ci": m["boot"]["ratioA_ci95"], + "health": h, "cvA": g["A_arrive_0->1->3"][mode]["cv"]} + return None + +# Reconfirmed run 43 section 7 at the hdf5 `rewards` level: the wrapper hdf5s are BIT-IDENTICAL, so these +# heads share one label and one reward-matched critic. A head with no idql cell of its own is therefore NOT +# baseline-less -- it is baselined through its alias, and saying "NO REPORTABLE IQL CELL" without the alias +# would wrongly retire a comparable row. +ALIAS = {"GOAL_SEGMENT_CONTRASTIVE": "GOAL_SEGMENT", "RISE_PROVENANCE": "EXPERT_EPISODE"} + +def strongest_idql(head): + best = None + for p in sorted(glob.glob(f"{ROOT}/status/real/stitch/{head}/idql_*/stitch_value.json")): + r = load(head, p.split("/")[-2]) + if not r or "err" in r or not (r["health"] >= HEALTH_BAR): continue + if best is None or r["A"] > best["A"]: best = r + if best is None and head in ALIAS: + best = strongest_idql(ALIAS[head]) + if best is not None: best["via_alias"] = ALIAS[head] + return best + +print("REWARD_MATRIX run 44 -- RSM fine-tune REPLICATE FLOOR on METRIC 1 (stitch_A)") +print("Verdict = disjointness of the two marginal episode-bootstrap CIs (conservative; see file header).\n") +print("| head | replicate pair | stitch_A twin 1 [CI] | stitch_A twin 2 [CI] | |delta| | CIs | health 1/2 | cv(A) 1/2 |") +print("|" + "---|" * 8) +pairs = [] +for p in sorted(glob.glob(f"{ROOT}/status/real/stitch/*/rsm_*_rep")): + head = p.split("/")[-2]; rep = p.split("/")[-1]; base = rep[:-4] + a = load(head, base); b = load(head, rep) + if not a or not b: print(f"| {head} | {base} / {rep} | MISSING one twin -- not reportable |"); continue + if "err" in a or "err" in b: + print(f"| {head} | {base} / {rep} | UNDEFINED twin -- not reportable |"); continue + d = abs(a["A"] - b["A"]) + disj = (a["ci"][1] < b["ci"][0]) or (b["ci"][1] < a["ci"][0]) + pairs.append({"head": head, "base": base, "rep": rep, "a": a, "b": b, "d": d, "disj": disj}) + print(f"| {head} | {base} / {rep} | {a['A']:+.4f} [{a['ci'][0]:+.4f},{a['ci'][1]:+.4f}] | " + f"{b['A']:+.4f} [{b['ci'][0]:+.4f},{b['ci'][1]:+.4f}] | {d:.4f} | " + f"{'**DISJOINT**' if disj else 'overlap -> UNDECIDED'} | {a['health']:.3f}/{b['health']:.3f} | " + f"{a['cvA']:.3f}/{b['cvA']:.3f} |") + +print("\nTHE FLOOR AGAINST THE EFFECT -- per head, the replicate spread beside the strongest reward-matched IQL baseline") +print("| head | max replicate |delta| | strongest IQL stitch_A [CI] (health) | floor / baseline | worst replicate MARGIN over baseline | margin / floor | what a single-cell verdict is worth |") +print("|" + "---|" * 7) +by = {} +for q in pairs: by.setdefault(q["head"], []).append(q) +for head in sorted(by): + mx = max(by[head], key=lambda q: q["d"]) + s = strongest_idql(head) + if s is None: + print(f"| {head} | {mx['d']:.4f} ({mx['base']}) | NO REPORTABLE IQL CELL -- head UNREPORTABLE across columns | -- | " + f"no cross-column verdict exists to be worth anything |") + continue + ratio = mx["d"] / s["A"] if s["A"] != 0 else float("inf") + # The margin that must survive the floor: over EVERY twin of EVERY replicate pair on this head, the + # SMALLEST distance from that cell's stitch_A to the baseline point. A head whose worst replicate still + # clears the baseline by several floors is a REPRODUCIBLE claim; that is the bar run 43's max-over-20 + # GOAL_SEGMENT headline does not meet and this head may. + twins = [q["a"] for q in by[head]] + [q["b"] for q in by[head]] + above = [t for t in twins if t["ci"][0] > s["ci"][1]] + below = [t for t in twins if t["ci"][1] < s["ci"][0]] + if len(above) == len(twins): + worst = min(t["A"] - s["A"] for t in twins); side = f"ALL {len(twins)}/{len(twins)} twins ABOVE" + elif len(below) == len(twins): + worst = min(s["A"] - t["A"] for t in twins); side = f"ALL {len(twins)}/{len(twins)} twins BELOW" + else: + worst = None; side = f"SPLIT ({len(above)} above / {len(below)} below / {len(twins)-len(above)-len(below)} straddling)" + mf = (worst / mx["d"]) if (worst is not None and mx["d"] > 0) else None + if ratio >= 1.0: + worth = (f"**NOT INTERPRETABLE** -- re-running the SAME config moves stitch_A by {ratio:.2f}x the " + f"whole baseline, so a single cell's ABOVE/BELOW verdict is a draw from that spread") + elif ratio >= 0.5: + worth = f"weak -- the floor is {ratio:.2f}x the baseline; only deltas well above the floor are claims" + else: + worth = f"usable -- the floor is {ratio:.2f}x the baseline" + via = f" VIA ALIAS {s['via_alias']}" if s.get("via_alias") else "" + mtxt = f"{worst:+.4f} ({side})" if worst is not None else side + mftxt = f"{mf:.2f}x" if mf is not None else "--" + if worst is not None and mf is not None and mf >= 2.0: + worth = (f"**REPRODUCIBLE** -- every replicate twin lands on the same side of the baseline and the " + f"worst margin is {mf:.2f}x the measured floor") + print(f"| {head} | {mx['d']:.4f} ({mx['base']}) | {s['A']:+.4f} [{s['ci'][0]:+.4f},{s['ci'][1]:+.4f}] " + f"({s['health']:.3f}) [{s['cell']}{via}] | {ratio:.2f}x | {mtxt} | {mftxt} | {worth} |") + +print("\nCONSEQUENCE FOR RUN 43's READING") +print("Run 43 attributed the GOAL_SEGMENT 8/2/10 split to the SEED. The replicate pairs falsify that:") +print("a seed-0 replicate can land on either side of the baseline. Restate the caution as the REPLICATE") +print("FLOOR, which is the stronger and less flattering claim: on this head no single-cell METRIC-1") +print("comparison -- single-seed or not -- is interpretable, and the +0.2999 maximum is a max over 20") +print("draws from a distribution whose within-config spread is of the order of the baseline itself.") +print("") +print("AND THE ROW THAT SURVIVES IT. Read against the floor rather than against a max, GOAL_SEGMENT is the") +print("WEAKEST of the three heads, not the strongest, and GOAL_SEGMENT_CONTRASTIVE's C10 cells are the") +print("strongest: baselined through the GOAL_SEGMENT critic by the bit-identical-label alias, all four C10") +print("twins (2 base seeds x 2 replicates) clear it with disjoint CIs while that head's own replicate floor") +print("is an order of magnitude below the margin. That is a reproducible cross-column claim; +0.2999 is not.") diff --git a/rsm_rise/scripts/real/reduce_square_matrix.py b/rsm_rise/scripts/real/reduce_square_matrix.py new file mode 100644 index 0000000000000000000000000000000000000000..3f6c9330a1cafa2ed4af4457fab12349f004dbf9 --- /dev/null +++ b/rsm_rise/scripts/real/reduce_square_matrix.py @@ -0,0 +1,184 @@ +#!/usr/bin/env python3 +"""THE SQUARE REWARD MATRIX -- one row per reward head, BOTH scorers on THAT head's label. + +Rows are reward heads. The RSM column and the IQL column of a row are trained on the SAME +reward array as each other and as the row (directly, or via a bit-identical label -- the two +measured aliases are printed). No row is ever compared against a number from another row. + +RSM column = CONFIG-MATCHED: base R_M, +10k fine-tune, ckpt_s110000, cap OFF (beta-trunc-eps + 0.99), default read-out, seeds 0 and 1. Every head has exactly this configuration, + so a difference down the column is a label difference, not a base/knob difference. +IQL column = STEP-MATCHED at epoch 1500 (`idql_rw_s*_e1500`), the one epoch at which all five + distinct labels have seeds on disk. UNDERTRAINED against the e5000 recipe. + +Each column is quoted beside ITS OWN logged-return no-stitch line, read at that column's own +discount (RSM gamma=0.999, IDQL discount=0.99) -- a value function that merely reproduced the +logged discounted return would print that line and did NOT stitch. +Per gen_q#281 + the run-39 addition posted there, every ratio prints its decomposition +A-E (numerator), C-E (denominator) and D-C, plus kept anchors, kept episodes and the group CVs. +""" +import json, os, statistics + +ROOT = "/proj/dmfexp/zwhong/rsm_rise" +STITCH = os.path.join(ROOT, "status/real/stitch") +GROUPS = ["A_arrive_0->1->3", "B_arrive_0->2->3", "C_S3entry_goal", + "D_S3late_goal", "E_arrive_0->5_FAIL"] +MODE_GAMMA = {"rsm": "0.999", "idql": "0.99"} + +# measured by scripts/real/stitch_anchor_label_audit.py over all 181530 frames +ALIAS = {"GOAL_SEGMENT_CONTRASTIVE": "GOAL_SEGMENT", "RISE_PROVENANCE": "EXPERT_EPISODE"} + +# does the head's own label mark group A (the 0->1->3 route) as reward 1.000? If it does, +# METRIC 1's numerator is the head reading its own label back and the test has no content there. +LABELS_GROUP_A = {"EXPERT_EPISODE": True, "RISE_PROVENANCE": True, "GOAL_EPISODE": False, + "GOAL_SEGMENT": False, "GOAL_SEGMENT_CONTRASTIVE": False, + "GOAL_WINDOW_400": False, "GOAL_WINDOW_100": False} +SEES_RANK_LABEL = {"EXPERT_EPISODE": "YES", "RISE_PROVENANCE": "YES", "GOAL_EPISODE": "no", + "GOAL_SEGMENT": "no", "GOAL_SEGMENT_CONTRASTIVE": "no", + "GOAL_WINDOW_400": "unmeasured", "GOAL_WINDOW_100": "unmeasured"} + +# row -> (head dir the RSM cells live under, RSM cell basename, label the row is trained on) +ROWS = [ + ("GOAL_EPISODE", "GOAL_EPISODE", "rsm_R_M_ft_v0"), + ("GOAL_SEGMENT", "GOAL_SEGMENT", "rsm_R_M_ft_v1"), + ("GOAL_SEGMENT_CONTRASTIVE", "GOAL_SEGMENT_CONTRASTIVE", "rsm_R_M_ft_C3"), + ("GOAL_SEGMENT_CONTRASTIVE", "GOAL_SEGMENT_CONTRASTIVE", "rsm_R_M_ft_C10"), + ("EXPERT_EPISODE", "EXPERT_EPISODE", "rsm_R_M_ft_v0lit"), + ("RISE_PROVENANCE", "EXPERT_EPISODE", "rsm_R_M_ft_v5"), + ("GOAL_WINDOW_400", "GOAL_WINDOW_400", "rsm_R_M_ft_B400"), + ("GOAL_WINDOW_100", "GOAL_WINDOW_100", "rsm_R_M_ft_B"), +] +IQL_EPOCH = 1500 + + +def nostitch(mode, head): + p = os.path.join(STITCH, "LOGGED_RETURN_NULL_g%s.json" % MODE_GAMMA[mode]) + r = json.load(open(p))["heads"].get(ALIAS.get(head, head), {}) + return r.get("nostitch_ratioA"), r.get("defined") + + +def read(head_dir, cell): + p = os.path.join(STITCH, head_dir, cell, "stitch_value.json") + if not os.path.exists(p): + return None + return json.load(open(p)) + + +def summarise(d, mode): + m = d["modes"][mode] + g = d["groups"] + mu = {k: g[k][mode]["mean"] for k in GROUPS} + cv = {k: g[k][mode]["cv"] for k in GROUPS} + return dict( + defined=m.get("defined", False), + A=m.get("stitch_A"), B=m.get("stitch_B"), + ciA=m.get("boot", {}).get("ratioA_ci95"), ciB=m.get("boot", {}).get("ratioB_ci95"), + dCE=m.get("C_minus_E"), ciCE=m.get("boot", {}).get("dCE_ci95"), + AmE=mu["A_arrive_0->1->3"] - mu["E_arrive_0->5_FAIL"], + DmC=mu["D_S3late_goal"] - mu["C_S3entry_goal"], + DmE=mu["D_S3late_goal"] - mu["E_arrive_0->5_FAIL"], + ka="/".join(str(m["kept_anchors"][k]) for k in GROUPS), + ke="/".join(str(m["kept_episodes"][k]) for k in GROUPS), + cv=cv, ckpt=d["config"].get("rsm_ckpt") or d["config"].get("idql_ckpt"), + beta=d["config"].get("beta"), gamma=d["config"].get("gamma"), + ) + + +def cells_for(row): + head, hdir, base = row + rsm = [(0, base), (1, base + "_s1")] + out = [] + for sd, c in rsm: + d = read(hdir, c) + if d is not None: + out.append((sd, c, summarise(d, "rsm"))) + iql_head = ALIAS.get(head, head) + iout = [] + for sd in (0, 1, 2): + d = read(iql_head, "idql_rw_s%d_e%d" % (sd, IQL_EPOCH)) + if d is not None: + iout.append((sd, "idql_rw_s%d_e%d" % (sd, IQL_EPOCH), summarise(d, "idql"))) + return out, iout, iql_head + + +def med(xs): + return statistics.median(xs) if xs else float("nan") + + +def main(): + print("=" * 130) + print("THE SQUARE REWARD MATRIX -- METRIC 1 (stitch value test), both scorers on the SAME label") + print("RSM column: base R_M, +10k ft, ckpt_s110000, cap OFF (beta=0.99), default read-out, " + "seeds 0/1, gamma=0.999") + print("IQL column: reward-matched IDQL, STEP-MATCHED at epoch %d, gamma=0.99 -- UNDERTRAINED " + "vs the e5000 recipe" % IQL_EPOCH) + print("Measured label aliases (0 frames differ over all 181530): " + "GOAL_SEGMENT_CONTRASTIVE == GOAL_SEGMENT, RISE_PROVENANCE == EXPERT_EPISODE.") + print("=" * 130) + print() + print("| head | labels group A? | sees S0 rank label? | RSM stitch_A (seed0 / seed1) | RSM " + "no-stitch line | IQL stitch_A (median over seeds) | IQL seeds | IQL no-stitch line |") + print("|" + "---|" * 8) + detail = [] + for row in ROWS: + head, hdir, base = row + rsm, iql, iql_head = cells_for(row) + nsr, _ = nostitch("rsm", head) + nsi, _ = nostitch("idql", head) + rtxt = " / ".join("%.4f" % s["A"] if s["defined"] else "UNDEF" for _, _, s in rsm) or "--" + ivals = [s["A"] for _, _, s in iql if s["defined"]] + itxt = ("%.4f" % med(ivals)) if ivals else "--" + iseeds = " / ".join("%.4f" % v for v in ivals) or "--" + tag = "**YES -- METRIC 1 not testable**" if LABELS_GROUP_A[head] else "no" + alias_note = "" if iql_head == head else " *(IQL via alias `%s`)*" % iql_head + print("| %s%s | %s | %s | %s | %.4f | %s | %s | %.4f |" % ( + head, + (" `%s`" % base.replace("rsm_R_M_ft_", "")) + alias_note + if head == "GOAL_SEGMENT_CONTRASTIVE" else alias_note, + tag, SEES_RANK_LABEL[head], rtxt, nsr, itxt, iseeds, nsi)) + detail.append((head, base, rsm, iql, iql_head)) + print() + print("## Decomposition of every ratio (gen_q#281 + run-39 addition): ratio = (A-E)/(C-E)") + print() + print("| head | col | cell | stitch_A | boot95 A | A-E | C-E | C-E boot95 | D-C | (C-E)/(D-E) " + "| stitch_B | kept anchors | kept episodes |") + print("|" + "---|" * 13) + for head, base, rsm, iql, iql_head in detail: + for col, cells in (("RSM", rsm), ("IQL", iql)): + for sd, c, s in cells: + if not s["defined"]: + print("| %s | %s | %s | **UNDEFINED** | -- | -- | %.4f | -- | -- | -- | -- | %s | %s |" + % (head, col, c, s["dCE"], s["ka"], s["ke"])) + continue + dh = s["dCE"] / s["DmE"] if s["DmE"] else float("nan") + print("| %s | %s | %s | %.4f | [%.4f,%.4f] | %.4f | %.4f | [%.4f,%.4f] | %+.4f | " + "%.3f%s | %.4f | %s | %s |" % ( + head, col, c, s["A"], s["ciA"][0], s["ciA"][1], s["AmE"], s["dCE"], + s["ciCE"][0], s["ciCE"][1], s["DmC"], dh, + "**" if dh == dh and dh < 0.30 else "", s["B"], s["ka"], s["ke"])) + print() + print("## Group score CV (degenerate-scorer check; a near-constant scorer has CV ~ 0 on A-D)") + print() + print("| head | col | cell | " + " | ".join(g.split("_")[0] for g in GROUPS) + " |") + print("|" + "---|" * 8) + for head, base, rsm, iql, iql_head in detail: + for col, cells in (("RSM", rsm), ("IQL", iql)): + for sd, c, s in cells: + print("| %s | %s | %s | %s |" % (head, col, c, + " | ".join("%.4f" % s["cv"][g] for g in GROUPS))) + print() + print("## Guards") + print("* Every row's two columns are trained on the same reward array; the only cross-name " + "pairings used are the two MEASURED bit-identical aliases printed above.") + print("* No row is compared against a number from a differently-labelled row.") + print("* Every IQL number here is at epoch %d and is UNDERTRAINED; never compared across epochs." + % IQL_EPOCH) + print("* A row whose `labels group A?` is YES is reading its own label back on METRIC 1's " + "numerator; it is the uninformative head, not the best one.") + print("* `(C-E)/(D-E)` < 0.30 (marked **) = the metric's reference interval spans under a third " + "of the head's own dynamic range, so a high ratio can be a compressed denominator rather " + "than a raised arrival. Read D-C beside it.") + + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/real/reduce_stitch_epoch_curve.py b/rsm_rise/scripts/real/reduce_stitch_epoch_curve.py new file mode 100644 index 0000000000000000000000000000000000000000..48e7a44e5c6a87348d21b2b021771ec53ab97b64 --- /dev/null +++ b/rsm_rise/scripts/real/reduce_stitch_epoch_curve.py @@ -0,0 +1,122 @@ +#!/usr/bin/env python3 +"""REWARD_MATRIX run 43 -- the IQL METRIC-1 column as its OWN EPOCH CURVE, per reward head. + +WHY THIS FILE EXISTS. status/real/SQUARE_MATRIX.txt reports the IQL side of METRIC 1 at a single +step-matched epoch (1500) and carries the caveat "UNDERTRAINED vs the e5000 recipe". That caveat is not +benign: read across the epoch cells already on disk, the reward-matched critic's stitch_A is strongly +epoch-dependent and on two heads it DECAYS toward zero with training. A single-epoch baseline therefore +flatters or penalises the baseline depending on the head, and no cross-column claim in the matrix is safe +until the whole curve is on the page. This reducer prints it. + +What each row prints, per gen_q#281: + * stitch_A with its EPISODE bootstrap CI (never a point alone); + * the head's own measured no-stitch reference (the statistic's fixed 0 = valued like the failure anchor); + * the denominator health (C-E)/(D-E) and the #281 UNREPORTABLE verdict when it is below 0.30; + * the group-A score CV, because a near-constant scorer producing a large ratio is a caution flag; + * kept anchors and kept episodes per group; + * whether the head labels group A (METRIC 1 is NOT TESTABLE when it does -- the scorer can read the + answer off its own label) and whether it can see the S0 rank label. +Nothing is compared across heads: rows of different heads carry different labels and are not commensurable. +""" +import argparse, glob, json, os, sys + +# Heads that LABEL group A (the 0->1->3 arrivals) positively: for these METRIC 1 is not a stitching test, +# because the arrival frames themselves carry reward 1.0. Measured in status/real/SQUARE_MATRIX.txt. +LABELS_A = {"EXPERT_EPISODE", "RISE_PROVENANCE"} +SEES_S0 = {"EXPERT_EPISODE", "RISE_PROVENANCE"} +HEALTH_BAR = 0.30 # gen_q#281 hard guard added run 40 + +def cell_rows(pat, mode): + out = [] + for p in sorted(glob.glob(pat)): + head, cell = p.split("/")[3], p.split("/")[4] + try: + d = json.load(open(p)) + except Exception as e: + out.append({"head": head, "cell": cell, "err": f"unreadable: {e}"}); continue + m = d.get("modes", {}).get(mode) + if not m or not m.get("defined"): + out.append({"head": head, "cell": cell, "err": "UNDEFINED (guard could not establish its reference)"}); continue + g = d["groups"] + def grp(k): + return g[k][mode] + C, E = m["mean_C"], m["mean_E"] + D = grp("D_S3late_goal")["mean"] + health = (C - E) / (D - E) if (D - E) != 0 else float("nan") + out.append({ + "head": head, "cell": cell, + "A": m["stitch_A"], "ci": m["boot"]["ratioA_ci95"], + "CmE": C - E, "DmE": D - E, "health": health, + "cvA": grp("A_arrive_0->1->3")["cv"], "cvC": grp("C_S3entry_goal")["cv"], + "anch": "/".join(str(m["kept_anchors"][k]) for k in + ["A_arrive_0->1->3","B_arrive_0->2->3","C_S3entry_goal","D_S3late_goal","E_arrive_0->5_FAIL"]), + "eps": "/".join(str(m["kept_episodes"][k]) for k in + ["A_arrive_0->1->3","B_arrive_0->2->3","C_S3entry_goal","D_S3late_goal","E_arrive_0->5_FAIL"]), + }) + return out + +def ep_of(cell): + t = cell.rsplit("_e", 1) + return int(t[1]) if len(t) == 2 and t[1].isdigit() else -1 + +def seed_of(cell): + for part in cell.split("_"): + if part.startswith("s") and part[1:].isdigit(): + return int(part[1:]) + return -1 + +def emit(rows, title): + print("=" * 150); print(title); print("=" * 150) + print("| head | labels A? | sees S0 label? | seed | epoch | stitch_A | boot95 (episodes) | C-E | D-E | health | #281 verdict | cv(A) | cv(C) | anchors A/B/C/D/E | episodes A/B/C/D/E |") + print("|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|") + for r in rows: + h = r["head"] + lab = "**YES -- METRIC 1 NOT TESTABLE**" if h in LABELS_A else "no" + s0 = "YES" if h in SEES_S0 else "no" + if "err" in r: + print(f"| {h} | {lab} | {s0} | {seed_of(r['cell'])} | {ep_of(r['cell'])} | **{r['err']}** | | | | | **UNDEFINED, loudly** | | | | |") + continue + v = "ok" if r["health"] >= HEALTH_BAR else f"**UNREPORTABLE (health {r['health']:.3f} < {HEALTH_BAR})**" + print(f"| {h} | {lab} | {s0} | {seed_of(r['cell'])} | {ep_of(r['cell'])} | {r['A']:+.4f} | " + f"[{r['ci'][0]:+.4f},{r['ci'][1]:+.4f}] | {r['CmE']:.3f} | {r['DmE']:.3f} | {r['health']:.3f} | {v} | " + f"{r['cvA']:.4f} | {r['cvC']:.4f} | {r['anch']} | {r['eps']} |") + print() + +def trend(rows): + """Per (head, seed) print the epoch curve on one line so the DIRECTION is visible, not inferred.""" + print("=" * 150) + print("EPOCH DIRECTION per (head, seed) -- stitch_A vs epoch. Reportable cells only; an UNREPORTABLE") + print("cell is printed as 'x' because the guard says its denominator cannot carry a ratio.") + print("=" * 150) + by = {} + for r in rows: + if "err" in r: continue + by.setdefault((r["head"], seed_of(r["cell"])), []).append(r) + for k in sorted(by): + rs = sorted(by[k], key=lambda r: ep_of(r["cell"])) + cells = " ".join(f"e{ep_of(r['cell'])}={r['A']:+.4f}" if r["health"] >= HEALTH_BAR + else f"e{ep_of(r['cell'])}=x" for r in rs) + ok = [r for r in rs if r["health"] >= HEALTH_BAR] + if len(ok) >= 2: + d = ok[-1]["A"] - ok[0]["A"] + # the two CIs are on the SAME episodes but DIFFERENT checkpoints; disjointness is the test + sep = "DISJOINT CIs" if (ok[-1]["ci"][0] > ok[0]["ci"][1] or ok[-1]["ci"][1] < ok[0]["ci"][0]) else "CIs overlap" + verdict = f" -> e{ep_of(ok[0]['cell'])}->e{ep_of(ok[-1]['cell'])} delta {d:+.4f} ({sep})" + else: + verdict = " -> fewer than 2 reportable epochs: NO direction claimed" + print(f" {k[0]:<18} seed{k[1]} {cells}{verdict}") + print() + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--root", default="/proj/dmfexp/zwhong/rsm_rise") + a = ap.parse_args() + os.chdir(a.root) + iq = cell_rows("status/real/stitch/*/idql_rw_*/stitch_value.json", "idql") + iq.sort(key=lambda r: (r["head"], seed_of(r["cell"]), ep_of(r["cell"]))) + emit(iq, "METRIC 1 -- the REWARD-MATCHED IQL column as an EPOCH CURVE (one reward head per row group)") + trend(iq) + print(f"[curve] {len(iq)} idql cells, " + f"{sum(1 for r in iq if 'err' not in r and r['health'] >= HEALTH_BAR)} reportable, " + f"{sum(1 for r in iq if 'err' not in r and r['health'] < HEALTH_BAR)} UNREPORTABLE on the #281 health guard, " + f"{sum(1 for r in iq if 'err' in r)} undefined.") diff --git a/rsm_rise/scripts/real/reduce_stitch_matrix.py b/rsm_rise/scripts/real/reduce_stitch_matrix.py new file mode 100644 index 0000000000000000000000000000000000000000..82085096c88f31178d6ab3fcc9a37fd2152128c2 --- /dev/null +++ b/rsm_rise/scripts/real/reduce_stitch_matrix.py @@ -0,0 +1,2081 @@ +#!/usr/bin/env python3 +"""REWARD_MATRIX (gen_q#280): reduce status/real/stitch///stitch_value.json into the +METRIC-1 table. Reads JSON only -- no model, no hdf5, no compute. + +Per gen_q#281 (spec of record) and the correction this stream posted to it, METRIC 1 is read against +its two FIXED reference points (0 = valued like the failure anchor / episode identity, 1 = full stitch) +with the episode-bootstrap CI. The group-label permutation null is printed only as a labelled +"no group structure" sanity check because a permutation null of a RATIO is heavy-tailed and +near-powerless (measured q05 -5.8 / q95 +7.6). A row whose bootstrap CI of mean(C)-mean(E) is not +strictly above 0 is printed UNDEFINED and no ratio is quoted for it. + +Rows are reward heads. A row NEVER mixes labels: the RSM and IQL columns of one row are the same head. +""" +import json, glob, os, re, collections + +ROOT = "/proj/dmfexp/zwhong/rsm_rise" +STITCH = os.path.join(ROOT, "status/real/stitch") + +# Which heads can see the S0 rank label at all (from run 1's measured per-route means). +SEES_LABEL = { + "GOAL_EPISODE": "no", "GOAL_SEGMENT": "no", "GOAL_SEGMENT_CONTRASTIVE": "no", + "GOAL_WINDOW_400": "no", "GOAL_WINDOW_100": "no", + "EXPERT_EPISODE": "YES", "RISE_PROVENANCE": "YES", +} + +def fmt_ci(ci): + return "[%.3f,%.3f]" % (ci[0], ci[1]) if ci else "--" + +def load(): + rows = collections.defaultdict(list) + for f in sorted(glob.glob(os.path.join(STITCH, "*", "*", "stitch_value.json"))): + head = f.split(os.sep)[-3] + cell = f.split(os.sep)[-2] + if head.startswith("_"): + continue + try: + d = json.load(open(f)) + except Exception as e: + print(" !! unreadable %s/%s: %s" % (head, cell, e)); continue + for mode, m in d.get("modes", {}).items(): + rows[head].append((cell, mode, m, d)) + return rows + + + +def fmt_ns(v): + """the no-stitch line, flagged when the row does not clear it.""" + return "--" if v is None else "%.4f" % v + + +def load_nostitch(gamma): + """RUN 27 -- the MEASURED no-stitch reference line for METRIC 1, per head, at ONE discount. + + Written by scripts/real/stitch_logged_return_null.py (jobs 1897246 / 1897252): the ratio a value + function that merely reproduces the discounted return LOGGED from each anchor would print, on the + identical anchor sets and through the identical statistic. No model, so it cannot be confounded + by training. Measured values -- EXPERT_EPISODE / RISE_PROVENANCE 0.0468 at gamma=0.999, 0.1890 at + gamma=0.99, 0.6357 at gamma=0.95; every goal head exactly 0.0000 at every gamma. + + The line is read at the COLUMN'S OWN discount, because the two columns do not share one: the RSM + is scored at gamma=0.999 (stitch_value_test.py's default) while the IDQL critic is TRAINED at + discount=0.99 (its own config.json). Quoting one line for both would misstate the EXPERT_EPISODE + baseline by a factor of four. + """ + try: + p = os.path.join(ROOT, "status/real/stitch/LOGGED_RETURN_NULL_g%s.json" % gamma) + return json.load(open(p)).get("heads", {}) + except Exception: + return {} + + +# the discount each column is actually read at. RSM: stitch_value_test.py --gamma default 0.999. +# IDQL: algo.discount in the cell's own robomimic config.json (verified 0.99 on +# cooking_v5_rw_EXPERT_EPISODE/.../S0Aidql_s1/config.json, run 27). +MODE_GAMMA = {"rsm": "0.999", "idql": "0.99"} + + +def nostitch_for(mode, head): + ns = load_nostitch(MODE_GAMMA.get(mode.split()[0], "0.999")) + r = ns.get(head) + return (r.get("nostitch_ratioA"), r.get("C_minus_E"), r.get("defined")) if r else (None, None, None) + + +def load_label_audit(): + """LABEL-SIDE GUARD (run 4). METRIC 1's ratio is (A-E)/(C-E), so C is the metric's + 'full stitch' reference point. A reward head that assigns C and E the SAME label does not + define that reference at all, and the ratio is then a value difference divided by an interval + the label never asked for -- whatever the value function's own C-E bootstrap says. Measured + (scripts/real/stitch_anchor_label_audit.py, job 1885253): every goal episode runs 435-1041 + frames (median 576) past its S3 entry, so GOAL_WINDOW_100 and GOAL_WINDOW_400 label the C + anchors 0.000, identical to the E anchors. Their rows are UNDEFINED on this metric. + This guard is on the LABEL and is independent of, and stricter than, #281's value-side guard.""" + try: + return json.load(open(os.path.join(ROOT, "status/real/stitch/ANCHOR_LABEL_AUDIT.json"))) + except Exception: + return None + + +# --------------------------------------------------------------------------------------------- +# REPLICATE SPREAD -- the nondeterminism floor of METRIC 1 (run 8 finding, amendment posted to the +# spec of record gen_q#281 / rsm_real#3). +# +# The episode bootstrap #281 mandates estimates SAMPLING uncertainty over anchor episodes for ONE +# trained cell. It says nothing about what a second training of the SAME configuration on the SAME +# data would give. Run 8 measured that directly: `R_M_ft_v0lit` and `R_M_ft_v5` have BIT-IDENTICAL +# reward arrays (0 of 181 530 frames differ) and identical launcher definitions -- same W, seed, +# parent, beta flags, steps, save-every -- differing only in the npy PATH STRING. They are two +# independent runs of one configuration, and on seed 1 their bootstrap CIs are DISJOINT. +# +# Each entry below is (head, seed, cell_a, cell_b, why_they_are_a_replicate). A pair is only listed +# here if the two cells are identical in EVERY training input; `*_rep` cells were launched for this +# purpose with only --out different. Nothing is inferred from a name -- adding a pair here is a +# claim that must be checkable in the launcher or the payload script named in the note. +REPLICATE_PAIRS = [ + ("EXPERT_EPISODE", 0, "rsm_R_M_ft_v0lit", "rsm_R_M_ft_v5", + "rr_rsm.sh:195 vs :229 -- identical but for the npy path, and the two npys are bit-identical"), + ("EXPERT_EPISODE", 1, "rsm_R_M_ft_v0lit_s1", "rsm_R_M_ft_v5_s1", + "rr_rsm.sh:196 vs :230 -- identical but for the npy path, and the two npys are bit-identical"), + ("GOAL_SEGMENT", 0, "rsm_R_M_ft_v1", "rsm_R_M_ft_v1_rep", + "jobs/rw/ft_R_M_ft_v1_rep.sh -- only --out differs"), + ("GOAL_SEGMENT", 1, "rsm_R_M_ft_v1_s1", "rsm_R_M_ft_v1_s1_rep", + "jobs/rw/ft_R_M_ft_v1_s1_rep.sh -- only --out differs"), + ("GOAL_SEGMENT_CONTRASTIVE", 0, "rsm_R_M_ft_C10", "rsm_R_M_ft_C10_rep", + "jobs/rw/ft_R_M_ft_C10_rep.sh -- only --out differs"), + ("GOAL_SEGMENT_CONTRASTIVE", 1, "rsm_R_M_ft_C10_s1", "rsm_R_M_ft_C10_s1_rep", + "jobs/rw/ft_R_M_ft_C10_s1_rep.sh -- only --out differs"), + ("GOAL_EPISODE", 0, "rsm_R_M_ft_v0", "rsm_R_M_ft_v0_rep", + "jobs/rw/ft_R_M_ft_v0_rep.sh -- replicates rr_rsm.sh:182, only --out differs"), + ("GOAL_EPISODE", 1, "rsm_R_M_ft_v0_s1", "rsm_R_M_ft_v0_s1_rep", + "jobs/rw/ft_R_M_ft_v0_s1_rep.sh -- replicates rr_rsm.sh:186, only --out differs"), +] + +# Between-cell differences that this stream has claimed or may claim, each stated as +# (label, head, seed, cell_hi, cell_lo). Each is printed against the replicate spread measured at +# ITS OWN head and seed; if that pair has not landed yet the row says so rather than borrowing a +# floor from a different head, because the floor is not known to be scale-free. +CLAIMS = [ + ("weight axis w=1 -> w=10", "GOAL_SEGMENT_CONTRASTIVE", 0, "rsm_R_M_ft_C10", "GOAL_SEGMENT", "rsm_R_M_ft_v1"), + ("weight axis w=1 -> w=10", "GOAL_SEGMENT_CONTRASTIVE", 1, "rsm_R_M_ft_C10_s1", "GOAL_SEGMENT", "rsm_R_M_ft_v1_s1"), + ("weight axis w=1 -> w=30", "GOAL_SEGMENT_CONTRASTIVE", 0, "rsm_R_M_ft_C30", "GOAL_SEGMENT", "rsm_R_M_ft_v1"), + ("weight axis w=1 -> w=30", "GOAL_SEGMENT_CONTRASTIVE", 1, "rsm_R_M_ft_C30_s1", "GOAL_SEGMENT", "rsm_R_M_ft_v1_s1"), + ("cap OFF -> cap ON [trunc 0.99 -> default 0.02]", "GOAL_SEGMENT", 0, "rsm_R_M_ft_v1", "GOAL_SEGMENT", "rsm_R_M_ft_v1_nt"), + ("cap OFF -> cap ON [trunc 0.99 -> default 0.02]", "GOAL_SEGMENT", 1, "rsm_R_M_ft_v1_s1", "GOAL_SEGMENT", "rsm_R_M_ft_v1_nt_s1"), + ("cap OFF -> cap ON [trunc 0.99 -> default 0.02]", "GOAL_EPISODE", 0, "rsm_R_M_ft_v0", "GOAL_EPISODE", "rsm_R_M_ft_v0_nt"), + ("cap OFF -> cap ON [trunc 0.99 -> default 0.02]", "GOAL_EPISODE", 1, "rsm_R_M_ft_v0_s1", "GOAL_EPISODE", "rsm_R_M_ft_v0_nt_s1"), + ("cap OFF -> cap ON [trunc 0.99 -> default 0.02]", "GOAL_SEGMENT_CONTRASTIVE", 0, "rsm_R_M_ft_C10", "GOAL_SEGMENT_CONTRASTIVE", "rsm_R_M_ft_C10_nt"), + ("failure-frame weight w=1 -> w=10", "GOAL_EPISODE", 0, "rsm_R_M_ft_v0_w10", "GOAL_EPISODE", "rsm_R_M_ft_v0"), + ("failure-frame weight w=1 -> w=10", "GOAL_EPISODE", 1, "rsm_R_M_ft_v0_w10_s1", "GOAL_EPISODE", "rsm_R_M_ft_v0_s1"), + # run 15: the STEP-MATCHED replacements for the rows above that print CONFOUNDED. The `*_x120` + # cells extend each capped cell from absolute 110000 to absolute 120000 with its own flags copied + # verbatim, so both sides of these rows are scored at ckpt_s120000.pt and the step guard passes. + # The 110000-vs-120000 rows are deliberately KEPT above so the confound stays visible next to the fix. + # Limitation: an `_nt` cell ran 100000->120000 in ONE optimizer run while an `_x120` cell ran + # 100000->110000 then a RESTARTED 110000->120000 (optimizer state is carried in ckpt.pt, but the + # data-order RNG restarts), so these are step-matched only to within the replicate floor. + ("cap OFF -> cap ON [trunc 0.99 -> default 0.02] [step-matched @120k]", "GOAL_SEGMENT", 0, "rsm_R_M_ft_v1_x120", "GOAL_SEGMENT", "rsm_R_M_ft_v1_nt"), + ("cap OFF -> cap ON [trunc 0.99 -> default 0.02] [step-matched @120k]", "GOAL_SEGMENT", 1, "rsm_R_M_ft_v1_s1_x120", "GOAL_SEGMENT", "rsm_R_M_ft_v1_nt_s1"), + ("cap OFF -> cap ON [trunc 0.99 -> default 0.02] [step-matched @120k]", "GOAL_EPISODE", 0, "rsm_R_M_ft_v0_x120", "GOAL_EPISODE", "rsm_R_M_ft_v0_nt"), + ("cap OFF -> cap ON [trunc 0.99 -> default 0.02] [step-matched @120k]", "GOAL_EPISODE", 1, "rsm_R_M_ft_v0_s1_x120", "GOAL_EPISODE", "rsm_R_M_ft_v0_nt_s1"), + ("cap OFF -> cap ON [trunc 0.99 -> default 0.02] [step-matched @120k]", "GOAL_SEGMENT_CONTRASTIVE", 0, "rsm_R_M_ft_C10_x120", "GOAL_SEGMENT_CONTRASTIVE", "rsm_R_M_ft_C10_nt"), + # run 23. FIVE MORE step-matched cap rows. The cap axis is the only knob in this stream whose + # sign is consistent -- 5 of 5 rows with cap ON scoring higher, exact two-sided p=0.0625, which is + # the FLOOR for n=5 -- and no single row clears its own cell's seed range except GOAL_EPISODE + # s0/s1. A direction like that can only be strengthened by ADDING ROWS. Two of these five put + # the cap axis on a head it has never been read on (EXPERT_EPISODE / `v0lit`, whose cap-OFF cells + # were already on disk at s120000 and simply unscored); the other three complete the C10 seed-1 + # pair and both C3 pairs. Every lo side is a cap-OFF (`--beta-trunc-eps 0.99`) +10k fine-tune of + # the SAME parent as its hi side, so each row stays a paired one-flag comparison at absolute 120000. + ("cap OFF -> cap ON [trunc 0.99 -> default 0.02] [step-matched @120k]", "EXPERT_EPISODE", 0, "rsm_R_M_ft_v0lit_x120", "EXPERT_EPISODE", "rsm_R_M_ft_v0lit_nt"), + ("cap OFF -> cap ON [trunc 0.99 -> default 0.02] [step-matched @120k]", "EXPERT_EPISODE", 1, "rsm_R_M_ft_v0lit_s1_x120", "EXPERT_EPISODE", "rsm_R_M_ft_v0lit_nt_s1"), + ("cap OFF -> cap ON [trunc 0.99 -> default 0.02] [step-matched @120k]", "GOAL_SEGMENT_CONTRASTIVE", 1, "rsm_R_M_ft_C10_s1_x120", "GOAL_SEGMENT_CONTRASTIVE", "rsm_R_M_ft_C10_nt_s1"), + ("cap OFF -> cap ON [trunc 0.99 -> default 0.02] [step-matched @120k]", "GOAL_SEGMENT_CONTRASTIVE", 0, "rsm_R_M_ft_C3_x120", "GOAL_SEGMENT_CONTRASTIVE", "rsm_R_M_ft_C3_nt"), + ("cap OFF -> cap ON [trunc 0.99 -> default 0.02] [step-matched @120k]", "GOAL_SEGMENT_CONTRASTIVE", 1, "rsm_R_M_ft_C3_s1_x120", "GOAL_SEGMENT_CONTRASTIVE", "rsm_R_M_ft_C3_nt_s1"), + ("weight axis w=1 -> w=30 [step-matched @120k]", "GOAL_SEGMENT_CONTRASTIVE", 0, "rsm_R_M_ft_C30", "GOAL_SEGMENT", "rsm_R_M_ft_v1_x120"), + ("weight axis w=1 -> w=30 [step-matched @120k]", "GOAL_SEGMENT_CONTRASTIVE", 1, "rsm_R_M_ft_C30_s1", "GOAL_SEGMENT", "rsm_R_M_ft_v1_s1_x120"), + ("weight axis w=3 -> w=30 [step-matched @120k]", "GOAL_SEGMENT_CONTRASTIVE", 0, "rsm_R_M_ft_C30", "GOAL_SEGMENT_CONTRASTIVE", "rsm_R_M_ft_C3_x120"), + ("weight axis w=3 -> w=30 [step-matched @120k]", "GOAL_SEGMENT_CONTRASTIVE", 1, "rsm_R_M_ft_C30_s1", "GOAL_SEGMENT_CONTRASTIVE", "rsm_R_M_ft_C3_s1_x120"), + ("weight axis w=1 -> w=10 [step-matched @120k]", "GOAL_SEGMENT_CONTRASTIVE", 0, "rsm_R_M_ft_C10_x120", "GOAL_SEGMENT", "rsm_R_M_ft_v1_x120"), + ("weight axis w=1 -> w=10 [step-matched @120k]", "GOAL_SEGMENT_CONTRASTIVE", 1, "rsm_R_M_ft_C10_s1_x120", "GOAL_SEGMENT", "rsm_R_M_ft_v1_s1_x120"), + # run 16, CORRECTED. An earlier version of this block claimed the `w=1 -> w=X` rows were head + # confounds because their two sides name different reward npy FILES. They are not: + # reward_v1_goaltrans.f32.npy and reward_C_kstate.f32.npy are BIT-IDENTICAL (sha1 31b0b44e0578, + # 181530 frames, 0 differing elements), so GOAL_SEGMENT and GOAL_SEGMENT_CONTRASTIVE are ONE + # reward head under two names and those rows are genuine weight knobs. The four + # `head GS -> GSC [varies: reward,weight]` rows added on that false premise are removed; the + # `knob_check` guard now hashes npy CONTENT and rejects them itself, which is why they went. + # and the weight knob the `_x120` pack made possible WITHIN the contrastive head: same reward npy, + # both sides at absolute 120000, only weight_C_w3 -> weight_C_w10 differs. + ("weight axis w=3 -> w=10 [step-matched @120k]", "GOAL_SEGMENT_CONTRASTIVE", 0, "rsm_R_M_ft_C10_x120", "GOAL_SEGMENT_CONTRASTIVE", "rsm_R_M_ft_C3_x120"), + ("weight axis w=3 -> w=10 [step-matched @120k]", "GOAL_SEGMENT_CONTRASTIVE", 1, "rsm_R_M_ft_C10_s1_x120", "GOAL_SEGMENT_CONTRASTIVE", "rsm_R_M_ft_C3_s1_x120"), + # run 17. The step-drift table showed METRIC 1 moves 0.124 (sd) along ONE trajectory over 10k + # steps against a 0.046 replicate sd, and the one knob that could be re-read 10k steps later + # FLIPPED SIGN. So every knob is now also read at absolute 130000 (the `_x130` pack, jobs + # 1890938/1890939) and at a THIRD arm of the weight axis that already exists at 110k and 120k + # (w=1 -> w=3). A knob is only a property of the knob if its sign survives all three reads. + ("weight axis w=1 -> w=3", "GOAL_SEGMENT_CONTRASTIVE", 0, "rsm_R_M_ft_C3", "GOAL_SEGMENT", "rsm_R_M_ft_v1"), + ("weight axis w=1 -> w=3", "GOAL_SEGMENT_CONTRASTIVE", 1, "rsm_R_M_ft_C3_s1", "GOAL_SEGMENT", "rsm_R_M_ft_v1_s1"), + ("weight axis w=1 -> w=3 [step-matched @120k]", "GOAL_SEGMENT_CONTRASTIVE", 0, "rsm_R_M_ft_C3_x120", "GOAL_SEGMENT", "rsm_R_M_ft_v1_x120"), + ("weight axis w=1 -> w=3 [step-matched @120k]", "GOAL_SEGMENT_CONTRASTIVE", 1, "rsm_R_M_ft_C3_s1_x120", "GOAL_SEGMENT", "rsm_R_M_ft_v1_s1_x120"), + ("weight axis w=1 -> w=3 [step-matched @130k]", "GOAL_SEGMENT_CONTRASTIVE", 0, "rsm_R_M_ft_C3_x130", "GOAL_SEGMENT", "rsm_R_M_ft_v1_x130"), + ("weight axis w=1 -> w=3 [step-matched @130k]", "GOAL_SEGMENT_CONTRASTIVE", 1, "rsm_R_M_ft_C3_s1_x130", "GOAL_SEGMENT", "rsm_R_M_ft_v1_s1_x130"), + ("weight axis w=1 -> w=10 [step-matched @130k]", "GOAL_SEGMENT_CONTRASTIVE", 0, "rsm_R_M_ft_C10_x130", "GOAL_SEGMENT", "rsm_R_M_ft_v1_x130"), + ("weight axis w=1 -> w=10 [step-matched @130k]", "GOAL_SEGMENT_CONTRASTIVE", 1, "rsm_R_M_ft_C10_s1_x130", "GOAL_SEGMENT", "rsm_R_M_ft_v1_s1_x130"), + ("weight axis w=3 -> w=10 [step-matched @130k]", "GOAL_SEGMENT_CONTRASTIVE", 0, "rsm_R_M_ft_C10_x130", "GOAL_SEGMENT_CONTRASTIVE", "rsm_R_M_ft_C3_x130"), + ("weight axis w=3 -> w=10 [step-matched @130k]", "GOAL_SEGMENT_CONTRASTIVE", 1, "rsm_R_M_ft_C10_s1_x130", "GOAL_SEGMENT_CONTRASTIVE", "rsm_R_M_ft_C3_s1_x130"), + # run 24. A THIRD INDEPENDENT BASE for the cap axis, found already trained on disk. + # + # run 23 measured that the 5 unanimous cap rows rest on only TWO independent base trainings + # (`R_M`, `R_M_s1`, both W=1024) because every one of them is a +10k fine-tune off one of those + # two, and flagged a third base as a full base run and therefore an orchestrator cost decision. + # It is not: `R_XL` (W=2048) is a SEPARATE base training that already exists, and both of its cap + # pairs are already fine-tuned and on disk -- + # rr_rsm.sh:303 R_XL_ft_v0 FT_FROM=R_XL --steps 110000 --save-every 2000 (cap ON, default eps) + # rr_rsm.sh:290 R_XL_ft_v0_nt FT_FROM=R_XL --steps 115000 --save-every 2500 --beta-trunc-eps 0.99 + # rr_rsm.sh:304 R_XL_ft_v1 / :291 R_XL_ft_v1_nt, the same two flags on the v1 label. + # Both sides of both pairs hold `ckpt_s110000.pt` (115000/2500 and 110000/2000 both land on + # 110000), so the rows are read STEP-MATCHED at absolute 110000 and the only training flag that + # can move them is `--beta-trunc-eps`; `--steps`/`--save-every` are reported by knob_check and are + # inert at a step-matched read for the reasons written at _INERT_AT_STEP_MATCHED_READ. + # These two rows take the cap axis from 2 independent bases to 3, and vary the base by WIDTH + # (1024 -> 2048) rather than by seed, which is a wider variation than a third seed would be. + # They cost four CPU reads and no GPU time. Heads are the ones the cells were TRAINED on: + # reward_v0_provenance = GOAL_EPISODE, reward_v1_goaltrans = GOAL_SEGMENT. + ("cap OFF -> cap ON [trunc 0.99 -> default 0.02] [step-matched @110k] [base R_XL]", "GOAL_EPISODE", 0, "rsm_R_XL_ft_v0", "GOAL_EPISODE", "rsm_R_XL_ft_v0_nt_s110000"), # run 31: the cap-OFF side was scored as an explicit @110k READ (`..._nt_s110000`); the terminal `..._nt` cell was never written, so the un-suffixed key printed `cell pending`. + ("cap OFF -> cap ON [trunc 0.99 -> default 0.02] [step-matched @110k] [base R_XL]", "GOAL_SEGMENT", 0, "rsm_R_XL_ft_v1", "GOAL_SEGMENT", "rsm_R_XL_ft_v1_nt_s110000"), # run 31: the cap-OFF side was scored as an explicit @110k READ (`..._nt_s110000`); the terminal `..._nt` cell was never written, so the un-suffixed key printed `cell pending`. + # run 24, second half. THREE MORE cap rows, on bases R_XL (W=2048) and R_L40 (W=1536), from + # cap-OFF cells that were already trained and had no cap-ON partner: `R_XL_ft_v0lit_nt` + # (rr_rsm.sh:316), `R_L40_ft_v0_nt` (:307), `R_L40_ft_v0lit_nt` (:331). The partners + # `ft_R_XL_ft_v0lit.sh` / `ft_R_L40_ft_v0.sh` / `ft_R_L40_ft_v0lit.sh` copy each `_nt` case line + # VERBATIM and omit exactly one flag, `--beta-trunc-eps 0.99`, so unlike the two @110k rows above + # these three carry NO inert flag difference at all -- `--steps 115000`, `--save-every 2500`, + # `--eval-every 5000`, width, seed, parent and reward npy are identical on both sides, and the + # read is step-matched at the terminal absolute 115000. `R_L40` is a FOURTH independent base. + ("cap OFF -> cap ON [trunc 0.99 -> default 0.02] [step-matched @115k] [base R_XL]", "EXPERT_EPISODE", 0, "rsm_R_XL_ft_v0lit", "EXPERT_EPISODE", "rsm_R_XL_ft_v0lit_nt"), + ("cap OFF -> cap ON [trunc 0.99 -> default 0.02] [step-matched @115k] [base R_L40]", "GOAL_EPISODE", 0, "rsm_R_L40_ft_v0", "GOAL_EPISODE", "rsm_R_L40_ft_v0_nt"), + ("cap OFF -> cap ON [trunc 0.99 -> default 0.02] [step-matched @115k] [base R_L40]", "EXPERT_EPISODE", 0, "rsm_R_L40_ft_v0lit", "EXPERT_EPISODE", "rsm_R_L40_ft_v0lit_nt"), +] + + +# --------------------------------------------------------------------------- +# run 16 GUARD: what TRAINING FLAGS did each side of a claim actually use? +# +# The step guard (run 13) caught rows whose two sides were scored at different steps. It cannot +# catch rows whose two sides were TRAINED ON DIFFERENT REWARD LABELS, and this stream had five such +# rows labelled "weight axis w=1 -> w=X". Their hi side is a GOAL_SEGMENT_CONTRASTIVE cell +# (--reward-npy reward_C_kstate) and their lo side is a GOAL_SEGMENT cell +# (--reward-npy reward_v1_goaltrans) with no --weight-npy at all, so the gap contains BOTH a change +# of reward head AND a change of failure-frame weight. Run 14 reported one of them as the stream's +# first ESTABLISHED knob. It is not a weight knob; it is a head+weight change. +# +# So: parse the flags every cell was launched with, from the authoritative launcher, and require that +# the flag DIFF between the two sides of a claim contains EXACTLY the knob the claim's label names. +# Two sources, both machine-read, never hand-typed: +# 1. scripts/real/jobs/rw/ft_.sh -- this stream's own payloads; the `exec bash rr_rsm.sh` +# line carries every flag verbatim (this is where the _rep / _x120 / _w10 / _nt cells live). +# 2. scripts/rr_rsm.sh -- the shared launcher's `)` case line, which holds CELL_EXTRA for +# every cell launched by name (v0, v1, C3, C10, C30, *_s1, *_nt). +# If both resolve and disagree, that is a FLAG SOURCE CONFLICT and the cell is treated as unknown. +# A cell whose flags cannot be resolved makes its row NOT REPORTABLE -- the same rule as an unknown +# scored step. Silence is never read as "the flags matched". +# --------------------------------------------------------------------------- + +_FLAG_CACHE = {} + + +_NPY_HASH = {} + + +def npy_id(path_basename): + """CONTENT identity of a reward/weight npy, not its filename. + + run 16 SECOND CORRECTION. The first version of this guard compared npy PATHS, and immediately + "caught" every `w=1 -> w=X` row as a reward-head confound. It is a FALSE POSITIVE: + cache/real_cooking_v5/reward_v1_goaltrans.f32.npy and .../reward_C_kstate.f32.npy are + BIT-IDENTICAL (sha1 31b0b44e0578 both, 181530 frames, 0 differing elements), so GOAL_SEGMENT and + GOAL_SEGMENT_CONTRASTIVE are ONE head under two names and those rows really are weight knobs. + Among the 13 reward npys in the cache there are only 7 distinct ARRAYS: + 31b0b44e0578 reward_A_tosucc == reward_C_kstate == reward_v1_goaltrans (GOAL_SEGMENT = GSC) + 29e31250081e reward_v0lit_finalS3S4 == reward_v5_riseprov (EXPERT_EPISODE = RISE_PROVENANCE) + b9adbf66a03d reward == reward_C_literal_marker == reward_v2_arrival == reward_v4_successtail + and singletons reward_B_H100, reward_B_H400, reward_v0_provenance, reward_v3_finalseg. + A guard that reads filenames would call two of those groups a head change and would also MISS a + real one if two heads were ever given the same filename in different directories. So identity is + the content hash, and the filename is printed beside it only so a human can see which file it was. + """ + if path_basename in _NPY_HASH: + return _NPY_HASH[path_basename] + if not path_basename or path_basename.startswith("("): + out = path_basename # "(none => w=1)" and friends are arms, not files + else: + import hashlib + f = "%s/cache/real_cooking_v5/%s" % (ROOT, path_basename) + if not os.path.exists(f): + out = "UNHASHABLE(%s)" % path_basename + else: + try: + import numpy as _np + out = hashlib.sha1(_np.load(f).tobytes()).hexdigest()[:12] + except Exception as e: + out = "UNHASHABLE(%s: %s)" % (path_basename, e) + _NPY_HASH[path_basename] = out + return out + + +def _parse_flags(text): + """--reward-npy / --weight-npy / --beta-trunc-eps out of a launcher fragment, basenames only.""" + def one(flag): + mo = re.search(r"--%s\s+(\S+)" % flag, text) + if not mo: + return None + # the token can end a shell string or a continued line, so strip quoting/continuation + # characters off it -- otherwise `...npy"` and `...npy` read as two different labels and the + # guard fires on a pair that is in fact identical. + return os.path.basename(mo.group(1).strip().rstrip("\\").strip("\"';")) + return {"reward": one("reward-npy"), + # no --weight-npy means every frame has weight 1: that IS the w=1 arm, not a missing value + "weight": one("weight-npy") or "(none => w=1)", + # no --beta-trunc-eps means the cap is at the launcher default: that IS the capped arm + "trunc": one("beta-trunc-eps") or "(none => cap ON at default)", + # run 24: parsed so the guard can SAY they differ, never counted in the knob diff -- see + # _INERT_AT_STEP_MATCHED_READ below for why they cannot change a step-matched checkpoint. + "steps": one("steps") or "(none => launcher default)", + "save_every": one("save-every") or "(none => launcher default)"} + + +def _flag_name_resolves(name): + """True if `name` has a flag SOURCE on disk (a payload or an rr_rsm.sh case), regardless of + whether those flags are self-consistent. Used only to pick which name to read flags from.""" + if os.path.exists("%s/scripts/real/jobs/rw/ft_%s.sh" % (ROOT, name)): + return True + launcher = "%s/scripts/rr_rsm.sh" % ROOT + if os.path.exists(launcher): + if re.search(r"^\s*%s\)" % re.escape(name), open(launcher).read(), re.M): + return True + return False + + +def cell_flags(cell): + """Training flags for a stitch-matrix cell key (`rsm_R_M_ft_C10` -> cell `R_M_ft_C10`). + + Returns a dict, or {"_unresolved": why}. Never guesses. + """ + if cell in _FLAG_CACHE: + return _FLAG_CACHE[cell] + name = cell[4:] if cell.startswith("rsm_") else cell + # A trailing `_s<5+ digits>` is a READ of an existing training at that absolute step, not a + # separate training: run 29 byte-compared history.json and found such dirs identical to their + # parent at every common logged step. So the TRAINING flags of `X_s110000` are X's. The + # unstripped name is tried first, so a hypothetical training that genuinely ends in `_s` + # still wins; only a name that resolves to nothing falls back to the stripped parent. + if not _flag_name_resolves(name): + stripped = re.sub(r"_s\d{5,}$", "", name) + if stripped != name and _flag_name_resolves(stripped): + name = stripped + got = {} + pay = "%s/scripts/real/jobs/rw/ft_%s.sh" % (ROOT, name) + if os.path.exists(pay): + t = open(pay).read() + i = t.find("exec bash") + got["payload"] = _parse_flags(t[i:] if i >= 0 else t) + launcher = "%s/scripts/rr_rsm.sh" % ROOT + if os.path.exists(launcher): + mo = re.search(r"^\s*%s\)(.*)$" % re.escape(name), open(launcher).read(), re.M) + if mo: + ce = mo.group(1) + # $RBETA carries --beta-lo/hi/q only, never a reward or weight npy, so it needs no expansion + got["rr_rsm"] = _parse_flags(ce) + if not got: + out = {"_unresolved": "no ft_%s.sh payload and no `%s)` case in rr_rsm.sh" % (name, name)} + elif len(got) == 2 and got["payload"] != got["rr_rsm"]: + out = {"_unresolved": "FLAG SOURCE CONFLICT payload=%s rr_rsm=%s" % (got["payload"], got["rr_rsm"])} + else: + out = got.get("payload") or got["rr_rsm"] + if out.get("reward") is None: + out = {"_unresolved": "launcher fragment carries no --reward-npy"} + _FLAG_CACHE[cell] = out + return out + + +# which flag key a claim label CLAIMS to be varying +_KNOB_KEY = (("cap", "trunc"), ("weight", "weight")) + +# run 24. FLAGS THAT DIFFER BUT CANNOT MOVE A STEP-MATCHED READ, and why that is not a loophole. +# +# Up to run 23 `_parse_flags` read only reward/weight/trunc, so a claim whose two sides also differed +# in `--steps` or `--save-every` passed knob_check while SAYING NOTHING about it. That was safe only +# by luck: every R_M cap pair happened to match on both. It stops being luck the moment a pair is +# built from cells launched with different run lengths -- which is exactly what the R_XL cap pairs are +# (`R_XL_ft_v0` ran `--steps 110000 --save-every 2000`, `R_XL_ft_v0_nt` `--steps 115000 --save-every +# 2500`), and a guard that is silent about a real difference is worse than no guard. +# +# They are parsed now, and reported, and still not counted in the knob diff, because at a READ TAKEN +# AT A STEP BOTH SIDES REACHED neither can change the weights in the checkpoint: +# * `--save-every` is used at exactly one place, train_rsm.py:1203 `if args.save_every and step % +# args.save_every == 0`, which decides WHICH checkpoints get written and touches nothing else. +# * `--steps` is used at train_rsm.py:752 as the loop bound and at :983 to force one extra EVAL on +# the final iteration. There is NO learning-rate schedule to scale: the optimiser is a plain +# AdamW built once at :706 with `lr=args.lr` and no scheduler anywhere in the file, so the LR at +# step 110000 is the same constant in a 110k run and in a 115k run. +# * the forced final eval cannot leak backwards: it runs AFTER the optimiser step of that +# iteration, and the checkpoint write at :1203 comes after it again, so `ckpt_s110000.pt` records +# weights determined entirely by iterations 1..110000. `--eval-every` is the same default on +# both sides, so the eval CADENCE -- and any RNG it draws -- is identical at every earlier step. +# If any of those three facts stops holding, this list must shrink, not the comment grow. +_INERT_AT_STEP_MATCHED_READ = ("steps", "save_every") + + +def knob_check(label, chi, clo): + """(ok, human_string). ok=False means the row is not reportable AS THE KNOB IT NAMES.""" + fh, fl = cell_flags(chi), cell_flags(clo) + for f, c in ((fh, chi), (fl, clo)): + if "_unresolved" in f: + return False, "**FLAGS UNRESOLVED for %s: %s**" % (c, f["_unresolved"]) + def ident(k, f): + # reward/weight are FILES: identity is their content. trunc is a scalar flag: itself. + return f[k] if k == "trunc" else npy_id(f[k]) + diff = sorted(k for k in ("reward", "weight", "trunc") if ident(k, fh) != ident(k, fl)) + same_file_diff = [k for k in ("reward", "weight") if fh[k] != fl[k] and ident(k, fh) == ident(k, fl)] + shown = ", ".join("%s %s -> %s" % (k, fl[k], fh[k]) for k in diff) or "none (identical labels)" + # run 24: name any inert-but-different launcher flag out loud. It never enters `diff`, so it can + # never make a row pass or fail; it exists so the row cannot LOOK like an exact flag twin when it + # is not one. The justification is in _INERT_AT_STEP_MATCHED_READ. + inert = [k for k in _INERT_AT_STEP_MATCHED_READ + if fh.get(k) is not None and fl.get(k) is not None and fh[k] != fl[k]] + if inert: + shown += (" *(also differs, INERT at a step-matched read: %s -- no LR schedule, loop bound " + "and checkpoint cadence only)*" + % "; ".join("%s %s -> %s" % (k, fl[k], fh[k]) for k in inert)) + if same_file_diff: + shown += " *(%s: different FILE, identical CONTENT -- %s)*" % ( + ",".join(same_file_diff), + "; ".join("%s == %s" % (fl[k], fh[k]) for k in same_file_diff)) + ll = label.lower() + # a label may DECLARE exactly which flags it varies: "... [varies: reward,weight]". That is how a + # deliberate joint change is written down honestly instead of being mislabelled as a single knob. + mo = re.search(r"\[varies:\s*([a-z,\s]+)\]", ll) + if mo: + want_set = sorted(x.strip() for x in mo.group(1).split(",") if x.strip()) + if diff == want_set: + return True, shown + " *(declared)*" + return False, ("**MISMATCH -- the row declares it varies %s but the measured flag diff is %s. " + "NOT REPORTABLE.**" % (",".join(want_set), shown)) + want = None + for pat, key in _KNOB_KEY: + if pat in ll: + want = key + break + if want is None: + return True, shown + if diff == [want]: + return True, shown + if "reward" in diff: + return False, ("**CONFOUNDED -- the two sides were trained on DIFFERENT REWARD LABELS " + "(%s). This is a head change, not a `%s` knob. NOT REPORTABLE as this knob.**" + % (shown, want)) + return False, ("**CONFOUNDED -- flag diff is %s but this row claims to vary `%s` only. " + "NOT REPORTABLE as this knob.**" % (shown, want)) + + +def ckpt_step(d): + """The TRAINING STEP the cell was scored at, parsed from the checkpoint filename. + + run 13 GUARD. `stitch_one_cell.sh` scores whatever rolling `ckpt_s.pt` a run dir + happens to hold, and this stream launched two families of fine-tunes: the capped cells with + `--steps 110000` and the cap-OFF (`*_nt`) cells and `C30*` with `--steps 120000`. With + `--save-every 2000` rolling over, only the LAST checkpoint survives, so every cap-OFF cell was + scored at s120000 and every capped cell at s110000. Every `cap OFF` and `w=1 -> w=30` claim in + runs 4-12 was therefore a comparison of 120k steps against 110k steps, not of the flag. Nothing + in the output said so, because nothing looked. It looks now: a claim whose two sides were + scored at different steps is CONFOUNDED and is not reportable at any floor. + Returns None if the path carries no step (e.g. a bare `ckpt.pt`), which is also not comparable. + """ + b = os.path.basename((d.get("config") or {}).get("rsm_ckpt") or "") + mo = re.search(r"ckpt_s(\d+)\.pt$", b) + return int(mo.group(1)) if mo else None + + +def ratio_index(rows): + """(head, cell) -> (stitch_A, ci95) for every DEFINED rsm cell that is not a PROBE.""" + idx = {} + for head, recs in rows.items(): + for cell, mode, m, d in recs: + if not mode.startswith("rsm") or cell.startswith("PROBE_"): + continue + if not m.get("defined", False): + continue + idx[(head, cell)] = (m.get("stitch_A", float("nan")), m.get("boot", {}).get("ratioA_ci95")) + return idx + + +def step_index(rows): + """(head, cell) -> scored training step, for every rsm cell that is not a PROBE.""" + idx = {} + for head, recs in rows.items(): + for cell, mode, m, d in recs: + if not mode.startswith("rsm") or cell.startswith("PROBE_"): + continue + idx[(head, cell)] = ckpt_step(d) + return idx + + +def print_replicate_spread(rows): + idx = ratio_index(rows) + sidx = step_index(rows) + print("## REPLICATE SPREAD -- the nondeterminism floor of METRIC 1") + print("# Two independent trainings of the SAME configuration on the SAME data. The spread below is") + print("# what METRIC 1 moves by when NOTHING was changed. Per the amendment to gen_q#281, a") + print("# between-cell difference smaller than the spread measured at its own head and seed is") + print("# NOT ESTABLISHED, whatever the episode bootstrap says.") + print() + print("| head | seed | cell A | stitch A | boot95 A | cell B | stitch B | boot95 B | spread | CIs overlap? |") + print("|" + "---|" * 10) + floors = {} + for head, seed, ca, cb, _why in REPLICATE_PAIRS: + a = idx.get((head, ca)); b = idx.get((head, cb)) + if a is None or b is None: + miss = ", ".join(c for c, got in ((ca, a), (cb, b)) if got is None) + print("| %s | %d | %s | %s | -- | %s | -- | -- | **pending** | -- |" % ( + head, seed, ca, "--", cb, )) + print("| | | | *not yet measured: %s* | | | | | | |" % miss) + continue + sa = sidx.get((head, ca)); sb = sidx.get((head, cb)) + if sa is None or sb is None or sa != sb: + print("| %s | %d | %s | %.3f | %s | %s | %.3f | %s | **VOID** | **scored at DIFFERENT " + "steps (%s vs %s) -- not a replicate pair** |" % ( + head, seed, ca, a[0], fmt_ci(a[1]), cb, b[0], fmt_ci(b[1]), sa, sb)) + continue + spread = abs(a[0] - b[0]) + floors[(head, seed)] = spread + ov = "--" + if a[1] and b[1]: + ov = "yes" if (a[1][0] <= b[1][1] and b[1][0] <= a[1][1]) else "**NO -- disjoint**" + print("| %s | %d | %s | %.3f | %s | %s | %.3f | %s | **%.3f** | %s |" % ( + head, seed, ca, a[0], fmt_ci(a[1]), cb, b[0], fmt_ci(b[1]), spread, ov)) + print() + if not floors: + print("*(no replicate pair has landed yet)*"); print(); return floors + print("Measured floors: " + ", ".join( + "%s s%d = %.3f" % (h, s, v) for (h, s), v in sorted(floors.items()))) + print() + return floors + + +SCORERNOISE = os.path.join(ROOT, "status/real/stitch_scorernoise") + + +def pooled_sigma(floors): + """Pool the replicate spreads into ONE training-noise sd per cell. + + run 14. Each replicate pair gives d = A - B where both cells are the same configuration + trained twice, so d ~ N(0, 2 sigma^2) with sigma the run-to-run sd of METRIC 1 for a single + training. The maximum-likelihood pooled estimate is sigma^2 = sum(d^2) / (2n). Run 13 used + max(d) over the pairs as the bar and called the floor "non-stationary"; max of n half-normals + is a large order statistic, so that reads sampling spread as heterogeneity. Both the pooled + bar and the per-pair max are printed and the homogeneity of the d's is tested below. + """ + ds = sorted(floors.values()) + if not ds: + return None, 0, [] + n = len(ds) + sig = (sum(d * d for d in ds) / (2.0 * n)) ** 0.5 + return sig, n, ds + + +def homogeneity_p(ds, n_sim=200000, seed=0): + """P(one sigma produces a spread of d's at least as uneven as observed). + + Statistic is max(d^2)/mean(d^2), which is scale-free, so it needs no sigma estimate. + """ + import numpy as np + ds = np.asarray(ds, dtype=float) + if ds.size < 2 or not np.any(ds > 0): + return None, None + obs = float((ds ** 2).max() / (ds ** 2).mean()) + rng = np.random.default_rng(seed) + sim = np.abs(rng.standard_normal((n_sim, ds.size))) + sim2 = sim ** 2 + stat = sim2.max(axis=1) / sim2.mean(axis=1) + return obs, float((stat >= obs).mean()) + + +def load_scorer_noise(): + """cell -> list of (seed, stitch_A) for the SAME checkpoint re-scored at several scorer seeds.""" + out = collections.defaultdict(dict) + for p in sorted(glob.glob(os.path.join(SCORERNOISE, "*", "*", "stitch_value.json"))): + try: + d = json.load(open(p)) + m = d["modes"]["rsm"] + ck = d["config"]["rsm_ckpt"] + cell = ck.split("/")[-2] + out[(d["head"], cell)][int(d["config"]["seed"])] = float(m["stitch_A"]) + except Exception: + continue + return out + + +def print_noise_budget(rows, floors): + """Split the METRIC-1 floor into its measured sources. run 14.""" + idx = ratio_index(rows) + print("## NOISE BUDGET of METRIC 1 -- where the floor actually comes from") + print("# Three sources, each measured on this stream's own data, none assumed:") + print("# (1) SCORER Monte-Carlo -- the SAME checkpoint re-scored at different `--seed`. In") + print("# stitch_value_test.py `--seed` feeds ONLY the Scorer's 16-particle chain rollout,") + print("# the bootstrap and the permutation; anchor/episode grouping is deterministic") + print("# upstream, so kept_anchors/kept_episodes are identical across seeds and this") + print("# isolates the scorer's share exactly.") + print("# (2) EPISODE resampling -- the n=4000 episode bootstrap CI that gen_q#281 mandates.") + print("# (3) TRAINING nondeterminism -- two independent trainings of the SAME config.") + print() + sn = load_scorer_noise() + if sn: + print("### (1) scorer Monte-Carlo: same checkpoint, several scorer seeds") + print("| head | cell | seeds | stitch_A per seed | range | sd |") + print("|" + "---|" * 6) + sds = [] + for (head, cell), per in sorted(sn.items()): + # the matrix index keys on the stitch DIRECTORY name (`rsm_`), the scorer-noise + # cell name comes from the ckpt path (``) -- try both so seed 0 merges in. + base = idx.get((head, cell)) or idx.get((head, "rsm_" + cell)) + if base is not None and 0 not in per: + per = dict(per); per[0] = base[0] + seeds = sorted(per) + vals = [per[s] for s in seeds] + if len(vals) < 2: + print("| %s | %s | %s | %s | -- | *needs >=2 seeds* |" % ( + head, cell, ",".join(str(x) for x in seeds), + " ".join("%+.4f" % v for v in vals))) + continue + mean = sum(vals) / len(vals) + sd = (sum((v - mean) ** 2 for v in vals) / (len(vals) - 1)) ** 0.5 + sds.append(sd) + print("| %s | %s | %s | %s | %.4f | **%.4f** |" % ( + head, cell, ",".join(str(x) for x in seeds), + " ".join("%+.4f" % v for v in vals), max(vals) - min(vals), sd)) + print() + if sds: + print("Scorer Monte-Carlo sd: **%.4f - %.4f**." % (min(sds), max(sds))) + print() + else: + print("### (1) scorer Monte-Carlo: *(no re-scored cells found under status/real/stitch_scorernoise)*") + print() + + sig, n, ds = pooled_sigma(floors) + if sig is None: + print("### (3) training nondeterminism: *(no replicate pair has landed)*"); print(); return None + print("### (3) training nondeterminism: %d replicate pairs pooled" % n) + print("Per-pair |A-B|: " + ", ".join("%.3f" % d for d in ds)) + print() + print("* pooled sd of METRIC 1 for ONE training: **sigma = %.4f** (sqrt(sum d^2 / 2n), n=%d)" % (sig, n)) + print("* sd of a gap between two independently trained cells: sigma*sqrt(2) = **%.4f**" % (sig * 2 ** 0.5)) + print("* two-sided 95%% bar a between-cell gap must clear: **%.3f**" % (1.96 * sig * 2 ** 0.5)) + print("* run 13's bar was max(|A-B|) = %.3f; the pooled bar is %.3f." % (max(ds), 1.96 * sig * 2 ** 0.5)) + obs, ph = homogeneity_p(ds) + if ph is not None: + print() + print("**Is the floor really non-stationary?** Statistic max(d^2)/mean(d^2) = %.2f; under ONE" + % obs) + print("common sigma, P(statistic >= observed) = **%.3f** (200k sims)." % ph) + if ph >= 0.05: + print() + print("> The %d pairs are CONSISTENT WITH A SINGLE training-noise sd. Run 13's " + "\"the floor is NOT stationary\" is **withdrawn**: max of %d half-normal draws is " + "a large order statistic, and 0.128 is an ordinary one for sigma=%.3f. The bar is " + "the pooled %.3f, not the outlier." % (n, n, sig, 1.96 * sig * 2 ** 0.5)) + else: + print() + print("> The pairs are NOT consistent with one sigma (p=%.3f); the per-pair max stays " + "the bar and the pooled number must not be used." % ph) + print() + if sn: + print("### Budget") + print("Scorer Monte-Carlo sd is a few thousandths; the pooled training sd is %.4f. Averaging" + % sig) + print("METRIC 1 over scorer seeds therefore CANNOT recover a between-cell claim -- it removes") + print("a variance component that is a small fraction of the one that dominates. The run-12") + print("proposal to amend gen_q#281 to \"average METRIC 1 over N scorer seeds\" is **withdrawn**;") + print("the only thing that shrinks this floor is more TRAINING seeds per cell.") + print() + return sig + + +def partner_map(): + """cell -> (its replicate partner cell, head, seed), from REPLICATE_PAIRS, both directions.""" + m = {} + for head, seed, ca, cb, _why in REPLICATE_PAIRS: + m[(head, ca)] = (cb, head, seed) + m[(head, cb)] = (ca, head, seed) + return m + + +IDQL_RW_RE = re.compile(r"^idql_rw_s(\d+)_e(\d+)$") + + +def print_idql_seed_spread(rows): + """SEED SPREAD -- the training-noise floor of METRIC 1 on the IQL side (run 20 finding). + + The RSM side has had a measured nondeterminism floor since run 8 (`print_replicate_spread`): + two cells with byte-identical flags land 0.046 apart, so no RSM difference smaller than that is + reportable. The IQL side had NO such floor, and run 18 used that gap without noticing -- it + read `GOAL_EPISODE` and `GOAL_SEGMENT` at e500 and e1000 on seed 1 ONLY, saw both move toward 0, + and reported it (correctly hedged as a consistency rather than a trend). Seed 0's e1000 + milestone landed in run 20 and the two heads split: + + GOAL_EPISODE s0 +0.1268 -> +0.1977 (UP) s1 +0.1660 -> +0.1442 (DOWN) + GOAL_SEGMENT s0 +0.0528 -> +0.0294 (DOWN) s1 +0.0591 -> +0.0268 (DOWN) + + So on GOAL_EPISODE the epoch effect and the seed noise are the SAME SIZE (mean |delta| 0.0463 + against a mean seed spread of 0.0463, 1.00x) and the SIGN FLIPS; on GOAL_SEGMENT the effect is + 6.3x the seed spread and the sign agrees. One head's claim is withdrawn, the other's survives + and is strengthened by an independent seed. + + Two things this function therefore enforces, both of which a future run would otherwise redo: + + (1) The floor is PER HEAD, never pooled. GOAL_EPISODE's seed spread is ~10x GOAL_SEGMENT's + (0.046 vs 0.004) on the same metric, the same anchors and the same epochs, so the floor is + measurably NOT scale-free and a pooled floor would license a GOAL_SEGMENT-sized claim on a + GOAL_EPISODE-sized noise. Same reasoning as the RSM side's per-(head,seed) floors. + (2) The episode bootstrap CI is NOT the uncertainty of a read. All four (head, epoch) cells + have a seed spread 2.2-3.2x their own mean CI width, and every within-seed e500->e1000 pair + has NON-OVERLAPPING CIs -- including the GOAL_EPISODE pair whose sign then flips across + seeds. The bootstrap resamples EPISODES only; it cannot see training noise, and on this + metric training noise dominates it. This is the IQL-side twin of run 14's "the floor is the + TRAINER, not the scorer". + + With 2 seeds the statistic is a RANGE over 2 draws, not an sd, and it is printed as such: it is + a floor ESTIMATE and it is biased low (E[range of 2] = 1.13 sd). Pack `rr_pack4_rwidql_D` + carries seed 2 for both heads and will make it a range over 3. + """ + print("## SEED SPREAD -- the training-noise floor of METRIC 1 on the IQL side (run 20)") + print("# Same role as the RSM replicate floor above, measured a different way: the RSM floor") + print("# comes from two byte-identical cells, the IQL floor from the same cell at different") + print("# TRAINING SEEDS. Both are training nondeterminism; neither is visible to the episode") + print("# bootstrap, which resamples episodes inside ONE trained critic.") + print() + + # (head, epoch) -> {seed: (ratioA, ci_width)}. PROBE_ cells are undertrained rolling + # checkpoints and are excluded by the regex, which requires the `_rw_` reward-matched prefix. + cells = collections.defaultdict(dict) + for head in rows: + for cell, mode, m, d in rows[head]: + mm = IDQL_RW_RE.match(cell) + if not mm or mode != "idql" or not m.get("defined", False): + continue + ci = m.get("boot", {}).get("ratioA_ci95") + cells[(head, int(mm.group(2)))][int(mm.group(1))] = ( + m.get("stitch_A", float("nan")), (ci[1] - ci[0]) if ci else float("nan")) + + floors = collections.defaultdict(list) # head -> [spread at each epoch that has >=2 seeds] + print("| head | epoch | per-seed stitch A | seeds | SEED SPREAD (range) | mean boot95 width | spread/width |") + print("|" + "---|" * 7) + for (head, ep) in sorted(cells): + per = cells[(head, ep)] + vals = [per[s][0] for s in sorted(per)] + wids = [per[s][1] for s in sorted(per)] + shown = ", ".join("s%d=%+.4f" % (s, per[s][0]) for s in sorted(per)) + if len(vals) < 2: + print("| %s | %d | %s | %d | *(needs >=2 seeds)* | %.4f | -- |" % ( + head, ep, shown, len(vals), wids[0])) + continue + spread = max(vals) - min(vals) + mw = sum(wids) / len(wids) + floors[head].append(spread) + print("| %s | %d | %s | %d | **%.4f** | %.4f | **%.2fx** |" % ( + head, ep, shown, len(vals), spread, mw, spread / mw if mw else float("nan"))) + print() + if not floors: + print("*(no head has >=2 reward-matched IQL seeds at the same epoch yet)*"); print() + return {} + + # One floor per head: the LARGEST spread seen across that head's epochs. Not the mean -- a + # claim has to clear the noise wherever it was measured, and with 2 draws per epoch the mean of + # two ranges is not a better estimate than the max, only a smaller one. + per_head = {h: max(v) for h, v in floors.items()} + print("Measured IQL seed floors (max range over the epochs measured): " + + ", ".join("%s = %.4f (%d epoch(s))" % (h, per_head[h], len(floors[h])) + for h in sorted(per_head))) + print() + print("**The floor is head-dependent, not scale-free.** %s. A pooled floor would license a " + "claim on one head using the noise of another, so every claim below is floored by its " + "OWN head." % " vs ".join("%s %.4f" % (h, per_head[h]) for h in sorted(per_head))) + print() + + # ---- epoch deltas, each against its OWN head's seed floor --------------------------------- + # run 22 FIX -- the span a head is read on must be one that >=2 SEEDS SHARE. + # The previous version took `lo, hi = eps[0], eps[-1]`: the head's global min and max epoch, + # pooled over seeds. If one seed had run further than the others -- which is the normal state + # of this stream, where the seeds are separate LSF jobs -- that widest span existed on ONE seed + # only, the seed intersection collapsed to that seed, and the section printed "only 1 seed with + # both epochs -- NOT a trend" even when a NARROWER span was on disk for two seeds. It bit + # GOAL_SEGMENT and GOAL_WINDOW_400 in run 21: both have e500/e1000 on two seeds and e1500 on + # seed 1 alone, so the cross-seed evidence that existed was never computed, and run 21 quoted + # GOAL_SEGMENT's drift off seed 1 alone. Now: pick the span maximising (n seeds sharing it, + # then width), report the trend verdict from THAT, and print any per-seed longer span below as + # single-seed context that no verdict is allowed to use. + print("### Epoch deltas on the IQL side, each read against its OWN head's seed floor") + print("# The span is the WIDEST one at least two seeds SHARE (run 22 fix); a seed that ran") + print("# further is shown afterwards as single-seed context and floors no verdict.") + print() + print("| head | seed | e_lo -> e_hi | delta | own-head seed floor | |delta| vs floor | verdict |") + print("|" + "---|" * 7) + verdicts = {} + spans = {} + extra = [] # (head, seed, lo, hi, delta) -- single-seed, longer than the common span + for head in sorted(set(h for h, _ in cells)): + eps = sorted(ep for h, ep in cells if h == head) + if len(eps) < 2: + continue + fl = per_head.get(head) + # every (lo, hi) pair, scored by how many seeds carry BOTH, then by width. + best, best_key = None, None + for a in range(len(eps)): + for b in range(a + 1, len(eps)): + lo, hi = eps[a], eps[b] + sh = set(cells[(head, lo)]) & set(cells[(head, hi)]) + if not sh: + continue + key = (len(sh), hi - lo) + if best_key is None or key > best_key: + best, best_key = (lo, hi, sorted(sh)), key + if best is None: + continue + lo, hi, seeds = best + spans[head] = (lo, hi) + for s in seeds: + dl = cells[(head, hi)][s][0] - cells[(head, lo)][s][0] + verdicts.setdefault(head, []).append(dl) + if fl is None: + v = "*(no floor)*" + elif abs(dl) >= fl: + v = "clears its floor" + else: + v = "**BELOW its floor -- not reportable**" + print("| %s | %d | %d -> %d | %+.4f | %.4f | %.2fx | %s |" % ( + head, s, lo, hi, dl, fl if fl else float("nan"), + abs(dl) / fl if fl else float("nan"), v)) + # any seed that reaches beyond the common span, shown but never scored into the verdict. + for s in sorted(set().union(*[set(cells[(head, e)]) for e in eps])): + mine = sorted(e for e in eps if s in cells[(head, e)]) + if len(mine) >= 2 and (mine[0], mine[-1]) != (lo, hi) and mine[-1] > hi: + extra.append((head, s, mine[0], mine[-1], + cells[(head, mine[-1])][s][0] - cells[(head, mine[0])][s][0], fl)) + print() + if extra: + print("Single-seed spans beyond the common span -- CONTEXT ONLY, no verdict uses these:") + print() + print("| head | seed | e_lo -> e_hi | delta | own-head seed floor | |delta| vs floor |") + print("|" + "---|" * 6) + for head, s, lo, hi, dl, fl in extra: + print("| %s | %d | %d -> %d | %+.4f | %s | %s |" % ( + head, s, lo, hi, dl, + "%.4f" % fl if fl else "--", + "%.2fx" % (abs(dl) / fl) if fl else "--")) + print() + for head in sorted(verdicts): + ds = verdicts[head] + lo, hi = spans[head] + if len(ds) < 2: + print("* `%s` (%d -> %d): only %d seed(s) share any span -- the direction is a single " + "draw and is NOT a trend." % (head, lo, hi, len(ds))) + continue + signs = set(d > 0 for d in ds) + mean_abs = sum(abs(d) for d in ds) / len(ds) + fl = per_head[head] + n_clear = sum(1 for d in ds if abs(d) >= fl) + if len(signs) > 1: + print("* `%s` (%d -> %d): the sign **FLIPS** across %d seeds (%s), and the mean |delta| " + "%.4f is %.2fx the seed floor %.4f. **No epoch trend is established for this " + "head.**" % (head, lo, hi, len(ds), ", ".join("%+.4f" % d for d in ds), + mean_abs, mean_abs / fl, fl)) + elif n_clear < len(ds): + print("* `%s` (%d -> %d): the sign agrees on all %d seeds (%s) but only %d of %d clear " + "the seed floor %.4f (mean |delta| %.4f = %.2fx). **Direction is SUGGESTED, not " + "established** -- a head whose every seed must clear its own floor cannot be " + "carried on the seeds that happen to." % ( + head, lo, hi, len(ds), ", ".join("%+.4f" % d for d in ds), n_clear, len(ds), + fl, mean_abs, mean_abs / fl)) + else: + print("* `%s` (%d -> %d): the sign AGREES on all %d seeds (%s), ALL of them clear the " + "seed floor %.4f, and the mean |delta| %.4f is %.2fx it. Direction is consistent " + "across independent seeds%s." % ( + head, lo, hi, len(ds), ", ".join("%+.4f" % d for d in ds), fl, mean_abs, + mean_abs / fl, "" if len(ds) >= 3 else + " -- 2 seeds, so a consistency, not yet a trend")) + print() + print("**Both rows above are UNDERTRAINED** against the e5000 read-out (`s0 @ e2000`, " + "`s1 @ e2500`) and are comparable only to each other, never to the read-out rows.") + print() + return per_head + + +def _size_token(cell): + """The `rr_rsm.sh ` size token a cell was launched with, or None. + + This is where the TRAINING SEED lives in this stream: `M` is seed 0 and `M_s1` is seed 1 + (scripts/rr_rsm.sh). Read from the payload rather than inferred from the `_s1` in the cell + name, so that a pair is only called a seed pair if the launcher really does change the seed. + """ + name = cell[4:] if cell.startswith("rsm_") else cell + pay = "%s/scripts/real/jobs/rw/ft_%s.sh" % (ROOT, name) + if not os.path.exists(pay): + return None + txt = open(pay).read() + # anchor on the EXEC line, never on prose: `ft_R_M_ft_v1_rep.sh:7` contains the words + # "as scripts/rr_rsm.sh does, so no shared launcher is edited", which a bare search reads as + # size token `so` and which made two genuine seed pairs SKIP as "same size token". + i = txt.find("exec bash") + mo = re.search(r"rr_rsm\.sh\s+(\S+)\s+(\S+)", txt[i:] if i >= 0 else txt) + return mo.group(2) if mo else None + + +def print_rsm_seed_floor(rows, floors): + """The RSM-side TRAINING-SEED floor of METRIC 1, per head. run 21. + + WHY THIS IS NOT THE REPLICATE FLOOR ALREADY ABOVE. `print_replicate_spread` measures two + trainings of the same configuration at the SAME seed: it is the nondeterminism floor. Every + claim this stream states is per-seed and is floored by that number, which is correct as far as + it goes. But the stream also reads the seed-0 and seed-1 rows of a claim SIDE BY SIDE and + treats an agreement in sign as support and a disagreement as a "sign flip" of the knob. That + reading needs a different floor -- how far apart two SEEDS of the SAME cell land -- and the RSM + side has never had one. This is the exact gap run 20 found and closed on the IQL side; the same + gap was open here. + + A pair is only used if, checked and not inferred from the name: + * both sides resolve their training flags and those flags are EQUAL (reward npy by CONTENT + hash via `npy_id`, weight npy, cap) -- so nothing but the seed differs; + * both sides were scored at the SAME training step (the run 13 guard); + * the launcher size tokens differ and are the M / M_s1 pair, i.e. the seed really did change. + """ + idx = ratio_index(rows) + sidx = step_index(rows) + print("## RSM TRAINING-SEED FLOOR -- how far apart two SEEDS of the SAME cell land (run 21)") + print("# The replicate floor above is same-seed nondeterminism. This is the DIFFERENT-SEED") + print("# spread, and it is the floor that any reading across the seed-0 and seed-1 rows of a") + print("# claim has to clear. Per-head, because run 20 measured the IQL floor to be ~10x") + print("# head-dependent and there is no reason this one is scale-free either.") + print() + cell_rng = {} + print("| head | config (seed stripped) | step | seed0 | seed1 | range | mean boot95 width | " + "range / CI width | signs agree? | size tokens |") + print("|" + "---|" * 10) + pairs = {} + for (head, cell) in sorted(idx): + if "_s1_" not in cell and not cell.endswith("_s1"): + continue + base = cell.replace("_s1_", "_") if "_s1_" in cell else cell[:-3] + if (head, base) not in idx: + continue + fa, fb = cell_flags(base), cell_flags(cell) + if "_unresolved" in fa or "_unresolved" in fb: + print("| %s | %s | -- | -- | -- | **SKIPPED** | -- | -- | -- | *flags unresolved: %s* |" % ( + head, base, fa.get("_unresolved") or fb.get("_unresolved"))) + continue + ka = (npy_id(fa["reward"]), fa["weight"], fa["trunc"]) + kb = (npy_id(fb["reward"]), fb["weight"], fb["trunc"]) + if ka != kb: + print("| %s | %s | -- | -- | -- | **SKIPPED** | -- | -- | -- | *not a seed pair: flags " + "differ %s vs %s* |" % (head, base, ka, kb)) + continue + sa, sb = sidx.get((head, base)), sidx.get((head, cell)) + if sa is None or sb is None or sa != sb: + print("| %s | %s | %s vs %s | -- | -- | **VOID** | -- | -- | -- | *scored at DIFFERENT " + "steps -- not comparable* |" % (head, base, sa, sb)) + continue + za, zb = _size_token(base), _size_token(cell) + if za is not None and zb is not None and za == zb: + print("| %s | %s | %s | -- | -- | **SKIPPED** | -- | -- | -- | *same size token `%s` -- " + "the launcher did NOT change the seed* |" % (head, base, sa, za)) + continue + a, b = idx[(head, base)], idx[(head, cell)] + rng = abs(a[0] - b[0]) + ws = [ci[1] - ci[0] for ci in (a[1], b[1]) if ci] + w = sum(ws) / len(ws) if ws else float("nan") + agree = "yes" if (a[0] > 0) == (b[0] > 0) else "**NO -- OPPOSITE SIGNS**" + zt = "%s / %s" % (za or "?", zb or "?") + print("| %s | %s | %s | %+.4f | %+.4f | **%.4f** | %.4f | %.1fx | %s | %s |" % ( + head, base, sa, a[0], b[0], rng, w, (rng / w if w == w and w > 0 else float("nan")), + agree, zt)) + pairs.setdefault(head, []).append((base, sa, a[0], b[0], rng, w, agree.startswith("yes"))) + # run 22: the same range, keyed by the CELL, so a claim can be floored by the measured + # movement of ITS OWN reference rather than by its head's worst pair. + cell_rng[(head, base)] = (rng, cell, sa) + cell_rng[(head, cell)] = (rng, base, sa) + print() + if not pairs: + print("*(no verified seed pair has landed yet)*"); print(); return {}, cell_rng + seed_floor = {} + print("### Per-head seed floor, against that head's own replicate floor") + print() + print("| head | seed floor (max range) | n pairs | sign agreement | replicate floor " + "(max over seeds) | seed floor / replicate floor |") + print("|" + "---|" * 6) + for head in sorted(pairs): + rs = pairs[head] + f = max(x[4] for x in rs) + seed_floor[head] = f + nag = sum(1 for x in rs if x[6]) + rep = [v for (h, s), v in floors.items() if h == head] + repmax = max(rep) if rep else None + ratio = ("%.1fx" % (f / repmax)) if repmax else "*(head has no landed replicate pair)*" + print("| %s | **%.4f** | %d | %d/%d agree | %s | %s |" % ( + head, f, len(rs), nag, len(rs), + ("%.4f" % repmax) if repmax else "--", ratio)) + print() + print("# READ THIS BEFORE QUOTING ANY CROSS-SEED READING. A head whose seed floor exceeds its") + print("# replicate floor by a wide margin has cells that are NOT reproducible across seeds at") + print("# the size of the differences this stream compares, and no agreement or disagreement") + print("# between its seed-0 and seed-1 rows carries information below that floor.") + for head in sorted(seed_floor): + rs = pairs[head] + if all(not x[6] for x in rs) and len(rs) >= 2: + print("# * %s: the two seeds land on OPPOSITE SIDES of zero in ALL %d verified pairs. " + "Its stitch sign is a property of the SEED, not of the head." % (head, len(rs))) + print() + return seed_floor, cell_rng + + +def print_claim_directions(rows): + """LABEL-DIRECTION GUARD (run 23). + + WHY THIS EXISTS. `print_claims` reports every row as `gap = hi - lo`, and it prints `hi cell`, + `lo cell` and `TRAINING FLAG DIFF (lo -> hi)`, so the table itself has always been correct. What + it did NOT do is check that the row's LABEL reads in the same direction. Every weight label does + ("weight axis w=1 -> w=10", hi=w10, lo=w1), but the cap labels read + `cap OFF (beta-trunc-eps 0.99)` -- which names the flag value sitting on the **LO** side, because + the cap-OFF `*_nt` cell is the lo cell and the DEFAULT-cap `*_x120` cell is the hi cell. + + It cost a published sign. Run 22 reduced the whole claims table to one surviving row and reported + it as "turning the cap OFF raises the stitch ratio on GOAL_EPISODE, +0.191 (s0) / +0.089 (s1)". + The measured cells say the opposite: cap ON (default eps 0.02) is +0.0096 (s0) / -0.0584 (s1) and + cap OFF (eps 0.99) is -0.1811 (s0) / -0.1479 (s1), so the gap is cap-ON MINUS cap-OFF and turning + the cap OFF LOWERS the stitch ratio. That also happens to be the physically expected direction: + eps 0.99 is the PRE-FIX behaviour in which the cap never binds, and rr_rsm.sh:110-112 documents it + as the bug the truncation fix removed. + + So: the labels are renamed to read `lo -> hi` like every other label, and this section derives the + direction from the RESOLVED FLAGS and states, per row, which side a positive gap favours. A label + that does not state a direction at all (no `->`) is named as NOT DIRECTION-STATING, which is the + exact defect that produced the reversed report. + """ + print() + print("## Claim LABEL-DIRECTION guard (run 23) -- every claim's sign, derived from its resolved flags") + print("# `gap` in the claims table is ALWAYS hi - lo. This section says, from the flags and not") + print("# from the label text, WHICH FLAG VALUE a positive gap favours, and flags any label that") + print("# does not state its own direction. run 22 read the label `cap OFF (beta-trunc-eps 0.99)`") + print("# as if cap OFF were the HI side and published the one surviving claim with its SIGN") + print("# REVERSED; the cap-OFF `*_nt` cell is the LO side.") + print() + print("| claim label | seed | lo cell (flag) | hi cell (flag) | a POSITIVE gap means | label states direction? |") + print("|" + "---|" * 6) + bad = [] + for label, hhi, seed, chi, hlo, clo in CLAIMS: + fh, fl = cell_flags(chi), cell_flags(clo) + if "_unresolved" in fh or "_unresolved" in fl: + print("| %s | %d | %s | %s | *(flags unresolved -- direction UNDEFINED)* | -- |" % ( + label, seed, clo, chi)) + continue + def ident(k, f): + return f[k] if k == "trunc" else npy_id(f[k]) + diff = sorted(k for k in ("reward", "weight", "trunc") if ident(k, fh) != ident(k, fl)) + if not diff: + print("| %s | %d | %s | %s | *(no flag differs -- this row is not a knob)* | -- |" % ( + label, seed, clo, chi)) + continue + def show(f): + return ", ".join("%s=%s" % (k, os.path.basename(str(f[k])) if k != "trunc" else f[k]) + for k in diff) + lo_s, hi_s = show(fl), show(fh) + states = "->" in label + if not states: + bad.append((label, seed)) + print("| %s | %d | %s (%s) | %s (%s) | **%s scores HIGHER than %s** | %s |" % ( + label, seed, clo, lo_s, chi, hi_s, hi_s, lo_s, + "yes" if states else "**NO -- NOT DIRECTION-STATING, the sign of this row cannot be " + "read off its label**")) + print() + if bad: + print("**%d claim label(s) do not state their direction and must not be quoted from the label " + "alone: %s**" % (len(bad), "; ".join("%s (seed %d)" % b for b in bad))) + else: + print("All %d claim labels read `lo -> hi`, so the label and the `gap = hi - lo` column agree " + "in direction." % len(CLAIMS)) + print() + +def print_claims(rows, floors, sig=None, seed_floor=None, cell_seed_rng=None): + idx = ratio_index(rows) + sidx = step_index(rows) + pm = partner_map() + print("## Between-cell differences read against their OWN replicate floor") + print("# run 12 FIX. The previous version floored a claim with the HI side's floor alone") + print("# (`floors.get((hhi, seed))`), falling back to the LO side only when the hi floor was") + print("# missing. That is wrong for every cross-head claim: a gap between two independently") + print("# trained cells carries BOTH cells' nondeterminism, so the floor cannot be the smaller") + print("# of the two. It mattered -- the w=1->w=10 rows were floored at 0.019-0.033 (the w=10") + print("# side) while the w=1 side's own floor is 0.128, and the w=1 cell's replicate partner") + print("# sits ABOVE the w=10 cell. Floor is now max(floor_hi, floor_lo) and is UNKNOWN unless") + print("# BOTH sides have a measured pair.") + print("#") + print("# `gap range` is the gap you would have quoted under every choice of which replicate of") + print("# each side to name. If it straddles 0 the SIGN of the effect is an artefact of that") + print("# choice, and no floor ratio can rescue it. ESTABLISHED needs >= 2x floor AND a gap") + print("# range that does not straddle 0; 1-2x is SUGGESTIVE; below 1x is NOT ESTABLISHED.") + print("#") + print("# run 22 SEED-STABILITY GUARD. Everything above this line is the SAME-SEED") + print("# nondeterminism floor. run 21 measured the DIFFERENT-SEED floor and found it 1.3-6.3x") + print("# larger on every head that has both, and found the `v1` reference cell moving") + print("# 0.367-0.388 between seeds at all three steps -- larger than every weight-axis gap") + print("# measured against it, and landing on OPPOSITE SIDES of zero. That was written down as") + print("# prose in run 21 while this table went on printing ESTABLISHED on the same rows. It is") + print("# now a guard: the `seed stability` column takes, for each side, that side's OWN") + print("# MEASURED seed range (the same cell at the other seed, same step, flags checked equal)") + print("# and falls back to the head-level seed floor only when the cell has no seed twin. A") + print("# gap smaller than the movement of its own reference is DEMOTED, whatever the replicate") + print("# floor says, because a per-seed claim that does not survive the choice of seed is a") + print("# property of the draw. Demotion never promotes: a row already NOT ESTABLISHED stays.") + print() + print("| claim | seed | hi cell | hi | lo cell | lo | gap | gap (replicate means) | gap range over replicate choices | floor = max(hi,lo) | gap/floor | vs POOLED 95% bar | seed stability (own-cell measured) | scored step hi vs lo | TRAINING FLAG DIFF (lo -> hi) | verdict |") + print("|" + "---|" * 16) + seed_floor = seed_floor or {} + cell_seed_rng = cell_seed_rng or {} + + def seed_guard(hhi, chi, hlo, clo, eff): + """(text, demote?) -- how far the two sides of this row move between SEEDS. + + Prefers the cell's OWN measured seed twin; falls back to the head-level floor, which is + the max over that head's pairs and so is a weaker, clearly-labelled statement. + """ + worst, src = None, None + for h, c in ((hhi, chi), (hlo, clo)): + got = cell_seed_rng.get((h, c)) + if got is not None: + if worst is None or got[0] > worst: + worst, src = got[0], "%s vs %s @%s" % (c, got[1], got[2]) + elif h in seed_floor: + f = seed_floor[h] + if worst is None or f > worst: + worst, src = f, "%s head floor" % h + if worst is None: + return "*(no seed twin on either side -- UNMEASURED)*", False + if worst <= 0: + return "*(0)*", False + r = abs(eff) / worst + if r >= 1.0: + return "%.3f / %.3f = %.2fx clears (%s)" % (abs(eff), worst, r, src), False + return "**%.3f / %.3f = %.2fx BELOW** (%s)" % (abs(eff), worst, r, src), True + bar = (1.96 * sig * 2 ** 0.5) if sig else None + + def vs_bar(g): + if bar is None: + return "--" + return "%.3f / %.3f = %.2fx %s" % (abs(g), bar, abs(g) / bar, + "**clears**" if abs(g) >= bar else "below") + for label, hhi, seed, chi, hlo, clo in CLAIMS: + a = idx.get((hhi, chi)); b = idx.get((hlo, clo)) + if a is None or b is None: + miss = ", ".join(c for c, got in ((chi, a), (clo, b)) if got is None) + print("| %s | %d | %s | -- | %s | -- | -- | -- | -- | -- | -- | -- | -- | -- | -- | **cell pending** (%s) |" % ( + label, seed, chi, clo, miss)) + continue + s_hi = sidx.get((hhi, chi)); s_lo = sidx.get((hlo, clo)) + step_s = "%s vs %s" % (s_hi if s_hi is not None else "?", s_lo if s_lo is not None else "?") + # run 16 GUARD, applied BEFORE the step guard: a row whose two sides were trained on + # different reward LABELS is not a knob at all, whatever its label says. + flag_ok, flag_s = knob_check(label, chi, clo) + if not flag_ok: + print("| %s | %d | %s | %.3f | %s | %.3f | %+.3f | -- | -- | -- | -- | -- | -- | %s | %s | %s |" % ( + label, seed, chi, a[0], clo, b[0], a[0] - b[0], step_s, flag_s, flag_s)) + continue + if s_hi is None or s_lo is None or s_hi != s_lo: + print("| %s | %d | %s | %.3f | %s | %.3f | %+.3f | -- | -- | -- | -- | -- | -- | **%s** | %s | " + "**CONFOUNDED -- the two sides were scored at DIFFERENT training steps; the gap " + "contains %s steps of extra training, not just the knob. NOT REPORTABLE.** |" % ( + label, seed, chi, a[0], clo, b[0], a[0] - b[0], step_s, flag_s, + ("+%d" % abs(s_hi - s_lo)) if (s_hi is not None and s_lo is not None) else "an unknown number of")) + continue + gap = a[0] - b[0] + + # every landed member of each side's replicate set + def members(head, cell): + vals = [idx[(head, cell)][0]] + pr = pm.get((head, cell)) + if pr is not None and (head, pr[0]) in idx: + vals.append(idx[(head, pr[0])][0]) + return vals + hi_vals = members(hhi, chi); lo_vals = members(hlo, clo) + gaps = [h - l for h in hi_vals for l in lo_vals] + gmin, gmax = min(gaps), max(gaps) + gap_mean = (sum(hi_vals) / len(hi_vals)) - (sum(lo_vals) / len(lo_vals)) + both_rep = len(hi_vals) > 1 and len(lo_vals) > 1 + gm_s = ("%+.3f" % gap_mean) if both_rep else ("%+.3f *(one side has no replicate)*" % gap_mean) + gr_s = "[%+.3f, %+.3f]%s" % (gmin, gmax, "" if not (gmin < 0 < gmax) else " **STRADDLES 0**") + + f_hi = floors.get((hhi, seed)); f_lo = floors.get((hlo, seed)) + if f_hi is None or f_lo is None: + missing = " and ".join(n for n, f in ((hhi, f_hi), (hlo, f_lo)) if f is None) + sg, _ = seed_guard(hhi, chi, hlo, clo, gap_mean if both_rep else gap) + print("| %s | %d | %s | %.3f | %s | %.3f | %+.3f | %s | %s | **not measured (%s)** | -- | %s | %s | %s | %s | " + "**FLOOR UNKNOWN per-head -- pooled bar shown for reference only** |" % ( + label, seed, chi, a[0], clo, b[0], gap, gm_s, gr_s, missing, + vs_bar(gap_mean if both_rep else gap), sg, step_s, flag_s)) + continue + fl = max(f_hi, f_lo) + if fl <= 0: + sg, _ = seed_guard(hhi, chi, hlo, clo, gap_mean if both_rep else gap) + print("| %s | %d | %s | %.3f | %s | %.3f | %+.3f | %s | %s | %.3f | -- | %s | %s | %s | %s | **FLOOR UNKNOWN** |" % ( + label, seed, chi, a[0], clo, b[0], gap, gm_s, gr_s, fl, + vs_bar(gap_mean if both_rep else gap), sg, step_s, flag_s)) + continue + eff = gap_mean if both_rep else gap + r = abs(eff) / fl + if gmin < 0 < gmax: + verdict = "**NOT ESTABLISHED -- replicate choice flips the SIGN**" + elif r >= 2.0: + verdict = "ESTABLISHED" + elif r >= 1.0: + verdict = "suggestive" + else: + verdict = "**NOT ESTABLISHED**" + sg, demote = seed_guard(hhi, chi, hlo, clo, eff) + if demote and verdict in ("ESTABLISHED", "suggestive"): + verdict = ("**NOT ESTABLISHED -- below its own SEED range** " + "(was %s on the replicate floor alone)" % verdict) + print("| %s | %d | %s | %.3f | %s | %.3f | %+.3f | %s | %s | %.3f (hi %.3f, lo %.3f) | %.1fx | %s | %s | %s | %s | %s |" % ( + label, seed, chi, a[0], clo, b[0], gap, gm_s, gr_s, fl, f_hi, f_lo, r, + vs_bar(eff), sg, step_s, flag_s, verdict)) + print() + + +def cell_family(cell): + """Drop the two suffixes that mark an INDEPENDENT DRAW of the same configuration. + + run 14. `_rep` is a re-training with only `--out` changed; `_s1` selects training seed 1 via + rr_rsm.sh's SIZE argument (`M`=0, `M_s1`=1) and changes nothing else. So + v1 / v1_rep / v1_s1 / v1_s1_rep are FOUR draws of one configuration. Every other suffix + (`_nt`, `_x120`, `_w10`, `_C30`) is a different configuration and is kept. + """ + c = cell + if c.endswith("_rep"): + c = c[: -len("_rep")] + if c.endswith("_s1"): + c = c[: -len("_s1")] + return c + + +def exact_ranksum(hi, lo): + """Exact two-sided permutation p for U = #{h>l}, and the SMALLEST p this design can reach. + + run 14. The z-test in the pooled table borrows strength from sigma, which was measured on 6 + other replicate pairs. This is the same comparison using only the 8 numbers in the row and no + sigma at all. With n=m=4 the smallest attainable two-sided p is 2/70 = 0.029, so a p near 0.057 + is ONE SWAP off this design's floor and is not evidence against the effect -- the floor is + printed beside it so the row cannot be misread as a failure to replicate. + """ + from itertools import combinations + allv = list(hi) + list(lo) + n, k = len(allv), len(hi) + if n > 20 or k == 0 or len(lo) == 0: + return None, None, None + obs = sum(1 for h in hi for l in lo if h > l) + mx = k * len(lo) + cnt = tot = 0 + best = 10 ** 9 + for c in combinations(range(n), k): + a = [allv[i] for i in c] + b = [allv[i] for i in range(n) if i not in c] + u = sum(1 for x in a for y in b if x > y) + tot += 1 + if u >= obs or u <= mx - obs: + cnt += 1 + # floor of the design: perfect separation + floor_cnt = sum(1 for c in combinations(range(n), k) + if (lambda u: u >= mx or u <= 0)( + sum(1 for x in [allv[i] for i in c] + for y in [allv[i] for i in range(n) if i not in c] if x > y))) + return obs, cnt / tot, max(2.0 / tot, floor_cnt / tot if floor_cnt else 2.0 / tot) + + +def print_pooled_claims(rows, sig): + """Each knob read once, pooling every independent draw of both sides. run 14. + + The per-seed table above spends a 4-draw dataset as two 1-vs-1 comparisons, each floored at the + full single-training sd. Pooling k draws per side divides the standard error by sqrt(k): the + bar on a gap falls from 1.96*sigma*sqrt(2) to 1.96*sigma*sqrt(1/n_hi + 1/n_lo). sigma is the + POOLED training sd measured in the noise budget, not an sd of these four numbers, so a knob with + only 2 draws a side is not rescued by an accidentally tight pair. + """ + idx = ratio_index(rows) + sidx = step_index(rows) + print("## KNOBS READ ONCE, pooling every independent draw of each side") + print("# Same data as the per-seed table, spent as ONE comparison instead of two. n is the") + print("# number of independent trainings landed on that side (replicates + seeds).") + print() + if not sig: + print("*(no pooled sigma -- no replicate pair has landed)*"); print(); return + print("| knob | hi (head/family) | n | mean | lo (head/family) | n | mean | gap | se | z | p (z, uses sigma) | p (exact rank, no sigma) | steps | TRAINING FLAG DIFF (lo -> hi) | verdict |") + print("|" + "---|" * 15) + + order, spec = [], {} + for label, hhi, seed, chi, hlo, clo in CLAIMS: + if label not in spec: + order.append(label) + # keep one representative cell pair so the run-16 flag guard can be applied to the knob + spec[label] = (hhi, cell_family(chi), hlo, cell_family(clo), chi, clo) + + def draws(head, fam): + out = [] + for (h, cell), (val, _ci) in idx.items(): + if h != head or cell.startswith("PROBE_") or not cell.startswith("rsm"): + continue + if cell_family(cell) != fam: + continue + out.append((cell, val, sidx.get((h, cell)))) + return sorted(out) + + for label in order: + hhi, fhi, hlo, flo, chi0, clo0 = spec[label] + flag_ok, flag_s = knob_check(label, chi0, clo0) + dh, dl = draws(hhi, fhi), draws(hlo, flo) + if not flag_ok: + print("| %s | %s/%s | %d | -- | %s/%s | %d | -- | -- | -- | -- | -- | -- | -- | %s | %s |" % ( + label, hhi, fhi, len(dh), hlo, flo, len(dl), flag_s, flag_s)) + continue + if not dh or not dl: + print("| %s | %s/%s | %d | -- | %s/%s | %d | -- | -- | -- | -- | -- | -- | -- | %s | " + "**cells pending** |" % (label, hhi, fhi, len(dh), hlo, flo, len(dl), flag_s)) + continue + steps = set(st for _c, _v, st in dh + dl) + if len(steps) != 1 or None in steps: + print("| %s | %s/%s | %d | %.3f | %s/%s | %d | %.3f | %+.3f | -- | -- | -- | -- | **%s** | %s | " + "**CONFOUNDED -- the draws were scored at DIFFERENT training steps. NOT " + "REPORTABLE.** |" % ( + label, hhi, fhi, len(dh), sum(v for _c, v, _s in dh) / len(dh), + hlo, flo, len(dl), sum(v for _c, v, _s in dl) / len(dl), + sum(v for _c, v, _s in dh) / len(dh) - sum(v for _c, v, _s in dl) / len(dl), + ",".join(str(x) for x in sorted(steps, key=lambda y: (y is None, y))), flag_s)) + continue + mh = sum(v for _c, v, _s in dh) / len(dh) + ml = sum(v for _c, v, _s in dl) / len(dl) + gap = mh - ml + se = sig * (1.0 / len(dh) + 1.0 / len(dl)) ** 0.5 + z = gap / se if se > 0 else 0.0 + try: + from math import erfc, sqrt as _sq + pv = erfc(abs(z) / _sq(2.0)) + except Exception: + pv = float("nan") + if len(dh) < 2 or len(dl) < 2: + verdict = "**single draw on one side -- not reportable**" + elif pv < 0.05: + verdict = "**ESTABLISHED** (p=%.3f)" % pv + elif pv < 0.20: + verdict = "suggestive" + else: + verdict = "**NOT ESTABLISHED**" + u, rp, rfloor = exact_ranksum([v for _c, v, _s in dh], [v for _c, v, _s in dl]) + rs = "--" if rp is None else ("%.3f (U=%d/%d; this design's floor is %.3f)" % ( + rp, u, len(dh) * len(dl), rfloor)) + print("| %s | %s/%s | %d | %.3f | %s/%s | %d | %.3f | %+.3f | %.3f | %+.2f | %.3f | %s | %s | %s | %s |" % ( + label, hhi, fhi, len(dh), mh, hlo, flo, len(dl), ml, gap, se, z, pv, rs, + sorted(steps)[0], flag_s, verdict)) + print("| | *draws:* %s | | | *draws:* %s | | | | | | | | | |" % ( + " ".join("%s=%+.3f" % (c.replace("rsm_R_M_ft_", ""), v) for c, v, _s in dh), + " ".join("%s=%+.3f" % (c.replace("rsm_R_M_ft_", ""), v) for c, v, _s in dl))) + print() + print("`sigma` is the pooled training-noise sd from the noise budget (%.4f)." % sig) + print("A knob with n=1 on either side is printed but NEVER called established: one draw cannot") + print("be separated from that side's own run-to-run spread.") + print() + + +def _raw_parent(cell): + """cell -> the parent cell it was seeded from, with NO flag filter (unlike continuation_map). + + Source order is the same as cell_flags(): the `ft_.sh` payload's `PAR=` line, else the + `)` case of rr_rsm.sh and its `FT_FROM=`. Returns None for a base training. + """ + name = cell[4:] if cell.startswith("rsm_") else cell + p = os.path.join(ROOT, "scripts", "real", "jobs", "rw", "ft_%s.sh" % name) + if os.path.exists(p): + txt = open(p).read() + mo = re.search(r"^PAR=.*?/rsm/([A-Za-z0-9_]+)\s*$", txt, re.M) + # it must actually COPY the parent forward, or it is not a continuation of it + if mo and "$PAR/ckpt.pt" in txt: + return mo.group(1) + lf = os.path.join(ROOT, "scripts", "rr_rsm.sh") + if os.path.exists(lf): + mo = re.search(r"^\s*%s\)(.*)$" % re.escape(name), open(lf).read(), re.M) + if mo: + m2 = re.search(r"FT_FROM=\"[^\"]*?/rsm/([A-Za-z0-9_]+)\"", mo.group(1)) + if m2: + return m2.group(1) + return None + + +def base_parent(cell): + """The ROOT of a cell's fine-tune lineage -- the base training all of its ancestors descend from. + + run 23 GUARD ON THE SIGN TEST. The cap-axis sign test is the only reading this stream has left + standing, and its H0 treats each row's sign as an independent coin. The rows are NOT independent + all the way down: every `*_x120` / `*_nt` / `C*` / `v0lit*` cell on this corpus is a +10k + fine-tune whose lineage terminates at `R_M` (seed 0) or `R_M_s1` (seed 1), so ten rows can rest + on TWO base trainings. The two ARMS of a row ARE separate optimizer runs off a shared parent, so + each row is a genuine paired one-flag comparison -- what the row count overstates is how many + independent BASES the agreement spans, and therefore how safe the binomial p is. Measured here + and printed by the sign test, so no reader has to assume n rows = n independent draws. + """ + seen = set() + cur = cell[4:] if cell.startswith("rsm_") else cell + # run 31. Same rule as cell_flags(): a trailing `_s<5+ digits>` is a checkpoint READ of an + # existing training, so its LINEAGE is that training's. Without this, `R_XL_ft_v0_nt_s110000` + # has no launcher entry, `_raw_parent` returns None, and it is reported as a BASE of its own -- + # the sign test then printed `6 (R_L40,R_M,R_M_s1,R_XL,R_XL_ft_v0_nt_s110000, + # R_XL_ft_v1_nt_s110000)` for a set of rows that in fact span FOUR bases. An inflated base + # count is exactly the independence overstatement base_parent exists to prevent. + if not _flag_name_resolves(cur): + stripped = re.sub(r"_s\d{5,}$", "", cur) + if stripped != cur and _flag_name_resolves(stripped): + cur = stripped + while cur and cur not in seen: + seen.add(cur) + nxt = _raw_parent(cur) + if nxt is None: + return cur + cur = nxt + return cur + + +def print_sign_tests(rows): + """Floor-free reading of a knob: does it move METRIC 1 the SAME WAY in every place it was tried? + + run 13. The magnitude floor measured in this stream is huge on one cell (GOAL_SEGMENT s0, + 0.128) and small on three others (0.018-0.032). That kills every SINGLE-pair magnitude claim + that involves the big-floor cell, and run 12 correctly retracted those. It does not kill a + PAIRED SIGN argument: each row of a claim group is the same knob flipped on a different + (head, seed), the two members of a row share everything but the knob, and the replicate noise + is not known to be one-signed. Under the null "the knob does nothing", each row's sign is a + fair coin independent across rows, so k of n rows agreeing has exact two-sided p = 2 * + P(Binom(n, 1/2) >= k). No floor enters. What this CANNOT do is say how big the effect is, + and it is void if any row's gap is itself inside that row's replicate spread in a way that + could flip -- so the per-row `within floor?` column is printed and rows flagged there are + counted separately. + """ + from math import comb + idx = ratio_index(rows) + sidx = step_index(rows) + pm = partner_map() + + def members(head, cell): + if (head, cell) not in idx: + return [] + vals = [idx[(head, cell)][0]] + pr = pm.get((head, cell)) + if pr is not None and (head, pr[0]) in idx: + vals.append(idx[(head, pr[0])][0]) + return vals + + groups = {} + for label, hhi, seed, chi, hlo, clo in CLAIMS: + groups.setdefault(label, []).append((seed, hhi, chi, hlo, clo)) + + print("## SIGN TEST per knob -- the one reading that needs no magnitude floor") + print("# H0: the knob does nothing, so each (head, seed) row's sign is a fair coin.") + print("# Exact two-sided p = 2 * P(Binom(n, 1/2) >= k) for k of n rows agreeing, capped at 1.") + print("# This says DIRECTION ONLY. It never licenses quoting a magnitude.") + print() + print("# run 23: `independent bases` is how many BASE trainings the counted rows trace back to") + print("# (lineage measured from each payload's PAR= / FT_FROM=, not from the cell name). n rows") + print("# off 2 bases is not n independent draws; the binomial p assumes it is, so both are printed.") + print() + print("| knob | rows landed | gaps (hi - lo, replicate means where available) | k of n same sign | exact two-sided p | independent bases | direction |") + print("|" + "---|" * 7) + _pooled = {} + for label in sorted(groups): + gaps = [] + dropped = [] + flagdrop = [] + bases = set() + for seed, hhi, chi, hlo, clo in sorted(groups[label]): + hv = members(hhi, chi); lv = members(hlo, clo) + if not hv or not lv: + continue + # run 13: a row whose two sides were scored at different training steps is confounded + # and contributes no information about the knob, so it is DROPPED from the sign test + # rather than counted -- otherwise the step difference, which is one-signed across every + # row of a group, manufactures a unanimous sign out of nothing. + s_hi = sidx.get((hhi, chi)); s_lo = sidx.get((hlo, clo)) + if s_hi is None or s_lo is None or s_hi != s_lo: + dropped.append("%s s%d (%s vs %s)" % (label, seed, s_hi, s_lo)) + continue + # run 16: same rule for the TRAINING FLAG guard. A row whose two sides differ in reward + # label is not a draw of this knob at all, and its sign is one-signed across the group in + # exactly the way that manufactures a unanimous direction out of a head effect. + fok, fwhy = knob_check(label, chi, clo) + if not fok: + flagdrop.append("%s s%d: %s" % (label, seed, fwhy)) + continue + _g = (sum(hv) / len(hv)) - (sum(lv) / len(lv)) + gaps.append(_g) + bases.add(base_parent(chi)); bases.add(base_parent(clo)) + # run 24: the same surviving row, filed under the FLAG it varies rather than under its + # label, for the pooled table below. + _ll = label.lower() + _key = None + for _pat, _k in _KNOB_KEY: + if _pat in _ll: + _key = _k + break + if _key is not None: + _pooled.setdefault(_key, []).append( + (label, hhi, seed, _g, base_parent(chi), base_parent(clo))) + n = len(gaps) + if n == 0: + why = ("**every row CONFOUNDED by a TRAINING FLAG mismatch: %s**" % "; ".join(flagdrop)) if flagdrop \ + else ("**every row CONFOUNDED by step mismatch: %s**" % "; ".join(dropped)) if dropped \ + else "**no row landed**" + print("| %s | 0 | -- | -- | -- | -- | %s |" % (label, why)) + continue + npos = sum(1 for g in gaps if g > 0) + nneg = sum(1 for g in gaps if g < 0) + k = max(npos, nneg) + p = min(1.0, 2.0 * sum(comb(n, j) for j in range(k, n + 1)) / float(2 ** n)) + if k < n: + direction = "**MIXED -- no direction**" + elif p <= 0.05: + direction = "**%s in %d/%d, p=%.3f**" % ("RAISES" if npos == n else "LOWERS", n, n, p) + else: + direction = "%s in %d/%d but n too small (p=%.3f)" % ( + "raises" if npos == n else "lowers", n, n, p) + if dropped: + direction += " *(%d row(s) DROPPED, step-confounded: %s)*" % (len(dropped), "; ".join(dropped)) + if flagdrop: + direction += " *(%d row(s) DROPPED, TRAINING FLAG confounded: %s)*" % ( + len(flagdrop), "; ".join(flagdrop)) + # run 23: how many INDEPENDENT BASE TRAININGS the agreeing rows actually rest on. + nb = len(bases) + base_s = "%d (%s)" % (nb, ",".join(sorted(bases))) + if k == n and nb < n: + direction += (" *(but these %d rows rest on only %d independent BASE training(s) -- " + "%s; every row is a paired one-flag comparison off a SHARED parent, so the " + "binomial p above assumes more independence than the design has. Quote the " + "DIRECTION and the base count together, never p alone.)*" + % (n, nb, ",".join(sorted(bases)))) + print("| %s | %d | %s | %d of %d | %.3f | %s | %s |" % ( + label, n, ", ".join("%+.3f" % g for g in gaps), k, n, p, base_s, direction)) + print() + print("*n=5 is the smallest n that can reach p<=0.05 on a two-sided sign test (p=0.0625 at n=5,") + print("0.031 at n=6), so a 5-of-5 knob is at p=0.0625 -- suggestive, not significant. Say so.*") + print() + _print_pooled_sign_tests(_pooled) + + +def _print_pooled_sign_tests(pooled): + """run 24. The SAME sign test, grouped by the FLAG a row varies instead of by its LABEL. + + WHY THIS EXISTS. The table above groups by label text, and a label carries the read step and the + base in it (`... [step-matched @120k]`, `... [step-matched @110k] [base R_XL]`). That is right + for reporting a specific comparison and wrong for answering the only question the cap axis is + actually asking -- does `--beta-trunc-eps` have a consistent direction. Split by label, ten + step-matched cap rows over four bases are reported as three separate tests of n=5, n=3 and n=2, + none of which can reach p<=0.05, purely because they were read at 120k, 115k and 110k. Pooled, + they are one test. + + WHAT MAKES POOLING LEGITIMATE HERE, and it is not general: every row entering this table has + ALREADY passed both guards above -- its two sides were scored at the SAME step as each other + (the step guard), and their training-flag diff is EXACTLY this one flag (knob_check). So each + row is a self-contained paired one-flag comparison, and which absolute step a given PAIR was read + at is a property of that pair, not a difference between the two things being compared. Rows + dropped by either guard never arrive here. + + WHAT IT STILL DOES NOT FIX. The binomial p assumes independent rows. Rows off the same base + training are not independent, so the base count is printed beside the p and, when it is smaller + than n, the same warning the per-label table uses is repeated. This table says DIRECTION ONLY; + it licenses no magnitude, and it is additive -- the per-label table above is unchanged and + remains the thing to quote for any single comparison. + """ + from math import comb + if not pooled: + return + print("## SIGN TEST POOLED BY FLAG -- every step-matched, flag-checked row of one knob, together") + print("# Additive to the per-label table above; both are printed and neither replaces the other.") + print("# Only rows that already passed the step guard AND knob_check are here.") + print() + print("| flag | rows | heads | bases | gaps | k of n | exact two-sided p | verdict |") + print("|" + "---|" * 8) + for key in sorted(pooled): + rows = pooled[key] + gaps = [r[3] for r in rows] + n = len(gaps) + heads = sorted(set(r[1] for r in rows)) + bases = sorted(set([r[4] for r in rows] + [r[5] for r in rows])) + npos = sum(1 for g in gaps if g > 0) + nneg = sum(1 for g in gaps if g < 0) + k = max(npos, nneg) + p = min(1.0, 2.0 * sum(comb(n, j) for j in range(k, n + 1)) / float(2 ** n)) + if k < n: + verdict = "**MIXED -- no direction (%d of %d)**" % (k, n) + elif p <= 0.05: + verdict = "**%s in %d/%d, p=%.3f**" % ("RAISES" if npos == n else "LOWERS", n, n, p) + else: + verdict = "%s in %d/%d but n too small (p=%.3f)" % ( + "raises" if npos == n else "lowers", n, n, p) + nb = len(bases) + if k == n and nb < n: + verdict += (" *(rests on %d independent BASE training(s) -- %s -- not %d; quote the " + "DIRECTION and the base count together, never p alone.)*" + % (nb, ",".join(bases), n)) + print("| `%s` | %d | %s | %d (%s) | %s | %d of %d | %.3f | %s |" % ( + key, n, ",".join(heads), nb, ",".join(bases), + ", ".join("%+.3f" % g for g in gaps), k, n, p, verdict)) + print() + print("# contributing rows, so the pooling is auditable row by row:") + for key in sorted(pooled): + for label, head, seed, g, bhi, blo in sorted(pooled[key], key=lambda r: (r[0], r[1], r[2])): + print("# %s %s s%d gap %+.3f bases %s/%s <- %s" % (key, head, seed, g, bhi, blo, label)) + print() + + + + +# --------------------------------------------------------------------------- +# run 17. STEP DRIFT -- the noise component the budget was missing. +# +# The noise budget above has three sources: scorer Monte-Carlo, episode resampling, and +# TRAINING nondeterminism (two independent trainings of the same config, both read at the +# SAME step). None of them asks whether METRIC 1 at a cell is STABLE IN THE STEP at which +# the cell is read. Every claim in this stream is read off ONE checkpoint per cell, so if +# the metric is still moving along a single trajectory, a between-cell gap is partly just +# where each cell happens to sit on its own curve. +# +# The `_x120` pack makes this measurable with no new compute and no confound at all. Each +# `*_x120` cell is a DIRECT CONTINUATION: its payload copies the parent's `ckpt.pt` and +# trains 10000 more steps with the parent's flags copied verbatim. So parent-at-110000 and +# child-at-120000 are the SAME optimizer trajectory read 10k steps apart -- the delta +# contains no training nondeterminism, no seed change and no flag change. It is pure drift. +# +# The parent link is READ FROM THE LAUNCHER (`PAR=` in `ft_.sh`), never a hand table, +# for the same reason cell_flags() is: a hand table silently goes stale. +# --------------------------------------------------------------------------- + +def continuation_map(): + """child cell -> parent cell, MEASURED from each payload's `PAR=` line. + + Returns {} entries only for payloads that both declare a parent and copy it forward, so a + payload that merely mentions a path cannot fabricate a continuation. + """ + out = {} + for p in sorted(glob.glob(os.path.join(ROOT, "scripts", "real", "jobs", "rw", "ft_*.sh"))): + try: + txt = open(p).read() + except Exception: + continue + mo = re.search(r"^PAR=.*?/rsm/([A-Za-z0-9_]+)\s*$", txt, re.M) + if not mo: + continue + # a continuation MUST seed itself from the parent checkpoint; otherwise it is an + # independent training that merely names a parent, and its delta is not pure drift. + if "$PAR/ckpt.pt" not in txt: + continue + child = "rsm_" + os.path.basename(p)[len("ft_"):-len(".sh")] + parent = "rsm_" + mo.group(1) + # run 17 FIX. Seeding from the parent ckpt is NOT sufficient: `*_nt` seeds from its parent + # and then turns the cap off, and `C30` seeds from `C10` and then swaps the weight npy. + # Those deltas are drift PLUS a flag change, which is the very confound this section exists + # to exclude -- and the first version of this table silently counted four of them. A pair is + # a continuation only if the MEASURED flags (reward content, weight content, trunc) are + # identical on both sides, using the same cell_flags()/npy_id() machinery as knob_check(). + fc, fp = cell_flags(child), cell_flags(parent) + if "_unresolved" in fc or "_unresolved" in fp: + continue + def _id(k, f): + return f[k] if k == "trunc" else npy_id(f[k]) + if any(_id(k, fc) != _id(k, fp) for k in ("reward", "weight", "trunc")): + continue + out[child] = parent + return out + + +def child_of_map(): + """parent cell -> its UNIQUE flag-identical continuation child (ambiguity is dropped loudly).""" + inv = {} + for child, parent in continuation_map().items(): + inv.setdefault(parent, []).append(child) + return {p: k[0] for p, k in inv.items() if len(k) == 1}, {p: k for p, k in inv.items() if len(k) > 1} + + +def print_step_drift(rows, sig): + """Table of parent(step N) -> child(step N+10k) on ONE trajectory, plus the pooled drift sd.""" + idx = ratio_index(rows) + steps = step_index(rows) + head_of = {} + for (h, c) in idx: + head_of[c] = h + cont = continuation_map() + print() + print("## STEP DRIFT of METRIC 1 -- the SAME trajectory, read 10k steps apart") + print("# Each `*_x120` cell copies its parent's ckpt.pt and trains +10000 steps with the parent's") + print("# flags verbatim (parent link parsed from `PAR=` in the payload, not assumed). So the delta") + print("# below is the SAME optimizer run read at two steps: no seed change, no flag change, no") + print("# second training. It is the drift of the metric along one trajectory, and it is a noise") + print("# component that the replicate floor -- which reads BOTH cells at the SAME step -- cannot see.") + print() + print("| head | parent cell | step | stitch | child cell | step | stitch | delta (child - parent) |") + print("|" + "---|" * 8) + ds = [] + for child in sorted(cont): + parent = cont[child] + h = head_of.get(child) + if h is None or head_of.get(parent) is None: + continue + if (h, child) not in idx or (head_of[parent], parent) not in idx: + continue + sp, sc = steps.get((head_of[parent], parent)), steps.get((h, child)) + vp = idx[(head_of[parent], parent)][0] + vc = idx[(h, child)][0] + if sp is None or sc is None or sp == sc: + # no step separation -> this pair says nothing about drift + continue + ds.append(vc - vp) + print("| %s | %s | %s | %+.3f | %s | %s | %+.3f | **%+.3f** |" % + (h, parent, sp, vp, child, sc, vc, vc - vp)) + if not ds: + print() + print("*(no continuation pair has both cells scored yet)*") + return None + n = len(ds) + rms = (sum(d * d for d in ds) / n) ** 0.5 + print() + print("* pairs landed: **%d**; deltas %s" % (n, ", ".join("%+.3f" % d for d in ds))) + print("* **step-drift sd over +10000 steps: %.4f** (rms of the deltas; each delta is one trajectory, " + "so this is the sd directly, not a difference of two draws)" % rms) + if sig: + print("* training-replicate sd (same config, two trainings, SAME step): **%.4f**" % sig) + print("* ratio drift/replicate = **%.1fx**" % (rms / sig if sig else float("nan"))) + if rms > sig: + print() + print("> **METRIC 1 IS NOT CONVERGED at 110k-120k steps.** The same run moves by %.3f (sd) " + "over 10k further steps, %.1fx more than two independent trainings of the same config " + "differ at a fixed step. A between-cell gap read off ONE checkpoint each is therefore " + "a claim about (config, step), not about the config: any gap smaller than ~%.3f can be " + "produced by reading the two cells at a slightly different point on their own curves. " + "Every claim below whose gap is under that value is flagged." % (rms, rms / sig, rms)) + return rms + + +def run_dir_of(d): + """The RUN DIRECTORY a record was scored from, read out of config.rsm_ckpt -- never the folder name. + + run 18. A cell can now be scored at SEVERAL steps, and stitch_one_cell.sh puts a non-terminal read + in `rsm__s` so it cannot collide with the terminal read's dir. Two dirs therefore map to + ONE trajectory, and the only trustworthy link between them is the checkpoint path recorded inside the + json. Stripping `_s` off the folder name would also "work" until a cell is legitimately named + with a trailing `_s...` -- `R_M_ft_v1_s1` already is -- so this reads the content instead. + """ + ck = (d.get("config") or {}).get("rsm_ckpt") or "" + if not ck: + return None + return os.path.basename(os.path.dirname(ck)) + + +def print_within_cell_trajectory(rows, sig): + """METRIC 1 read at MANY steps of ONE run -- the drift CURVE, not a two-point delta. + + run 17 measured step drift from 7 parent/child pairs, i.e. one delta per trajectory over a 10k gap. + That is enough to say the metric is not converged and not enough to say what its curve looks like. + The `_x130` leg is launched with `--eval-every 2000` (see ft_*_x130.sh): `ckpt_s.pt` is written + at train_rsm.py:1203 NESTED inside the eval gate at line 983, so --save-every only fires on steps that + are ALSO eval steps -- 5000 x 2000 gave one checkpoint per 10k, which is why every earlier run dir + holds exactly one. At 2000 each x130 cell writes 122k/124k/126k/128k/130k. + + Rows here are grouped by RUN DIRECTORY, so every read below is the same optimizer trajectory: no seed + change, no flag change, no second training. The spread within a row is pure read-step noise. + """ + idx = ratio_index(rows) + print() + print("## WITHIN-CELL STEP SERIES of METRIC 1 -- one trajectory, read at several steps") + print("# Grouped by the RUN DIR recorded in config.rsm_ckpt, so each row is ONE optimizer run.") + print("# Anything a row spans is noise in the STEP a cell is read at, and every claim in this file") + print("# is read off one checkpoint per side.") + print() + by_run = collections.defaultdict(dict) # (head, run_dir) -> {step: ratio} + for head, recs in rows.items(): + for cell, mode, m, d in recs: + if not mode.startswith("rsm") or cell.startswith("PROBE_"): + continue + if not m.get("defined", False): + continue + rd = run_dir_of(d) + st = ckpt_step(d) + if rd is None or st is None: + continue + by_run[(head, rd)][st] = m.get("stitch_A", float("nan")) + multi = {k: v for k, v in by_run.items() if len(v) >= 2} + if not multi: + print("*(no run dir has been scored at more than one step yet -- the `_x130` leg supplies the") + print("first ones; until then the two-point table below is all there is)*") + return None + print("| head | run dir | reads | steps | stitch at each step | range (max-min) | consecutive deltas |") + print("|" + "---|" * 7) + per_step_sd = [] + ranges = [] + for (head, rd) in sorted(multi): + ser = multi[(head, rd)] + st = sorted(ser) + vals = [ser[x] for x in st] + deltas = [(vals[i + 1] - vals[i], st[i + 1] - st[i]) for i in range(len(vals) - 1)] + rng = max(vals) - min(vals) + ranges.append(rng) + for dv, dstep in deltas: + if dstep > 0: + per_step_sd.append((dv, dstep)) + print("| %s | %s | %d | %s | %s | **%.3f** | %s |" % ( + head, rd, len(st), ", ".join(str(x) for x in st), + ", ".join("%+.3f" % v for v in vals), rng, + ", ".join("%+.3f/%dk" % (dv, dstep // 1000) for dv, dstep in deltas))) + print() + print("* run dirs with >=2 reads: **%d**; median within-run range **%.3f**, max **%.3f**" % ( + len(multi), sorted(ranges)[len(ranges) // 2], max(ranges))) + if per_step_sd: + # scale every delta to a common 10k gap so short-gap and long-gap reads are comparable: + # a random-walk-like drift grows as sqrt(gap), so divide by sqrt(gap/10000). + scaled = [dv / ((dstep / 10000.0) ** 0.5) for dv, dstep in per_step_sd] + rms = (sum(x * x for x in scaled) / len(scaled)) ** 0.5 + print("* consecutive deltas: **%d**, gaps %s" % ( + len(per_step_sd), ", ".join(sorted({"%dk" % (g // 1000) for _, g in per_step_sd})))) + print("* **drift sd rescaled to a 10k gap: %.4f** (each delta divided by sqrt(gap/10000); the") + print(" sqrt scaling ASSUMES the drift is random-walk-like and is an assumption, not a") + print(" measurement -- if the per-gap deltas above do not grow like sqrt(gap), say so and drop it)") + if sig: + print("* training-replicate sd (same config, two trainings, SAME step): **%.4f**; ratio **%.1fx**" + % (sig, rms / sig if sig else float("nan"))) + return rms + return None + + +def print_step_consistency(rows): + """Does a knob's measured effect SURVIVE +10k steps on both of its own trajectories? + + The strongest form of the drift question, and the one that needs no sd at all: take a claim + whose hi and lo cells BOTH have a continuation child, and recompute the SAME gap from the two + children. Same configs, same seeds, same knob, both sides step-matched at each read -- only + the step at which the pair is read changes. If the sign flips, the knob's effect is not a + property of the knob. + """ + idx = ratio_index(rows) + steps = step_index(rows) + cont, ambig = child_of_map() + head_of = {} + for (h, c) in idx: + head_of[c] = h + print() + print("## STEP CONSISTENCY per knob -- the same two trajectories, read 10k steps apart") + print("# No sd and no floor is used here. For every claim whose BOTH sides have a continuation") + print("# child, the identical gap is recomputed from the children. Nothing changes except the step.") + print() + for par, kids in sorted(ambig.items()): + print("*(ambiguous: `%s` has %d flag-identical continuations %s -- dropped)*" % + (par, len(kids), ",".join(sorted(kids)))) + print("| knob | seed | gap @ parent step | gap @ child step | swing | sign |") + print("|" + "---|" * 6) + seen = 0 + flips = 0 + # run 17 FIX. The first version skipped any label containing "[step-matched @120k]", which was + # right only while 120000 was the last step on disk. With the `_x130` cells a @120k row is a + # legitimate PARENT whose children are the @130k cells, and hard-coding the step name would have + # silently thrown that comparison away. The real rule is the one being enforced: never pair a + # (hi, lo) that is already some other claim's CHILD pair, because that read is counted there. + child_pairs = set() + for _l, _hh, _sd, _chi, _hl, _clo in CLAIMS: + kh, kl = cont.get(_chi), cont.get(_clo) + if kh and kl: + child_pairs.add((kh, kl)) + for label, hhi, seed, chi, hlo, clo in CLAIMS: + if (chi, clo) in child_pairs: + continue # this pair is the child read of another claim; pairing it again double-counts + kid_hi, kid_lo = cont.get(chi), cont.get(clo) + if not kid_hi or not kid_lo: + continue + need = [(hhi, chi), (hlo, clo), (head_of.get(kid_hi), kid_hi), (head_of.get(kid_lo), kid_lo)] + if any(h is None or (h, c) not in idx for h, c in need): + continue + ok, _ = knob_check(label, chi, clo) + ok2, _ = knob_check(label, kid_hi, kid_lo) + if not (ok and ok2): + print("| %s | %s | -- | -- | -- | **flag guard rejects this row; not reportable** |" % (label, seed)) + continue + sp = (steps.get((hhi, chi)), steps.get((hlo, clo))) + sc = (steps.get((head_of[kid_hi], kid_hi)), steps.get((head_of[kid_lo], kid_lo))) + if sp[0] != sp[1] or sc[0] != sc[1]: + print("| %s | %s | -- | -- | -- | **a side is step-confounded (%s vs %s at parent, %s vs %s at child)** |" + % (label, seed, sp[0], sp[1], sc[0], sc[1])) + continue + gp = idx[(hhi, chi)][0] - idx[(hlo, clo)][0] + gc = idx[(head_of[kid_hi], kid_hi)][0] - idx[(head_of[kid_lo], kid_lo)][0] + seen += 1 + flip = (gp > 0) != (gc > 0) + flips += 1 if flip else 0 + print("| %s | %s | %+.3f (@%s) | %+.3f (@%s) | %.3f | %s |" % + (label, seed, gp, sp[0], gc, sc[0], abs(gc - gp), + "**SIGN FLIPS**" if flip else "same sign")) + print() + if seen == 0: + print("*(no claim yet has a continuation child on BOTH sides)*") + else: + print("* rows landed: **%d**, of which **%d FLIP SIGN** between the two steps." % (seen, flips)) + if flips: + print() + print("> **A knob whose sign flips when the same two runs are read 10k steps later has not been " + "shown to do anything.** These rows are the same configurations, the same seeds and the " + "same knob; only the checkpoint changed. Any verdict of ESTABLISHED on such a knob is a " + "statement about one checkpoint pair, and this stream should not carry it forward as a " + "property of the knob. Reported here rather than dropped, because the parent-step rows " + "are what runs 14-16 published.") + + +def main(): + rows = load() + audit = load_label_audit() + if not rows: + print("no stitch JSONs yet"); return + print("# METRIC 1 -- STITCH VALUE TEST, by reward head") + print("# ratio 1.0 = arrival valued like a goal episode's S3 entry (full stitch);") + print("# ratio 0.0 = arrival valued like a real failure (value keyed on episode identity).") + print("# Every row's RSM and IQL columns are trained on the SAME label as that row.") + print() + hdr = ("| head | sees rank label | scorer / cell | stitch A | no-stitch A (own gamma)" + + " | boot95 A | stitch B | boot95 B | C-E | C-E boot95 | (C-E)/(D-E) | eps A/B/C/E | perm-null A q05..q95 |") + print(hdr) + print("|" + "---|" * 13) + for head in sorted(rows): + for cell, mode, m, d in sorted(rows[head], key=lambda r: (r[0], r[1])): + # display-only tag; `mode` itself is the key into d["groups"][*] and must NOT be renamed + mode_disp = (mode + " PROBE(undertrained)") if cell.startswith("PROBE_") else mode + # DENOMINATOR HEALTH (added run 4). The ratio is (A-E)/(C-E). A head whose C (a goal + # episode's own S3 entry) sits close to E (a real failure) on its OWN scale has a + # near-collapsed denominator, so a high ratio is a small difference over a small + # difference even when the bootstrap CI excludes 0. D (S3-late goal) is the head's + # high reference, so (C-E)/(D-E) says what fraction of the head's own dynamic range the + # metric's denominator spans. This is a DIAGNOSTIC printed beside the ratio, NOT a + # redefinition of the metric: C stays the reference point #281 specifies, because the + # arrival IS an S3-entry situation and D is a strictly later state. + g = d.get("groups", {}) + def gm(k): + return g.get(k, {}).get(mode, {}).get("mean", float("nan")) + dCE = gm("C_S3entry_goal") - gm("E_arrive_0->5_FAIL") + dDE = gm("D_S3late_goal") - gm("E_arrive_0->5_FAIL") + denom_health = (dCE / dDE) if dDE not in (0.0,) and dDE == dDE else float("nan") + dh = ("%.2f" % denom_health) + ("**" if denom_health == denom_health and denom_health < 0.30 else "") + sees = SEES_LABEL.get(head, "?") + # RUN 27 -- this guard was on the INSTANTANEOUS LABEL at C, but METRIC 1 scores a VALUE. + # Measured (stitch_logged_return_null.py, job 1897252): GOAL_WINDOW_400 and _100 label the + # C anchors 0.000, yet the discounted RETURN from those same anchors is 274.76 and 59.19 at + # gamma=0.999, because the head's reward arrives later in the episode and the discount + # still reaches it. So the reference interval C-E is NOT zero for those heads and the 12 + # rows previously printed `**UNDEFINED (label)**` are DEFINED. That verdict is WITHDRAWN. + # The guard now uses the RETURN-level interval at the column's own discount, which is the + # quantity the metric actually divides by. + ns_ratio, ns_dCE, ns_def = nostitch_for(mode, head) + if ns_def is False or (ns_dCE is not None and abs(ns_dCE) < 1e-9): + print("| %s | %s | %s %s | **UNDEFINED (return)** | the discounted logged return at C " + "equals that at E (C-E=%.5f at gamma=%s), so this head does not define the " + "metric's reference interval at this column's discount " + "| -- | -- | -- | -- | -- | -- | -- |" % ( + head, sees, mode_disp, cell, ns_dCE if ns_dCE is not None else float("nan"), + MODE_GAMMA.get(mode.split()[0], "0.999"))) + continue + ke = m.get("kept_episodes", {}) + eps = "/".join(str(ke.get(k, "-")) for k in + ["A_arrive_0->1->3", "B_arrive_0->2->3", "C_S3entry_goal", "E_arrive_0->5_FAIL"]) + if not m.get("defined", False): + print("| %s | %s | %s %s | **UNDEFINED** | %s | -- | -- | -- | %.3f | %s | %s | %s | -- |" % ( + head, sees, mode_disp, cell, fmt_ns(ns_ratio), m.get("C_minus_E", float("nan")), + fmt_ci(m.get("boot", {}).get("dCE_ci95")), dh, eps)) + continue + b = m.get("boot", {}) + nl = m.get("null", {}).get("ratioA_null", {}) + print("| %s | %s | %s %s | %.3f | %s | %s | %.3f | %s | %.3f | %s | %s | %s | %.2f..%.2f |" % ( + head, sees, mode_disp, cell, + m.get("stitch_A", float("nan")), fmt_ns(ns_ratio), fmt_ci(b.get("ratioA_ci95")), + m.get("stitch_B", float("nan")), fmt_ci(b.get("ratioB_ci95")), + m.get("C_minus_E", float("nan")), fmt_ci(b.get("dCE_ci95")), dh, eps, + nl.get("q05", float("nan")), nl.get("q95", float("nan")))) + print() + # ---- run 7: MEASURED label identity ------------------------------------------------------ + # The brief lists 6 reward heads. scripts/real/stitch_anchor_label_audit.py compared the npys + # frame-by-frame over all 181 530 frames and found two pairs that are BIT-IDENTICAL, i.e. they + # are one label under two names. That matters both ways: it licenses putting their cells in one + # row (they are the same label, so it is not a cross-label comparison), and it means an IDQL + # critic trained on either name is the reward-matched baseline for both. + ident = collections.defaultdict(set) # head -> set of heads with a bit-identical label + hid = (audit or {}).get("head_identity", {}) + for pair, rec in sorted(hid.items()): + if rec.get("identical"): + a, b = pair.split("|") + ident[a].add(b); ident[b].add(a) + if ident: + print("## MEASURED label identity (stitch_anchor_label_audit.py, all %s frames)" % + "181530") + for pair, rec in sorted(hid.items()): + if rec.get("identical"): + a, b = pair.split("|") + print("* `%s` and `%s` are the SAME array (0 frames differ, mean %.4f) -- one label, " + "two names." % (a, b, rec["mean_a"])) + print("* Consequence: a row may draw its IQL column from a label-identical head, and it is " + "still reward-matched. It may NOT draw it from any other head.") + print() + + floors = print_replicate_spread(rows) + sig = print_noise_budget(rows, floors) + print_step_drift(rows, sig) + print_within_cell_trajectory(rows, sig) + print_step_consistency(rows) + print_idql_seed_spread(rows) + seed_floor, cell_seed_rng = print_rsm_seed_floor(rows, floors) + print_claim_directions(rows) + print_claims(rows, floors, sig, seed_floor, cell_seed_rng) + print_pooled_claims(rows, sig) + print_sign_tests(rows) + + # Reward-matched pairs: a head with BOTH an rsm and an idql cell. + print("## Reward-matched rows (both scorers on the SAME label)") + print("# MATCHED = this head has a non-PROBE cell on BOTH sides trained on THIS label\n# (directly, or via a bit-identical label above). It is a COVERAGE statement, not a\n# quality one: it does not say the two sides were read at comparable training amounts,\n# and run 25 added the separate check that the metric is DEFINED for the head at all.") + for head in sorted(rows): + # A cell whose directory name starts with PROBE_ is an UNDERTRAINED pipeline validation at a + # rolling checkpoint (read-out is e2000/e2500). It must never make a head count as MATCHED. + modes = set(m for c, m, _, _ in rows[head] if not c.startswith("PROBE_")) + probes = sorted(c for c, _, _, _ in rows[head] if c.startswith("PROBE_")) + have_rsm = any(x.startswith("rsm") for x in modes) + have_iql = any(x.startswith("idql") for x in modes) + via = "" + if have_rsm and not have_iql: + # a bit-identical label elsewhere IS this head's label; an IQL cell there is matched. + for other in sorted(ident.get(head, ())): + omodes = set(m for c, m, _, _ in rows.get(other, []) if not c.startswith("PROBE_")) + if any(x.startswith("idql") for x in omodes): + have_iql = True + via = " [IQL column via label-identical head `%s` (0 frames differ)]" % other + break + tag = "MATCHED" if (have_rsm and have_iql) else ("RSM only -- IQL still training" if have_rsm else "IQL only") + # run 25. "MATCHED" meant only "this head has at least one cell on each side". It said + # nothing about whether the metric is DEFINED for the head, so GOAL_WINDOW_100 and + # GOAL_WINDOW_400 printed MATCHED while EVERY one of their rows in the table above is + # `**UNDEFINED (label)**` -- a reader of this summary alone would count 6 reportable heads + # when only 4 have a metric at all. The definedness test is the SAME one the table uses + # (label audit, C_S3entry_goal vs E_arrive_0->5_FAIL on this head's own anchors), so the two + # can never disagree. No number changes; the tag does. + # RUN 27: the summary must use the SAME guard the rows use, and the rows now guard on the + # RETURN-level interval at each column's own discount, not the instantaneous label. Under the + # label guard both GOAL_WINDOW heads printed METRIC UNDEFINED; measured, their C anchors carry + # returns of 274.76 (_400) and 59.19 (_100) at gamma=0.999, so they are DEFINED and that + # verdict is withdrawn. A head is UNDEFINED here only if it is undefined for BOTH columns. + lab_h = (audit or {}).get("label_on_anchors", {}).get(head) + undef = True + for _mode in ("rsm", "idql"): + _r, _d, _ok = nostitch_for(_mode, head) + if _ok is not False and not (_d is not None and abs(_d) < 1e-9): + undef = False + if undef: + tag = "METRIC UNDEFINED -- no row of this head is reportable" + # and "MATCHED" also hid n: a head with one cell per side reads the same as one with twenty. + n_rsm = len(set(c for c, m, _, _ in rows[head] if m.startswith("rsm") and not c.startswith("PROBE_"))) + n_iql = len(set(c for c, m, _, _ in rows[head] if m.startswith("idql") and not c.startswith("PROBE_"))) + if not n_iql and via: + other = via.split("`")[1] + n_iql = len(set(c for c, m, _, _ in rows.get(other, []) + if m.startswith("idql") and not c.startswith("PROBE_"))) + counts = " [cells: rsm=%d idql=%d%s]" % (n_rsm, n_iql, " (aliased)" if (via and n_iql) else "") + extra = (" [+%d PROBE cell(s), NOT matrix rows: %s]" % (len(probes), ",".join(probes))) if probes else "" + print("* %-26s %s (modes: %s)%s%s%s" % (head, tag, ",".join(sorted(modes)), counts, extra, via)) + if undef: + print(" %-26s reason: the discounted logged RETURN at C equals that at E on this head's " + "anchors at BOTH columns' discounts, so the metric's reference interval C-E is zero " + "and the ratio has no denominator." % "") + # print the no-stitch line for the head on both columns, so no row of it can be read without it + _nr, _nd, _ = nostitch_for("rsm", head) + _ir, _id_, _ = nostitch_for("idql", head) + if _nr is not None or _ir is not None: + print(" %-26s no-stitch line: RSM(gamma=0.999) %s IQL(gamma=0.99) %s " + "-- a row AT its line reproduced its own logged return and did NOT stitch" + % ("", fmt_ns(_nr), fmt_ns(_ir))) + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/real/relabel_dino_lerobot.py b/rsm_rise/scripts/real/relabel_dino_lerobot.py new file mode 100644 index 0000000000000000000000000000000000000000..95e87cfdecfd829bd17bbc55c8c0de5867eae4d7 --- /dev/null +++ b/rsm_rise/scripts/real/relabel_dino_lerobot.py @@ -0,0 +1,322 @@ +#!/usr/bin/env python +"""Stage-1 DINOv2 cache for a LeRobot v2.1 REAL dataset (rsm_cooking_v5), in the exact +layout rsm_libero/LiberoRSMData expects -- i.e. the same files scripts/relabel_dino.py +writes for the sim RISE hdf5 caches, so train_rsm.py runs unchanged. + +Writes, under --out: + z.f16.npy [N,D] fp16 D = 1536 per camera used; default both -> 3072 + [global CLS(384) | global GeM(384) | wrist CLS | wrist GeM] + proprio.f32.npy [N,10] fp32 observation.state = [x,y,z,R00,R10,R20,R01,R11,R21,gripper_w] + act.f32.npy [N,10] fp32 action (absolute target pose + commanded gripper width) + meta.npz ep_from/ep_to/ep_len/ep_task/ep_success/ep_demo/ep_valid/ + tasks/dim/adim/stride/n_frames/ep_src (+ real-only extras: + ep_route/ep_path/ep_n_seg/ep_elapsed_s) + feat_stats.npz mu/sd over ALL frames of [z|proprio], sd floored, z_clip + PACK.json provenance + the exact state formula + VALIDATION.json frame-count / NaN / temporal-NN checks + +Encoder is byte-for-byte the sim one (dinov2_vits14, CLS + GeM(patches)); only the input +transform can differ, because the source frames are 480x640 rather than 84x84: + --crop-mode dino Resize(256) short side -> CenterCrop(224) [exact DinoV2Core transform] + --crop-mode square Resize((224,224)) [full FOV, aspect squashed] + --crop-mode sim84 Resize((84,84)) -> then the exact sim pipeline (Resize(256)+CenterCrop(224)) +Reward: next.reward is 1 only on a goal_reached row whose reached_state_id is a reward state +(state 4 for this task). ep_success = that episode ever earned reward. +""" +from __future__ import annotations +import argparse, json, os, time +from pathlib import Path +import numpy as np +import torch +import torch.nn as nn +import pyarrow.parquet as pq + +D_TOK = 384 +N_PATCH = 256 +SD_FLOOR = 1e-2 +Z_CLIP = 10.0 +CAM_KEYS = {"global": "observation.images.global", "wrist": "observation.images.wrist"} + + +def load_dino(device): + hub_dir = os.environ.get("TORCH_HOME", os.path.expanduser("~/.cache/torch")) + "/hub" + repo = Path(hub_dir) / "facebookresearch_dinov2_main" + if repo.exists(): + m = torch.hub.load(str(repo), "dinov2_vits14", source="local") + else: + m = torch.hub.load("facebookresearch/dinov2", "dinov2_vits14") + return m.to(device).eval() + + +class DinoTransform(nn.Module): + """DinoV2Core.transform, optionally preceded by a downsample to the sim 84px grid.""" + def __init__(self, mode="dino"): + super().__init__() + from torchvision import transforms + norm = transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) + if mode == "dino": + self.t = transforms.Compose([transforms.Resize(256), transforms.CenterCrop(224), norm]) + elif mode == "square": + self.t = transforms.Compose([transforms.Resize((224, 224)), norm]) + elif mode == "sim84": + self.t = transforms.Compose([transforms.Resize((84, 84)), transforms.Resize(256), + transforms.CenterCrop(224), norm]) + else: + raise SystemExit(f"bad crop mode {mode}") + self.mode = mode + + def forward(self, x): + return self.t(x) + + +def gem_pool(patch_tokens): + B = patch_tokens.shape[0] + pd = int(np.sqrt(patch_tokens.shape[-2])) + p = patch_tokens.reshape(B, pd, pd, -1).clamp(min=1e-6).permute(0, 3, 1, 2) + return nn.functional.avg_pool2d(p.pow(4), (pd, pd)).pow(1 / 4).reshape(B, -1) + + +@torch.no_grad() +def encode_u8(model, tf, imgs_u8, device, batch): + """[M,H,W,3] uint8 -> [M,768] fp32 pooled ([CLS|GeM]), identical maths to the sim builder.""" + out = [] + for i in range(0, len(imgs_u8), batch): + x = torch.from_numpy(np.ascontiguousarray(imgs_u8[i:i + batch])).to(device) + x = x.float().div_(255.0).clamp_(0.0, 1.0).permute(0, 3, 1, 2) # ObsUtils.process_frame + x = tf(x) + f = model.forward_features(x) + cls, pt = f["x_norm_clstoken"], f["x_norm_patchtokens"] + assert pt.shape[1] == N_PATCH and pt.shape[2] == D_TOK, pt.shape + out.append(torch.cat([cls, gem_pool(pt)], -1).float().cpu()) + return torch.cat(out).numpy() + + +def decode_mp4(path, expect=None): + """Decode every frame of an mp4 in presentation order -> [T,H,W,3] uint8 RGB.""" + import av + frames = [] + with av.open(str(path)) as c: + st = c.streams.video[0] + st.thread_type = "AUTO" + for fr in c.decode(st): + frames.append(fr.to_ndarray(format="rgb24")) + a = np.stack(frames) if frames else np.zeros((0, 480, 640, 3), np.uint8) + if expect is not None and len(a) != expect: + raise RuntimeError(f"{path}: decoded {len(a)} frames, parquet has {expect}") + return a + + +def write_stats(out, s1, s2, N, dim): + out = Path(out) + mu = (s1 / N).astype(np.float64) + sd_raw = np.sqrt(np.maximum(s2 / N - mu ** 2, 0.0)) + degenerate = np.where(sd_raw < SD_FLOOR)[0] + sd = np.maximum(sd_raw, SD_FLOOR) + np.savez(out / "feat_stats.npz", mu=mu.astype(np.float32), sd=sd.astype(np.float32), dim=dim, + n=N, sd_floor=SD_FLOOR, z_clip=Z_CLIP, sd_raw=sd_raw.astype(np.float32), + degenerate_dims=degenerate) + print(f"[relabel] feat_stats: {len(degenerate)} dims with raw sd < {SD_FLOOR}; z_clip={Z_CLIP}", + flush=True) + return mu, sd, sd_raw, degenerate + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--root", default="/proj/dmfexp/zwhong/rsm_rise/data/real/rsm_cooking_v5") + ap.add_argument("--out", required=True) + ap.add_argument("--cams", default="global,wrist", help="comma list from {global,wrist}") + ap.add_argument("--crop-mode", default="dino", choices=["dino", "square", "sim84"]) + ap.add_argument("--batch", type=int, default=256) + ap.add_argument("--max-eps", type=int, default=0) + ap.add_argument("--task-name", default="real_cooking_v5") + ap.add_argument("--reward-states", default="4") + ap.add_argument("--validate", type=int, default=1) + ap.add_argument("--seed", type=int, default=0) + args = ap.parse_args() + + t0 = time.time() + root = Path(args.root) + out = Path(args.out); out.mkdir(parents=True, exist_ok=True) + dev = "cuda" if torch.cuda.is_available() else "cpu" + cams = [c.strip() for c in args.cams.split(",") if c.strip()] + for c in cams: + assert c in CAM_KEYS, c + rew_states = {int(x) for x in args.reward_states.split(",") if x != ""} + + info = json.loads((root / "meta/info.json").read_text()) + n_ep = int(info["total_episodes"]) + if args.max_eps: + n_ep = min(n_ep, args.max_eps) + data_path, video_path = info["data_path"], info["video_path"] + chunks = int(info["chunks_size"]) + print(f"[relabel] {root} -> {out} device={dev} cams={cams} crop={args.crop_mode}", flush=True) + + # ---- pass 1: read every parquet, fix the frame layout ------------------------------- + rows, lens, succ, route, npath, nseg, elapsed = [], [], [], [], [], [], [] + for i in range(n_ep): + p = root / data_path.format(episode_chunk=i // chunks, episode_index=i) + names = pq.read_schema(p).names + want = ["observation.state", "action", "next.reward", "annotation.goal_reached", + "annotation.reached_state_id", "annotation.route_index", + "annotation.segment_index", "annotation.edge_from", "annotation.edge_to", + "timing.capture_elapsed_s"] + t = pq.read_table(p, columns=[c for c in want if c in names]).to_pandas() + L = len(t); lens.append(L) + st = np.stack([np.asarray(v, np.float32) for v in t["observation.state"]]) + ac = np.stack([np.asarray(v, np.float32) for v in t["action"]]) + gr = np.asarray(t["annotation.goal_reached"], np.int64).ravel() + rs = np.asarray(t["annotation.reached_state_id"], np.int64).ravel() + r = ((gr == 1) & np.isin(rs, list(rew_states))).astype(np.float32) + if "next.reward" in t: + r_file = np.asarray(t["next.reward"], np.float32).ravel() + if not np.allclose(r, r_file): + print(f"[relabel] WARN ep{i}: recomputed reward != next.reward " + f"({r.sum()} vs {r_file.sum()}); using next.reward", flush=True) + r = r_file + succ.append(bool(r.sum() > 0)) + route.append(int(np.asarray(t["annotation.route_index"]).ravel()[0])) + sg = np.asarray(t["annotation.segment_index"], np.int64).ravel() + nseg.append(int(sg.max()) + 1) + ef = np.asarray(t["annotation.edge_from"], np.int64).ravel() + et = np.asarray(t["annotation.edge_to"], np.int64).ravel() + seen = list(dict.fromkeys(zip(ef.tolist(), et.tolist()))) + npath.append("->".join(map(str, [seen[0][0]] + [b for _, b in seen]))) + if "timing.capture_elapsed_s" in t and L > 1: + ce = np.asarray(t["timing.capture_elapsed_s"], np.float64).ravel() + elapsed.append(float(ce[-1] - ce[0])) + else: + elapsed.append(float("nan")) + rows.append({"state": st, "act": ac, "r": r}) + lens = np.asarray(lens, np.int64) + ep_to = np.cumsum(lens); ep_from = ep_to - lens + N = int(ep_to[-1]) + P = rows[0]["state"].shape[1]; A = rows[0]["act"].shape[1] + D = 2 * D_TOK * len(cams) + succ = np.asarray(succ) + print(f"[relabel] {n_ep} eps, N={N} frames, success {succ.sum()} ({succ.mean():.3f}), " + f"proprio={P}, A={A}, D={D}", flush=True) + + model = load_dino(dev) + tf = DinoTransform(args.crop_mode).to(dev) + print(f"[relabel] dinov2_vits14 loaded ({time.time()-t0:.1f}s)", flush=True) + + zmm = np.lib.format.open_memmap(out / "z.f16.npy", mode="w+", dtype=np.float16, shape=(N, D)) + pmm = np.lib.format.open_memmap(out / "proprio.f32.npy", mode="w+", dtype=np.float32, shape=(N, P)) + amm = np.lib.format.open_memmap(out / "act.f32.npy", mode="w+", dtype=np.float32, shape=(N, A)) + rmm = np.lib.format.open_memmap(out / "reward.f32.npy", mode="w+", dtype=np.float32, shape=(N,)) + s1 = np.zeros(D + P, np.float64); s2 = np.zeros(D + P, np.float64) + + t_enc = time.time() + for i in range(n_ep): + s, e = int(ep_from[i]), int(ep_to[i]) + per = [] + for c in cams: + vp = root / video_path.format(episode_chunk=i // chunks, video_key=CAM_KEYS[c], + episode_index=i) + imgs = decode_mp4(vp, expect=e - s) + per.append(encode_u8(model, tf, imgs, dev, args.batch)) + del imgs + z = np.concatenate(per, -1) + zmm[s:e] = z.astype(np.float16) + pmm[s:e] = rows[i]["state"]; amm[s:e] = rows[i]["act"]; rmm[s:e] = rows[i]["r"] + x = np.concatenate([z, rows[i]["state"]], -1).astype(np.float64) + s1 += x.sum(0); s2 += (x * x).sum(0) + if (i + 1) % 10 == 0 or i + 1 == n_ep: + for mm in (zmm, pmm, amm, rmm): mm.flush() + fps = e / max(time.time() - t_enc, 1e-6) + print(f"[relabel] {i+1}/{n_ep} eps, {e}/{N} frames, {fps:.0f} frames/s, " + f"eta {(N-e)/max(fps,1e-6)/60:.1f} min", flush=True) + for mm in (zmm, pmm, amm, rmm): mm.flush() + del zmm, pmm, amm, rmm + + write_stats(out, s1, s2, N, D + P) + + np.savez(out / "meta.npz", ep_from=ep_from, ep_to=ep_to, ep_len=lens, + ep_task=np.zeros(n_ep, np.int64), ep_success=succ, + ep_demo=np.zeros(n_ep, bool), ep_valid=np.ones(n_ep, bool), + tasks=np.array([args.task_name]), dim=D, adim=A, stride=1, n_frames=N, + ep_src=np.array([f"episode_{i:06d}" for i in range(n_ep)]), + ep_route=np.asarray(route, np.int64), ep_n_seg=np.asarray(nseg, np.int64), + ep_path=np.array(npath), ep_elapsed_s=np.asarray(elapsed, np.float64)) + + pack = { + "cam_res": [480, 640], "encoder": "dinov2_vits14_clsgem", "crop_mode": args.crop_mode, + "src": str(root.resolve()), "src_kind": "LeRobot v2.1 (parquet + mp4)", + "src_codebase_version": info.get("codebase_version"), "src_robot": info.get("robot_type"), + "episodes": int(n_ep), "frames": N, "dim": D, "adim": A, "stride": 1, + "proprio_dim": P, "state_dim": D + P, "cams": cams, + "nominal_fps": info.get("fps"), + "effective_fps_retained": float(np.nansum(lens) / np.nansum(elapsed)) if np.isfinite(np.nansum(elapsed)) and np.nansum(elapsed) > 0 else None, + "fps_note": "rows are MOTION-FILTERED (only ticks where the measured 10D state changed are " + "retained), so `timestamp` = row/50 is a playback clock, not wall time. Use " + "timing.capture_elapsed_s / effective_fps_retained for real-time horizons.", + "success_rate": float(succ.mean()), "n_success": int(succ.sum()), "n_demo": 0, + "tasks": [args.task_name], "task_id_source": "single task, id 0", + "episode_success_rule": f"next.reward > 0 somewhere, i.e. an operator-marked arrival at a " + f"reward state {sorted(rew_states)} (state 4 = pan on grate, tomato in bowl)", + "z_layout": " | ".join(sum([[f"{c} CLS(384)", f"{c} GeM(384)"] for c in cams], [])), + "proprio_layout": "observation.state = [x,y,z,R00,R10,R20,R01,R11,R21,gripper_width]", + "action_layout": "action = absolute target pose (same 9) + commanded gripper width", + "state": f"data.py concatenates z ({D}) and proprio ({P}) -> {D+P}, then z-scores with feat_stats.npz", + "sd_floor": SD_FLOOR, "z_clip": Z_CLIP, + "state_formula": f"x = clip((feat - mu) / max(sd, {SD_FLOOR}), -{Z_CLIP}, {Z_CLIP}) with " + f"feat = [z({D}) | proprio({P})], mu/sd from feat_stats.npz", + "image_pipeline": f"mp4 (PyAV, rgb24, presentation order, asserted 1:1 with parquet rows) -> " + f"uint8 HWC -> float/255 -> CHW -> {args.crop_mode} transform -> " + f"ImageNet Normalize -> dinov2_vits14 forward_features -> " + f"CLS + GeM(patches: clamp 1e-6, pow 4, avg 16x16, pow 1/4)", + "precision": "fp32 compute, fp16 storage", "tokens": None, + "torch": torch.__version__, + "written_by": "rsm_rise/scripts/real/relabel_dino_lerobot.py", + } + (out / "PACK.json").write_text(json.dumps(pack, indent=2)) + print(f"[relabel] cache written in {time.time()-t0:.0f}s: N={N}, z {N*D*2/1e9:.2f} GB", flush=True) + + if args.validate: + validate(out, N, D, P, A, seed=args.seed) + print("[relabel] DONE", flush=True) + + +def validate(out, N, D, P, A, seed=0): + out = Path(out) + rng = np.random.default_rng(seed) + z = np.load(out / "z.f16.npy", mmap_mode="r") + pr = np.load(out / "proprio.f32.npy", mmap_mode="r") + ac = np.load(out / "act.f32.npy", mmap_mode="r") + m = np.load(out / "meta.npz", allow_pickle=True) + fs = np.load(out / "feat_stats.npz") + idx = np.sort(rng.choice(N, size=min(2000, N), replace=False)) + zz = np.asarray(z[idx], np.float32) + rep = {"frames": {"cache": int(N), "z_shape": list(z.shape), "proprio_shape": list(pr.shape), + "act_shape": list(ac.shape), "feat_stats_dim": int(fs["dim"]), + "ok": bool(z.shape == (N, D) and pr.shape == (N, P) and ac.shape == (N, A)), + "nan_in_2000_random_rows": int(np.isnan(zz).sum()), + "nan_proprio": int(np.isnan(np.asarray(pr[idx])).sum()), + "nan_act": int(np.isnan(np.asarray(ac[idx])).sum())}} + # temporal NN: a frame's nearest neighbour in its own episode should be adjacent in time + ep_from, ep_to = m["ep_from"], m["ep_to"] + same, within5, dts = 0, 0, [] + for _ in range(20): + e = int(rng.integers(len(ep_from))) + lo, hi = int(ep_from[e]), int(ep_to[e]) + if hi - lo < 20: continue + t = int(rng.integers(lo + 5, hi - 5)) + blk = np.asarray(z[lo:hi], np.float32) + q = blk[t - lo] + d = np.linalg.norm(blk - q, axis=1); d[t - lo] = np.inf + j = int(d.argmin()) + lo + same += 1; dt = abs(j - t); dts.append(int(dt)); within5 += int(dt <= 5) + rep["nn_temporal"] = {"n_queries": same, "nn_within_5_frames": within5, "dt": dts} + lens = m["ep_len"] + rep["success_vs_length"] = { + "n_eps": int(len(lens)), "n_success": int(m["ep_success"].sum()), + "len_mean_success": float(lens[m["ep_success"]].mean()) if m["ep_success"].any() else None, + "len_mean_failure": float(lens[~m["ep_success"]].mean()) if (~m["ep_success"]).any() else None} + rep["sizes_bytes"] = {p.name: p.stat().st_size for p in sorted(out.glob("*")) if p.is_file()} + (out / "VALIDATION.json").write_text(json.dumps(rep, indent=2)) + print("[relabel] VALIDATION:", json.dumps(rep["frames"]), flush=True) + print("[relabel] nn_temporal:", json.dumps(rep["nn_temporal"]), flush=True) + + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/real/render_pour.py b/rsm_rise/scripts/real/render_pour.py new file mode 100644 index 0000000000000000000000000000000000000000..89687807aa9438d06f588bf5fda58ff3252b88bd --- /dev/null +++ b/rsm_rise/scripts/real/render_pour.py @@ -0,0 +1,56 @@ +#!/usr/bin/env python +"""Filmstrip of the END of successful episodes, to locate the POUR relative to the episode end +(gen_q #261 doc-simplification note). The annotation marks only the ARRIVAL at state 4, which is the +LAST frame of every successful episode (status/real/SUCCESS_TAIL.json), so the pour itself is +unlabelled -- this strip is how it is read off by eye. + +Renders, for each chosen successful episode, the last WINDOW frames at STRIDE, as one grid row-major, +and writes the frame indices to status/real/POUR_STRIP.json. +""" +import json, sys +from pathlib import Path +import numpy as np, torch, av +from torchvision.io import write_png +from torchvision import transforms + +ROOT = Path("/proj/dmfexp/zwhong/rsm_rise/data/real/rsm_cooking_v5") +CACHE = Path("/proj/dmfexp/zwhong/rsm_rise/cache/real_cooking_v5") +OUT = Path("/proj/dmfexp/zwhong/rsm_rise/docs/figs/real_stages") +EPS = [int(x) for x in (sys.argv[1].split(",") if len(sys.argv) > 1 else ["148"])] +WINDOW = int(sys.argv[2]) if len(sys.argv) > 2 else 1500 +STRIDE = int(sys.argv[3]) if len(sys.argv) > 3 else 100 + +info = json.loads((ROOT / "meta/info.json").read_text()) +vp, cs = info["video_path"], int(info["chunks_size"]) +m = np.load(CACHE / "meta.npz", allow_pickle=True) +ep_from, ep_to = m["ep_from"].astype(int), m["ep_to"].astype(int) +ef = np.load(CACHE / "edge_from.i16.npy").astype(int) +et = np.load(CACHE / "edge_to.i16.npy").astype(int) +S = transforms.Resize((180, 240)) +rec = {} +for ep in EPS: + a, b = ep_from[ep], ep_to[ep]; L = int(b - a) + idx = list(range(max(0, L - WINDOW), L, STRIDE)) + [L - 1] + idx = sorted(set(idx)) + p = ROOT / vp.format(episode_chunk=ep // cs, video_key="observation.images.global", episode_index=ep) + got, mx = {}, max(idx) + with av.open(str(p)) as c: + st = c.streams.video[0]; st.thread_type = "AUTO" + for i, fr in enumerate(c.decode(st)): + if i in idx: + got[i] = torch.from_numpy(fr.to_ndarray(format="rgb24")).permute(2, 0, 1).to(torch.uint8) + if i >= mx: + break + tiles = [S(got[i]) for i in idx if i in got] + ncol = 6 + rows = [] + for r in range(0, len(tiles), ncol): + row = tiles[r:r + ncol] + row += [torch.zeros_like(tiles[0])] * (ncol - len(row)) + rows.append(torch.cat(row, dim=2)) + fn = OUT / f"pour_strip_ep{ep:03d}.png" + write_png(torch.cat(rows, dim=1), str(fn)) + rec[str(ep)] = {"episode": ep, "len": L, "frames": idx, "stride": STRIDE, "ncol": ncol, + "png": str(fn), "edge_at_frames": [f"{int(ef[a+i])}->{int(et[a+i])}" for i in idx]} + print(f"[pour] ep{ep} len={L} frames={idx} -> {fn}") +Path("/proj/dmfexp/zwhong/rsm_rise/status/real/POUR_STRIP.json").write_text(json.dumps(rec, indent=2)) diff --git a/rsm_rise/scripts/real/render_stages.py b/rsm_rise/scripts/real/render_stages.py new file mode 100644 index 0000000000000000000000000000000000000000..df30ad6ae046abb43af141f0115d5738afad209b --- /dev/null +++ b/rsm_rise/scripts/real/render_stages.py @@ -0,0 +1,124 @@ +#!/usr/bin/env python +"""Render representative frames of EVERY task stage (0..6) of rsm_cooking_v5, both cameras. + +Why: the reward-head study (gen_q #261) defines its labels off the dataset's per-frame stage +annotations (annotation.edge_from / edge_to). These pictures let the owner verify the stage +semantics by eye instead of trusting the annotation. + +A frame's annotation is an EDGE (edge_from -> edge_to), not a state, so "a picture of stage s" is +taken to be the LAST frame of a segment whose edge_to == s (the moment of arrival at s), and for the +start states (which are never an edge_to) the FIRST frame of an episode whose edge_from starts there. + +Outputs: docs/figs/real_stages/stage_ep_.png (one per episode/camera) + docs/figs/real_stages/stage_grid_.png (one contact sheet per camera) + status/real/STAGE_FRAMES.json (frame provenance for every picture) +""" +import json +from pathlib import Path +from collections import defaultdict +import numpy as np, torch, av +from torchvision.io import write_png +from torchvision import transforms + +ROOT = Path("/proj/dmfexp/zwhong/rsm_rise/data/real/rsm_cooking_v5") +CACHE = Path("/proj/dmfexp/zwhong/rsm_rise/cache/real_cooking_v5") +OUT = Path("/proj/dmfexp/zwhong/rsm_rise/docs/figs/real_stages"); OUT.mkdir(parents=True, exist_ok=True) +N_PER_STAGE = 2 + +info = json.loads((ROOT / "meta/info.json").read_text()) +vp, cs = info["video_path"], int(info["chunks_size"]) +m = np.load(CACHE / "meta.npz", allow_pickle=True) +ep_from, ep_to = m["ep_from"].astype(int), m["ep_to"].astype(int) +succ = np.asarray(m["ep_success"], bool); route = np.asarray(m["ep_route"], int) +path = np.asarray(m["ep_path"]) +ef = np.load(CACHE / "edge_from.i16.npy").astype(int) +et = np.load(CACHE / "edge_to.i16.npy").astype(int) + +# ---- choose frames ------------------------------------------------------------------------ +picks = defaultdict(list) # stage -> [(ep, local_frame, kind)] +states = sorted(set(ef.tolist()) | set(et.tolist())) +for s in states: + # arrivals: last frame of each segment with edge_to == s + for i in range(len(ep_from)): + a, b = ep_from[i], ep_to[i] + e = et[a:b] + hit = np.nonzero(e == s)[0] + if len(hit): + picks[s].append((i, int(hit[-1]), "arrival")) + if len(picks[s]) >= N_PER_STAGE: + break + if not picks[s]: + # start state: first frame of an episode whose edge_from begins at s + for i in range(len(ep_from)): + a, b = ep_from[i], ep_to[i] + if ef[a] == s: + picks[s].append((i, 0, "start")) + if len(picks[s]) >= N_PER_STAGE: + break +# state 0 and state 2 are START states of some routes -- add those too so every state has a picture +for s in states: + if all(k == "arrival" for _, _, k in picks[s]): + for i in range(len(ep_from)): + if ef[ep_from[i]] == s: + picks[s].append((i, 0, "start")); break + +want = defaultdict(set) +for s, lst in picks.items(): + for ep, fi, _ in lst: + want[ep].add(fi) + + +def grab(ep, cam, idxs): + p = ROOT / vp.format(episode_chunk=ep // cs, video_key=f"observation.images.{cam}", + episode_index=ep) + got = {} + mx = max(idxs) + with av.open(str(p)) as c: + st = c.streams.video[0]; st.thread_type = "AUTO" + for i, fr in enumerate(c.decode(st)): + if i in idxs: + got[i] = fr.to_ndarray(format="rgb24") + if i >= mx: + break + return got + + +SMALL = transforms.Resize((240, 320)) +rep, grid = [], defaultdict(list) +cached = {} +for ep in sorted(want): + for cam in ("global", "wrist"): + cached[(ep, cam)] = grab(ep, cam, want[ep]) +for s in states: + for ep, fi, kind in picks[s]: + for cam in ("global", "wrist"): + img = cached[(ep, cam)].get(fi) + if img is None: + print(f"[stage] MISSING ep{ep} {cam} f{fi}"); continue + x = torch.from_numpy(img).permute(2, 0, 1) + fn = OUT / f"stage{s}_ep{ep:03d}_{cam}_{kind}.png" + write_png(x, str(fn)) + grid[cam].append((s, SMALL(x))) + rep.append({"stage": s, "kind": kind, "episode": int(ep), "local_frame": int(fi), + "global_frame": int(ep_from[ep] + fi), "camera": cam, + "route": int(route[ep]), "path": str(path[ep]), + "success": bool(succ[ep]), + "edge": f"{int(ef[ep_from[ep]+fi])}->{int(et[ep_from[ep]+fi])}", + "png": str(fn)}) + print(f"[stage] s={s} {kind} ep{ep} {cam} f{fi} -> {fn.name}") + +for cam, items in grid.items(): + per = {} + for s, x in items: + per.setdefault(s, []).append(x) + rows = [] + ncol = max(len(v) for v in per.values()) + for s in sorted(per): + cols = per[s] + [torch.zeros_like(per[s][0])] * (ncol - len(per[s])) + rows.append(torch.cat(cols, dim=2)) + write_png(torch.cat(rows, dim=1).to(torch.uint8), str(OUT / f"stage_grid_{cam}.png")) + print(f"[stage] contact sheet {OUT/f'stage_grid_{cam}.png'} rows={sorted(per)}") + +Path("/proj/dmfexp/zwhong/rsm_rise/status/real/STAGE_FRAMES.json").write_text( + json.dumps({"states": states, "frames": rep}, indent=2)) +print("[stage] done") diff --git a/rsm_rise/scripts/real/render_stitch_endpoints.py b/rsm_rise/scripts/real/render_stitch_endpoints.py new file mode 100644 index 0000000000000000000000000000000000000000..b89bacb3e0dd7b9bc0b87c43af85027423f89e59 --- /dev/null +++ b/rsm_rise/scripts/real/render_stitch_endpoints.py @@ -0,0 +1,164 @@ +#!/usr/bin/env python +"""gen_q#271 -> #270 handoff: retrieval-render the ENDPOINTS of the stitching chains. + +REWARD_STITCH's diagnostic 3 writes, per anchor, the cache row its best- and worst-scoring +candidate chain lands on after `hops` hops (status/real/REWARD_HEAD_DIAG_STITCH.json -> +by_hop..heads..render). Those rows are indices into cache/real_cooking_v5, which is +packed 1:1 (stride 1) from the LeRobot parquet/mp4 episodes, so a row is exactly one video frame: + episode = searchsorted(ep_from, row); local_frame = row - ep_from[episode] +(the same mapping scripts/real/render_story.py:58 uses). We decode that frame from both cameras +and lay the page out as anchor | best endpoint | worst endpoint per anchor. + +Deliberately NO green/red membership outlines: REWARD_STITCH asked for the retrieval renders only +("that was a SIM visualisation and is not part of #271"). Each tile is captioned with the +annotation's own segment edge (edge_from->edge_to), which is ground truth, not a head decision. + +usage: render_stitch_endpoints.py [--diag JSON] [--hop 4] [--heads B,A] [--n 6] [--out DIR] +""" +import argparse, json +from pathlib import Path +import numpy as np, torch, av +from torchvision import transforms +from torchvision.io import write_png +from PIL import Image, ImageDraw, ImageFont + +ROOT = Path("/proj/dmfexp/zwhong/rsm_rise") +SRC = ROOT / "data/real/rsm_cooking_v5" +CACHE = ROOT / "cache/real_cooking_v5" + +ap = argparse.ArgumentParser() +ap.add_argument("--diag", default=str(ROOT / "status/real/REWARD_HEAD_DIAG_STITCH.json")) +ap.add_argument("--hop", default="4") +ap.add_argument("--heads", default="B,A") +ap.add_argument("--n", type=int, default=6) +ap.add_argument("--out", default=str(ROOT / "docs/figs/real_stitch")) +ap.add_argument("--tile", type=int, default=320) +a = ap.parse_args() + +OUT = Path(a.out); OUT.mkdir(parents=True, exist_ok=True) +D = json.loads(Path(a.diag).read_text()) +hop = D["by_hop"][a.hop] +info = json.loads((SRC / "meta/info.json").read_text()) +vp, cs = info["video_path"], int(info["chunks_size"]) + +m = np.load(CACHE / "meta.npz", allow_pickle=True) +ep_from = m["ep_from"].astype(int); ep_to = m["ep_to"].astype(int) +succ = np.asarray(m["ep_success"], bool); path = np.asarray(m["ep_path"]) +ef = np.load(CACHE / "edge_from.i16.npy").astype(int) +et = np.load(CACHE / "edge_to.i16.npy").astype(int) + + +def where(row): + ep = int(np.searchsorted(ep_from, row, "right") - 1) + return ep, int(row - ep_from[ep]) + + +# ---- pick the anchors to show: contrastive first (best lands on the goal edge 4, worst on the +# failure terminal 6), then any anchor whose best and worst endpoints differ at all. +def pick(rend, n): + key = lambda x: -(x["best_q"] - x["worst_q"]) + tier1 = [x for x in rend if x["best_endpoint_edge_to"] == 4 and x["worst_endpoint_edge_to"] == 6] + tier2 = [x for x in rend if x["best_endpoint_row"] != x["worst_endpoint_row"] and x not in tier1] + out, seen = [], set() + for x in sorted(tier1, key=key) + sorted(tier2, key=key): + if x["episode"] in seen and len(tier1) + len(tier2) > n: # one anchor per episode if we can + continue + seen.add(x["episode"]); out.append(x) + if len(out) == n: + break + return out + + +# ---- decode ------------------------------------------------------------------------------------ +want = {} +plans = {} +for head in a.heads.split(","): + plans[head] = pick(hop["heads"][head]["render"], a.n) + for r in plans[head]: + for row in (r["anchor_cache_row"], r["best_endpoint_row"], r["worst_endpoint_row"]): + ep, fi = where(row); want.setdefault(ep, set()).add(fi) +print(f"[endpoints] hop={a.hop} heads={a.heads} anchors/head={a.n} " + f"episodes={len(want)} frames={sum(len(v) for v in want.values())}", flush=True) + +cached = {} +for ep in sorted(want): + idxs, mx = want[ep], max(want[ep]) + for cam in ("global", "wrist"): + p = SRC / vp.format(episode_chunk=ep // cs, video_key=f"observation.images.{cam}", episode_index=ep) + got = {} + with av.open(str(p)) as c: + st = c.streams.video[0]; st.thread_type = "AUTO" + for i, fr in enumerate(c.decode(st)): + if i in idxs: + got[i] = fr.to_ndarray(format="rgb24") + if i >= mx: + break + cached[(ep, cam)] = got + miss = sorted(f for f in idxs if f not in got) + if miss: + print(f"[endpoints] MISSING ep{ep} {cam} {miss}", flush=True) + print(f"[endpoints] decoded ep{ep} ({len(idxs)} frames)", flush=True) + + +def border(x, color, w=6): + c = torch.tensor(color, dtype=torch.uint8).view(3, 1, 1) + o = c.expand(3, x.shape[1] + 2 * w, x.shape[2] + 2 * w).clone() + o[:, w:w + x.shape[1], w:w + x.shape[2]] = x + return o + + +def inset(g, w, frac=0.32, pad=8): + h = int(g.shape[1] * frac); ww = int(w.shape[2] * h / w.shape[1]) + s = border(transforms.Resize((h, ww))(w), (255, 255, 255), 3) + o = g.clone(); h2, w2 = s.shape[1], s.shape[2] + o[:, -h2 - pad:-pad, -w2 - pad:-pad] = s + return o + + +def tile(row, tag, sub): + ep, fi = where(row) + g, w = cached[(ep, "global")].get(fi), cached[(ep, "wrist")].get(fi) + if g is None: + img = torch.zeros(3, a.tile * 3 // 4, a.tile, dtype=torch.uint8) + else: + g = torch.from_numpy(g).permute(2, 0, 1) + if w is not None: + g = inset(g, torch.from_numpy(w).permute(2, 0, 1)) + img = transforms.Resize((a.tile * 3 // 4, a.tile))(g) + # caption strip under the tile + cap = Image.new("RGB", (a.tile, 46), (255, 255, 255)) + d = ImageDraw.Draw(cap) + try: + f1 = ImageFont.truetype("DejaVuSans-Bold.ttf", 13); f2 = ImageFont.truetype("DejaVuSans.ttf", 11) + except Exception: + f1 = f2 = ImageFont.load_default() + d.text((4, 2), tag, fill=(0, 0, 0), font=f1) + d.text((4, 19), f"ep{ep} f{fi} row{row} edge {int(ef[row])}->{int(et[row])}" + f"{' SUCCESS-EP' if succ[ep] else ''}", fill=(60, 60, 60), font=f2) + d.text((4, 32), sub, fill=(60, 60, 60), font=f2) + capt = torch.from_numpy(np.array(cap)).permute(2, 0, 1) + return torch.cat([border(img, (30, 30, 30), 3), border(capt, (255, 255, 255), 3)], dim=1) + + +REPORT = {"diag": a.diag, "hop": a.hop, "hop_frames": D["hop_frames"], "n_cand": D["n_cand"], + "read_out": D["read_out"], "endpoint_flow": D["endpoint_flow"], "policy": D["policy"], + "note": "endpoint rows are indices into cache/real_cooking_v5; row->(ep,frame) by ep_from", + "heads": {}} +for head, rs in plans.items(): + rows = [] + for r in rs: + q_b, q_w = r["best_q"], r["worst_q"] + rows.append(torch.cat([ + tile(r["anchor_cache_row"], "ANCHOR (failure state)", f"head {head}, hop {a.hop} x {D['hop_frames']} frames"), + tile(r["best_endpoint_row"], f"BEST cand #{r['best_cand']}", f"Q = {q_b:.4f} (argmax of {D['n_cand']})"), + tile(r["worst_endpoint_row"], f"WORST cand #{r['worst_cand']}", f"Q = {q_w:.4f} dQ = {q_b - q_w:+.4f}"), + ], dim=2)) + page = torch.cat(rows, dim=1) + fn = OUT / f"endpoints_hop{a.hop}_{head}.png" + write_png(page, str(fn)) + print(f"[endpoints] wrote {fn} {page.shape[2]}x{page.shape[1]}", flush=True) + REPORT["heads"][head] = {"png": str(fn), "auc_pooled": hop["heads"][head]["auc_pooled"], + "anchors": [{k: r[k] for k in r} for r in rs]} + +(OUT / f"ENDPOINTS_hop{a.hop}.json").write_text(json.dumps(REPORT, indent=1)) +print(f"[endpoints] wrote {OUT / f'ENDPOINTS_hop{a.hop}.json'}", flush=True) diff --git a/rsm_rise/scripts/real/render_story.py b/rsm_rise/scripts/real/render_story.py new file mode 100644 index 0000000000000000000000000000000000000000..b3f5515f6e05123d910d3ee1ffa2f03a11463f84 --- /dev/null +++ b/rsm_rise/scripts/real/render_story.py @@ -0,0 +1,222 @@ +#!/usr/bin/env python +"""Simple, in-order picture story of the rsm_cooking_v5 task (gen_q #261, owner note 2026-09-22 05:20). + +Three figure sets, all decoded from the LeRobot mp4s in data/real/rsm_cooking_v5: + + 1. END-OF-STAGE. For every task state s, the frame at which the annotation declares s REACHED -- + the last frame of a segment with annotation.edge_to == s (cache edge_to.i16.npy), preferring a + SUCCESSFUL episode when s occurs in one. Plus one episode-start frame for context. + -> end_stage_{global,wrist}.png, story_start_{global,wrist}.png, story_grid_global.png + 2. SUCCESS. The FINAL frame of the first 6 successful episodes (ep_success, route 2->3->4), so the + end state of a success is unambiguous, next to the arrival-marker frame of the same episode. + -> success_final_ep.png, success_marker_ep.png, success_final_grid.png, + success_marker_vs_final_ep.png + 3. REWARD STRIPS. Three frames of one successful and one suboptimal episode; for each reward + variant the frames that get +1 are outlined GREEN, the rest RED. + -> reward_strip_success.png, reward_strip_subopt.png + +Provenance for every picture (episode, local frame, global frame, edge, labels) -> status/real/STORY_FRAMES.json +""" +import json +from collections import defaultdict +from pathlib import Path +import numpy as np, torch, av +from torchvision.io import write_png +from torchvision import transforms + +ROOT = Path("/proj/dmfexp/zwhong/rsm_rise/data/real/rsm_cooking_v5") +CACHE = Path("/proj/dmfexp/zwhong/rsm_rise/cache/real_cooking_v5") +OUT = Path("/proj/dmfexp/zwhong/rsm_rise/docs/figs/real_stages"); OUT.mkdir(parents=True, exist_ok=True) + +info = json.loads((ROOT / "meta/info.json").read_text()) +vp, cs = info["video_path"], int(info["chunks_size"]) +m = np.load(CACHE / "meta.npz", allow_pickle=True) +ep_from, ep_to = m["ep_from"].astype(int), m["ep_to"].astype(int) +succ = np.asarray(m["ep_success"], bool); route = np.asarray(m["ep_route"], int) +path = np.asarray(m["ep_path"]) +ef = np.load(CACHE / "edge_from.i16.npy").astype(int) +et = np.load(CACHE / "edge_to.i16.npy").astype(int) +seg = np.load(CACHE / "seg.i16.npy").astype(int) +r_ds = np.load(CACHE / "reward.f32.npy").astype(np.float32) +LAB = {} +for nm, f in [("v0", "reward_v0_provenance.f32.npy"), ("v1", "reward_v1_goaltrans.f32.npy"), + ("v2", "reward_v2_arrival.f32.npy"), ("v3", "reward_v3_finalseg.f32.npy"), + ("v4", "reward_v4_successtail.f32.npy")]: + if (CACHE / f).exists(): + LAB[nm] = np.load(CACHE / f) > 0 + +states = sorted(set(ef.tolist()) | set(et.tolist())) +succ_eps = [int(i) for i in np.nonzero(succ)[0]] +sub_eps = [int(i) for i in np.nonzero(~succ)[0]] + +# ---------------- pick frames ----------------------------------------------------------------- +want = defaultdict(set) # ep -> {local frames} +rec = [] # provenance records + + +def note(**kw): + ep, fi = kw["episode"], kw["local_frame"] + g = int(ep_from[ep] + fi) + kw.update(global_frame=g, route=int(route[ep]), path=str(path[ep]), success=bool(succ[ep]), + edge=f"{int(ef[g])}->{int(et[g])}", segment=int(seg[g]), + labels={k: bool(v[g]) for k, v in LAB.items()}) + rec.append(kw); want[ep].add(fi) + return kw + + +# 1. end-of-stage frames (arrival at s), successful episode preferred +end_stage = {} +for s in states: + pick = None + for pool in (succ_eps, list(range(len(ep_from)))): + for i in pool: + a, b = ep_from[i], ep_to[i] + hit = np.nonzero(et[a:b] == s)[0] + if len(hit): + pick = (i, int(hit[-1])); break + if pick: + break + if pick: + end_stage[s] = note(kind="end_of_stage", stage=s, episode=pick[0], local_frame=pick[1]) +# one start frame for context: the first successful episode's frame 0 +start_ep = succ_eps[0] +start = note(kind="start", stage=int(ef[ep_from[start_ep]]), episode=start_ep, local_frame=0) + +# 2. success page: final frame + arrival-marker frame of 6 successful episodes +SUCC_SHOW = succ_eps[:6] +succ_pairs = [] +for i in SUCC_SHOW: + a, b = ep_from[i], ep_to[i] + k = int(np.nonzero(r_ds[a:b] > 0)[0][0]) + last = int(b - a - 1) + succ_pairs.append((i, + note(kind="success_marker", episode=i, local_frame=k), + note(kind="success_final", episode=i, local_frame=last), + {"tail_frames": last - k + 1, + "edge_to_stays_goal": bool((et[a + k:b] == 4).all())})) + +# 3. reward strips: 3 frames of one successful and one suboptimal episode +strips = {} +for tag, i in (("success", SUCC_SHOW[0]), ("subopt", sub_eps[0])): + a, b = ep_from[i], ep_to[i]; L = b - a + segs = seg[a:b] + last_seg_start = int(np.nonzero(segs == segs.max())[0][0]) + fr = sorted({int(0.08 * L), int((last_seg_start + L) / 2), L - 1}) + strips[tag] = (i, [note(kind=f"strip_{tag}", episode=i, local_frame=f) for f in fr]) + +# ---------------- decode ------------------------------------------------------------------------ +def grab(ep, cam, idxs): + p = ROOT / vp.format(episode_chunk=ep // cs, video_key=f"observation.images.{cam}", episode_index=ep) + got, mx = {}, max(idxs) + with av.open(str(p)) as c: + st = c.streams.video[0]; st.thread_type = "AUTO" + for i, fr in enumerate(c.decode(st)): + if i in idxs: + got[i] = fr.to_ndarray(format="rgb24") + if i >= mx: + break + return got + + +cached = {} +for ep in sorted(want): + for cam in ("global", "wrist"): + cached[(ep, cam)] = grab(ep, cam, want[ep]) + miss = [f for f in want[ep] if f not in cached[(ep, cam)]] + if miss: + print(f"[story] MISSING ep{ep} {cam} {miss}") + + +def img(ep, cam, fi): + a = cached[(ep, cam)].get(fi) + return None if a is None else torch.from_numpy(a).permute(2, 0, 1).to(torch.uint8) + + +def border(x, color, w=10): + c = torch.tensor(color, dtype=torch.uint8).view(3, 1, 1) + out = c.expand(3, x.shape[1] + 2 * w, x.shape[2] + 2 * w).clone() + out[:, w:w + x.shape[1], w:w + x.shape[2]] = x + return out + + +def inset(g, w, frac=0.30, pad=12): + """wrist camera as an inset in the bottom-right corner of the global frame""" + h = int(g.shape[1] * frac) + ww = int(w.shape[2] * h / w.shape[1]) + small = transforms.Resize((h, ww))(w) + out = g.clone() + small = border(small, (255, 255, 255), 4) + h2, w2 = small.shape[1], small.shape[2] + out[:, -h2 - pad:-pad, -w2 - pad:-pad] = small + return out + + +SMALL = transforms.Resize((216, 288)) +written = [] +# --- end-of-stage figures +grid = [] +for s in sorted(end_stage): + r = end_stage[s] + g, w = img(r["episode"], "global", r["local_frame"]), img(r["episode"], "wrist", r["local_frame"]) + if g is None: + continue + fn = OUT / f"end_stage{s}_global.png"; write_png(g, str(fn)); r["png_global"] = str(fn) + if w is not None: + fw = OUT / f"end_stage{s}_wrist.png"; write_png(w, str(fw)); r["png_wrist"] = str(fw) + fc = OUT / f"end_stage{s}_combo.png"; write_png(inset(g, w), str(fc)); r["png_combo"] = str(fc) + grid.append((s, SMALL(g))) + written.append(str(fn)) +gs, gw = img(start["episode"], "global", 0), img(start["episode"], "wrist", 0) +write_png(gs, str(OUT / "story_start_global.png")); start["png_global"] = str(OUT / "story_start_global.png") +if gw is not None: + write_png(inset(gs, gw), str(OUT / "story_start_combo.png")) + start["png_combo"] = str(OUT / "story_start_combo.png") +if grid: + row = torch.cat([SMALL(gs)] + [x for _, x in grid], dim=2) + write_png(row, str(OUT / "story_grid_global.png")) + print("[story] grid states:", ["start"] + [s for s, _ in grid]) + +# --- success page +fins = [] +for i, mk, fi, meta in succ_pairs: + a = img(i, "global", mk["local_frame"]); b = img(i, "global", fi["local_frame"]) + if a is None or b is None: + continue + write_png(a, str(OUT / f"success_marker_ep{i:03d}.png")); mk["png_global"] = str(OUT / f"success_marker_ep{i:03d}.png") + write_png(b, str(OUT / f"success_final_ep{i:03d}.png")); fi["png_global"] = str(OUT / f"success_final_ep{i:03d}.png") + write_png(torch.cat([SMALL(a), SMALL(b)], dim=2), str(OUT / f"success_marker_vs_final_ep{i:03d}.png")) + fi.update(meta); mk.update(meta) + fins.append(SMALL(b)) +if fins: + n = len(fins); half = (n + 1) // 2 + r1 = torch.cat(fins[:half], dim=2) + r2 = torch.cat(fins[half:] + [torch.zeros_like(fins[0])] * (half - len(fins[half:])), dim=2) + write_png(torch.cat([r1, r2], dim=1), str(OUT / "success_final_grid.png")) + +# --- reward strips: rows = variants, cols = the 3 frames, green border where the label is +1 +for tag, (ep, rs) in strips.items(): + rows = [] + for v in ["v0", "v1", "v2", "v3", "v4"]: + if v not in LAB: + continue + cols = [] + for r in rs: + x = img(ep, "global", r["local_frame"]) + if x is None: + continue + pos = bool(LAB[v][r["global_frame"]]) + cols.append(border(SMALL(x), (0, 220, 0) if pos else (200, 40, 40))) + if cols: + rows.append(torch.cat(cols, dim=2)) + if rows: + fn = OUT / f"reward_strip_{tag}.png" + write_png(torch.cat(rows, dim=1), str(fn)) + print(f"[story] {fn.name} ep{ep} frames={[r['local_frame'] for r in rs]} " + f"rows={[v for v in ['v0','v1','v2','v3','v4'] if v in LAB]}") + +Path("/proj/dmfexp/zwhong/rsm_rise/status/real/STORY_FRAMES.json").write_text(json.dumps({ + "states": states, "start": start, "end_of_stage": end_stage, + "success_pairs": [{"ep": i, "marker": mk, "final": fi, **meta} for i, mk, fi, meta in succ_pairs], + "strips": {k: {"episode": v[0], "frames": v[1]} for k, v in strips.items()}, + "frames": rec}, indent=2, default=str)) +print("[story] done ->", OUT) diff --git a/rsm_rise/scripts/real/replay_watcher.sh b/rsm_rise/scripts/real/replay_watcher.sh new file mode 100644 index 0000000000000000000000000000000000000000..357de79a74499955a1fb1fa56fca677a02cccf18 --- /dev/null +++ b/rsm_rise/scripts/real/replay_watcher.sh @@ -0,0 +1,79 @@ +#!/usr/bin/env bash +# Polls (no compute) for checkpoints and submits the held-out replay evals once per checkpoint: +# openpi: runs/openpi/checkpoints/pi05_cooking_/_s0/ for step in $OPENPI_STEPS +# ours : S0Aidql / S0B model_epoch_.pth (every-500 series) for e in $OUR_EPOCHS +set -uo pipefail +ROOT=/proj/dmfexp/zwhong/rsm_rise; cd $ROOT +# orbax keeps only the newest checkpoint + multiples of keep_period (10k for stock/rise, 5k for riseadv) +OPENPI_STEPS=${OPENPI_STEPS:-"5000 10000 15000 20000 25000 29999"}; OUR_EPOCHS=${OUR_EPOCHS:-"500 1000 2000 3000 4000 5000"} +export RR_QUEUE=preemptable RR_GROUP=grp_preemptable RR_MEM=96G +while true; do + echo "[watcher] pass $(date -u +%H:%M:%S)" + # snapshot the queue ONCE per pass and only trust a snapshot that plausibly succeeded: bjobs must exit 0 and + # list at least one of my jobs. A transient LSF failure previously read as "everything vanished" and + # resubmitted all eight cells (duplicates corrupt a cell's checkpoint dir). + QSNAP=$(bjobs -w 2>/dev/null); QRC=$? + QOK=0; [ $QRC -eq 0 ] && [ "$(echo "$QSNAP" | grep -cE 'rr_(openpi|cook|e1|rsm)')" -ge 1 ] && QOK=1 + [ $QOK -eq 1 ] || echo "[watcher] bjobs snapshot unusable (rc=$QRC) -- skipping the vanished-job checks this pass" + for v in stock rise riseadv; do for st in $OPENPI_STEPS; do + d=runs/openpi/checkpoints/pi05_cooking_$v/${v}_s0/$st; o=runs/openpi/checkpoints/pi05_cooking_$v/${v}_s0/replay_$st + [ -d $d/params ] && [ ! -e $o ] && { mkdir -p $o; scripts/bsub_gpu.sh rr_openpi_replay_${v}_$st scripts/real/openpi_eval.sh $ROOT/scripts/real/openpi_replay_eval.py --config pi05_cooking_$v --ckpt $ROOT/$d --out $ROOT/$o 2>&1 | tail -1; echo "[watcher] submitted openpi replay $v $st $(date -u)"; } + done; done + # gen_q#265 critic diagnostic protocol on every S0Aidql 500-series checkpoint (required before quoting an IDQL row) + for e in $OUR_EPOCHS; do + ck=$(ls runs/cooking_v5_expert_suboptimal/policy/S0Aidql_seed0/*/*/models/model_epoch_$e.pth 2>/dev/null | head -1); o=status/real/critic_diag_idql_s0_e$e.json + [ -n "$ck" ] && [ ! -e $o ] && [ ! -e $o.submitted ] && { touch $o.submitted; scripts/bsub_gpu.sh rr_cook_critic_diag_e$e scripts/real/run_env.sh $ROOT/scripts/tmp/critic_diag.py $ROOT/$ck $ROOT/$o 2>&1 | tail -1; echo "[watcher] submitted critic_diag e$e $(date -u)"; } + done + for cell in S0Aidql S0B; do for e in $OUR_EPOCHS; do + ck=$(ls runs/cooking_v5_expert_suboptimal/policy/${cell}_seed0/*/*/models/model_epoch_$e.pth 2>/dev/null | head -1); o=runs/cooking_v5_expert_suboptimal/policy/${cell}_seed0/replay_e$e + [ -n "$ck" ] && [ ! -e $o ] && { mkdir -p $o; scripts/bsub_gpu.sh rr_cook_replay_${cell}_e$e scripts/real/run_env.sh $ROOT/scripts/real/rise_replay_eval.py --ckpt $ROOT/$ck --out $ROOT/$o 2>&1 | tail -1; echo "[watcher] submitted our replay $cell e$e $(date -u)"; } + done; done + # open-loop scorer comparison (#263 item 2) once per new S0B rolling checkpoint multiple of 1000 + for e in 1000 2000 3000 4000 5000; do + ck=$(ls runs/cooking_v5_expert_suboptimal/policy/S0B_seed0/*/*/models/model_epoch_$e.pth 2>/dev/null | head -1) + idq=$(ls runs/cooking_v5_expert_suboptimal/policy/S0Aidql_seed0/*/*/models/model_epoch_*.pth runs/cooking_v5_expert_suboptimal/policy/S0Aidql_seed0/rolling/model_epoch_*.pth 2>/dev/null | awk -F'model_epoch_' '{split($2,a,"."); print a[1], $0}' | sort -n | tail -1 | cut -d' ' -f2-) + o=status/real/scorer_openloop_s0b_e$e + [ -n "$ck" ] && [ -n "$idq" ] && [ ! -e $o ] && { mkdir -p $o; scripts/bsub_gpu.sh rr_cook_scorer_ol_e$e scripts/real/run_env.sh $ROOT/scripts/real/scorer_openloop.py --policy robomimic:$ROOT/$ck --idql-ckpt $ROOT/$idq --out $ROOT/$o 2>&1 | tail -1; echo "[watcher] submitted scorer_openloop S0B e$e $(date -u)"; } + done + # admin-kill / vanished-job watch: resubmit any training cell that is neither queued nor running + for spec in "rr_cook_idql_s0:S0Aidql:0:idql" "rr_cook_idql_s1:S0Aidql:1:idql" "rr_cook_S0B_s0:S0B:0:bc" "rr_cook_S0B_s1:S0B:1:bc"; do + j=${spec%%:*}; rest=${spec#*:}; cell=${rest%%:*}; rest=${rest#*:}; sd=${rest%%:*}; kind=${rest##*:} + [ $QOK -eq 1 ] || continue + # ORCH 2026-09-22 14:50Z: do NOT resubmit a cell that already holds its final checkpoint. + # Without this the loop re-ran all 4 finished cells every 30 min; each re-load of the 131 GB + # dataset cache burns ~30 GPU-min and exits with zero Epoch lines (see ORCH_STATE run 17/18). + ls $ROOT/runs/cooking_v5_expert_suboptimal/policy/${cell}_seed${sd}/*/*/models/model_epoch_5000.pth >/dev/null 2>&1 \ + && { echo "[watcher] $j COMPLETE (model_epoch_5000.pth) -- not resubmitting"; continue; } + echo "$QSNAP" | awk -v n=$j '$7==n' | grep -q . && continue + [ -f $ROOT/status/real/.resub_$j ] && [ $(( $(date +%s) - $(stat -c %Y $ROOT/status/real/.resub_$j) )) -lt 1800 ] && continue + touch $ROOT/status/real/.resub_$j + if [ "$kind" = idql ]; then + RR_MEM=300G scripts/bsub_gpu.sh $j scripts/run_train.sh cooking_v5_expert_suboptimal S0Aidql $sd training.spectral_norm_policy=False training.policy_bottleneck_beta=0.0 training.action_augmentation=False training.advanced_augmentation=False 2>&1 | tail -1 + else + RR_MEM=300G scripts/bsub_gpu.sh $j scripts/run_train.sh cooking_v5_expert_suboptimal S0B $sd 2>&1 | tail -1 + fi + echo "[watcher] RESUBMITTED vanished $j $(date -u)" + done + for spec in "rr_openpi_stock_s0:pi05_cooking_stock:stock_s0:0" "rr_openpi_stock_s1:pi05_cooking_stock:stock_s1:1" "rr_openpi_rise_s0:pi05_cooking_rise:rise_s0:0" "rr_openpi_rise_s1:pi05_cooking_rise:rise_s1:1"; do + j=${spec%%:*}; rest=${spec#*:}; cfg=${rest%%:*}; rest=${rest#*:}; exp=${rest%%:*}; sd=${rest##*:} + [ $QOK -eq 1 ] || continue + # ORCH 2026-09-22 14:50Z: same guard for openpi -- 29999 is the final step of these configs. + [ -d $ROOT/runs/openpi/checkpoints/$cfg/$exp/29999 ] \ + && { echo "[watcher] $j COMPLETE (step 29999) -- not resubmitting"; continue; } + echo "$QSNAP" | awk -v n=$j '$7==n' | grep -q . && continue + [ -f $ROOT/status/real/.resub_$j ] && [ $(( $(date +%s) - $(stat -c %Y $ROOT/status/real/.resub_$j) )) -lt 1800 ] && continue + touch $ROOT/status/real/.resub_$j + scripts/bsub_gpu.sh $j scripts/real/openpi_train.sh $cfg $exp --seed $sd 2>&1 | tail -1 + echo "[watcher] RESUBMITTED vanished $j $(date -u)" + done + # hop-depth sweep (#263): fire per family as soon as its Stage-2 hop head lands (durable trigger -- does not + # depend on any interactive monitor being armed). hop_depth_sweep.sh is idempotent: it skips cells that exist. + for fam in gauss flow; do + [ -f $ROOT/runs/real_cooking_v5/hop/$fam/policy_r1.pt ] || continue + [ -f $ROOT/status/real/.sweep_fired_$fam ] && continue + touch $ROOT/status/real/.sweep_fired_$fam + echo "[watcher] hop head $fam ready -> launching the depth sweep $(date -u)" + FAMS=$fam bash $ROOT/scripts/real/hop_depth_sweep.sh 2>&1 | tail -12 + done + sleep 300 +done diff --git a/rsm_rise/scripts/real/reward_head_diag.py b/rsm_rise/scripts/real/reward_head_diag.py new file mode 100644 index 0000000000000000000000000000000000000000..51202fd669e0ea89b5c5bcb91ee9fa7f4a41ac09 --- /dev/null +++ b/rsm_rise/scripts/real/reward_head_diag.py @@ -0,0 +1,209 @@ +#!/usr/bin/env python +"""Diagnostics 1 and 2 of gen_q #271, for every reward head, on the CACHED features. + + 1. S4-vs-S6 SEPARABILITY. S4 ("pan on grate, tomato in the bowl", the goal) and S6 ("pan on the + stove, tomato in bowl", a failure terminal) both have the tomato in the bowl and differ only in + where the pan ends, so a head that scores them apart has encoded the pan position. Two forms: + terminal the single operator-marked arrival frame of each route-3 episode (k(t)=S4, n=50) + against the single arrival frame of each route-4 episode (k(t)=S6, n=50). This is + the issue's literal k(t) reading; on this corpus reached_state_id is a sparse + one-frame marker, so it is the ONLY thing that reading can mean. + segment every frame whose segment leads into S4 (edge_to=4, n=30292) against every frame + whose segment leads into S6 (edge_to=6, n=8322). The same contrast with support. + Reported as AUC of the head's probability, plus the score histograms. + + 2. JUNCTION AMBIGUITY. S2 is the junction: routes R2 (0->2->3), R3 (2->3->4) and R4 (0->2->6) all + pass through it. The head's score is reported on the +-W frames around each episode's S2 + crossing, split by the route the episode then continued on. A head whose junction scores + already separate R3 from R4 is reading trajectory identity, not state; a head that is ambiguous + there is the one stitching needs. + +usage: reward_head_diag.py --ckpt [--ckpt ...] --out (names default to the cell dir) +""" +from __future__ import annotations +import argparse, json, sys +from pathlib import Path +import numpy as np +import torch + +sys.path.insert(0, "/proj/dmfexp/zwhong/projs/issue_resolver_richardrl/gen_q_rsm/rsm_libero") +from data import LiberoRSMData # noqa: E402 +from model import RewardHead, IdentityEncoder # noqa: E402 + +CACHE = "/proj/dmfexp/zwhong/rsm_rise/cache/real_cooking_v5" +S2, S3, S4, S5, S6 = 2, 3, 4, 5, 6 + + +def auc(score, label): + """Rank AUC of `score` for the binary `label` (1 = positive). Ties get mid-ranks.""" + score = np.asarray(score, np.float64).ravel() + label = np.asarray(label).ravel().astype(bool) + n1, n0 = int(label.sum()), int((~label).sum()) + if n1 == 0 or n0 == 0: + return float("nan") + order = np.argsort(score, kind="mergesort") + r = np.empty(len(score), np.float64) + r[order] = np.arange(1, len(score) + 1, dtype=np.float64) + # mid-ranks for ties + s_sorted = score[order] + i = 0 + while i < len(s_sorted): + j = i + while j + 1 < len(s_sorted) and s_sorted[j + 1] == s_sorted[i]: + j += 1 + if j > i: + r[order[i:j + 1]] = 0.5 * (i + 1 + j + 1) + i = j + 1 + return float((r[label].sum() - n1 * (n1 + 1) / 2.0) / (n1 * n0)) + + +def hist(v, bins=20, lo=0.0, hi=1.0): + h, e = np.histogram(np.asarray(v, np.float64), bins=bins, range=(lo, hi)) + return {"counts": h.tolist(), "edges": [float(x) for x in e]} + + +def desc(v): + v = np.asarray(v, np.float64) + if len(v) == 0: + return {"n": 0} + return {"n": int(len(v)), "mean": float(v.mean()), "std": float(v.std()), + "p10": float(np.percentile(v, 10)), "median": float(np.median(v)), + "p90": float(np.percentile(v, 90)), + "min": float(v.min()), "max": float(v.max())} + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--ckpt", action="append", required=True, + help="name=path, or a bare path (name taken from the parent directory)") + ap.add_argument("--cache", default=CACHE) + ap.add_argument("--window", type=int, default=50, + help="+-W frames around the S2 crossing count as 'at the junction'") + ap.add_argument("--batch", type=int, default=8192) + ap.add_argument("--out", default="/proj/dmfexp/zwhong/rsm_rise/status/real/REWARD_HEAD_DIAG.json") + args = ap.parse_args() + dev = "cuda" if torch.cuda.is_available() else "cpu" + + C = Path(args.cache) + m = np.load(C / "meta.npz", allow_pickle=True) + ep_from, ep_to = m["ep_from"].astype(int), m["ep_to"].astype(int) + route = np.asarray(m["ep_route"], int) + path = np.asarray(m["ep_path"]) + et = np.load(C / "edge_to.i16.npy").astype(int) + ef = np.load(C / "edge_from.i16.npy").astype(int) + ks = np.load(C / "reached_state.i16.npy").astype(int) + N, n_ep = len(et), len(ep_from) + + # ---- the frame sets ------------------------------------------------------------------- + term_S4 = np.nonzero(ks == S4)[0] + term_S6 = np.nonzero(ks == S6)[0] + term_S5 = np.nonzero(ks == S5)[0] + seg_S4 = np.nonzero(et == S4)[0] + seg_S6 = np.nonzero(et == S6)[0] + seg_S5 = np.nonzero(et == S5)[0] + + # junction: the S2 crossing of each episode. R2/R4 cross into S2 mid-episode (the frame where + # edge_from becomes 2); R3's logged path STARTS at S2, so its crossing is the episode's first + # frame. Both are "the same physical junction state, different continuation". + junc_idx, junc_route = [], [] + for i in range(n_ep): + a, b = ep_from[i], ep_to[i] + hit = np.nonzero(ef[a:b] == S2)[0] + if len(hit) == 0: + continue + c = a + int(hit[0]) + lo, hi = max(a, c - args.window), min(b, c + args.window + 1) + junc_idx.append(np.arange(lo, hi)) + junc_route.append(np.full(hi - lo, int(route[i]))) + junc_idx = np.concatenate(junc_idx) if junc_idx else np.zeros(0, int) + junc_route = np.concatenate(junc_route) if junc_route else np.zeros(0, int) + + need = np.unique(np.concatenate([term_S4, term_S5, term_S6, seg_S4, seg_S5, seg_S6, junc_idx])) + print(f"[diag] frames: termS4={len(term_S4)} termS6={len(term_S6)} termS5={len(term_S5)} " + f"segS4={len(seg_S4)} segS6={len(seg_S6)} segS5={len(seg_S5)} " + f"junction={len(junc_idx)} (unique to score: {len(need)})", flush=True) + + out = {"cache": str(C), "window": args.window, + "frame_counts": {"terminal_S4": len(term_S4), "terminal_S5": len(term_S5), + "terminal_S6": len(term_S6), "segment_S4": len(seg_S4), + "segment_S5": len(seg_S5), "segment_S6": len(seg_S6), + "junction": len(junc_idx)}, + "junction_frames_by_route": {str(r): int((junc_route == r).sum()) + for r in sorted(set(junc_route.tolist()))}, + "route_paths": {str(int(route[i])): str(path[i]) for i in range(n_ep)}, + "heads": {}} + + data_cache = {} + for spec in args.ckpt: + name, _, p = spec.partition("=") + if not p: + p, name = name, Path(name).parent.name + p = Path(p) + if not p.exists(): + print(f"[diag] SKIP {name}: {p} missing", flush=True) + continue + c = torch.load(p, map_location=dev, weights_only=False) + cfg = c["config"] + step = int(c.get("step", -1)) + key = (int(cfg["chunk"]), int(cfg["k_success"]), int(cfg["seed"])) + if key not in data_cache: + data_cache[key] = LiberoRSMData(str(C), chunk=key[0], k_success=key[1], seed=key[2], + in_ram=True, val_frac=0.1, reward_mode="dense") + d = data_cache[key] + enc = IdentityEncoder(int(c["d_in"])).to(dev).eval() + rew = RewardHead(int(c["d_lat"]), len(c["tasks"])).to(dev).eval() + rew.load_state_dict(c["rew"]) + task0 = torch.zeros(1, dtype=torch.long, device=dev) + + prob = np.zeros(N, np.float32); logit = np.zeros(N, np.float32) + with torch.no_grad(): + for s in range(0, len(need), args.batch): + idx = need[s:s + args.batch] + x = torch.from_numpy(d._feat(idx.astype(np.int64))).to(dev) + z = enc(x) + lg = rew(z, task0.expand(len(idx))).float().cpu().numpy().ravel() + logit[idx] = lg + prob[idx] = 1.0 / (1.0 + np.exp(-lg)) + + h = {"ckpt": str(p), "step": step, + "reward_npy": str(cfg.get("reward_npy", "")), + "weight_npy": str(cfg.get("weight_npy", "")), + "seed": int(cfg["seed"])} + # -- 1. S4 vs S6 ------------------------------------------------------------------ + for tag, pos, neg in (("terminal", term_S4, term_S6), ("segment", seg_S4, seg_S6)): + sc = np.concatenate([prob[pos], prob[neg]]) + lb = np.concatenate([np.ones(len(pos)), np.zeros(len(neg))]) + h[f"auc_S4_vs_S6_{tag}"] = auc(sc, lb) + h[f"S4_{tag}"] = desc(prob[pos]); h[f"S6_{tag}"] = desc(prob[neg]) + h[f"hist_S4_{tag}"] = hist(prob[pos]); h[f"hist_S6_{tag}"] = hist(prob[neg]) + for tag, pos, neg in (("terminal", term_S4, term_S5), ("segment", seg_S4, seg_S5)): + sc = np.concatenate([prob[pos], prob[neg]]) + lb = np.concatenate([np.ones(len(pos)), np.zeros(len(neg))]) + h[f"auc_S4_vs_S5_{tag}"] = auc(sc, lb) + # -- 2. junction ------------------------------------------------------------------ + jr = {} + for r in sorted(set(junc_route.tolist())): + sel = junc_idx[junc_route == r] + jr[str(r)] = {"stats": desc(prob[sel]), "hist": hist(prob[sel]), + "logit_mean": float(logit[sel].mean())} + h["junction_by_route"] = jr + # the number that matters: can the head tell the success continuation from the failure + # continuation while still AT the junction? + for a_, b_, nm in ((3, 4, "R3_vs_R4"), (2, 4, "R2_vs_R4"), (3, 2, "R3_vs_R2")): + pa = prob[junc_idx[junc_route == a_]]; pb = prob[junc_idx[junc_route == b_]] + if len(pa) and len(pb): + h[f"auc_junction_{nm}"] = auc(np.concatenate([pa, pb]), + np.concatenate([np.ones(len(pa)), np.zeros(len(pb))])) + out["heads"][name] = h + print(f"[diag] {name:14s} step={step:6d} AUC(S4>S6) term={h['auc_S4_vs_S6_terminal']:.4f} " + f"seg={h['auc_S4_vs_S6_segment']:.4f} AUC(junction R3>R4)=" + f"{h.get('auc_junction_R3_vs_R4', float('nan')):.4f} " + f"junction mean p: " + + " ".join(f"R{r}={jr[r]['stats']['mean']:.3f}" for r in sorted(jr)), flush=True) + + Path(args.out).write_text(json.dumps(out, indent=2)) + print(f"[diag] wrote {args.out}", flush=True) + + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/real/reward_head_probe.py b/rsm_rise/scripts/real/reward_head_probe.py new file mode 100644 index 0000000000000000000000000000000000000000..be20d90e26893e5f525dd2e88a3882340e3f9382 --- /dev/null +++ b/rsm_rise/scripts/real/reward_head_probe.py @@ -0,0 +1,343 @@ +"""SUCC_DEBUG run 17 (gen_q#277): IS THE READ-OUT THE PLANNER INTEGRATES ABLE TO SEE THE +SUCCESSOR MODEL AT ALL? + +WHY. Run 16's distributional table (successor_dist_test.py, widths 1024..4096) reports the reward +mixture of four sets at every anchor -- the model's N=256 samples, the logged futures, the ORACLE +draws and STAY-PUT. At every stage the four agree to 1e-9, and the per-stage fraction is an EXACT +rational (S2: 0.46808510638297873 = 22/47 in all four sets, S0 0.0, S3 1.0). An exact k/n with +n = the anchor count can only happen if EVERY sample at an anchor votes the same way as the anchor +itself: the within-anchor variance of sigmoid(rewhead) is identically zero in all four sets. So the +planner's value, mean_i sigmoid(rewhead(z'_i)), equals sigmoid(rewhead(z_anchor)) exactly and the +successor model cannot move it. That would explain the flat proposal-test AUC without any of the +capacity story. Two things are NOT yet measured and this script measures them: + + A. LOGIT SPECTRUM. chain_reach.py already logs rhead_logit_mean = +25 at hop 1 in every cell and + -73..-146 in the logged arm by hop 8. sigmoid(25) = 1 - 1.4e-11. How much of the TRAIN + manifold sits in the soft band |logit| < 3 where the sigmoid carries any ranking information? + B. BOUNDARY WIDTH vs HOP LENGTH, in the SAME units (||.||_1 / dim). Interpolate between a + rewarding and a non-rewarding train frame, find where the logit crosses 0, and report the + width of the |logit| < 3 band along that segment. Compare to the model's own one-hop + displacement and the data's. A boundary far thinner than a hop means the head is a step + function; far thicker means a hop can never reach it. + C. THE DIRECTION TEST -- the decisive one. g = grad_z logit at the anchor is the ONLY direction + the read-out can see. Report cos(delta_model, g) and || against the same two + for delta_data = z_logged_future - z_anchor. If the data's hop has a real component along g + and the model's does not, the model moves but never along the reward axis -- a direction + defect in the one coordinate that matters, not a magnitude or a capacity defect. + D. THE CROSS-EPISODE BRACKET. Run 16's reward-mixture check is VACUOUS as specified: the + empirical logged set is drawn from the SAME episode, which has already committed to a route, + so it is route-unanimous and STAY-PUT passes the check exactly (absdiff 7.8e-11). The + distribution a value function must integrate at the S2 junction is the CROSS-EPISODE one: the + futures of OTHER train episodes that pass through a nearby S2 state, which contains both the + rewarding route 2->3->4 and the non-rewarding alternative. Report the model's mixture against + THAT set, with the same oracle/stay brackets. + +Reads only. Does not edit the trainer or any in-flight payload. +""" +import argparse, json, os, sys, time +import numpy as np + +RSM = "/proj/dmfexp/zwhong/projs/issue_resolver_richardrl/gen_q_rsm/rsm_libero" +ROOT = "/proj/dmfexp/zwhong/rsm_rise" +sys.path.insert(0, RSM) +GOAL_PATH = "2->3->4" + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--cache", default=f"{ROOT}/cache/real_cooking_v5") + ap.add_argument("--hdf5", default=f"{ROOT}/data/raw/cooking_v5_expert_suboptimal.hdf5") + ap.add_argument("--ckpt", default=f"{ROOT}/runs/real_cooking_v5/rsm/R_M/ckpt_s100000.pt") + ap.add_argument("--tag", default="R_M_s100000") + ap.add_argument("--beta", type=float, default=0.95) + ap.add_argument("--anchors", type=int, default=200) + ap.add_argument("--n-samples", type=int, default=256) + ap.add_argument("--spectrum-n", type=int, default=20000) + ap.add_argument("--interp-pairs", type=int, default=200) + ap.add_argument("--interp-grid", type=int, default=257) + ap.add_argument("--knn-eps", type=int, default=8) # cross-episode neighbours per anchor + ap.add_argument("--chunk", type=int, default=8) + ap.add_argument("--k-success", type=int, default=10) + ap.add_argument("--seed", type=int, default=0) + ap.add_argument("--eval-seed", type=int, default=1234) + ap.add_argument("--beta-trunc-eps", type=float, default=0.02) + ap.add_argument("--flow-steps", type=int, default=8) + ap.add_argument("--sample-clip", type=float, default=10.0) + ap.add_argument("--in-ram", type=int, default=1) + # SUCC_DEBUG run 17: run 17's TRAIN read shows the head separates the two S2 routes at +-25 + # with ZERO frames in between and that S2 nearest neighbours from OTHER episodes are + # route-unanimous at 197/197 anchors. On the TRAIN split that has two readings and they have + # opposite consequences: either the route really is decided at S2 (a task property -- there is + # no junction uncertainty for a value function to resolve), or the head has memorised episode + # identity (an overfitting defect -- the deployed value is meaningless off-train). Re-running + # the identical probe on the HELD-OUT episodes separates them. Default stays "train" so every + # JSON written before this flag existed is still reproducible bit-for-bit. + ap.add_argument("--split", default="train", choices=["train", "val"]) + ap.add_argument("--out", required=True) + a = ap.parse_args() + + import torch, h5py + from data import LiberoRSMData, truncated_geometric_future + from is_ope import load_critic + from train_rsm import sample_future + + dev = "cuda" if torch.cuda.is_available() else "cpu" + t0 = time.time() + os.makedirs(os.path.dirname(os.path.abspath(a.out)) or ".", exist_ok=True) + print(f"[rhp] ckpt={a.ckpt} dev={dev}", flush=True) + + d = LiberoRSMData(a.cache, chunk=a.chunk, k_success=a.k_success, seed=a.seed, + stratify_success=False, in_ram=bool(a.in_ram), reward_mode="dense") + D = int(d.feat_dim) + enc, rew, flow, rms, cfg = load_critic(a.ckpt, D, d.n_task, dev, data=d) + clip = float(cfg.get("sample_clip", a.sample_clip) or 0.0) + fsteps = int(cfg.get("flow_steps", a.flow_steps)) + rng = np.random.default_rng(a.eval_seed) + tr = np.asarray(d.train_eps if a.split == "train" else d.val_eps, np.int64) + trset = set(int(x) for x in tr) + assert len(tr), f"split {a.split} is empty" + out = {"ckpt": a.ckpt, "tag": a.tag, "D": D, "beta": a.beta, "eval_seed": a.eval_seed, + "flow_steps": fsteps, "sample_clip": clip, "flow_width": cfg.get("flow_width"), + "n_samples": a.n_samples, "anchors_requested": a.anchors, "split": a.split} + L1 = lambda X, Y: (X - Y).abs().mean(-1) + + allrows = np.concatenate([np.arange(int(d.ep_from[e]), int(d.ep_to[e])) for e in sorted(trset)]) + row_ep = np.concatenate([np.full(int(d.ep_to[e]) - int(d.ep_from[e]), e, np.int64) + for e in sorted(trset)]) + try: + edge_from = np.load(f"{a.cache}/edge_from.i16.npy") + except Exception: + edge_from = None + + # ================= A. LOGIT SPECTRUM ON THE TRAIN MANIFOLD ============================== + sel = rng.choice(len(allrows), size=min(a.spectrum_n, len(allrows)), replace=False) + rr, re_ = allrows[sel], row_ep[sel] + logits = [] + with torch.no_grad(): + for i in range(0, len(rr), 4096): + X = torch.from_numpy(d._feat(rr[i:i + 4096])).to(dev) + tk = torch.from_numpy(d.ep_task[re_[i:i + 4096]]).long().to(dev) + logits.append(rew(X, tk).float().view(-1).cpu().numpy()) + lg = np.concatenate(logits) + qs = [0, 1, 5, 25, 50, 75, 95, 99, 100] + out["logit_spectrum"] = { + "n": int(len(lg)), + "quantiles": {f"p{q}": float(np.percentile(lg, q)) for q in qs}, + "frac_pos": float((lg > 0).mean()), + "frac_abs_lt_1": float((np.abs(lg) < 1).mean()), + "frac_abs_lt_3": float((np.abs(lg) < 3).mean()), + "frac_abs_lt_10": float((np.abs(lg) < 10).mean()), + "mean_abs": float(np.abs(lg).mean()), + "note": "frac_abs_lt_3 is the fraction of the TRAIN manifold on which sigmoid(rewhead) is " + "not already saturated to within 5%. A value near 0 means the read-out is a step " + "function and mean-over-samples is a hard vote count, not a graded value.", + } + if edge_from is not None: + st = edge_from[rr] + out["logit_spectrum"]["by_stage"] = { + f"S{int(s)}": {"n": int((st == s).sum()), + "mean": float(lg[st == s].mean()), + "frac_pos": float((lg[st == s] > 0).mean()), + "frac_abs_lt_3": float((np.abs(lg[st == s]) < 3).mean())} + for s in sorted(set(st.tolist()))} + print(f"[rhp] A logit p1/p50/p99 = {out['logit_spectrum']['quantiles']['p1']:.1f}/" + f"{out['logit_spectrum']['quantiles']['p50']:.1f}/" + f"{out['logit_spectrum']['quantiles']['p99']:.1f} " + f"frac|l|<3 = {out['logit_spectrum']['frac_abs_lt_3']:.5f}", flush=True) + + # ================= B. BOUNDARY WIDTH vs HOP LENGTH ====================================== + pos = np.where(lg > 0)[0]; neg = np.where(lg <= 0)[0] + bw = {"n_pairs": 0} + if len(pos) and len(neg): + npair = min(a.interp_pairs, len(pos), len(neg)) + ip = rng.choice(pos, npair, replace=False); inn = rng.choice(neg, npair, replace=False) + u = torch.linspace(0, 1, a.interp_grid, device=dev)[:, None] + widths, crossings, seg = [], [], [] + with torch.no_grad(): + for j in range(npair): + zp = torch.from_numpy(d._feat(rr[ip[j]:ip[j] + 1])).to(dev) + zn = torch.from_numpy(d._feat(rr[inn[j]:inn[j] + 1])).to(dev) + tk = torch.from_numpy(d.ep_task[re_[ip[j]:ip[j] + 1]]).long().to(dev) + Z = zn + u * (zp - zn) # [G, D] + l = rew(Z, tk.expand(Z.shape[0])).float().view(-1) + seglen = float(L1(zp, zn)) + soft = (l.abs() < 3.0).float().mean().item() + s = torch.sign(l) + cross = int((s[1:] != s[:-1]).sum().item()) + widths.append(soft * seglen); crossings.append(cross); seg.append(seglen) + bw = {"n_pairs": npair, + "soft_band_width_L1_mean": float(np.mean(widths)), + "soft_band_width_L1_median": float(np.median(widths)), + "segment_L1_median": float(np.median(seg)), + "sign_crossings_mean": float(np.mean(crossings)), + "note": "soft_band_width_L1 = the L1/dim length of the piece of a pos->neg segment on " + "which |logit| < 3. Compare with hop_L1 below: the units are identical."} + out["boundary_width"] = bw + print(f"[rhp] B soft-band width {bw.get('soft_band_width_L1_median', float('nan')):.5f} " + f"(segment {bw.get('segment_L1_median', float('nan')):.4f})", flush=True) + + # ================= C. THE DIRECTION TEST ================================================ + b = d.sample(2048, rng, a.beta, a.beta, a.split, dev, a.beta_trunc_eps) + z_now = enc(b["x_now"]).detach(); z_fut = enc(b["x_fut"]).detach() + zg = z_now.clone().requires_grad_(True) + lo_ = rew(zg, b["task"]).float().sum() + g, = torch.autograd.grad(lo_, zg) + with torch.no_grad(): + xs = sample_future(flow, z_now, b["a_now"], b["task"], b["beta"], rms, fsteps, n=1) + if clip > 0: + xs = xs.clamp(-clip, clip) + dm = xs - z_now + dd = z_fut - z_now + gn = g / g.norm(dim=1, keepdim=True).clamp_min(1e-9) + proj_m = (dm * gn).sum(1); proj_d = (dd * gn).sum(1) + cos_m = proj_m / dm.norm(dim=1).clamp_min(1e-9) + cos_d = proj_d / dd.norm(dim=1).clamp_min(1e-9) + # what the read-out actually changes by, to first order + dlogit_m = (dm * g).sum(1); dlogit_d = (dd * g).sum(1) + # and the EXACT (non-linear) change the head reports + exact_m = (rew(xs, b["task"]).float().view(-1) - rew(z_now, b["task"]).float().view(-1)) + exact_d = (rew(z_fut, b["task"]).float().view(-1) - rew(z_now, b["task"]).float().view(-1)) + out["direction_test"] = { + "rows": int(z_now.shape[0]), + "grad_norm_median": float(g.norm(dim=1).median()), + "cos_model_median": float(cos_m.median()), "cos_data_median": float(cos_d.median()), + "abscos_model_median": float(cos_m.abs().median()), + "abscos_data_median": float(cos_d.abs().median()), + "proj_model_median": float(proj_m.median()), "proj_data_median": float(proj_d.median()), + "absproj_model_median": float(proj_m.abs().median()), + "absproj_data_median": float(proj_d.abs().median()), + "dlogit_linear_model_median": float(dlogit_m.median()), + "dlogit_linear_data_median": float(dlogit_d.median()), + "dlogit_exact_model_median": float(exact_m.median()), + "dlogit_exact_data_median": float(exact_d.median()), + "absdlogit_exact_model_median": float(exact_m.abs().median()), + "absdlogit_exact_data_median": float(exact_d.abs().median()), + "hop_L1_model": float(dm.abs().mean()), "hop_L1_data": float(dd.abs().mean()), + "note": "g = grad_z logit at the anchor: the ONLY direction the read-out can see. cos_* is " + "the alignment of a hop with it; absdlogit_exact_* is how much the head's own " + "output actually moves. The DATA row is the bracket -- it is what a correct hop " + "would have done to the read-out.", + } + dt = out["direction_test"] + print(f"[rhp] C |cos| model={dt['abscos_model_median']:.4f} data={dt['abscos_data_median']:.4f} " + f"| |dlogit| model={dt['absdlogit_exact_model_median']:.3f} " + f"data={dt['absdlogit_exact_data_median']:.3f} | hop_L1 " + f"{dt['hop_L1_model']:.4f}/{dt['hop_L1_data']:.4f}", flush=True) + + # ================= D. THE CROSS-EPISODE S2 BRACKET ====================================== + # S2 frames of TRAIN episodes, tagged by the episode's route: the within-episode set is + # route-unanimous by construction, the cross-episode set is not. + route = {} + with h5py.File(a.hdf5, "r") as f: + g5 = f["data"] + _meta = np.load(os.path.join(a.cache, "meta.npz"), allow_pickle=True) + src2ep = {str(s): i for i, s in enumerate(_meta["ep_src"])} + for k in g5: + ei = int(g5[k].attrs["episode_index"]) + e = src2ep.get(f"episode_{ei:06d}") + if e is not None and int(e) in trset: + route[int(e)] = str(g5[k].attrs.get("path", "?")) + s2rows = allrows[edge_from[allrows] == 2] if edge_from is not None else np.array([], np.int64) + s2ep = row_ep[edge_from[allrows] == 2] if edge_from is not None else np.array([], np.int64) + ce = {"n_anchors": 0} + if len(s2rows) > 32: + with torch.no_grad(): + Zs2 = torch.from_numpy(d._feat(s2rows)).to(dev) + na = min(a.anchors, len(s2rows)) + pick = rng.choice(len(s2rows), na, replace=False) + recs = [] + N = a.n_samples + for j in pick: + t = int(s2rows[j]); e = int(s2ep[j]) + hi = int(d.ep_to[e]) + with torch.no_grad(): + zA = torch.from_numpy(d._feat(np.array([t], np.int64))).to(dev) + tk = torch.from_numpy(d.ep_task[np.array([e])]).long().to(dev) + # cross-episode neighbours: nearest S2 frames from OTHER train episodes + dist = L1(Zs2, zA) + dist = dist + torch.from_numpy((s2ep == e).astype(np.float32)).to(dev) * 1e6 + nb = torch.topk(-dist, min(a.knn_eps * 4, len(s2rows))).indices.cpu().numpy() + seen, nbe = [], set() + for ii in nb: + ee = int(s2ep[ii]) + if ee in nbe: + continue + nbe.add(ee); seen.append(int(s2rows[ii])) + if len(seen) >= a.knn_eps: + break + if len(seen) < 2: + continue + # the CROSS-EPISODE logged set: futures of those neighbour episodes' S2 states + per = max(1, N // len(seen)) + ks, kep = [], [] + for tt in seen: + ee = int(row_ep[np.searchsorted(allrows, tt)]) + hh = int(d.ep_to[ee]) + ks.append(truncated_geometric_future(np.full(per, tt, np.int64), + np.full(per, hh, np.int64), + np.full(per, a.beta, np.float64), + rng.random(per))) + kep.append(np.full(per, ee, np.int64)) + kx = np.concatenate(ks); kep = np.concatenate(kep) + Ycross = torch.from_numpy(d._feat(kx)).to(dev) + # the WITHIN-episode set, the one run 16 used + kin = truncated_geometric_future(np.full(N, t, np.int64), np.full(N, hi, np.int64), + np.full(N, a.beta, np.float64), rng.random(N)) + Yin = torch.from_numpy(d._feat(kin)).to(dev) + aC = torch.from_numpy(d._chunk_at(np.array([t], np.int64), + np.array([e], np.int64))).to(dev) + bt = torch.full((1,), a.beta, device=dev) + Xm = sample_future(flow, zA, aC, tk, bt, rms, fsteps, n=N) + if clip > 0: + Xm = Xm.clamp(-clip, clip) + r = {"route_anchor_goal": int(route.get(e, "?") == GOAL_PATH), + "n_nb_eps": len(seen), + "nb_goal_frac": float(np.mean([route.get(int(row_ep[np.searchsorted(allrows, tt)]), "?") == GOAL_PATH + for tt in seen]))} + for name, X in (("model", Xm), ("within", Yin), ("cross", Ycross), + ("stay", zA.expand(N, -1))): + p = torch.sigmoid(rew(X, tk.expand(X.shape[0])).float()).view(-1).cpu().numpy() + r[f"rew_mean_{name}"] = float(p.mean()) + r[f"rew_frac_hi_{name}"] = float((p > 0.5).mean()) + r[f"rew_std_{name}"] = float(p.std()) + recs.append(r) + if recs: + keys = [k for k in recs[0]] + ce = {"n_anchors": len(recs), + **{k: float(np.mean([x[k] for x in recs])) for k in keys}} + # the quantity that says whether the bracket is non-degenerate at all + ce["within_is_unanimous_frac"] = float(np.mean( + [min(x["rew_frac_hi_within"], 1 - x["rew_frac_hi_within"]) < 1e-9 for x in recs])) + ce["cross_is_unanimous_frac"] = float(np.mean( + [min(x["rew_frac_hi_cross"], 1 - x["rew_frac_hi_cross"]) < 1e-9 for x in recs])) + ce["model_is_unanimous_frac"] = float(np.mean( + [min(x["rew_frac_hi_model"], 1 - x["rew_frac_hi_model"]) < 1e-9 for x in recs])) + ce["absdiff_model_vs_cross"] = float(np.mean( + [abs(x["rew_frac_hi_model"] - x["rew_frac_hi_cross"]) for x in recs])) + ce["absdiff_stay_vs_cross"] = float(np.mean( + [abs(x["rew_frac_hi_stay"] - x["rew_frac_hi_cross"]) for x in recs])) + ce["absdiff_within_vs_cross"] = float(np.mean( + [abs(x["rew_frac_hi_within"] - x["rew_frac_hi_cross"]) for x in recs])) + ce["note"] = ("*_is_unanimous_frac is the fraction of anchors at which a set gives the " + "SAME binary reward to every member. The within-episode set is unanimous " + "by construction (the episode has committed to a route), which is why the " + "run-16 mixture check is passed exactly by STAY-PUT. The cross-episode " + "set is the bimodal one the planner must integrate; absdiff_*_vs_cross " + "is scored against it, with STAY as the bracket.") + out["cross_episode_S2"] = ce + print(f"[rhp] D anchors={ce.get('n_anchors', 0)} within_unanim={ce.get('within_is_unanimous_frac', -1):.3f} " + f"cross_unanim={ce.get('cross_is_unanimous_frac', -1):.3f} " + f"model_unanim={ce.get('model_is_unanimous_frac', -1):.3f} | absdiff model/stay vs cross " + f"{ce.get('absdiff_model_vs_cross', -1):.4f}/{ce.get('absdiff_stay_vs_cross', -1):.4f}", + flush=True) + + out["seconds"] = time.time() - t0 + tmp = a.out + f".tmp.{os.getpid()}" + with open(tmp, "w") as f: + json.dump(out, f, indent=1) + os.replace(tmp, a.out) + print(f"[rhp] wrote {a.out} in {out['seconds']:.0f}s", flush=True) + + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/real/reward_head_profile.py b/rsm_rise/scripts/real/reward_head_profile.py new file mode 100644 index 0000000000000000000000000000000000000000..83c3b0b20960cefd52e08f43c5dd93aed62d1a89 --- /dev/null +++ b/rsm_rise/scripts/real/reward_head_profile.py @@ -0,0 +1,194 @@ +#!/usr/bin/env python +"""Run 31 (2026-09-24) -- what the logged discounted return ACTUALLY does from S3 entry to S3 late, +per reward head. This decides run 30's open finding (c). + +Run 30 measured that on EXPERT_EPISODE the IDQL critic's value FALLS from group C (goal-route S3 +entry) to group D (goal-route S3 late) in both seeds -- -3.783 and -4.204 against 2-SE margins of +0.306 / 0.343 -- and that EE/IDQL is the only cell in the matrix that does so. It reported that as +a defect, on the stated premise "EE labels 1.0 on the final S3/S4 frames, so a correctly fit +discounted value must be non-decreasing approaching them". + +That premise is an ASSUMPTION about the label, read off a head NAME +(`reward_v0lit_finalS3S4`) and off a route-level column in the stream's own head table. It has +never been measured. If the EE head instead labels 1.0 over a LONG span of the goal episode, then +the logged discounted return from a point near the END of the episode is SMALLER than from earlier +(fewer discounted reward frames remain before the recording stops), a correctly fit critic must +DECLINE, and it is the RSM's climb that needs explaining, not the IDQL's fall. + +So: compute the reference the claim needs, from the reward arrays and the frame index alone, with +no checkpoint anywhere. For each head and each route: + * the per-frame reward profile (mean, fraction non-zero, max); + * for the goal route 2->3->4, the LOGGED discounted return from the exact C and D windows that + stitch_value_test.py uses, at each column's own discount (IDQL 0.99, RSM 0.999), truncated at + the episode end with NO bootstrap -- the same convention run 27's no-stitch line uses; + * the sign of D - C in that logged return, per episode, with a bootstrap over EPISODES. +The output says, per head, which sign a correctly fit critic should have. +""" +import json +import os +import sys + +import numpy as np + +ROOT = "/proj/dmfexp/zwhong/rsm_rise" +CACHE = os.path.join(ROOT, "cache/real_cooking_v5") +HDF5 = os.path.join(ROOT, "data/raw/cooking_v5_expert_suboptimal.hdf5") +TAIL = 25 # stitch_value_test.py --tail +HORIZON = 8 # stitch_value_test.py --horizon +GAMMAS = {"idql": 0.99, "rsm": 0.999} +N_BOOT = 4000 + +# The five DISTINCT heads (run 28 md5'd the npys; the aliases are bit-identical arrays). +HEADS = { + "GOAL_EPISODE": "reward_v0_provenance.f32.npy", + "GOAL_SEGMENT": "reward_v1_goaltrans.f32.npy", + "EXPERT_EPISODE": "reward_v0lit_finalS3S4.f32.npy", + "GOAL_WINDOW_100": "reward_B_H100.f32.npy", + "GOAL_WINDOW_400": "reward_B_H400.f32.npy", +} + + +def logged_return(r, start, gamma): + """Discounted sum of the LOGGED reward from `start` to the end of the array, no bootstrap.""" + n = len(r) + if start >= n: + return float("nan") + disc = gamma ** np.arange(n - start, dtype=np.float64) + return float(np.dot(disc, r[start:].astype(np.float64))) + + +def boot_mean(x, rng, n_boot=N_BOOT): + x = np.asarray([v for v in x if np.isfinite(v)], dtype=np.float64) + if len(x) < 2: + return (float("nan"), float("nan"), float("nan"), len(x)) + idx = rng.integers(0, len(x), size=(n_boot, len(x))) + bs = x[idx].mean(axis=1) + return (float(x.mean()), float(np.percentile(bs, 2.5)), float(np.percentile(bs, 97.5)), len(x)) + + +def main(): + import h5py + + meta = np.load(os.path.join(CACHE, "meta.npz"), allow_pickle=True) + print("[meta] keys:", sorted(meta.files)) + ep_from = np.asarray(meta["ep_from"]).astype(int) + ep_to = np.asarray(meta["ep_to"]).astype(int) + stage = np.load(os.path.join(CACHE, "edge_from.i16.npy")) + n_frames_cache = int(ep_to[-1]) + print("[meta] episodes=%d cache_frames=%d stage_len=%d" % (len(ep_from), n_frames_cache, len(stage))) + + # routes and lengths straight from the hdf5 ATTRS (no pixel data touched) + routes, lens = {}, {} + with h5py.File(HDF5, "r") as f: + d = f["data"] + for k in d: + ep = int(k.split("_")[1]) + routes[ep] = str(d[k].attrs.get("path", "")) + lens[ep] = int(len(d[k]["annot"]["edge_from"])) + print("[hdf5] demos=%d" % len(routes)) + + # HARD ALIGNMENT ASSERT -- the npy slice and the hdf5 frames must line up per demo, or every + # number below is silently wrong. This is the assert the stream brief asks for. + bad = [(ep, lens[ep], int(ep_to[ep] - ep_from[ep])) for ep in sorted(routes) + if lens[ep] != int(ep_to[ep] - ep_from[ep])] + if bad: + print("[FATAL] hdf5 length != cache ep_to-ep_from for %d demos, first 5: %s" % (len(bad), bad[:5])) + sys.exit(3) + print("[assert] all %d demos: hdf5 frames == ep_to-ep_from OK" % len(routes)) + + route_counts = {} + for ep, r in routes.items(): + route_counts[r] = route_counts.get(r, 0) + 1 + print("[routes]", json.dumps({k: route_counts[k] for k in sorted(route_counts)})) + + out = {"tail": TAIL, "horizon": HORIZON, "gammas": GAMMAS, "n_boot": N_BOOT, "heads": {}} + + for head, fn in sorted(HEADS.items()): + path = os.path.join(CACHE, fn) + if not os.path.exists(path): + print("\n### %s -- MISSING %s, SKIPPED" % (head, fn)) + continue + R = np.load(path) + if len(R) != n_frames_cache: + print("\n### %s -- FATAL length %d != cache frames %d" % (head, len(R), n_frames_cache)) + sys.exit(3) + print("\n" + "=" * 100) + print("### HEAD %s (%s)" % (head, fn)) + print("=" * 100) + + # ---- 1. per-route per-frame profile + print("%-12s %5s %8s %10s %10s %10s %10s" % + ("route", "n_ep", "n_frames", "mean_r", "frac_r>0", "max_r", "mean_len")) + prof = {} + for r in sorted(route_counts): + eps = [ep for ep in sorted(routes) if routes[ep] == r] + v = np.concatenate([R[ep_from[ep]:ep_to[ep]] for ep in eps]) + prof[r] = {"n_ep": len(eps), "n_frames": int(len(v)), "mean_r": float(v.mean()), + "frac_pos": float((v > 0).mean()), "max_r": float(v.max()), + "mean_len": float(np.mean([lens[ep] for ep in eps]))} + print("%-12s %5d %8d %10.4f %10.4f %10.4f %10.1f" % + (r, prof[r]["n_ep"], prof[r]["n_frames"], prof[r]["mean_r"], + prof[r]["frac_pos"], prof[r]["max_r"], prof[r]["mean_len"])) + + # ---- 2. the C and D windows on the goal route, exactly as stitch_value_test.py builds them + rng = np.random.default_rng(0) + goal_eps = [ep for ep in sorted(routes) if routes[ep] == "2->3->4"] + rows = {m: {"C": [], "D": [], "diff": []} for m in GAMMAS} + n_used = 0 + for ep in goal_eps: + n = lens[ep] + st = stage[ep_from[ep]:ep_to[ep]] + i3 = np.where(st == 3)[0] + if not len(i3): + continue + e0 = int(i3[0]) + cs = list(range(e0, min(e0 + TAIL, n - HORIZON))) + ds = list(range(max(e0, n - TAIL - HORIZON), n - HORIZON)) + if not cs or not ds: + continue + n_used += 1 + r_ep = R[ep_from[ep]:ep_to[ep]] + for m, g in GAMMAS.items(): + c = float(np.mean([logged_return(r_ep, t, g) for t in cs])) + dd = float(np.mean([logged_return(r_ep, t, g) for t in ds])) + rows[m]["C"].append(c) + rows[m]["D"].append(dd) + rows[m]["diff"].append(dd - c) + + print("\nLOGGED discounted return from the C / D windows on route 2->3->4 " + "(%d of %d goal episodes usable), truncated at episode end, NO bootstrap value:" % + (n_used, len(goal_eps))) + print("%-6s %10s %10s %12s %28s %10s" % + ("col", "mean_C", "mean_D", "mean_D-C", "boot95(D-C)", "sign")) + hres = {"profile": prof, "n_goal_used": n_used, "n_goal": len(goal_eps), "cols": {}} + for m in ("idql", "rsm"): + mc, _, _, _ = boot_mean(rows[m]["C"], np.random.default_rng(1)) + md, _, _, _ = boot_mean(rows[m]["D"], np.random.default_rng(2)) + mdiff, lo, hi, nn = boot_mean(rows[m]["diff"], np.random.default_rng(3)) + sign = "CLIMB" if lo > 0 else ("FALL" if hi < 0 else "UNRESOLVED") + print("%-6s %10.4f %10.4f %12.4f [%12.4f, %12.4f] %10s" % (m, mc, md, mdiff, lo, hi, sign)) + hres["cols"][m] = {"gamma": GAMMAS[m], "mean_C": mc, "mean_D": md, "mean_diff": mdiff, + "boot95": [lo, hi], "n_episodes": nn, "sign": sign} + out["heads"][head] = hres + + # ---- 3. plain-language verdict for this head + for m in ("idql", "rsm"): + s = hres["cols"][m]["sign"] + if s == "UNRESOLVED": + print("[verdict/%s] the logged return itself does not resolve a sign here; " + "NO expectation can be placed on a critic's C->D direction." % m) + else: + print("[verdict/%s] a correctly fit critic at gamma=%s should %s from C to D on this head." + % (m, GAMMAS[m], s)) + + op = os.path.join(ROOT, "status/real/stitch/REWARD_HEAD_PROFILE.json") + with open(op, "w") as fh: + json.dump(out, fh, indent=1, sort_keys=True) + print("\n[wrote] %s heads=%d" % (op, len(out["heads"]))) + if not out["heads"]: + print("[FATAL] no head produced a row") + sys.exit(2) + + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/real/rhead_route_confusion.py b/rsm_rise/scripts/real/rhead_route_confusion.py new file mode 100644 index 0000000000000000000000000000000000000000..16cdfd3bfceed00c69ffe9598801791ab7771257 --- /dev/null +++ b/rsm_rise/scripts/real/rhead_route_confusion.py @@ -0,0 +1,110 @@ +"""SUCC_DEBUG run 17 (gen_q#277): DOES THE REWARD HEAD'S S2 SIGN EQUAL THE ROUTE LABEL ON +HELD-OUT EPISODES? One measurement: the confusion matrix, per split. + +reward_head_probe.py reports two S2 numbers on the VAL split that do not agree and neither can be +trusted until this runs: + * section A, over every one of the 15,446 val frames: frac(logit > 0) at S2 = 0.194 + * section D, over 161 sampled S2 anchors: frac(sigmoid > 0.5) = 0.0373, which is + EXACTLY the goal-route fraction of those anchors' episodes +On TRAIN the same two numbers agree exactly (0.472 / 0.472). Either the val positives are +concentrated in frames the anchor sampler under-draws, or one of the two paths is wrong. This +script computes the thing both were proxies for, directly and with no sampling at all: over ALL S2 +frames of a split, the 2x2 of sign(logit) against the episode's hdf5 `path` attribute, plus the +per-episode breakdown. Reads only. +""" +import argparse, json, os, sys +import numpy as np + +RSM = "/proj/dmfexp/zwhong/projs/issue_resolver_richardrl/gen_q_rsm/rsm_libero" +ROOT = "/proj/dmfexp/zwhong/rsm_rise" +sys.path.insert(0, RSM) +GOAL_PATH = "2->3->4" + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--cache", default=f"{ROOT}/cache/real_cooking_v5") + ap.add_argument("--hdf5", default=f"{ROOT}/data/raw/cooking_v5_expert_suboptimal.hdf5") + ap.add_argument("--ckpt", default=f"{ROOT}/runs/real_cooking_v5/rsm/R_M/ckpt_s100000.pt") + ap.add_argument("--tag", default="R_M_s100000") + ap.add_argument("--chunk", type=int, default=8) + ap.add_argument("--k-success", type=int, default=10) + ap.add_argument("--seed", type=int, default=0) + ap.add_argument("--in-ram", type=int, default=1) + ap.add_argument("--out", required=True) + a = ap.parse_args() + + import torch, h5py + from data import LiberoRSMData + from is_ope import load_critic + + dev = "cuda" if torch.cuda.is_available() else "cpu" + os.makedirs(os.path.dirname(os.path.abspath(a.out)) or ".", exist_ok=True) + d = LiberoRSMData(a.cache, chunk=a.chunk, k_success=a.k_success, seed=a.seed, + stratify_success=False, in_ram=bool(a.in_ram), reward_mode="dense") + D = int(d.feat_dim) + enc, rew, flow, rms, cfg = load_critic(a.ckpt, D, d.n_task, dev, data=d) + edge_from = np.load(f"{a.cache}/edge_from.i16.npy") + _meta = np.load(os.path.join(a.cache, "meta.npz"), allow_pickle=True) + src2ep = {str(s): i for i, s in enumerate(_meta["ep_src"])} + route = {} + with h5py.File(a.hdf5, "r") as f: + g5 = f["data"] + for k in g5: + e = src2ep.get("episode_%06d" % int(g5[k].attrs["episode_index"])) + if e is not None: + route[int(e)] = str(g5[k].attrs.get("path", "?")) + out = {"ckpt": a.ckpt, "tag": a.tag, "D": D, "flow_width": cfg.get("flow_width"), "splits": {}} + for split, eps in (("train", d.train_eps), ("val", d.val_eps)): + rows = np.concatenate([np.arange(int(d.ep_from[e]), int(d.ep_to[e])) for e in sorted(eps)]) + rep = np.concatenate([np.full(int(d.ep_to[e]) - int(d.ep_from[e]), e, np.int64) + for e in sorted(eps)]) + m = edge_from[rows] == 2 + rows, rep = rows[m], rep[m] + lg = [] + with torch.no_grad(): + for i in range(0, len(rows), 4096): + X = torch.from_numpy(d._feat(rows[i:i + 4096])).to(dev) + tk = torch.from_numpy(d.ep_task[rep[i:i + 4096]]).long().to(dev) + lg.append(rew(X, tk).float().view(-1).cpu().numpy()) + lg = np.concatenate(lg) + goal = np.array([route.get(int(e), "?") == GOAL_PATH for e in rep]) + pos = lg > 0 + tp, fp = int((pos & goal).sum()), int((pos & ~goal).sum()) + fn, tn = int((~pos & goal).sum()), int((~pos & ~goal).sum()) + ueps = sorted(set(int(x) for x in rep)) + per_ep = {} + for e in ueps: + s = rep == e + per_ep[str(e)] = {"n": int(s.sum()), "frac_pos": float(pos[s].mean()), + "goal": bool(goal[s][0]), "mean_logit": float(lg[s].mean())} + mixed = [k for k, v in per_ep.items() if 1e-9 < v["frac_pos"] < 1 - 1e-9] + out["splits"][split] = { + "n_eps": len(ueps), "n_S2_frames": int(len(rows)), + "goal_frame_frac": float(goal.mean()), + "goal_ep_frac": float(np.mean([v["goal"] for v in per_ep.values()])), + "frac_pos_frames": float(pos.mean()), + "confusion": {"tp": tp, "fp": fp, "fn": fn, "tn": tn}, + "accuracy": float((tp + tn) / max(len(rows), 1)), + "precision": float(tp / max(tp + fp, 1)), "recall": float(tp / max(tp + fn, 1)), + "n_eps_mixed_sign": len(mixed), + "mean_abs_logit": float(np.abs(lg).mean()), + "frac_abs_logit_lt_10": float((np.abs(lg) < 10).mean()), + "note": "sign(logit) at an S2 frame vs whether that frame's episode is on the goal " + "route. n_eps_mixed_sign counts episodes whose S2 block is NOT sign-unanimous; " + "0 means the head assigns one label to the whole episode.", + } + c = out["splits"][split] + print(f"[conf] {split}: S2 frames {c['n_S2_frames']} in {c['n_eps']} eps | goal frames " + f"{c['goal_frame_frac']:.3f} eps {c['goal_ep_frac']:.3f} | pos {c['frac_pos_frames']:.3f} " + f"| tp/fp/fn/tn {tp}/{fp}/{fn}/{tn} | acc {c['accuracy']:.3f} prec {c['precision']:.3f} " + f"rec {c['recall']:.3f} | mixed-sign eps {c['n_eps_mixed_sign']}", flush=True) + tmp = a.out + f".tmp.{os.getpid()}" + with open(tmp, "w") as f: + json.dump(out, f, indent=1) + os.replace(tmp, a.out) + print(f"[conf] wrote {a.out}", flush=True) + + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/real/rise_replay_eval.py b/rsm_rise/scripts/real/rise_replay_eval.py new file mode 100644 index 0000000000000000000000000000000000000000..4eafd1b09d096c86e81a7a04d669191d177e8139 --- /dev/null +++ b/rsm_rise/scripts/real/rise_replay_eval.py @@ -0,0 +1,83 @@ +#!/usr/bin/env python +"""Open-loop replay of a robomimic (our stack: S0B / S0Aidql / S3H1) checkpoint on the held-out cooking episodes +(#263 sanity check for column 2), the same metrics as scripts/real/openpi_replay_eval.py: +per-dim MSE (gripper separately), xyz L2 of the first action and over the executed chunk (cm), per-segment errors. +Obs history of To=2 frames is built from the hdf5 (mask/valid demos), images CHW/255 as ObsUtils.process_obs does. + env/bin/python scripts/real/rise_replay_eval.py --ckpt --out [--stride 10] +""" +import argparse, json, time, collections +from pathlib import Path +import numpy as np, h5py, torch + +ROOT = "/proj/dmfexp/zwhong/rsm_rise" +NAMES = ("x", "y", "z", "r0", "r1", "r2", "r3", "r4", "r5", "grip") +GRIP_MID = 0.0357 + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--ckpt", required=True) + ap.add_argument("--out", required=True) + ap.add_argument("--hdf5", default=f"{ROOT}/data/raw/cooking_v5_expert_suboptimal.hdf5") + ap.add_argument("--mask", default="valid") + ap.add_argument("--stride", type=int, default=10) + ap.add_argument("--batch", type=int, default=64) + ap.add_argument("--max-eps", type=int, default=0) + args = ap.parse_args() + import robomimic.utils.file_utils as FileUtils, robomimic.utils.tensor_utils as TensorUtils, robomimic.utils.obs_utils as ObsUtils + dev = torch.device("cuda") + policy, ckpt = FileUtils.policy_from_checkpoint(ckpt_path=args.ckpt, device=dev, verbose=False) + algo = policy.policy; algo.set_eval() + obs_keys = list(algo.obs_shapes.keys()); To = algo.algo_config.horizon.observation_horizon + Ta = algo.algo_config.horizon.action_horizon; Tp = algo.algo_config.horizon.prediction_horizon + print(f"[replay] obs_keys={obs_keys} To={To} Ta={Ta} Tp={Tp} use_bc={algo.algo_config.use_bc}", flush=True) + out = Path(args.out); out.mkdir(parents=True, exist_ok=True) + per_ep, seg_err, t0 = [], collections.defaultdict(list), time.time() + with h5py.File(args.hdf5, "r") as f: + # actions in the hdf5 are min-max normalised to [-1,1] (scripts/real/normalize_hdf5_actions.py); compare RAW + lo = np.array(json.loads(f["data"].attrs["action_min"])); hi = np.array(json.loads(f["data"].attrs["action_max"])) + unnorm = lambda n: (n + 1.0) / 2.0 * (hi - lo) + lo + demos = [x.decode() for x in f["mask"][args.mask][()]] + if args.max_eps: demos = demos[:args.max_eps] + for d in demos: + g = f["data"][d]; T = int(g.attrs["num_samples"]); A = g["actions_raw"][()] + obs = {k: g["obs"][k][()] for k in obs_keys} + ef, et = g["annot"]["edge_from"][()], g["annot"]["edge_to"][()] + idxs = list(range(0, T - Ta, args.stride)); preds = [] + for b0 in range(0, len(idxs), args.batch): + bi = idxs[b0:b0 + args.batch] + ob = {} + for k in obs_keys: + hist = np.stack([np.stack([obs[k][max(0, i - (To - 1) + j)] for j in range(To)]) for i in bi]) # [B,To,...] + x = torch.from_numpy(hist).to(dev).float() + if ObsUtils.key_is_obs_modality(k, "rgb"): + x = ObsUtils.process_obs(x, obs_modality="rgb") # [B,To,C,H,W] in [0,1] + ob[k] = x + with torch.no_grad(): + na = algo._sample_action_chunks(ob) # [B,Tp,ac] (normalised? check) + if isinstance(na, tuple): na = na[0] + preds.append(unnorm(na[:, :Ta, :].float().cpu().numpy())) + P = np.concatenate(preds); G = np.stack([A[i:i + Ta] for i in idxs]); dlt = P - G + xyz = np.linalg.norm(dlt[..., :3], axis=-1) + rec = {"demo": d, "path": str(g.attrs["path"]), "provenance": str(g.attrs["provenance"]), "T": T, "n": len(P), + "xyz_l2_first_cm": 100 * float(xyz[:, 0].mean()), "xyz_l2_chunk_cm": 100 * float(xyz.mean()), + "xyz_l2_first_max_cm": 100 * float(xyz[:, 0].max()), + "rot6d_l2_first": float(np.linalg.norm(dlt[:, 0, 3:9], axis=-1).mean()), + "grip_abs_first_mm": 1000 * float(np.abs(dlt[:, 0, 9]).mean()), + "grip_bin_acc": float(((P[..., 9] > GRIP_MID) == (G[..., 9] > GRIP_MID)).mean())} + for k, n in enumerate(NAMES): rec[f"mse_{n}"] = float((dlt[..., k] ** 2).mean()) + for j, i in enumerate(idxs): seg_err[f"{ef[i]}->{et[i]}"].append(100 * xyz[j, 0]) + per_ep.append(rec) + print(f"[replay] {d} {rec['path']} n={rec['n']} xyz_first={rec['xyz_l2_first_cm']:.2f}cm chunk={rec['xyz_l2_chunk_cm']:.2f}cm " + f"grip_acc={rec['grip_bin_acc']:.3f} {time.time()-t0:.0f}s", flush=True) + pooled = {k: float(np.mean([r[k] for r in per_ep])) for k in per_ep[0] if isinstance(per_ep[0][k], float)} + pooled["xyz_l2_first_cm_worst_episode"] = float(max(r["xyz_l2_first_cm"] for r in per_ep)) + seg = {k: {"n": len(v), "mean_cm": float(np.mean(v)), "p90_cm": float(np.percentile(v, 90))} for k, v in sorted(seg_err.items())} + res = {"ckpt": args.ckpt, "mask": args.mask, "stride": args.stride, "n_episodes": len(per_ep), "pooled_episode_mean": pooled, + "per_segment_xyz_first": seg, "per_episode": per_ep} + json.dump(res, open(out / "replay_eval.json", "w"), indent=1) + print("[replay] pooled:", json.dumps(pooled, indent=1)); print("[replay] per segment:", json.dumps(seg, indent=1)) + + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/real/rr_cpu_stitch_endpoints.sh b/rsm_rise/scripts/real/rr_cpu_stitch_endpoints.sh new file mode 100644 index 0000000000000000000000000000000000000000..5f1a0c3eeb955af69deb10a53089b093d63654b8 --- /dev/null +++ b/rsm_rise/scripts/real/rr_cpu_stitch_endpoints.sh @@ -0,0 +1,9 @@ +#!/usr/bin/env bash +# gen_q#271->#270: retrieval renders of the stitching-chain endpoints (CPU; decodes LeRobot mp4). +set -uo pipefail +ROOT=/proj/dmfexp/zwhong/rsm_rise +source $ROOT/scripts/env.sh +export CUDA_VISIBLE_DEVICES="" MPLBACKEND=Agg MUJOCO_GL=disable PYTHONUNBUFFERED=1 OMP_NUM_THREADS=8 +echo "[endpoints] host=$(hostname) $(date) args=$*" +python $ROOT/scripts/real/render_stitch_endpoints.py "$@" +rc=$?; echo "[endpoints] rc=$rc $(date)"; exit $rc diff --git a/rsm_rise/scripts/real/rr_rsm_aug.sh b/rsm_rise/scripts/real/rr_rsm_aug.sh new file mode 100644 index 0000000000000000000000000000000000000000..a4d6fbda3dcb8c7c9014e369ada94ef2c23525f3 --- /dev/null +++ b/rsm_rise/scripts/real/rr_rsm_aug.sh @@ -0,0 +1,48 @@ +#!/usr/bin/env bash +# AUG_SUCC (gen_q#279): one successor-model cell with RISE-style COUNTERFACTUAL ACTION AUGMENTATION. +# usage: rr_rsm_aug.sh [extra train_rsm.py args...] +# +# Deliberately NOT a new cell inside scripts/rr_rsm.sh: that file is shared with the other streams and +# its OUT dir is derived from the cell name, so a typo there would overwrite the flagship R_M checkpoint +# the whole real-robot analysis is read off. Every flag below is copied verbatim from rr_rsm.sh's +# `R_M` cell (width 1024, depth 4, chunk 8, batch 4096, lr 3e-4, ema 0.995, 100k steps, dense/bce reward, +# w-actcon 0.5, sample-clip 10) plus scripts/stage1_config.env, so the ONLY difference from R_M is the +# three augmentation flags. Out dir: runs/real_cooking_v5/rsm/AUG__t_s. +set -euo pipefail +MODE="$1"; THR="$2"; SEED="$3"; shift 3 +ROOT=/proj/dmfexp/zwhong/rsm_rise +RSM=/proj/dmfexp/zwhong/projs/issue_resolver_richardrl/gen_q_rsm/rsm_libero +TASK=real_cooking_v5 +# ONE TABLE PER SEED. data.py's --seed permutes the episode split as well as the init +# (rr_rsm.sh:108), so a seed-0 table used by a seed-1 run would put held-out episodes into the +# augmented ACTION channel -- data.py's split guard refuses it (that is what killed pack 1881633). +# TASK 4 adds two OPTIONAL env overrides, both empty by default, so every cell launched before this +# edit (and every requeued cell of packs 1883604-1883607) resolves to exactly the same table and the +# same OUT dir as before: +# RR_AUG_TABLE -- use a different pair table (the JUNCTION table from build_junction_pairs.py) +# RR_TAG -- override the cell name, so a capped/junction arm cannot land on an existing +# checkpoint dir (the tag does NOT encode the extra args, so without this a +# --augment-frac-cap rerun would overwrite the uncapped cell) +if [ -n "${RR_AUG_TABLE:-}" ]; then TABLE="$RR_AUG_TABLE" +elif [ "$SEED" = "0" ]; then TABLE="$ROOT/data/derived/augsucc/aug_knn_ee.npz" +else TABLE="$ROOT/data/derived/augsucc/aug_knn_ee_s${SEED}.npz"; fi +[ -f "$TABLE" ] || { echo "missing neighbour table $TABLE (build it with build_aug_knn.py --seed $SEED)"; exit 4; } +source "$ROOT/wandb_env.sh" || true +STAGE1_EXTRA="" +[ -r "$ROOT/scripts/stage1_config.env" ] && source "$ROOT/scripts/stage1_config.env" +PY="$ROOT/venv_rsm/bin/python" +TAG="${RR_TAG:-AUG_${MODE}_t$(echo "$THR" | tr '.' 'p')_s${SEED}}" +OUT="$ROOT/runs/$TASK/rsm/$TAG"; mkdir -p "$OUT" +case "$OUT" in *"/rsm/AUG_"*|*"/rsm/AUGCAP_"*|*"/rsm/JUNC_"*) ;; + *) echo "refusing to write outside an AUG_/AUGCAP_/JUNC_ dir: $OUT"; exit 3;; esac +echo "[rr_rsm_aug] host=$(hostname) cell=$TAG mode=$MODE thr=$THR seed=$SEED table=$TABLE $(date)" +nvidia-smi --query-gpu=name,memory.total --format=csv || true +# shellcheck disable=SC2086 +exec "$PY" "$RSM/train_rsm.py" --cache "$ROOT/cache/$TASK" --out "$OUT" \ + --enc identity --append-proprio 0 --reward-mode dense --reward-loss bce \ + --flow-width 1024 --flow-depth 4 --chunk 8 --beta-lo 0.95 --beta-hi 0.99 --beta-q 0.98 \ + --w-actcon 0.5 --var-floor 0 --warmup-reward 0 \ + --batch 4096 --lr 3e-4 --ema 0.995 --steps 100000 --save-every 10000 --eval-every 5000 \ + --eval-minmse-n 16 --eval-nnl1-k 16 --eval-nnl1-b 256 --sample-clip 10 --in-ram 1 --seed "$SEED" \ + --action-augment "$THR" --augment-mode "$MODE" --augment-table "$TABLE" --augment-neighbors 15 \ + --wandb-name "${TASK}/rsm/${TAG}" $STAGE1_EXTRA "$@" diff --git a/rsm_rise/scripts/real/rsm_feat_live_vs_cache.py b/rsm_rise/scripts/real/rsm_feat_live_vs_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..824c941af391cc798e6113579e273a6659260e32 --- /dev/null +++ b/rsm_rise/scripts/real/rsm_feat_live_vs_cache.py @@ -0,0 +1,136 @@ +#!/usr/bin/env python +"""ACT_COND run 6 (gen_q#278): is a LIVE DINO featurisation of the raw frames the same state the RSM +read-out was measured on? + +Run 6 wired `obs["rsm_feat"]` for the REPLAY backend as a cache lookup by (episode, frame), which is +byte-identical to the measurement scripts by construction. The FR3 backend has no cache -- it must +featurise the camera frames live -- and a wrong featuriser there is a SILENT state bug: the model still +returns a number, it is just a number about the wrong state. `rsm_scorer.PooledDinoState` is the +tempting reuse and it is WRONG for this corpus (RISE's DinoV2Core pooling, sim camera keys), whereas +`twin_rollout.StateTracker.feat` already implements the cache builder's own recipe -- +cache/real_cooking_v5/PACK.json: CLS + GeM(clamp 1e-6, pow 4, avg 16x16, pow 1/4) per camera, +crop_mode 'square' = Resize((224,224)) + ImageNet Normalize. + +This script MEASURES that claim instead of asserting it by reading, on the replay episodes where both +paths are available, and then measures the only consequence that matters: does the live state pick the +SAME candidate as the cache state? Feature error is a diagnostic; decision agreement is the result. + +Fails loudly (exit 3) if decision agreement is below --min-agree. +""" +from __future__ import annotations +import argparse, json, os, sys, time +from pathlib import Path +import numpy as np + +ROOT = "/proj/dmfexp/zwhong/rsm_rise" +sys.path.insert(0, f"{ROOT}/scripts/real") + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--cache", default=f"{ROOT}/cache/real_cooking_v5") + ap.add_argument("--hdf5", default=f"{ROOT}/data/raw/cooking_v5_expert_suboptimal.hdf5") + ap.add_argument("--state-head", default=f"{ROOT}/runs/real/state_head_w25/state_head.pt") + ap.add_argument("--rsm-ckpt", default=f"{ROOT}/runs/real_cooking_v5/rsm/R_M/ckpt_s100000.pt") + ap.add_argument("--hop-ckpt", default=f"{ROOT}/runs/real_cooking_v5/hop/gauss/policy_r1.pt") + ap.add_argument("--episodes", default="7,12,60") + ap.add_argument("--n-frames", type=int, default=12, help="frames per episode, evenly spaced") + ap.add_argument("--n-cand", type=int, default=16) + ap.add_argument("--horizon", type=int, default=8) + ap.add_argument("--particles", type=int, default=16) + ap.add_argument("--beta", type=float, default=0.99) + ap.add_argument("--gamma", type=float, default=0.999) + ap.add_argument("--temperature", type=float, default=25.0) + ap.add_argument("--min-agree", type=float, default=0.90) + ap.add_argument("--seed", type=int, default=0) + ap.add_argument("--out", required=True) + a = ap.parse_args() + t0 = time.time() + import h5py, torch + from twin_rollout import StateTracker, ReplayEnv, CacheRsmFeat, Scorer + rng = np.random.default_rng(a.seed) + os.makedirs(os.path.dirname(a.out) or ".", exist_ok=True) + + feat = CacheRsmFeat(a.cache) + tracker = StateTracker(a.state_head) # loaded for its ENCODER; the classifier is unused here + assert tracker.model is not None, "no state head -> no DINO encoder to test the live path with" + eps = [int(x) for x in a.episodes.split(",") if x] + + f = h5py.File(a.hdf5, "r"); d = f["data"] + lo = np.array(json.loads(d.attrs["action_min"]), np.float32) + hi = np.array(json.loads(d.attrs["action_max"]), np.float32) + # candidate pool: logged chunks drawn from anywhere in the corpus, so the 16 candidates span stages + pool = [] + keys = sorted(d, key=lambda k: int(k.split("_")[1])) + for k in rng.choice(keys, size=min(40, len(keys)), replace=False): + A = np.asarray((d[k]["actions_raw"] if "actions_raw" in d[k] else d[k]["actions"])[()], np.float32) + if len(A) > a.horizon + 2: + t = int(rng.integers(0, len(A) - a.horizon)) + pool.append(A[t:t + a.horizon]) + pool = np.stack(pool[:max(a.n_cand, 8)]) + f.close() + + sc = Scorer("rsm", lo, hi, rsm_ckpt=a.rsm_ckpt, rsm_hop_ckpt=a.hop_ckpt, seed=a.seed, + rsm_mode="chain", rsm_beta=a.beta, rsm_gamma=a.gamma, rsm_particles=a.particles, + rsm_dim=feat.d, rsm_score_kind="prob", rsm_temperature=a.temperature) + dev = sc.rsm.device + + rows, agree, sp = [], [], [] + for ep in eps: + env = ReplayEnv(ep, a.hdf5, rsm_feat=feat) + n = len(env.S) + ts = np.unique(np.linspace(0, n - 1, a.n_frames).astype(int)) + for t in ts: + env.i = int(t) + o = env._obs() + with torch.no_grad(): + live_dino = tracker.feat(o["images"]).cpu().numpy()[0].astype(np.float32) # [1536] + cache_dino = np.asarray(feat.z[int(feat.ep_from[ep]) + int(t)], np.float32) + # the state the scorer actually sees: concat proprio, z-score, clip (data.py:_feat) + live_x = np.clip((np.concatenate([live_dino, np.asarray(o["state"], np.float32)]) - feat.mu) + / feat.sd, -feat.zclip, feat.zclip).astype(np.float32) + cache_x = feat(ep, int(t)) + cand = pool[:a.n_cand] + seed = int(rng.integers(1 << 30)) # SAME seed both sides: common random numbers + with torch.no_grad(): + s_live = sc.rsm.score(torch.as_tensor(live_x, device=dev)[None], cand, seed=seed).cpu().numpy() + s_cache = sc.rsm.score(torch.as_tensor(cache_x, device=dev)[None], cand, seed=seed).cpu().numpy() + rl, rc = np.argsort(np.argsort(-s_live)), np.argsort(np.argsort(-s_cache)) + rho = float(np.corrcoef(rl, rc)[0, 1]) if rl.std() > 0 and rc.std() > 0 else float("nan") + same = bool(np.argmax(s_live) == np.argmax(s_cache)) + agree.append(same); sp.append(rho) + rows.append({ + "ep": int(ep), "t": int(t), + "dino_max_abs": float(np.abs(live_dino - cache_dino).max()), + "dino_rel_l2": float(np.linalg.norm(live_dino - cache_dino) / (np.linalg.norm(cache_dino) + 1e-12)), + "dino_cos": float(live_dino @ cache_dino / + (np.linalg.norm(live_dino) * np.linalg.norm(cache_dino) + 1e-12)), + "x_max_abs_sd": float(np.abs(live_x - cache_x).max()), # in z-score units + "argmax_same": same, "rank_spearman": rho, + "score_max_live": float(s_live.max()), "score_max_cache": float(s_cache.max()), + }) + print(f"[live] ep {ep}: {len(ts)} frames, agree so far {np.mean(agree):.3f} {time.time()-t0:.0f}s", flush=True) + + g = lambda k: np.array([r[k] for r in rows], float) + summary = { + "n_frames": len(rows), "episodes": eps, "n_cand": int(a.n_cand), + "readout": {"mode": "chain", "beta": a.beta, "gamma": a.gamma, + "particles": a.particles, "score_kind": "prob", "temperature": a.temperature}, + "dino_max_abs": {"max": float(g("dino_max_abs").max()), "mean": float(g("dino_max_abs").mean())}, + "dino_rel_l2": {"max": float(g("dino_rel_l2").max()), "mean": float(g("dino_rel_l2").mean())}, + "dino_cos": {"min": float(g("dino_cos").min()), "mean": float(g("dino_cos").mean())}, + "x_max_abs_sd": {"max": float(g("x_max_abs_sd").max()), "mean": float(g("x_max_abs_sd").mean())}, + "argmax_agreement": float(np.mean(agree)), + "rank_spearman": {"mean": float(np.nanmean(sp)), "min": float(np.nanmin(sp))}, + "wall_s": time.time() - t0, + } + json.dump({"summary": summary, "rows": rows}, open(a.out, "w"), indent=1) + print("[live] " + json.dumps(summary, indent=1), flush=True) + ok = summary["argmax_agreement"] >= a.min_agree + print(f"[live] {'PASS' if ok else 'FAIL'}: argmax agreement {summary['argmax_agreement']:.3f} " + f"vs min {a.min_agree}", flush=True) + sys.exit(0 if ok else 3) + + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/real/run/rr_concleader53b.sh b/rsm_rise/scripts/real/run/rr_concleader53b.sh new file mode 100644 index 0000000000000000000000000000000000000000..f366d6feac701a80aac09a95edd39564baf17505 --- /dev/null +++ b/rsm_rise/scripts/real/run/rr_concleader53b.sh @@ -0,0 +1,9 @@ +#!/bin/bash +set -euo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +export OMP_NUM_THREADS=1 +venv_rsm/bin/python scripts/real/actcond_conc_leaderboard.py --tol tol_0p02 \ + --out status/real/ACT_COND/CONC_LEADER_run53b.json +echo "########## tol 0.05 robustness ##########" +venv_rsm/bin/python scripts/real/actcond_conc_leaderboard.py --tol tol_0p05 \ + --out status/real/ACT_COND/CONC_LEADER_run53b_tol05.json diff --git a/rsm_rise/scripts/real/run/rr_concsweep53.sh b/rsm_rise/scripts/real/run/rr_concsweep53.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3dc69a9adad2be616bca0b511c89317a3950280 --- /dev/null +++ b/rsm_rise/scripts/real/run/rr_concsweep53.sh @@ -0,0 +1,8 @@ +#!/bin/bash +set -euo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +export OMP_NUM_THREADS=1 OPENBLAS_NUM_THREADS=1 MKL_NUM_THREADS=1 +exec venv_rsm/bin/python scripts/real/actcond_conc_sweep.py \ + --root status/real/rankctrl \ + --out status/real/ACT_COND/CONC_SWEEP_run53.json \ + --procs 8 --min-shared 8 diff --git a/rsm_rise/scripts/real/run/rr_frozen48.sh b/rsm_rise/scripts/real/run/rr_frozen48.sh new file mode 100644 index 0000000000000000000000000000000000000000..feed36e5229fe7f1e047e8cd4810786783fe8220 --- /dev/null +++ b/rsm_rise/scripts/real/run/rr_frozen48.sh @@ -0,0 +1,5 @@ +#!/bin/bash +set -euo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +venv_rsm/bin/python scripts/real/actcond_frozen.py \ + --out /proj/dmfexp/zwhong/rsm_rise/status/real/ACT_COND/FROZEN_run48.json diff --git a/rsm_rise/scripts/real/run/rr_goaldir.sh b/rsm_rise/scripts/real/run/rr_goaldir.sh new file mode 100644 index 0000000000000000000000000000000000000000..047243d7815a28f19f42ac265b161351b17fd059 --- /dev/null +++ b/rsm_rise/scripts/real/run/rr_goaldir.sh @@ -0,0 +1,5 @@ +#!/bin/bash +set -euo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +exec venv_rsm/bin/python scripts/real/actcond_goal_directedness.py \ + --out status/real/ACT_COND/GOAL_DIRECTED_run39.json diff --git a/rsm_rise/scripts/real/run/rr_hauc46.sh b/rsm_rise/scripts/real/run/rr_hauc46.sh new file mode 100644 index 0000000000000000000000000000000000000000..fe9f0315f6db772aea4179f9c719c9fcdd9b47e0 --- /dev/null +++ b/rsm_rise/scripts/real/run/rr_hauc46.sh @@ -0,0 +1,5 @@ +#!/bin/bash +set -euo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +venv_rsm/bin/python scripts/real/actcond_headline_auc.py \ + --out /proj/dmfexp/zwhong/rsm_rise/status/real/ACT_COND/HEADLINE_AUC_run46.json diff --git a/rsm_rise/scripts/real/run/rr_lift_reconcile.sh b/rsm_rise/scripts/real/run/rr_lift_reconcile.sh new file mode 100644 index 0000000000000000000000000000000000000000..a50a42cae6008989e5512260ea772c410ba8ab76 --- /dev/null +++ b/rsm_rise/scripts/real/run/rr_lift_reconcile.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -euo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +exec venv_rsm/bin/python scripts/real/actcond_lift_reconcile.py rsm diff --git a/rsm_rise/scripts/real/run/rr_prefix45.sh b/rsm_rise/scripts/real/run/rr_prefix45.sh new file mode 100644 index 0000000000000000000000000000000000000000..d1b8645c22342777b44540951fa239520c3c44f4 --- /dev/null +++ b/rsm_rise/scripts/real/run/rr_prefix45.sh @@ -0,0 +1,5 @@ +#!/bin/bash +set -euo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +venv_rsm/bin/python scripts/real/actcond_prefix.py \ + --out /proj/dmfexp/zwhong/rsm_rise/status/real/ACT_COND/PREFIX_run45.json diff --git a/rsm_rise/scripts/real/run/rr_prefix46.sh b/rsm_rise/scripts/real/run/rr_prefix46.sh new file mode 100644 index 0000000000000000000000000000000000000000..d095d4994cd0300c9e20fc7689cb6dcd5de26af1 --- /dev/null +++ b/rsm_rise/scripts/real/run/rr_prefix46.sh @@ -0,0 +1,5 @@ +#!/bin/bash +set -euo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +venv_rsm/bin/python scripts/real/actcond_prefix_cachewide.py \ + --out /proj/dmfexp/zwhong/rsm_rise/status/real/ACT_COND/PREFIX_CACHEWIDE_run46.json diff --git a/rsm_rise/scripts/real/run/rr_readout.sh b/rsm_rise/scripts/real/run/rr_readout.sh new file mode 100644 index 0000000000000000000000000000000000000000..ffbc18fd36fc4cee4f82b1c0844908a59120386f --- /dev/null +++ b/rsm_rise/scripts/real/run/rr_readout.sh @@ -0,0 +1,5 @@ +#!/bin/bash +set -euo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +exec venv_rsm/bin/python scripts/real/actcond_readout.py \ + --out status/real/ACT_COND/READOUT_run40.json diff --git a/rsm_rise/scripts/real/run/rr_readout2.sh b/rsm_rise/scripts/real/run/rr_readout2.sh new file mode 100644 index 0000000000000000000000000000000000000000..d42862b2fc35035d76b75cfa41696ee620a78d48 --- /dev/null +++ b/rsm_rise/scripts/real/run/rr_readout2.sh @@ -0,0 +1,5 @@ +#!/bin/bash +set -euo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +exec venv_rsm/bin/python scripts/real/actcond_readout.py --reuse \ + --out status/real/ACT_COND/READOUT_run40.json diff --git a/rsm_rise/scripts/real/run/rr_readout2_retry.sh b/rsm_rise/scripts/real/run/rr_readout2_retry.sh new file mode 100644 index 0000000000000000000000000000000000000000..c80ec0c13df6f3be11c4ada5bceb9562e8a81acc --- /dev/null +++ b/rsm_rise/scripts/real/run/rr_readout2_retry.sh @@ -0,0 +1,20 @@ +#!/bin/bash +# Retry-submit the run-40 read-out aggregation replay until LSF answers. +# Writes the job id to status/real/ACT_COND/READOUT_run40.jobid on success. +cd /proj/dmfexp/zwhong/rsm_rise +STAMP=status/real/ACT_COND/READOUT_run40.jobid +LOG=logs/lsf/rr_readout2_retry.log +for i in $(seq 1 30); do + if [ -s "$STAMP" ]; then echo "$(date -u +%FT%TZ) already submitted: $(cat $STAMP)" >> "$LOG"; exit 0; fi + OUT=$(timeout 60 bsub -G grp_runtime -q normal -n 8 -M 64G \ + -J rr_cpu_actcond_readout2 \ + -o logs/lsf/rr_cpu_actcond_readout2.%J.out \ + -e logs/lsf/rr_cpu_actcond_readout2.%J.err \ + scripts/real/run/rr_readout2.sh 2>&1) + echo "$(date -u +%FT%TZ) try $i: $OUT" >> "$LOG" + JID=$(echo "$OUT" | grep -oE 'Job <[0-9]+>' | grep -oE '[0-9]+' | head -1) + if [ -n "$JID" ]; then echo "$JID" > "$STAMP"; echo "$(date -u +%FT%TZ) SUBMITTED $JID" >> "$LOG"; exit 0; fi + sleep 120 +done +echo "$(date -u +%FT%TZ) gave up after 30 tries" >> "$LOG" +exit 1 diff --git a/rsm_rise/scripts/real/run/rr_readout_dod.sh b/rsm_rise/scripts/real/run/rr_readout_dod.sh new file mode 100644 index 0000000000000000000000000000000000000000..3226d0d7f9febfac29865b3040489254f9456038 --- /dev/null +++ b/rsm_rise/scripts/real/run/rr_readout_dod.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -euo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +exec venv_rsm/bin/python scripts/real/actcond_readout_dod.py diff --git a/rsm_rise/scripts/real/run/rr_readout_fresh43.sh b/rsm_rise/scripts/real/run/rr_readout_fresh43.sh new file mode 100644 index 0000000000000000000000000000000000000000..1d85205c3c3551682656cdf88d80de19ee32075e --- /dev/null +++ b/rsm_rise/scripts/real/run/rr_readout_fresh43.sh @@ -0,0 +1,11 @@ +#!/bin/bash +# RUN 43: a FRESH rescan of the edge cache (no --reuse), now that the 7 dirs that were still being +# written during run 40 have been static for >2h, followed by the run-42 DoD on that fresh cache. +# Writes to NEW paths so run 40's / run 42's artefacts are never clobbered. +set -euo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +venv_rsm/bin/python scripts/real/actcond_readout.py \ + --out status/real/ACT_COND/READOUT_run43fresh.json +venv_rsm/bin/python scripts/real/actcond_readout_dod.py \ + --rows status/real/ACT_COND/READOUT_run43fresh.rows.json \ + --out status/real/ACT_COND/READOUT_DOD_run43fresh.json diff --git a/rsm_rise/scripts/real/run/rr_routeasi51.sh b/rsm_rise/scripts/real/run/rr_routeasi51.sh new file mode 100644 index 0000000000000000000000000000000000000000..7b2fcfb8f12309bf2ebaeb3003169708140bf096 --- /dev/null +++ b/rsm_rise/scripts/real/run/rr_routeasi51.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +exec venv_rsm/bin/python scripts/real/actcond_route_asi.py \ + --src status/real/logged_action_rank_G999 \ + --out status/real/ACT_COND/ROUTE_ASI_run51.json diff --git a/rsm_rise/scripts/real/run/rr_routeasi52.sh b/rsm_rise/scripts/real/run/rr_routeasi52.sh new file mode 100644 index 0000000000000000000000000000000000000000..60b415c81f130872627036ce5557d5e0ec8e95d2 --- /dev/null +++ b/rsm_rise/scripts/real/run/rr_routeasi52.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +exec venv_rsm/bin/python scripts/real/actcond_route_asi_multi.py \ + --root status/real/rankctrl \ + --out status/real/ACT_COND/ROUTE_ASI_run52b.json diff --git a/rsm_rise/scripts/real/run/rr_senspays.sh b/rsm_rise/scripts/real/run/rr_senspays.sh new file mode 100644 index 0000000000000000000000000000000000000000..2286a88ee03c91e5a180a156c0f9d118994fe1e6 --- /dev/null +++ b/rsm_rise/scripts/real/run/rr_senspays.sh @@ -0,0 +1,5 @@ +#!/bin/bash +set -euo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +exec venv_rsm/bin/python scripts/real/actcond_sensitivity_pays.py \ + --out status/real/ACT_COND/SENS_PAYS_run38.json diff --git a/rsm_rise/scripts/real/run/rr_topk47.sh b/rsm_rise/scripts/real/run/rr_topk47.sh new file mode 100644 index 0000000000000000000000000000000000000000..9111e60348010a785e44e5612388b2115cba556b --- /dev/null +++ b/rsm_rise/scripts/real/run/rr_topk47.sh @@ -0,0 +1,5 @@ +#!/bin/bash +set -euo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +venv_rsm/bin/python scripts/real/actcond_topk.py \ + --out /proj/dmfexp/zwhong/rsm_rise/status/real/ACT_COND/TOPK_run47.json diff --git a/rsm_rise/scripts/real/run/rr_topk48.sh b/rsm_rise/scripts/real/run/rr_topk48.sh new file mode 100644 index 0000000000000000000000000000000000000000..6f3945367203d9dbea1265d60d4a968a349c6bd9 --- /dev/null +++ b/rsm_rise/scripts/real/run/rr_topk48.sh @@ -0,0 +1,5 @@ +#!/bin/bash +set -euo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +venv_rsm/bin/python scripts/real/actcond_topk.py \ + --out /proj/dmfexp/zwhong/rsm_rise/status/real/ACT_COND/TOPK_run48frozen.json diff --git a/rsm_rise/scripts/real/run/rr_topkfig49.sh b/rsm_rise/scripts/real/run/rr_topkfig49.sh new file mode 100644 index 0000000000000000000000000000000000000000..040f693ebbcea614cb95b26dc2d0b26be2786233 --- /dev/null +++ b/rsm_rise/scripts/real/run/rr_topkfig49.sh @@ -0,0 +1,6 @@ +#!/usr/bin/env bash +set -euo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +exec venv_rsm/bin/python scripts/real/actcond_topk_figure.py \ + --src status/real/ACT_COND/TOPK_run48frozen.json \ + --out status/real/ACT_COND/fig/topk_contribution diff --git a/rsm_rise/scripts/real/run/rr_vintage44.sh b/rsm_rise/scripts/real/run/rr_vintage44.sh new file mode 100644 index 0000000000000000000000000000000000000000..093cf788377b7cf41c71a6d0d9af1a7becc6bc95 --- /dev/null +++ b/rsm_rise/scripts/real/run/rr_vintage44.sh @@ -0,0 +1,5 @@ +#!/bin/bash +set -euo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +venv_rsm/bin/python scripts/real/actcond_vintage.py \ + --out /proj/dmfexp/zwhong/rsm_rise/status/real/ACT_COND/VINTAGE_run44.json diff --git a/rsm_rise/scripts/real/run_271_docs.sh b/rsm_rise/scripts/real/run_271_docs.sh new file mode 100644 index 0000000000000000000000000000000000000000..1e6af8d8f7e71218166cf282731d8dc522592642 --- /dev/null +++ b/rsm_rise/scripts/real/run_271_docs.sh @@ -0,0 +1,9 @@ +#!/usr/bin/env bash +# gen_q #271: regenerate the CHECKPOINTS.md reward block and rebuild docs/real_reward_study.pdf +# from the current JSONs (screen, stitching significance, reproducibility, upload stamps). +set -uo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +rc=0 +scripts/real/run_ckptrows.sh || rc=1 +scripts/real/build_reward_study_pdf.sh || rc=1 +exit $rc diff --git a/rsm_rise/scripts/real/run_271_stats.sh b/rsm_rise/scripts/real/run_271_stats.sh new file mode 100644 index 0000000000000000000000000000000000000000..6b1383510c2a62d3a2d0b2d5f01f7e655d45c0ea --- /dev/null +++ b/rsm_rise/scripts/real/run_271_stats.sh @@ -0,0 +1,25 @@ +#!/usr/bin/env bash +# gen_q #271: re-derive ALL THREE summary statistics from the artefacts on disk, in one job. +# 1. the stitching number <- REWARD_HEAD_DIAG_STITCH.json_parts (rr_sn_full*) +# 2. the open-loop screen <- the RW_SCREEN_TAG dirs (RW271b = run 5's rerun on hardened checkpoint +# resolvers; RW271c = run 7's, the first with a real v0lit column on both proposer seeds) +# 3. the screen's noise floor <- every PAIR of complete screen runs (run 7: three of them exist) +# Keep 1 and 3 in the same job as 2: leaving the reproducibility statistic out is how the quoted screen +# and the noise floor it is supposed to be read with drifted apart in the first place. +set -uo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +rc=0 +scripts/real/run_env.sh scripts/real/stitch_significance.py || rc=1 +RW_SCREEN_TAG=${RW_SCREEN_TAG:-RW271c} scripts/real/run_env.sh scripts/real/build_reward_screen.py || rc=1 +scripts/real/run_env.sh scripts/real/screen_reproducibility.py || rc=1 +# 4. the STITCHING number's own noise floor, across an independent candidate draw (run 8). In the same +# job for the same reason as 3: the stitching AUC and the spread it has to be read with were quoted +# apart for two runs, and that is how "the stitching number reproduces" got published as a claim +# about the statistic when it was only a claim about the seeding being deterministic. +scripts/real/run_env.sh scripts/real/stitch_reproducibility.py \ + --label-a "stride50 draw" --label-b "stride25 draw, same anchors" || rc=1 +# 5. WHY the stitching number behaves as it does, and whether it survives replication (run 9). Same +# reason again: the mechanism numbers and the AUC they explain must be regenerated together. +scripts/real/run_env.sh scripts/real/stitch_mechanism.py || rc=1 +[ -d status/real/STITCH_DRAW_s1.json_parts ] && { scripts/real/_draws271.sh || rc=1; } +exit $rc diff --git a/rsm_rise/scripts/real/run_beta.sh b/rsm_rise/scripts/real/run_beta.sh new file mode 100644 index 0000000000000000000000000000000000000000..0c29834f355cdec26b6a066a312e7887f5218120 --- /dev/null +++ b/rsm_rise/scripts/real/run_beta.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +set -uo pipefail +exec /proj/dmfexp/zwhong/rsm_rise/venv_rsm/bin/python /proj/dmfexp/zwhong/rsm_rise/scripts/real/beta_band.py diff --git a/rsm_rise/scripts/real/run_cand_align.sh b/rsm_rise/scripts/real/run_cand_align.sh new file mode 100644 index 0000000000000000000000000000000000000000..0cf8f49685ecd5b04d3e577749e35e54471e3be9 --- /dev/null +++ b/rsm_rise/scripts/real/run_cand_align.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -x +cd /proj/dmfexp/zwhong/rsm_rise +export MUJOCO_GL=disable +venv_rsm/bin/python scripts/real/check_cand_alignment.py \ + R_val31 JUNC_feat_t45_c0p5_s0__Rval31 JUNC_feat_t40_c0p5_s0__Rval31 diff --git a/rsm_rise/scripts/real/run_chars.sh b/rsm_rise/scripts/real/run_chars.sh new file mode 100644 index 0000000000000000000000000000000000000000..e04a1b2d36f4e2b964bb81dafa194f7029c63f12 --- /dev/null +++ b/rsm_rise/scripts/real/run_chars.sh @@ -0,0 +1,4 @@ +#!/usr/bin/env bash +set -uo pipefail +ROOT=/proj/dmfexp/zwhong/rsm_rise +exec "$ROOT/venv_rsm/bin/python" "$ROOT/scripts/real/characterize_cooking.py" diff --git a/rsm_rise/scripts/real/run_ckptrows.sh b/rsm_rise/scripts/real/run_ckptrows.sh new file mode 100644 index 0000000000000000000000000000000000000000..70fdf903e29b45d6bca2f0d36feaf3bbf3f9159a --- /dev/null +++ b/rsm_rise/scripts/real/run_ckptrows.sh @@ -0,0 +1,4 @@ +#!/usr/bin/env bash +set -uo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +exec scripts/real/run_env.sh scripts/real/build_checkpoints_reward_rows.py diff --git a/rsm_rise/scripts/real/run_confound.sh b/rsm_rise/scripts/real/run_confound.sh new file mode 100644 index 0000000000000000000000000000000000000000..cf9c58e86281f173ddf15c09c92c578c1d3d3d60 --- /dev/null +++ b/rsm_rise/scripts/real/run_confound.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +set -uo pipefail +exec /proj/dmfexp/zwhong/rsm_rise/venv_rsm/bin/python /proj/dmfexp/zwhong/rsm_rise/scripts/real/check_reward_confound.py diff --git a/rsm_rise/scripts/real/run_d3.sh b/rsm_rise/scripts/real/run_d3.sh new file mode 100644 index 0000000000000000000000000000000000000000..7ee852a670e9816069526af4a0662103d7fe4d60 --- /dev/null +++ b/rsm_rise/scripts/real/run_d3.sh @@ -0,0 +1,15 @@ +#!/usr/bin/env bash +# D3 stitching feasibility: shipped provenance head vs the goal-anchored fine-tunes, side by side. +# Runs in the RISE env (it needs robomimic.algo.rsm_scorer, the SAME read-out the open-loop scorer uses). +set -uo pipefail +ROOT=/proj/dmfexp/zwhong/rsm_rise +R=$ROOT/runs/real_cooking_v5/rsm +args=() +for n in shipped_R_M:$R/R_M/ckpt_s100000.pt ft_v0:$R/R_M_ft_v0/ckpt_s110000.pt \ + ft_v1:$R/R_M_ft_v1/ckpt_s110000.pt ft_v2:$R/R_M_ft_v2/ckpt_s110000.pt \ + ft_v3:$R/R_M_ft_v3/ckpt_s110000.pt ft_v1_s1:$R/R_M_ft_v1_s1/ckpt_s110000.pt \ + ft_v5:$R/R_M_ft_v5/ckpt_s110000.pt ft_v5_s1:$R/R_M_ft_v5_s1/ckpt_s110000.pt; do + k=${n%%:*}; p=${n#*:}; [ -f "$p" ] && args+=(--ckpt "$k=$p") || echo "[d3] skip $k" +done +exec $ROOT/scripts/real/run_env.sh $ROOT/scripts/real/stitch_feasibility.py "${args[@]}" \ + --out $ROOT/status/real/STITCH_FEASIBILITY.json "$@" diff --git a/rsm_rise/scripts/real/run_d3_2x2.sh b/rsm_rise/scripts/real/run_d3_2x2.sh new file mode 100644 index 0000000000000000000000000000000000000000..85c14a5f8068fe0b51e6d98569c5c1a5aebde8aa --- /dev/null +++ b/rsm_rise/scripts/real/run_d3_2x2.sh @@ -0,0 +1,23 @@ +#!/usr/bin/env bash +# D3 on the crossed 2x2 that separates "the v5 LABEL passes" from "the seed-1 TRUNK passes": +# ft_v5 = seed-0 trunk x seed-0 RNG/split +# ft_v5_s1 = seed-1 trunk x seed-1 RNG/split +# ft_v5_x10 = seed-0 trunk x seed-1 RNG/split +# ft_v5_x01 = seed-1 trunk x seed-0 RNG/split +# plus the two provenance references. Three independent candidate draws per head (the same three +# seeds used for STITCH_FEASIBILITY2 / _seed777 / _seed999) so the cells are directly comparable. +set -uo pipefail +ROOT=/proj/dmfexp/zwhong/rsm_rise +R=$ROOT/runs/real_cooking_v5/rsm +args=() +for n in ft_v5:$R/R_M_ft_v5/ckpt_s110000.pt ft_v5_s1:$R/R_M_ft_v5_s1/ckpt_s110000.pt \ + ft_v5_x10:$R/R_M_ft_v5_x10/ckpt_s110000.pt ft_v5_x01:$R/R_M_ft_v5_x01/ckpt_s110000.pt \ + shipped_R_M:$R/R_M/ckpt_s100000.pt shipped_R_M_s1:$R/R_M_s1/ckpt_s100000.pt \ + scratch_v0:$R/R_RW_v0/ckpt_s100000.pt; do + k=${n%%:*}; p=${n#*:}; [ -f "$p" ] && args+=(--ckpt "$k=$p") || echo "[d3x] skip $k ($p)" +done +for s in 12345 777 999; do + echo "[d3x] === candidate draw seed=$s $(date -u) ===" + $ROOT/scripts/real/run_env.sh $ROOT/scripts/real/stitch_feasibility.py "${args[@]}" \ + --anchors 64 --seed $s --out $ROOT/status/real/STITCH_FEASIBILITY_2x2_seed$s.json +done diff --git a/rsm_rise/scripts/real/run_d3_cpu.sh b/rsm_rise/scripts/real/run_d3_cpu.sh new file mode 100644 index 0000000000000000000000000000000000000000..3d6a49cec33ac98bc06c6b630c3286526afa0052 --- /dev/null +++ b/rsm_rise/scripts/real/run_d3_cpu.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +# CPU twin of run_d3.sh (the preemptable GPU queue is saturated; the d1 read-out at 32 anchors is +# minutes on 8 cores). Writes to a separate file so it cannot race the GPU cell. +exec /proj/dmfexp/zwhong/rsm_rise/scripts/real/run_d3.sh --anchors 32 \ + --out /proj/dmfexp/zwhong/rsm_rise/status/real/STITCH_FEASIBILITY_cpu.json diff --git a/rsm_rise/scripts/real/run_d3_scratch.sh b/rsm_rise/scripts/real/run_d3_scratch.sh new file mode 100644 index 0000000000000000000000000000000000000000..87199cdff1e4a7738fa0e14930a45d331d026cac --- /dev/null +++ b/rsm_rise/scripts/real/run_d3_scratch.sh @@ -0,0 +1,14 @@ +#!/usr/bin/env bash +# D3 on the FROM-SCRATCH reward controls (R_RW_v0..v3, 100k steps, no warm start). Tests whether any +# label trained from scratch ranks the stitch above chance -- the fine-tune round left that open. +set -uo pipefail +ROOT=/proj/dmfexp/zwhong/rsm_rise +R=$ROOT/runs/real_cooking_v5/rsm +args=() +for v in v0 v1 v2 v3; do + p=$(ls -t $R/R_RW_$v/ckpt_s*.pt 2>/dev/null | head -1) + [ -n "$p" ] && args+=(--ckpt "scratch_$v=$p") || echo "[d3sc] skip $v" +done +args+=(--ckpt "ft_v5_s1=$R/R_M_ft_v5_s1/ckpt_s110000.pt") # the passing head, as the in-run reference +exec $ROOT/scripts/real/run_env.sh $ROOT/scripts/real/stitch_feasibility.py "${args[@]}" \ + --out $ROOT/status/real/STITCH_FEASIBILITY_SCRATCH.json "$@" diff --git a/rsm_rise/scripts/real/run_d3_seed1.sh b/rsm_rise/scripts/real/run_d3_seed1.sh new file mode 100644 index 0000000000000000000000000000000000000000..498305b8a47660f838b44257525650581d07d7d0 --- /dev/null +++ b/rsm_rise/scripts/real/run_d3_seed1.sh @@ -0,0 +1,15 @@ +#!/usr/bin/env bash +# D3 on the SEED-1 family, to separate "the v5 label passes D3" from "the seed-1 trunk passes D3". +# Pairs with run_d3.sh (seed-0 family). Heads: the seed-1 flagship (provenance, never D3-tested) and +# every seed-1 fine-tune. +set -uo pipefail +ROOT=/proj/dmfexp/zwhong/rsm_rise +R=$ROOT/runs/real_cooking_v5/rsm +args=() +for n in shipped_R_M_s1:$R/R_M_s1/ckpt_s100000.pt ft_v0_s1:$R/R_M_ft_v0_s1/ckpt_s110000.pt \ + ft_v2_s1:$R/R_M_ft_v2_s1/ckpt_s110000.pt ft_v3_s1:$R/R_M_ft_v3_s1/ckpt_s110000.pt \ + ft_v5_s1:$R/R_M_ft_v5_s1/ckpt_s110000.pt ft_v5:$R/R_M_ft_v5/ckpt_s110000.pt; do + k=${n%%:*}; p=${n#*:}; [ -f "$p" ] && args+=(--ckpt "$k=$p") || echo "[d3s1] skip $k" +done +exec $ROOT/scripts/real/run_env.sh $ROOT/scripts/real/stitch_feasibility.py "${args[@]}" \ + --out $ROOT/status/real/STITCH_FEASIBILITY_SEED1.json "$@" diff --git a/rsm_rise/scripts/real/run_decisive.sh b/rsm_rise/scripts/real/run_decisive.sh new file mode 100644 index 0000000000000000000000000000000000000000..afad5f4b2aa392af3cabae031d7a81142644532b --- /dev/null +++ b/rsm_rise/scripts/real/run_decisive.sh @@ -0,0 +1,17 @@ +#!/usr/bin/env bash +# DECISIVE TEST D1+D2 (reward-head separability / junction ambiguity) on every trained head. +set -uo pipefail +ROOT=/proj/dmfexp/zwhong/rsm_rise +R=$ROOT/runs/real_cooking_v5/rsm +PY=$ROOT/venv_rsm/bin/python +args=() +add(){ [ -f "$2" ] && args+=(--ckpt "$1=$2") || echo "[dec] skip $1 (no $2)"; } +add shipped_R_M $R/R_M/ckpt_s100000.pt +add shipped_R_M_s1 $R/R_M_s1/ckpt_s100000.pt +for v in ${DEC_CELLS:-v0 v1 v2 v3 v5}; do + add ft_$v $R/R_M_ft_$v/ckpt_s110000.pt + add ft_${v}_s1 $R/R_M_ft_${v}_s1/ckpt_s110000.pt + p=$(ls -t $R/R_RW_$v/ckpt_s*.pt 2>/dev/null | head -1); [ -n "$p" ] && args+=(--ckpt "scratch_$v=$p") +done +set -x +$PY $ROOT/scripts/real/decisive_reward.py "${args[@]}" --out ${DEC_OUT:-$ROOT/status/real/DECISIVE_REWARD.json} diff --git a/rsm_rise/scripts/real/run_decisive_x.sh b/rsm_rise/scripts/real/run_decisive_x.sh new file mode 100644 index 0000000000000000000000000000000000000000..8196c2f5e7dd6a23fd9a18b64070ab6452a409c7 --- /dev/null +++ b/rsm_rise/scripts/real/run_decisive_x.sh @@ -0,0 +1,17 @@ +#!/usr/bin/env bash +# D1+D2 on the crossed v5 replications (x10 / x01), with the two v5 originals and the shipped heads +# as in-run references, so the goal-inversion finding can be checked across trunk/RNG seeds. +set -uo pipefail +ROOT=/proj/dmfexp/zwhong/rsm_rise +R=$ROOT/runs/real_cooking_v5/rsm +PY=$ROOT/venv_rsm/bin/python +args=() +add(){ [ -f "$2" ] && args+=(--ckpt "$1=$2") || echo "[decx] skip $1 (no $2)"; } +add shipped_R_M $R/R_M/ckpt_s100000.pt +add shipped_R_M_s1 $R/R_M_s1/ckpt_s100000.pt +add ft_v5 $R/R_M_ft_v5/ckpt_s110000.pt +add ft_v5_s1 $R/R_M_ft_v5_s1/ckpt_s110000.pt +add ft_v5_x10 $R/R_M_ft_v5_x10/ckpt_s110000.pt +add ft_v5_x01 $R/R_M_ft_v5_x01/ckpt_s110000.pt +set -x +$PY $ROOT/scripts/real/decisive_reward.py "${args[@]}" --out $ROOT/status/real/DECISIVE_REWARD_X.json diff --git a/rsm_rise/scripts/real/run_dump.sh b/rsm_rise/scripts/real/run_dump.sh new file mode 100644 index 0000000000000000000000000000000000000000..29c60d82b30b19059d2d1f1696fd18faf6a21e79 --- /dev/null +++ b/rsm_rise/scripts/real/run_dump.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +set -uo pipefail +exec /proj/dmfexp/zwhong/rsm_rise/venv_rsm/bin/python /proj/dmfexp/zwhong/rsm_rise/scripts/real/dump_frames.py diff --git a/rsm_rise/scripts/real/run_env.sh b/rsm_rise/scripts/real/run_env.sh new file mode 100644 index 0000000000000000000000000000000000000000..ceb38a68342e310b4980943cf0c4de2037664b3c --- /dev/null +++ b/rsm_rise/scripts/real/run_env.sh @@ -0,0 +1,6 @@ +#!/usr/bin/env bash +# GPU/CPU runner in the RISE env (robomimic + torch): run_env.sh [args...] +set -uo pipefail +ROOT=/proj/dmfexp/zwhong/rsm_rise; source $ROOT/scripts/env.sh; export PYTHONPATH=$ROOT/code/rise_code:${PYTHONPATH:-}; cd $ROOT +echo "[run_env] host=$(hostname) job=${LSB_JOBID:-none} $* $(date -u)"; nvidia-smi -L 2>/dev/null +exec $ROOT/env/bin/python "$@" diff --git a/rsm_rise/scripts/real/run_env_openpi.sh b/rsm_rise/scripts/real/run_env_openpi.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a8b3717924377e29e860754bd7a06c69c9cc3c5 --- /dev/null +++ b/rsm_rise/scripts/real/run_env_openpi.sh @@ -0,0 +1,18 @@ +#!/usr/bin/env bash +# rsm_rise #269: run a scripts/real/*.py that needs BOTH openpi (jax, the pi0.5 proposer) and the RISE stack +# (torch + robomimic: the IDQL critic and the RSM scorer) in ONE process. The openpi venv already has torch, +# h5py and jax; robomimic and its siblings are editable installs in the RISE env, so they are added by path +# (the same roots the RISE env's .pth files inject). XLA is capped so torch keeps room on the same GPU. +# usage: run_env_openpi.sh [args...] +set -uo pipefail +ROOT=/proj/dmfexp/zwhong/rsm_rise +export OPENPI_DATA_HOME=$ROOT/.openpi_assets HF_LEROBOT_HOME=$ROOT/data/real/lerobot_home UV_CACHE_DIR=$ROOT/.uv_cache +export HF_HUB_OFFLINE=1 TOKENIZERS_PARALLELISM=false PYTHONUNBUFFERED=1 +export XLA_PYTHON_CLIENT_MEM_FRACTION=${XLA_PYTHON_CLIENT_MEM_FRACTION:-0.45} +export XLA_PYTHON_CLIENT_PREALLOCATE=false +export MUJOCO_GL=egl PYOPENGL_PLATFORM=egl +export PYTHONPATH=$ROOT/code/rise_robomimic:$ROOT/code/diffusion_policy:$ROOT/code/robosuite:$ROOT/code/mimicgen_environments:$ROOT/code/rise_code:$ROOT/scripts/real:${PYTHONPATH:-} +cd $ROOT/third_party/openpi +echo "[run_env_openpi] host=$(hostname) job=${LSB_JOBID:-none} $* $(date -u)"; nvidia-smi -L 2>/dev/null +source $ROOT/scripts/real/gpu_preflight.sh; rr_gpu_preflight $ROOT/third_party/openpi/.venv/bin/python +exec $ROOT/third_party/openpi/.venv/bin/python "$@" diff --git a/rsm_rise/scripts/real/run_ft_openloop.sh b/rsm_rise/scripts/real/run_ft_openloop.sh new file mode 100644 index 0000000000000000000000000000000000000000..0757da6a839c74ff94df4c9580d8f0976568683b --- /dev/null +++ b/rsm_rise/scripts/real/run_ft_openloop.sh @@ -0,0 +1,31 @@ +#!/usr/bin/env bash +# Resolve the fine-tuned checkpoints AT RUN TIME (so this can be submitted with an LSF dependency, +# before the trainings have written anything) and run one open-loop pass in which every reward variant +# is an extra scoring column on the SAME candidates. +# usage: run_ft_openloop.sh [extra scorer_openloop.py args...] +set -uo pipefail +ROOT=/proj/dmfexp/zwhong/rsm_rise +R=$ROOT/runs/real_cooking_v5/rsm +POL=$1; TAG=$2; shift 2 +EXTRA=() +# #271 scheme cells. NAMING: v1 IS scheme A (its label array is bit-identical to reward_A_tosucc, +# asserted in make_goal_reward.py), so it is listed once and reported as A; v0/v2/v3 stay as the +# provenance / arrival / final-segment controls. RW_CELLS can override the list. +for c in ${RW_CELLS:-v0 v1 v2 v3 v0_s1 v1_s1 v2_s1 v3_s1 v0lit v0lit_s1 B B_s1 B400 B400_s1 C3 C3_s1 C10 C10_s1}; do + p="" + # ckpt_s110000.pt is the finished 10k fine-tune; ckpt_s105000.pt is a mid-run save. ckpt.pt is NOT a + # safe fallback: a cell that has only just been seeded has ckpt.pt = the COPIED-IN step-100000 base + # checkpoint, i.e. ZERO fine-tune steps, and scoring that silently reports the BASE head under the + # scheme's name. That is exactly what happened to the B_s1 / v0lit / v0lit_s1 columns of the first + # #271 screen. A cell without a real save is now SKIPPED; RW_ALLOW_PARTIAL=1 opts back in. + for f in "$R/R_M_ft_$c/ckpt_s110000.pt" "$R/R_M_ft_$c/ckpt_s105000.pt" ${RW_ALLOW_PARTIAL:+"$R/R_M_ft_$c/ckpt.pt"}; do + [ -f "$f" ] && { p=$f; break; } + done + [ -n "$p" ] || { echo "[ft-ol] SKIP ft_$c: no fine-tuned checkpoint on disk"; continue; } + echo "[ft-ol] ft_$c -> $p" + EXTRA+=(--rsm-ckpt-extra "ft_$c=$p") +done +exec $ROOT/scripts/real/run_env.sh $ROOT/scripts/real/scorer_openloop.py \ + --policy "robomimic:$POL" --idql-ckpt "$POL" --rsm-ckpt "$R/R_M/ckpt_s100000.pt" "${EXTRA[@]}" \ + --rsm-mode d1 --rsm-depth 1 --rsm-beta 0.99 --rsm-score-kind prob --rsm-temperature 25 \ + --tag "$TAG" --out "$ROOT/status/real/openloop_$TAG" "$@" diff --git a/rsm_rise/scripts/real/run_ft_stitch.sh b/rsm_rise/scripts/real/run_ft_stitch.sh new file mode 100644 index 0000000000000000000000000000000000000000..9fd6e149fc7ffe6281ba84154f374ea96af16b59 --- /dev/null +++ b/rsm_rise/scripts/real/run_ft_stitch.sh @@ -0,0 +1,16 @@ +#!/usr/bin/env bash +# Stitch / chained-hop control on the FINE-TUNED successors. Resolves checkpoints at run time so the +# job can be submitted with an LSF dependency. usage: run_ft_stitch.sh [cell...] +set -uo pipefail +ROOT=/proj/dmfexp/zwhong/rsm_rise +R=$ROOT/runs/real_cooking_v5/rsm +for c in "$@"; do + p="" + for f in "$R/R_M_ft_$c/ckpt_s110000.pt" "$R/R_M_ft_$c/ckpt_s105000.pt" "$R/R_M_ft_$c/ckpt.pt"; do + [ -f "$f" ] && { p=$f; break; } + done + [ -n "$p" ] || { echo "[ft-stitch] SKIP $c: no checkpoint"; continue; } + echo "[ft-stitch] $c -> $p" + $ROOT/scripts/real/run_multihop.sh --ckpt "$p" --out "$ROOT/status/real/stitch_multihop_R_M_ft_$c.json" \ + || echo "[ft-stitch] FAILED $c" +done diff --git a/rsm_rise/scripts/real/run_goalrw.sh b/rsm_rise/scripts/real/run_goalrw.sh new file mode 100644 index 0000000000000000000000000000000000000000..0e7296ddff050dfdb7d82bf8148d7a951a5e7d35 --- /dev/null +++ b/rsm_rise/scripts/real/run_goalrw.sh @@ -0,0 +1,4 @@ +#!/usr/bin/env bash +set -euo pipefail +ROOT=/proj/dmfexp/zwhong/rsm_rise +exec "$ROOT/venv_rsm/bin/python" "$ROOT/scripts/real/make_goal_reward.py" "$@" diff --git a/rsm_rise/scripts/real/run_knn.sh b/rsm_rise/scripts/real/run_knn.sh new file mode 100644 index 0000000000000000000000000000000000000000..342bdf08e39ac460c2870d14ca5e649b04fc23ac --- /dev/null +++ b/rsm_rise/scripts/real/run_knn.sh @@ -0,0 +1,4 @@ +#!/usr/bin/env bash +set -uo pipefail +ROOT=/proj/dmfexp/zwhong/rsm_rise; source $ROOT/scripts/env.sh +exec $ROOT/env/bin/python $ROOT/scripts/real/build_knn_pairs.py "$@" diff --git a/rsm_rise/scripts/real/run_multihop.sh b/rsm_rise/scripts/real/run_multihop.sh new file mode 100644 index 0000000000000000000000000000000000000000..ed1f5d152de5d3a6b11871006be57247521a9b72 --- /dev/null +++ b/rsm_rise/scripts/real/run_multihop.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +set -uo pipefail +exec /proj/dmfexp/zwhong/rsm_rise/venv_rsm/bin/python /proj/dmfexp/zwhong/rsm_rise/scripts/real/stitch_multihop.py "$@" diff --git a/rsm_rise/scripts/real/run_pair4540.sh b/rsm_rise/scripts/real/run_pair4540.sh new file mode 100644 index 0000000000000000000000000000000000000000..1bb453df27be418327b09c4e837fa819972afafd --- /dev/null +++ b/rsm_rise/scripts/real/run_pair4540.sh @@ -0,0 +1,5 @@ +#!/bin/bash +set -x +cd /proj/dmfexp/zwhong/rsm_rise +export MUJOCO_GL=disable +venv_rsm/bin/python scripts/real/check_pair_t45_t40.py diff --git a/rsm_rise/scripts/real/run_reward_screen.sh b/rsm_rise/scripts/real/run_reward_screen.sh new file mode 100644 index 0000000000000000000000000000000000000000..58d1a022f9bd9351948cdd5c95a0fc10d6ddcd44 --- /dev/null +++ b/rsm_rise/scripts/real/run_reward_screen.sh @@ -0,0 +1,4 @@ +#!/usr/bin/env bash +set -uo pipefail +cd /proj/dmfexp/zwhong/rsm_rise +exec scripts/real/run_env.sh scripts/real/build_reward_screen.py diff --git a/rsm_rise/scripts/real/run_rwcheck.sh b/rsm_rise/scripts/real/run_rwcheck.sh new file mode 100644 index 0000000000000000000000000000000000000000..94d21f1fe7ea9d879316e66e659750b5cf0c7943 --- /dev/null +++ b/rsm_rise/scripts/real/run_rwcheck.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +set -uo pipefail +exec /proj/dmfexp/zwhong/rsm_rise/venv_rsm/bin/python /proj/dmfexp/zwhong/rsm_rise/scripts/tmp/check_reward_geom.py diff --git a/rsm_rise/scripts/real/run_rwdiag.sh b/rsm_rise/scripts/real/run_rwdiag.sh new file mode 100644 index 0000000000000000000000000000000000000000..07bd0857646327985984c97c8a8bfbaad1ee9178 --- /dev/null +++ b/rsm_rise/scripts/real/run_rwdiag.sh @@ -0,0 +1,4 @@ +#!/usr/bin/env bash +set -uo pipefail +exec /proj/dmfexp/zwhong/rsm_rise/venv_rsm/bin/python \ + /proj/dmfexp/zwhong/rsm_rise/scripts/real/reward_head_diag.py "$@" diff --git a/rsm_rise/scripts/real/run_rwdiag_all.sh b/rsm_rise/scripts/real/run_rwdiag_all.sh new file mode 100644 index 0000000000000000000000000000000000000000..141bf5eff0d7c4be5918b0c710a270700d48d38c --- /dev/null +++ b/rsm_rise/scripts/real/run_rwdiag_all.sh @@ -0,0 +1,25 @@ +#!/usr/bin/env bash +# Diagnostics 1+2 of gen_q #271 on every reward head that exists on disk. Resolves checkpoints at +# run time, so this can be submitted with a dependency before the fine-tunes have finished. +set -uo pipefail +ROOT=/proj/dmfexp/zwhong/rsm_rise +R=$ROOT/runs/real_cooking_v5/rsm +ARGS=(--ckpt "base_R_M=$R/R_M/ckpt_s100000.pt" --ckpt "base_R_M_s1=$R/R_M_s1/ckpt_s100000.pt") +# A == v1 (asserted bit-identical in make_goal_reward.py), so the A rows ARE the v1 cells. +for c in v0 v0_s1 A:v1 A_s1:v1_s1 v2 v2_s1 v3 v3_s1 v0lit v0lit_s1 B B_s1 B400 B400_s1 C3 C3_s1 C10 C10_s1; do + nm="${c%%:*}"; cell="${c##*:}" + p="" + # ckpt.pt of a freshly seeded cell is the COPIED-IN step-100000 base checkpoint (zero fine-tune + # steps), so taking it as a fallback reports the BASE head under the scheme's name. Opt back in with + # RWD_ALLOW_PARTIAL=1 if you actually want a partial cell scored. + for f in "$R/R_M_ft_$cell/ckpt_s110000.pt" "$R/R_M_ft_$cell/ckpt_s108000.pt" \ + "$R/R_M_ft_$cell/ckpt_s106000.pt" "$R/R_M_ft_$cell/ckpt_s104000.pt" \ + ${RWD_ALLOW_PARTIAL:+"$R/R_M_ft_$cell/ckpt.pt"}; do + [ -f "$f" ] && { p=$f; break; } + done + [ -n "$p" ] || { echo "[rwdiag] SKIP $nm: no checkpoint for R_M_ft_$cell"; continue; } + echo "[rwdiag] $nm -> $p" + ARGS+=(--ckpt "$nm=$p") +done +exec "$ROOT/scripts/real/run_rwdiag.sh" "${ARGS[@]}" \ + --out "$ROOT/status/real/REWARD_HEAD_DIAG.json" "$@" diff --git a/rsm_rise/scripts/real/run_score.sh b/rsm_rise/scripts/real/run_score.sh new file mode 100644 index 0000000000000000000000000000000000000000..69cabd3fd15c239bfaf31cd134918889414c690e --- /dev/null +++ b/rsm_rise/scripts/real/run_score.sh @@ -0,0 +1,7 @@ +#!/usr/bin/env bash +# GPU runner for the fixed-protocol successor-fit scorer. +set -uo pipefail +ROOT=/proj/dmfexp/zwhong/rsm_rise +echo "[run_score] host=$(hostname) $(date -u)" +nvidia-smi --query-gpu=name --format=csv,noheader || true +exec "$ROOT/venv_rsm/bin/python" "$ROOT/scripts/real/score_nnl1.py" "$@" diff --git a/rsm_rise/scripts/real/run_seg.sh b/rsm_rise/scripts/real/run_seg.sh new file mode 100644 index 0000000000000000000000000000000000000000..d97341d500ccee22f8d7b95de87b3ab2aaff9e64 --- /dev/null +++ b/rsm_rise/scripts/real/run_seg.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +set -uo pipefail +exec /proj/dmfexp/zwhong/rsm_rise/venv_rsm/bin/python /proj/dmfexp/zwhong/rsm_rise/scripts/real/add_segment_labels.py diff --git a/rsm_rise/scripts/real/run_stagefigs.sh b/rsm_rise/scripts/real/run_stagefigs.sh new file mode 100644 index 0000000000000000000000000000000000000000..2459e4cb18c0bff18ab1974dc6b6ca11de50b511 --- /dev/null +++ b/rsm_rise/scripts/real/run_stagefigs.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +set -uo pipefail +P=/proj/dmfexp/zwhong/rsm_rise/venv_rsm/bin/python +$P /proj/dmfexp/zwhong/rsm_rise/scripts/real/plot_reward_timelines.py +$P /proj/dmfexp/zwhong/rsm_rise/scripts/real/render_stages.py diff --git a/rsm_rise/scripts/real/run_stitch.sh b/rsm_rise/scripts/real/run_stitch.sh new file mode 100644 index 0000000000000000000000000000000000000000..7fabf8116b35c3fe6e2cadda158811223f1da249 --- /dev/null +++ b/rsm_rise/scripts/real/run_stitch.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +set -uo pipefail +exec /proj/dmfexp/zwhong/rsm_rise/venv_rsm/bin/python /proj/dmfexp/zwhong/rsm_rise/scripts/real/check_stitch.py diff --git a/rsm_rise/scripts/real/run_stitch_arr.sh b/rsm_rise/scripts/real/run_stitch_arr.sh new file mode 100644 index 0000000000000000000000000000000000000000..9156cb86bea99e070275f62ac3264e23090eca5f --- /dev/null +++ b/rsm_rise/scripts/real/run_stitch_arr.sh @@ -0,0 +1,4 @@ +#!/usr/bin/env bash +set -uo pipefail +export TORCH_HOME="${TORCH_HOME:-$HOME/.cache/torch}" +exec /proj/dmfexp/zwhong/rsm_rise/venv_rsm/bin/python /proj/dmfexp/zwhong/rsm_rise/scripts/real/check_stitch_arrivals.py diff --git a/rsm_rise/scripts/real/run_stitch_decompose.sh b/rsm_rise/scripts/real/run_stitch_decompose.sh new file mode 100644 index 0000000000000000000000000000000000000000..7334c6cd14d817701a8adb7fcf601871757d3543 --- /dev/null +++ b/rsm_rise/scripts/real/run_stitch_decompose.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# #271 open question 3: R read at the CHAINED latent, on the published stitching number's own +# candidates. Same head resolution and same CANONICAL measurement settings as +# run_stitch_number.sh (stride 50, N=128, hops 1,2,4) -- they must match or the fidelity check +# against the published parts is meaningless. +set -uo pipefail +ROOT=/proj/dmfexp/zwhong/rsm_rise +R=$ROOT/runs/real_cooking_v5/rsm +POL=$ROOT/runs/cooking_v5_expert_suboptimal/policy/S0Aidql_seed0/cooking_v5_expert_suboptimal_S0Aidql_s0/20260921193225/models/model_epoch_2000.pth +CELLS="v0:R_M_ft_v0 v0lit:R_M_ft_v0lit v0lit_s1:R_M_ft_v0lit_s1 A:R_M_ft_v1 A_s1:R_M_ft_v1_s1 B:R_M_ft_B B_s1:R_M_ft_B_s1 B400:R_M_ft_B400 B400_s1:R_M_ft_B400_s1 C3:R_M_ft_C3 C3_s1:R_M_ft_C3_s1 C10:R_M_ft_C10 C10_s1:R_M_ft_C10_s1 v2:R_M_ft_v2 v3:R_M_ft_v3" +CK=(--ckpt "base=$R/R_M/ckpt_s100000.pt") +for nc in $CELLS; do + n=${nc%%:*}; cell=${nc##*:}; p="" + for f in "$R/$cell/ckpt_s110000.pt"; do [ -f "$f" ] && { p=$f; break; }; done + [ -n "$p" ] || { echo "[dc] SKIP $n: no checkpoint for $cell"; continue; } + CK+=(--ckpt "$n=$p") +done +exec $ROOT/scripts/real/run_env.sh $ROOT/scripts/real/stitch_decompose.py \ + --policy "$POL" "${CK[@]}" --out "${DC_OUT:-$ROOT/status/real/STITCH_DECOMP.json}" \ + --anchor-stride 50 --n-cand 128 --retr-pool 30000 --report-hops 1,2,4 "$@" diff --git a/rsm_rise/scripts/real/run_stitch_number.sh b/rsm_rise/scripts/real/run_stitch_number.sh new file mode 100644 index 0000000000000000000000000000000000000000..f88c2008d6adb50d86be7f89deee7d94c010b137 --- /dev/null +++ b/rsm_rise/scripts/real/run_stitch_number.sh @@ -0,0 +1,36 @@ +#!/usr/bin/env bash +# Diagnostic 3 of #271 (the STITCHING NUMBER) over every reward head that has a checkpoint on disk. +# Checkpoints are resolved AT RUN TIME so this can be submitted before the trainings finish. +# usage: run_stitch_number.sh [extra stitch_number.py args...] +set -uo pipefail +ROOT=/proj/dmfexp/zwhong/rsm_rise +R=$ROOT/runs/real_cooking_v5/rsm +POL=$ROOT/runs/cooking_v5_expert_suboptimal/policy/S0Aidql_seed0/cooking_v5_expert_suboptimal_S0Aidql_s0/20260921193225/models/model_epoch_2000.pth +# name:cell -- the #271 scheme names, mapped onto the cells that hold them (see REWARD_STITCH_DONE +# "Correction 1": R_M_ft_v1 IS scheme A, bit-identical labels). +CELLS="v0:R_M_ft_v0 v0lit:R_M_ft_v0lit v0lit_s1:R_M_ft_v0lit_s1 A:R_M_ft_v1 A_s1:R_M_ft_v1_s1 B:R_M_ft_B B_s1:R_M_ft_B_s1 B400:R_M_ft_B400 B400_s1:R_M_ft_B400_s1 C3:R_M_ft_C3 C3_s1:R_M_ft_C3_s1 C10:R_M_ft_C10 C10_s1:R_M_ft_C10_s1 v2:R_M_ft_v2 v3:R_M_ft_v3" +CK=(--ckpt "base=$R/R_M/ckpt_s100000.pt") +for nc in $CELLS; do + n=${nc%%:*}; cell=${nc##*:}; p="" + # Only the FINISHED fine-tune counts. A half-trained cell still has the step-100000 weights copied + # in as ckpt.pt, and scoring that would silently report the BASE head under the scheme's name (that is + # how run 2's diagnostics-1+2 table ended up with stale B/C rows). SN_ALLOW_PARTIAL=1 opts back in. + for f in "$R/$cell/ckpt_s110000.pt" ${SN_ALLOW_PARTIAL:+"$R/$cell/ckpt_s105000.pt" "$R/$cell/ckpt.pt"}; do + [ -f "$f" ] && { p=$f; break; } + done + [ -n "$p" ] || { echo "[sn] SKIP $n: no checkpoint for $cell"; continue; } + echo "[sn] $n -> $p" + CK+=(--ckpt "$n=$p") +done +# THE CANONICAL MEASUREMENT SETTINGS, pinned here on purpose. Every stitching number that has been +# published for #271 (CHECKPOINTS.md, the PDF, PR #1, the HF card, the issue) was measured at +# --anchor-stride 50 (3 anchors per route-4 episode, 150 anchors) and classified at hops 1,2,4. +# stitch_number.py's own defaults are stride 25 / hops 1,4, so a BARE `run_stitch_number.sh` silently +# measured a DIFFERENT anchor set -- anchors are seeded by anchor INDEX, so a different stride means a +# different candidate draw per anchor and the numbers are not comparable to the published ones (run 8). +# Anything passed on the command line still wins, because it comes after these on the exec line. +SN_DEFAULTS=(--anchor-stride "${SN_ANCHOR_STRIDE:-50}" --n-cand "${SN_N_CAND:-128}" \ + --retr-pool "${SN_RETR_POOL:-30000}" --report-hops "${SN_REPORT_HOPS:-1,2,4}") +exec $ROOT/scripts/real/run_env.sh $ROOT/scripts/real/stitch_number.py \ + --policy "$POL" "${CK[@]}" --out "${SN_OUT:-$ROOT/status/real/REWARD_HEAD_DIAG_STITCH.json}" \ + "${SN_DEFAULTS[@]}" "$@" diff --git a/rsm_rise/scripts/real/run_succtables.sh b/rsm_rise/scripts/real/run_succtables.sh new file mode 100644 index 0000000000000000000000000000000000000000..6f7b76f3f2f305d04e186f3305ffa02834a6ed66 --- /dev/null +++ b/rsm_rise/scripts/real/run_succtables.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +set -uo pipefail +exec /proj/dmfexp/zwhong/rsm_rise/venv_rsm/bin/python /proj/dmfexp/zwhong/rsm_rise/scripts/real/build_successor_tables.py "$@" diff --git a/rsm_rise/scripts/real/run_uninf_null.sh b/rsm_rise/scripts/real/run_uninf_null.sh new file mode 100644 index 0000000000000000000000000000000000000000..d2acf4036d2fde63f38d6cc13beb496ac3ae4f87 --- /dev/null +++ b/rsm_rise/scripts/real/run_uninf_null.sh @@ -0,0 +1,8 @@ +#!/bin/bash +set -x +cd /proj/dmfexp/zwhong/rsm_rise +export MUJOCO_GL=disable +venv_rsm/bin/python scripts/real/gate_uninformative_null.py \ + --baseline R_val31 \ + --cells JUNC_feat_t45_c0p5_s0__Rval31 JUNC_feat_t40_c0p5_s0__Rval31 \ + --out status/real/augsucc/uninformative_null.json diff --git a/rsm_rise/scripts/real/run_v5_and_prov.sh b/rsm_rise/scripts/real/run_v5_and_prov.sh new file mode 100644 index 0000000000000000000000000000000000000000..7e7c02204d5f22e271da8a860ca76e2f1e2b5f2d --- /dev/null +++ b/rsm_rise/scripts/real/run_v5_and_prov.sh @@ -0,0 +1,12 @@ +#!/usr/bin/env bash +# CPU job: (1) build the v5 "RISE reward as shipped" labels, (2) re-cut the landed open-loop cells by +# episode provenance. Both are pure numpy over the cache and the persisted scores. +set -uo pipefail +ROOT=/proj/dmfexp/zwhong/rsm_rise +PY=$ROOT/venv_rsm/bin/python +$PY $ROOT/scripts/real/make_v5_reward.py || echo "[v5] FAILED" +D=() +for t in FT_S0Aidql_s1_e2500_d1_T25 FT_S0Aidql_s0_e2000_d1_T25 FT_S0Aidql_s1_e2500_d1_T25_ep6 FT_S0Aidql_s0_e2000_d1_T25_ep6; do + [ -f "$ROOT/status/real/openloop_$t/scores.npz" ] && D+=(--dir "$ROOT/status/real/openloop_$t") +done +[ ${#D[@]} -gt 0 ] && $PY $ROOT/scripts/real/openloop_by_provenance.py "${D[@]}" || echo "[prov] no cells yet" diff --git a/rsm_rise/scripts/real/score_advantage.py b/rsm_rise/scripts/real/score_advantage.py new file mode 100644 index 0000000000000000000000000000000000000000..9fc28f9df0a2e54c8f167df6a1b9fc7f2cc038ba --- /dev/null +++ b/rsm_rise/scripts/real/score_advantage.py @@ -0,0 +1,95 @@ +#!/usr/bin/env python +"""Offline IQL advantage for the RISE-policy pi0.5 cell (#263 column-3 proposer). + +Loads an S0Aidql checkpoint (our robomimic iql_diffusion stack, trained on cooking_v5_expert_suboptimal.hdf5 with the +provenance reward) and scores, exactly as robomimic.algo.iql_diffusion does for the actor at train time +(ONE_STEP: obs = frame t, action = a_t, adv = min_k Q_target_k(o_t, a_t) - V(o_t)): + * every frame of every episode (global LeRobot frame order = episodes ascending, all 248) -> adv [N] + * every RISE kNN pair (obs i, neighbour action a_j) that scripts/real/build_knn_pairs_ee.npz + the threshold + produce, in the SAME deterministic order openpi's KNNAugmentedDataset builds them (p2e pairs row-major over + play states, then p2p) -> adv_pairs [P] +Weights w = clip(exp(adv / beta), max 100) are formed at load time in openpi (beta as in the sim, 1.0). +Actions in the hdf5 are the min-max normalised ones the critic was trained on. + env/bin/python scripts/real/score_advantage.py --ckpt --out data/derived/cooking_v5_adv_idql_s0.npz +""" +import argparse, json, time +import numpy as np, h5py, torch + +ROOT = "/proj/dmfexp/zwhong/rsm_rise" + + +def knn_pairs(z, thr, augment_play): + play, gripper, demo = z["play_gidx"], z["gripper"], z["demo"] + ok_e = (z["p2e_dist"] <= thr) & (gripper[z["p2e_gidx"]] == gripper[play][:, None]) + src = [np.repeat(play, ok_e.sum(1))]; nbr = [z["p2e_gidx"][ok_e]] + if augment_play: + ok_p = (z["p2p_dist"] <= thr) & (z["p2p_gidx"] != play[:, None]) & (demo[z["p2p_gidx"]] != demo[play][:, None]) + src.append(np.repeat(play, ok_p.sum(1))); nbr.append(z["p2p_gidx"][ok_p]) + return np.concatenate(src), np.concatenate(nbr) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--ckpt", required=True) + ap.add_argument("--out", required=True) + ap.add_argument("--hdf5", default=f"{ROOT}/data/raw/cooking_v5_expert_suboptimal.hdf5") + ap.add_argument("--pairs", default=f"{ROOT}/data/derived/cooking_v5_knn_pairs_ee.npz") + ap.add_argument("--thr", type=float, default=0.01) + ap.add_argument("--augment-play", type=int, default=1) + ap.add_argument("--batch", type=int, default=512) + args = ap.parse_args() + import robomimic.utils.file_utils as FileUtils, robomimic.utils.tensor_utils as TensorUtils, robomimic.utils.obs_utils as ObsUtils + dev = torch.device("cuda") + policy, _ = FileUtils.policy_from_checkpoint(ckpt_path=args.ckpt, device=dev, verbose=False) + algo = policy.policy; algo.set_eval() + critics, vf = algo.nets["critic_target"], algo.nets["vf"] + obs_keys = list(algo.obs_shapes.keys()) + print(f"[adv] ckpt {args.ckpt} obs_keys={obs_keys} n_critics={len(critics)} beta(sim)={algo.algo_config.adv.beta}", flush=True) + t0 = time.time() + with h5py.File(args.hdf5, "r") as f: + demos = sorted(f["data"].keys(), key=lambda k: int(k.split("_")[1])) + lengths = [int(f["data"][d].attrs["num_samples"]) for d in demos] + starts = np.concatenate([[0], np.cumsum(lengths)[:-1]]); N = int(sum(lengths)) + obs_all = {k: [] for k in obs_keys}; act_all = [] + for d in demos: + g = f["data"][d] + for k in obs_keys: obs_all[k].append(g["obs"][k][()]) + act_all.append(g["actions"][()]) + obs_all = {k: np.concatenate(v) for k, v in obs_all.items()}; act_all = np.concatenate(act_all).astype(np.float32) + assert len(act_all) == N + print(f"[adv] loaded {N} frames in {time.time()-t0:.0f}s", flush=True) + + @torch.no_grad() + def score(oidx, aidx): + q_out, v_out = [], [] + for b0 in range(0, len(oidx), args.batch): + oi, ai = oidx[b0:b0 + args.batch], aidx[b0:b0 + args.batch] + ob = {k: torch.from_numpy(np.ascontiguousarray(obs_all[k][oi])) for k in obs_keys} + ob = TensorUtils.to_float(TensorUtils.to_device(ob, dev)) + ob = ObsUtils.process_obs_dict(ob) # rgb -> CHW / 255, as in training + acts = torch.from_numpy(act_all[ai]).to(dev) + qs = torch.cat([c(obs_dict=ob, acts=acts) for c in critics], dim=1).min(dim=1, keepdim=True)[0] + v = vf(obs_dict=ob) + q_out.append(qs[:, 0].cpu().numpy()); v_out.append(v[:, 0].cpu().numpy()) + return np.concatenate(q_out), np.concatenate(v_out) + + idx = np.arange(N) + q, v = score(idx, idx); adv = q - v + print(f"[adv] frames: q mean {q.mean():.4f} v mean {v.mean():.4f} adv mean {adv.mean():.4f} sd {adv.std():.4f} " + f"p5/p50/p95 {np.percentile(adv,5):.4f}/{np.percentile(adv,50):.4f}/{np.percentile(adv,95):.4f} {time.time()-t0:.0f}s", flush=True) + z = np.load(args.pairs, allow_pickle=False) + src, nbr = knn_pairs(z, args.thr, bool(args.augment_play)) + qp, vp = score(src, nbr); adv_pairs = qp - vp + print(f"[adv] {len(src)} kNN pairs (thr {args.thr}): adv mean {adv_pairs.mean():.4f} sd {adv_pairs.std():.4f} " + f"p5/p50/p95 {np.percentile(adv_pairs,5):.4f}/{np.percentile(adv_pairs,50):.4f}/{np.percentile(adv_pairs,95):.4f}", flush=True) + rew = z["reward"] + for name, m in (("expert frames", rew > 0), ("suboptimal frames", rew == 0)): + print(f"[adv] {name}: adv mean {adv[m].mean():.4f} exp(adv) mean {np.exp(np.clip(adv[m], None, np.log(100))).mean():.3f}") + np.savez_compressed(args.out, adv=adv.astype(np.float32), q=q.astype(np.float32), v=v.astype(np.float32), + adv_pairs=adv_pairs.astype(np.float32), pair_src=src, pair_nbr=nbr, thr=args.thr, + augment_play=int(args.augment_play), ckpt=args.ckpt, hdf5=args.hdf5, pairs=args.pairs, n_frames=N) + print(f"[adv] wrote {args.out} {time.time()-t0:.0f}s") + + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/real/score_nnl1.py b/rsm_rise/scripts/real/score_nnl1.py new file mode 100644 index 0000000000000000000000000000000000000000..1584ae8ede563c534b58cf8e69c26065f8e82d45 --- /dev/null +++ b/rsm_rise/scripts/real/score_nnl1.py @@ -0,0 +1,290 @@ +#!/usr/bin/env python +"""Offline successor-fit scorer: re-score saved checkpoints under ONE FIXED protocol. + +Why this exists. The in-training `--eval-nnl1-*` hook samples beta with the run's OWN +`--beta-trunc-eps`, so the capped and uncapped arms of the truncation A/B were scored on +DIFFERENT beta distributions and their nnl1 numbers were not comparable. It also draws a fresh +256-anchor batch each eval, and the resulting jitter is the same size as the entire late-training +change, so the argmin of the in-training curve is selection noise rather than a peak. + +This script fixes both: one FIXED eval beta_trunc_eps for every arm, a FIXED anchor seed, and R +independent repeats so every number carries a standard error. + +Metrics (all in the z-scored 1546-d cache state, L1 per dim): + in samples vs the anchor trajectory's OWN FUTURE + cross the same samples vs ONE DIFFERENT trajectory (the control) + rand random pool frames vs the own future (what chance achieves) + stay the anchor latent itself vs its own future + stay_cross the anchor latent vs the different trajectory + vs_stay (in/cross) / (stay/stay_cross) -- the honest zero point, because sample_future + returns z_now + rms*residual and is therefore anchored at the anchor + sameseg / nextseg own future restricted to the current / a LATER segment +""" +from __future__ import annotations +import argparse, json, sys, time +from pathlib import Path +import numpy as np +import torch + +sys.path.insert(0, "/proj/dmfexp/zwhong/projs/issue_resolver_richardrl/gen_q_rsm/rsm_libero") +from data import LiberoRSMData # noqa: E402 +from model import RewardHead, OccFlow, IdentityEncoder # noqa: E402 +from train_rsm import sample_future, auc # noqa: E402 + + +def build(ckpt, dev): + c = torch.load(ckpt, map_location=dev, weights_only=False) + cfg = c["config"] + d_lat = int(c["d_lat"]); d_act = int(c["d_act"]) + n_task = len(c["tasks"]) + enc = IdentityEncoder(int(c["d_in"])).to(dev).eval() + rew = RewardHead(d_lat, n_task).to(dev).eval() + flow = OccFlow(d_lat, d_act, n_task, width=int(cfg["flow_width"]), + depth=int(cfg["flow_depth"]), norm=bool(cfg.get("flow_norm", 0)), + dropout=float(cfg.get("flow_dropout", 0.0))).to(dev).eval() + rew.load_state_dict(c["rew"]); flow.load_state_dict(c["flow"]) + return c, cfg, enc, rew, flow, c["rms"].to(dev), int(c["step"]) + + +def make_pool(d, enc, dev, cache, n_pool): + stride = max(1, int(d.ep_to[-1]) // max(n_pool, 1)) + idx = np.concatenate([np.arange(int(d.ep_from[i]), int(d.ep_to[i]), stride, dtype=np.int64) + for i in range(d.n_ep)]) + ep_of = np.zeros(len(idx), np.int64) + for i in range(d.n_ep): + ep_of[(idx >= d.ep_from[i]) & (idx < d.ep_to[i])] = i + with torch.no_grad(): + Z = torch.cat([torch.from_numpy(d._feat(idx[j:j + 2048])).to(dev).half() + for j in range(0, len(idx), 2048)]) + by_ep = {int(i): np.nonzero(ep_of == i)[0] for i in np.unique(ep_of)} + try: + segf = np.load(Path(cache) / "seg.i16.npy") + if len(segf) != int(d.ep_to[-1]): + segf = None + except Exception: + segf = None + tr = set(int(x) for x in d.train_eps) + eps_all = np.array(sorted(by_ep.keys()), np.int64) + return {"Z": Z, "t": idx, "by_ep": by_ep, "eps": eps_all, "segf": segf, + "seg": (segf[idx] if segf is not None else None), + "eps_by_split": {"train": np.array([e for e in eps_all if int(e) in tr], np.int64), + "val": np.array([e for e in eps_all if int(e) not in tr], np.int64)}} + + +@torch.no_grad() +def score_once(d, P, enc, rew, flow, rms, cfg, dev, rng, split, B, K, M, trunc_eps, + flow_steps, sample_clip, beta_lo, beta_hi, tgen=None): + b = d.sample(B, rng, beta_lo, beta_hi, split, dev, trunc_eps) + z_now = b["x_now"] # identity encoder: lat(x) = x + t_np, ep_np = b["t_idx"], b["ep"] + in_i = np.zeros((B, M), np.int64); cr_i = np.zeros((B, M), np.int64) + sg_i = np.zeros((B, M), np.int64); nx_i = np.zeros((B, M), np.int64) + sg_ok = np.zeros(B, bool); nx_ok = np.zeros(B, bool); keep = np.zeros(B, bool) + for i in range(B): + e = int(ep_np[i]); cand = P["by_ep"].get(e) + if cand is None: continue + fut = cand[P["t"][cand] > int(t_np[i])] + if len(fut) == 0: continue + pe = P["eps_by_split"].get(split, P["eps"]) + if len(pe) < 2: pe = P["eps"] + others = pe[pe != e] + if len(others) == 0: continue + oc = P["by_ep"][int(rng.choice(others))] + in_i[i] = rng.choice(fut, size=M, replace=len(fut) < M) + cr_i[i] = rng.choice(oc, size=M, replace=len(oc) < M) + keep[i] = True + if P["seg"] is not None: + s0 = int(P["segf"][int(t_np[i])]) + sm = fut[P["seg"][fut] == s0]; lt = fut[P["seg"][fut] > s0] + if len(sm): sg_i[i] = rng.choice(sm, size=M, replace=len(sm) < M); sg_ok[i] = True + if len(lt): nx_i[i] = rng.choice(lt, size=M, replace=len(lt) < M); nx_ok[i] = True + kp = np.nonzero(keep)[0] + kpt = torch.from_numpy(kp).to(dev) + zk = z_now[kpt] + bk = {k: (v[kpt] if torch.is_tensor(v) else v[kp]) for k, v in b.items()} + nB = len(kp) + # RNG PINNING. sample_future draws its Euler initial noise from the GLOBAL torch RNG when x0 + # is None, so a score depended on how many checkpoints had been scored before it in the same + # process: the same ckpt under the same protocol reproduced only to ~4e-4, which is below the + # truncation-A/B deltas being quoted (3e-3 to 1.1e-2). Passing an explicit x0 from a dedicated + # seeded Generator makes every arm see the IDENTICAL noise draws (common random numbers, which + # is also what sample_future's x0 argument exists for) and makes repeats bit-reproducible. + x0 = None + if tgen is not None: + x0 = torch.randn(nB * K, zk.shape[1], generator=tgen, device=dev) + xs = sample_future(flow, zk, bk["a_now"], bk["task"], bk["beta"], rms, flow_steps, n=K, x0=x0) + if sample_clip > 0: + xs = xs.clamp(-sample_clip, sample_clip) + dimf = xs.shape[-1] + xs = xs.view(nB, K, dimf).float() + rnd = P["Z"][torch.from_numpy(rng.choice(len(P["t"]), size=nB * K)).to(dev)] \ + .view(nB, K, dimf).float() + + def nn(q, cidx, sel=None): + sel = np.arange(len(cidx)) if sel is None else sel + acc = [] + for j in range(0, len(sel), 32): + ss = sel[j:j + 32] + C = P["Z"][torch.from_numpy(cidx[ss]).to(dev)].float() + acc.append(torch.cdist(q[torch.from_numpy(ss).to(dev)], C, p=1) + .div_(dimf).min(-1).values) + return float(torch.cat(acc).mean()) + + o = {"in": nn(xs, in_i[kp]), "cross": nn(xs, cr_i[kp]), "rand": nn(rnd, in_i[kp]), + "stay": nn(zk.float()[:, None], in_i[kp]), + "stay_cross": nn(zk.float()[:, None], cr_i[kp]), "n_anchors": int(nB)} + o["ratio"] = o["in"] / max(o["cross"], 1e-12) + o["ratio_stay"] = o["stay"] / max(o["stay_cross"], 1e-12) + o["vs_stay"] = o["ratio"] / max(o["ratio_stay"], 1e-12) + if P["seg"] is not None: + for tag, ok, ci in (("sameseg", sg_ok, sg_i), ("nextseg", nx_ok, nx_i)): + sel = np.nonzero(ok[kp])[0] + if len(sel) >= 8: + o[tag] = nn(xs, ci[kp], sel); o[tag + "_n"] = int(len(sel)) + logit_anchor = rew(zk, bk["task"]).float() + pr = torch.sigmoid(logit_anchor).cpu().numpy().ravel() + lab = bk["r_now"].float().cpu().numpy().ravel() + o["rhead_mae"] = float(np.abs(pr - lab).mean()) + # AUC ON THE LOGIT, not the probability. auc() is rank-based and the two are rank-equivalent + # when nothing ties -- but at mean|logit| ~67 the sigmoid returns EXACTLY 0.0/1.0 in fp32, so + # 98% of scores tie and a rank AUC collapses toward 0.5 no matter how well the head separates. + # That is the same saturation failure as prob-ranking in the open-loop scorer, hitting my own + # metric: the sigmoid-based AUC read 0.533 on a head whose logit-based AUC is near 1. Both are + # reported so the gap is visible rather than silently absorbed. + o["rhead_auc"] = auc(logit_anchor.cpu().numpy().ravel(), lab) + o["rhead_auc_prob"] = auc(pr, lab) + o["rhead_pos_rate"] = float((lab > 0.5).mean()) + # ---- SATURATION DIAGNOSTIC (#266): which ranking array is usable is a property of the + # checkpoint, not a principled choice. At mean|logit| ~28 the sigmoid underflows or ties at + # 1.0, so Q-bar = mean sigmoid carries no ordering across candidates and only `logit` ranks; + # where the head is well-scaled, prob's product fold aggregates more evidence and wins. + # mean|logit| is the number that tells you which, so it is reported with every score. + # Measured in BOTH places, because they can differ and the difference is the informative part: + # _anchor = on real cache states (on-manifold saturation) + # _samples = on the flow's sampled successors, which is where the scorer actually evaluates + lg_s = rew(xs.reshape(-1, dimf), bk["task"].repeat_interleave(K, 0)).float() + o["rhead_logit_abs_anchor"] = float(logit_anchor.abs().mean()) + o["rhead_logit_abs_samples"] = float(lg_s.abs().mean()) + o["rhead_logit_sat_frac_anchor"] = float((logit_anchor.abs() > 15).float().mean()) + o["rhead_logit_sat_frac_samples"] = float((lg_s.abs() > 15).float().mean()) + o["rhead_prob_spread_samples"] = float( + torch.sigmoid(lg_s).view(-1, K).std(1).mean()) # what prob-ranking has left to rank on + o["rhead_logit_spread_samples"] = float(lg_s.view(-1, K).std(1).mean()) + return o + + +@torch.no_grad() +def rhead_exact(d, rew, dev, split, bs=8192): + """Reward-head MAE/AUC over EVERY frame of the split, not a sampled anchor batch. + + A 256- or 1024-anchor draw cannot validate a sparse label here: the seed-0 val split holds only + 2 of the 50 rewarded episodes, so at k=40 the val base rate is 4.4e-4 and a 256-anchor eval sees + ~0.1 positives. The in-training `val auc` for the terminal cells is noise for that reason. This + pass is exact and costs one forward over ~18k rows. + """ + eps = d.val_eps if split == "val" else d.train_eps + rows = np.concatenate([np.arange(int(d.ep_from[e]), int(d.ep_to[e])) for e in eps]) + lg, lab = [], d.r[rows] + for j in range(0, len(rows), bs): + x = torch.from_numpy(d._feat(rows[j:j + bs])).to(dev) + t = torch.zeros(len(x), dtype=torch.long, device=dev) + lg.append(rew(x, t).float().cpu().numpy().ravel()) + lg = np.concatenate(lg) + return {"n_frames": int(len(rows)), "n_pos": int((lab > 0.5).sum()), + "base_rate": float((lab > 0.5).mean()), + "auc_logit": auc(lg, lab), "mae": float(np.abs(1 / (1 + np.exp(-lg)) - lab).mean()), + "logit_absmean": float(np.abs(lg).mean()), + "n_pos_episodes": int(sum(1 for e in eps if d.r[int(d.ep_from[e]):int(d.ep_to[e])].max() > 0.5))} + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--cache", default="/proj/dmfexp/zwhong/rsm_rise/cache/real_cooking_v5") + ap.add_argument("--ckpts", nargs="+", required=True) + ap.add_argument("--trunc-eps", type=float, default=0.02, + help="FIXED eval-time beta_trunc_eps applied to EVERY arm") + ap.add_argument("--split", default="val") + ap.add_argument("--b", type=int, default=1024) + ap.add_argument("--k", type=int, default=16) + ap.add_argument("--m", type=int, default=128) + ap.add_argument("--repeats", type=int, default=8) + ap.add_argument("--pool", type=int, default=20000) + ap.add_argument("--seed", type=int, default=12345) + ap.add_argument("--out", default="") + args = ap.parse_args() + dev = "cuda" if torch.cuda.is_available() else "cpu" + print(f"[score] FIXED protocol: trunc_eps={args.trunc_eps} split={args.split} " + f"B={args.b} K={args.k} M={args.m} repeats={args.repeats} seed={args.seed} dev={dev}", + flush=True) + + res = {} + d = None; d_key = None + for ck in args.ckpts: + ck = Path(ck) + if not ck.exists(): + print(f"[score] MISSING {ck}"); continue + c, cfg, enc, rew, flow, rms, step = build(ck, dev) + # The REWARD LABEL is part of the dataset, so a single shared LiberoRSMData silently scored + # every checkpoint against the FIRST one's labels -- a terminal-trained head was being + # evaluated against dense labels and read AUC 0.53 (chance) for that reason alone. Rebuild + # whenever the label definition changes. (The nnl1 geometry columns never touch d.r, so + # earlier all-dense comparisons were unaffected.) + # the SPLIT is part of the label too: a stratified checkpoint must be scored on its own + # val episodes or the held-out numbers are not its held-out numbers. + strat = bool(cfg.get("stratify_success", 0)) + key = (cfg["reward_mode"], int(cfg["k_success"]), int(cfg["seed"]), strat) + if d is None or key != d_key: + d = LiberoRSMData(args.cache, chunk=int(cfg["chunk"]), k_success=int(cfg["k_success"]), + seed=int(cfg["seed"]), in_ram=True, val_frac=0.1, + reward_mode=cfg["reward_mode"], stratify_success=strat) + d_key = key + P = make_pool(d, enc, dev, args.cache, args.pool) + print(f"[score] pool {len(P['t'])} frames; {d.n_ep} eps " + f"({len(d.train_eps)}tr/{len(d.val_eps)}va), dim={d.feat_dim}, " + f"reward={key[0]} k={key[1]} stratified={strat} " + f"base_rate={float(d.r.mean()):.5f}", flush=True) + # NOTE: chunk differs for R_M_chunk20, so d.chunk must match that ckpt's config. + if int(cfg["chunk"]) != d.chunk: + d.chunk = int(cfg["chunk"]) + acc = [] + t0 = time.time() + for r in range(args.repeats): + rng = np.random.default_rng(args.seed + 1000 * r) # SAME anchors across arms + tgen = torch.Generator(device=dev) # SAME flow noise across arms + tgen.manual_seed(args.seed + 1000 * r) + acc.append(score_once(d, P, enc, rew, flow, rms, cfg, dev, rng, args.split, + args.b, args.k, args.m, args.trunc_eps, + int(cfg["flow_steps"]), float(cfg["sample_clip"]), + float(cfg["beta_lo"]), float(cfg["beta_hi"]), tgen)) + keys = [k for k in acc[0] if not k.endswith("_n") and k != "n_anchors"] + agg = {k: (float(np.mean([a[k] for a in acc])), + float(np.std([a[k] for a in acc], ddof=1) / np.sqrt(len(acc)))) for k in keys} + tag = f"{ck.parent.name}@s{step}" + exact = {sp: rhead_exact(d, rew, dev, sp) for sp in ("train", "val")} + print(f"[score] {tag} EXACT reward head over every frame:") + for sp, e in exact.items(): + print(f"[score] {sp:5s} n={e['n_frames']:6d} pos={e['n_pos']:5d} " + f"({e['base_rate']:.5f}, {e['n_pos_episodes']} eps) auc={e['auc_logit']:.4f} " + f"mae={e['mae']:.4f} |logit|={e['logit_absmean']:.2f}") + res[tag] = {"mean_sem": agg, "rhead_exact": exact, "cell": ck.parent.name, "step": step, + "reward_mode": cfg["reward_mode"], "k_success": int(cfg["k_success"]), + "train_trunc_eps": float(cfg.get("beta_trunc_eps", 0.02)), + "beta_lo": float(cfg["beta_lo"]), "beta_hi": float(cfg["beta_hi"]), + "chunk": int(cfg["chunk"]), "flow_width": int(cfg["flow_width"]), + "secs": time.time() - t0} + print(f"\n[score] {tag} (train trunc_eps={cfg.get('beta_trunc_eps',0.02)}, " + f"w={cfg['flow_width']}, chunk={cfg['chunk']}, {time.time()-t0:.0f}s)") + for k in ("in", "cross", "rand", "stay", "stay_cross", "ratio", "ratio_stay", "vs_stay", + "sameseg", "nextseg", "rhead_mae", "rhead_auc", + "rhead_logit_abs_anchor", "rhead_logit_abs_samples", + "rhead_logit_sat_frac_anchor", "rhead_logit_sat_frac_samples", + "rhead_prob_spread_samples", "rhead_logit_spread_samples", "rhead_auc_prob"): + if k in agg: + print(f"[score] {k:11s} = {agg[k][0]:.4f} +/- {agg[k][1]:.4f}") + if args.out: + Path(args.out).write_text(json.dumps(res, indent=2)) + print(f"\n[score] wrote {args.out}") + + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/real/scorer_openloop.py b/rsm_rise/scripts/real/scorer_openloop.py new file mode 100644 index 0000000000000000000000000000000000000000..dc41f4f5e9b3b2a4bef46904b86de148df7fa467 --- /dev/null +++ b/rsm_rise/scripts/real/scorer_openloop.py @@ -0,0 +1,769 @@ +#!/usr/bin/env python +"""OPEN-LOOP scorer comparison on held-out episodes (#263 item 2). No hardware, no closed loop. + +At every --stride-th frame of every held-out episode: draw the SAME N candidate action chunks from one proposal +policy, then let each scorer pick one and measure ||chosen - logged expert chunk||_2 (xyz, cm). Lower is better. +Because all scorers see the identical candidate set at the identical state, the only difference between columns is +the ranking rule -- so this isolates "does the scorer pick better actions than sampling?" without a robot. + +RANKING QUALITY (#264 ask). For every decision the oracle induces a total order over that decision's N candidates +(by |chosen xyz - logged xyz|). For each scorer we record where its pick lands in that order: + rank_pct = (# candidates strictly worse than the pick) / (N - 1) 1.0 = the oracle's own choice, 0.0 = worst +greedy is uniform by construction (candidate 0 is an unbiased draw), so its mean rank_pct ~ 0.5 is the built-in null; +a scorer that ranks well sits above it, and one that anti-selects sits below. Per-candidate score and error vectors +are persisted to scores.npz so later metrics need no re-scoring. + +Scorers: greedy (candidate 0, i.e. a plain sample) | idql (argmax min_k Q_target_k) | permuted (same scores, shuffled +-- the control) | oracle (argmin of the true error; the attainable ceiling of the candidate set) | rsm (once #261's +successor checkpoint exists). Reported per scorer: mean/median/p90 of the first-action error, of the chunk-mean +error, the win rate vs greedy, and the candidate spread (so a degenerate candidate set is visible). +""" +from __future__ import annotations +import argparse, json, sys, time +from pathlib import Path +import numpy as np + +ROOT = "/proj/dmfexp/zwhong/rsm_rise" +sys.path.insert(0, f"{ROOT}/scripts/real") + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--policy", required=True, help="robomimic: | openpi:: | random") + ap.add_argument("--idql-ckpt", default=None) + ap.add_argument("--rsm-ckpt", default=None) + ap.add_argument("--rsm-cache", default=f"{ROOT}/cache/real_cooking_v5", help="DINO cache the successor was trained on") + ap.add_argument("--rsm-backend", default="mlp") + # gen_q#272 (owner 2026-09-22 20:45Z conformance audit): the DEFAULT read-out is the + # coin-terminated beta chain -- the planner of RSM_PLANNING_SPEC.tex. `fold` is still + # selectable HERE (this is the research repo; the twin ships the chain only) so the + # pre-#272 real-rig screens in status/real/openloop_* can be reproduced, but every number + # measured with it is a fixed-depth fold number and must be labelled as one. + ap.add_argument("--rsm-mode", default="chain") + ap.add_argument("--rsm-depth", type=int, default=2, help="fold only; the chain's length is drawn " + "and its cap is computed from (beta, gamma)") + ap.add_argument("--rsm-beta", type=float, default=0.95, + help="must be < gamma or the chain degenerates to one draw (p = 0)") + ap.add_argument("--rsm-gamma", type=float, default=0.99, + help="the planner's discount. The chain needs beta < gamma; at beta == gamma p = 0 and the " + "walk is a SINGLE beta-read with no composition (gen_q#276, owner 2026-09-23 11:30Z).") + ap.add_argument("--rsm-particles", type=int, default=16) + ap.add_argument("--rsm-flow-steps", type=int, default=8, + help="Euler steps of the occupancy flow per sampled hop (gen_q#278 rung R). The " + "chain's CANDIDATE ACTION conditions only the FIRST hop, so the accuracy of " + "that one sample is what the ranking rides on; rung Q measured the action-" + "conditioned share of the score (W/A 0.41 -> 0.72 as the action fraction went " + "0.10 -> 0.50) but bought only +0.015 of d_vs_greedy, so the remaining " + "standard eval knob is the integration itself. 8 = the RSMScorer default " + "that EVERY arm measured before 2026-09-24 ran, so the default reproduces " + "them bit-identically.") + ap.add_argument("--rsm-temperature", type=float, default=0.0, + help="plan_temp for the fold: c_k = sigma(R(z_k)/T). 0 = the checkpoint's " + "calib.json T, else 1.0 (which is what the real cells have been running, NOT " + "sim's archived 0.2). A LARGER T pulls R/T toward 0, de-saturates the sigmoid " + "and should collapse the tie count while KEEPING the product fold's " + "aggregation over hops -- the property the logit array discards by reading " + "only the terminal hop. At mean|logit| 25 (dense) / 70 (terminal k=40) on this " + "cache, leaving saturation needs T of roughly 6 / 18.") + ap.add_argument("--rsm-score-kind", default="prob", choices=["prob", "logit"], + help="ranking array: prob = mean sigmoid (historic); logit = mean raw logit, which " + "does not saturate. d1/fold + mlp backend only.") + ap.add_argument("--rsm-hop-ckpt", default="", help="Stage-2 hop head; required by the fold read-out at depth>1") + ap.add_argument("--rsm-ckpt-extra", action="append", default=[], metavar="NAME=PATH", + help="repeatable: an EXTRA successor checkpoint scored as column 'rsm@NAME' with the " + "SAME read-out settings on the SAME candidates as --rsm-ckpt. Candidate generation " + "(the expensive part: N diffusion samples per decision) happens once, so K reward-head " + "variants cost one proposal pass instead of K -- and the comparison is exactly paired, " + "decision by decision (#261 reward-head study).") + ap.add_argument("--tag", default="") + ap.add_argument("--hdf5", default=f"{ROOT}/data/raw/cooking_v5_expert_suboptimal.hdf5") + ap.add_argument("--split", default=f"{ROOT}/data/derived/cooking_v5_split.json") + ap.add_argument("--n-cand", type=int, default=128) + ap.add_argument("--cand-shrink", type=float, default=1.0, metavar="ALPHA", + help="#269 run 49: contract each decision's candidate cloud toward its OWN mean, " + "c_i <- mean + ALPHA*(c_i - mean), applied to the proposer's draws right after " + "sampling and BEFORE the error / spread / scorer read-out. Rationale: run 48 " + "measured `rsm` lag-1 r across four TRAINED arms (spread 0.148 -> 0.620 cm) and " + "found a threshold, not a gradient -- but every arm changes the training recipe " + "AND the spread together, so spread is confounded with the recipe and no arm " + "sits in the 0.148-0.332 cm interval where the transition must be. This knob " + "moves spread with the proposer HELD FIXED (spread is a scale statistic of the " + "cloud, so it scales by exactly ALPHA), which both bisects that interval and " + "turns the published mechanism into a falsifiable claim: contracting the wide " + "arm to stock's spread must RESTORE stock's autocorrelation if spread is the " + "causal variable. ALPHA<1 keeps candidates inside the convex hull of real " + "draws (on-manifold); ALPHA>1 extrapolates OFF the proposer's manifold and any " + "row measured that way must say so. ALPHA=1 is exactly the unmodified run.") + ap.add_argument("--horizon", type=int, default=8) + ap.add_argument("--stride", type=int, default=25) + ap.add_argument("--max-eps", type=int, default=0) + ap.add_argument("--lerobot-root", default=f"{ROOT}/data/real/rsm_cooking_v5", + help="#269: an openpi (pi0.5) proposer needs the FULL-RESOLUTION frames, which the 84 px hdf5 " + "does not carry. They live in the LeRobot copy of the same episodes as two mp4s per " + "episode; observation.state / action there are bit-identical to the hdf5's ee_state / " + "actions_raw (checked on the held-out episodes), so the decision grid, the ground truth, " + "the IDQL critic's 84 px obs and the RSM's DINO features are unchanged -- only the " + "proposer's camera input is upgraded. Decoded lazily, one episode at a time.") + ap.add_argument("--seed", type=int, default=0) + # gen_q#278: a REPLICATE that keeps the candidate draw fixed and re-seeds ONLY the scorers, so the + # within-anchor (action) component of a score can be split into signal and Monte-Carlo noise. + # Default None => use --seed, i.e. every previously measured number is bit-identical. + ap.add_argument("--scorer-seed", type=int, default=None) + # ---- gen_q#276 OFFLINE EDGE TEST (rise_stack/EDGE_TEST.md). Same harness, same candidate draw, + # same scorers: the only addition is that each candidate chunk is CLASSIFIED into a graph edge by the + # direction its end-effector displacement takes (actions_raw is an ABSOLUTE ee target, so a chunk at + # frame t proposes the displacement a[edge_horizon-1,:3] - p_t), and the decision grid is replaced by + # the ANCHOR grid -- frames on the shared prefix of a branch state, where a counterfactual exists. + ap.add_argument("--edge-test", action="store_true") + ap.add_argument("--edge-horizon", type=int, default=0, help="chunk index used for the displacement; 0 = --horizon") + ap.add_argument("--edge-knn", type=int, default=64) + ap.add_argument("--edge-min-move-mm", type=float, default=2.0) + ap.add_argument("--edge-anchor-radius-mm", type=float, default=30.0) + ap.add_argument("--edge-anchor-min-support", type=int, default=20) + ap.add_argument("--edge-min-sep-deg", type=float, default=30.0, + help="an anchor is admissible only where EVERY pair of edges leaving that state has " + "direction fields at least this far apart. At S0 the on-route edge 0->1 and the " + "failure edge 0->5 both begin by reaching for the tomato, so before the grasp no " + "direction separates them and an anchor there carries zero information for ANY " + "ranking rule; this threshold is a property of the LABELS and the geometry only.") + ap.add_argument("--edge-anchor-stride", type=int, default=0, help="0 = use --stride") + # 2026-09-23 18:15Z correction (gen_q#281): the direction ruler is only sound NEAR meta-state ENTRY + # (proxy_fidelity_window.py, jobs 1884691/1884695). Restrict anchors to the first W frames of the + # state. 0 = the whole meta state = the historic behaviour, so every existing arm is reproducible. + ap.add_argument("--edge-entry-window", type=int, default=0, + help="anchor only within W frames of the episode's ENTRY into the meta state; 0 = all") + ap.add_argument("--edge-states", default="", + help="comma list of branch states to anchor on (e.g. '2'); empty = all of BRANCH_STATES") + ap.add_argument("--edge-max-anchors-per-ep", type=int, default=0) + # RANK_CTRL (gen_q#276 ADDENDUM 2026-09-23): the discrepancy between the LOGGED-chunk ranking test + # (top-1 0.969) and the PROPOSER-candidate edge test (rank pct 0.464, i.e. chance) has two readings -- + # (a) the logged result is on-manifold PROVENANCE (the anchor's own chunk is the only in-distribution + # candidate) or (b) the value is goal-directed but the 128 proposer draws carry no spread of + # goal-relevance. Injecting REAL logged chunks into the proposer's candidate set at the same anchor + # separates them: under (a) every injected logged chunk beats all 128 draws regardless of its route; + # under (b) only the goal-route one does. + ap.add_argument("--inject-logged", action="store_true", + help="append 3 logged chunks to each anchor's candidate set: own (this episode at t), " + "goal (route 2->3->4, same stage, other episode), fail (route 0->2->6, same stage)") + ap.add_argument("--inject-stride", type=int, default=25, help="chunk stride of the injection pool") + # MEASURED 2026-09-23 20:0xZ (RANK_CTRL, on edge_INJ_base/edge_parts): the unmatched injection is + # CONFOUNDED. At the 257 S2 anchors the injected goal/fail chunks displace 178.3 / 143.2 mm over the + # same H=8 frames while the proposer's 128 draws displace 25.1 mm with a within-anchor sd of 5.4 mm -- + # i.e. the injected chunks sit ~28 sd outside the cloud and are separable on gross speed alone, with no + # notion of route. `own` (29.9 mm, magnitude rank 0.705) is the only injected chunk inside the cloud, + # and it is also the only one the RSM does not bury. So "goal and fail both rank last" cannot + # distinguish provenance from goal-direction until the magnitude is matched. + ap.add_argument("--inject-mag-match", type=float, default=0.0, metavar="TOL", + help="draw the goal/fail injection chunks only from pool entries whose end-effector " + "displacement ||chunk[-1,:3]-chunk[0,:3]|| is within a factor TOL of the anchor's " + "OWN logged chunk (kept if 1/TOL <= ratio <= TOL, so 1.5 means +-50%%). 0 = off, " + "which reproduces the unmatched arm exactly. With this on, route provenance is " + "the only remaining difference between the goal and fail injections.") + # MEASURED 2026-09-23 20:3xZ (RANK_CTRL, on edge_INJMM_*): --inject-mag-match matched the WRONG + # quantity. It constrains the chunk's INTERNAL displacement, but every read-out uses + # disp = cands[:, eh-1, :3] - p_now, measured from the ANCHOR'S pose. The action is an ABSOLUTE ee + # target (job 1881603), so an injected chunk from another episode is a command sequence for wherever + # THAT episode's arm was: matching moved cand_mag_mm only 178.3->157.8 (goal) / 143.2->134.1 mm (fail) + # against a cloud at 23.5 +- 3.4 mm whose largest draw reaches 40.2 mm. The injected candidates are + # ~100 mm DISCONTINUOUS TELEPORTS and every pose-continuity-sensitive scorer buries them for that + # reason alone, regardless of route. Re-basing removes the teleport and keeps the MOTION under test. + ap.add_argument("--inject-rebase", action="store_true", + help="translate each injected logged chunk so chunk[0,:3] coincides with the anchor's " + "own first commanded pose, leaving rotation/gripper dims alone. Without this an " + "injected chunk is a ~100 mm teleport from p_now and the arm cannot separate " + "provenance from goal-direction. Run WITHOUT --inject-mag-match: re-basing " + "subsumes the offset and keeping both is two changes in one measurement.") + ap.add_argument("--baselines", default="", + help="comma list of GOAL-BLIND plausibility baselines to score as extra columns on the " + "SAME candidate set: 'pose' = -||a[0] - p_now|| (zero-parameter pose continuity; " + "the action space is the ABSOLUTE 10-d ee pose, job 1881603) and 'bc' = " + "log pi_beta(a | s) under the Gaussian hop head the RSM chain itself hops with. " + "Both already exist for the LOGGED battery, where they read 1.000 and beat the RSM; " + "this puts them on the PROPOSER draws so the two batteries share a ruler. Each " + "name also gets its 'permuted:' control. Implemented by BaselineScorer from " + "logged_action_rank.py, so the backend / featurisation / action units are the same " + "objects the rsm column uses -- not a reimplementation.") + ap.add_argument("--baseline-hop-ckpt", default=f"{ROOT}/runs/real_cooking_v5/hop/gauss/policy_r1.pt", + help="the 'bc' baseline needs a TRACTABLE density, i.e. the gauss hop family, while the " + "chain read-out of record hops with the FLOW head. So bc is hosted on its own " + "second backend loaded with this checkpoint instead of borrowing the rsm column's " + "-- otherwise adding the baseline would silently change the RSM's own read-out, " + "which is two changes in one measurement. Same successor weights, hop head only.") + ap.add_argument("--edge-train-anchors", action="store_true", + help="debugging only: anchor on the TRAIN episodes. Headline numbers are held-out.") + ap.add_argument("--ep-ids", default="", + help="FT_EVAL guard 1 (gen_q#280): anchor on an EXPLICIT list of corpus episode ids " + "(comma-separated, or @file with one id per line), bypassing the train/valid " + "split entirely. Written for the frozen S0 SELECT/CONFIRM split " + "(status/real/S0_UPRANK_SPLIT.json), where 90 of the 100 S0-labelled episodes " + "are TRAIN episodes: the 25-episode valid screen keeps only ~15 episodes after " + "the >=4-of-each anchor filter, and an AUC bootstrapped over 15 episodes is " + "+-0.03. Any row measured with this flag is NOT a held-out number and must say " + "so. Applied BEFORE --ep-shard, so sharding stays exactly equivalent.") + ap.add_argument("--out", required=True) + ap.add_argument("--no-resume", action="store_true", + help="#269: ignore /parts/ep*.npz and recompute every episode. By default a " + "finished episode is cached there, so a preempted screen (these run in the " + "preemptable queue for ~70 min at N=128) restarts where it stopped instead of " + "losing everything -- job 1841739 lost 30 min that way.") + ap.add_argument("--ep-shard", default="", + help="#269 run 23: 'I/K' -- process only held-out episodes eps[I::K]. The 1-GPU ban " + "(admin 2026-09-22) forces screens through bsub_gpu_pack.sh, so a 25-episode screen " + "is split over the 4 GPUs of one node. This is EXACTLY equivalent to an unsharded " + "run: every episode's proposer noise and permuted shuffle are seeded per episode " + "from [seed, ep] (see the per-episode RNG block below), so an episode's candidates " + "do not depend on which episodes ran beside it. Shards share one --out: each writes " + "its own parts/ep*.npz, and a final unsharded pass resumes all 25 from parts and " + "writes scorer_openloop.json.") + a = ap.parse_args() + import h5py + from twin_rollout import RandomPolicy, RobomimicPolicy, OpenpiPolicy, Scorer, obs_key # noqa: F401 + t0 = time.time(); out = Path(a.out); out.mkdir(parents=True, exist_ok=True) + parts = out / "parts"; parts.mkdir(exist_ok=True) # one npz per finished episode (resume) + + def _k(m): # npz keys cannot keep the ':' of "permuted:idql" + return m.replace(":", "__").replace("@", "_AT_") + + def save_part(ep, meta, ep_rows, ep_rank, ep_spread, ep_err, ep_scores): + d = {"__meta__": np.frombuffer(json.dumps(meta).encode(), np.uint8), + "spread": np.asarray(ep_spread, np.float64), + "err_first": np.stack(ep_err).astype(np.float32) if ep_err else np.zeros((0, 0), np.float32)} + # float64 for the aggregated quantities: the summary is built from these, and float32 would make a + # resumed screen differ from an uninterrupted one in the 7th digit (test_screen_resume.sh compares + # them exactly). err_first / the score vectors are float32 in the un-resumed path too. + for m in ep_rows: d["rows_" + _k(m)] = np.asarray(ep_rows[m], np.float64).reshape(-1, 2) + for m in ep_rank: d["rank_" + _k(m)] = np.asarray(ep_rank[m], np.float64) + for m, v in ep_scores.items(): d["score_" + _k(m)] = np.stack(v).astype(np.float32) + # np.savez_compressed APPENDS .npz when the name does not end in it, so the tmp name must already + # end in .npz or the rename below chases a file that was never written (caught by test_screen_resume.sh). + tmp = parts / f"ep{ep:06d}.tmp.npz" + np.savez_compressed(tmp, **d); tmp.rename(parts / f"ep{ep:06d}.npz") + + def load_part(ep, modes_all): + f = parts / f"ep{ep:06d}.npz" + if not f.exists(): return None + try: + z = np.load(f) + meta = json.loads(bytes(z["__meta__"]).decode()) + r = {m: [tuple(x) for x in z["rows_" + _k(m)]] for m in modes_all} + k = {m: list(map(float, z["rank_" + _k(m)])) for m in modes_all} + sc = {m: list(z["score_" + _k(m)]) for m in modes_all if "score_" + _k(m) in z.files} + return meta, r, k, list(map(float, z["spread"])), list(z["err_first"]), sc + except Exception as e: # truncated by a kill mid-write -> just recompute + print(f"[ol] part ep{ep} unreadable ({e}); recomputing", flush=True); return None + with h5py.File(a.hdf5, "r") as f: + lo = np.array(json.loads(f["data"].attrs["action_min"]), np.float32) + hi = np.array(json.loads(f["data"].attrs["action_max"]), np.float32) + grip_thresh = float(f["data"].attrs["gripper_thresh"]) + kind = a.policy.split(":")[0] + if kind == "random": + pol = RandomPolicy(lo, hi, a.seed) + elif kind == "robomimic": + pol = RobomimicPolicy(a.policy.split(":", 1)[1], lo, hi) + elif kind == "openpi": + _, cfgname, ck = a.policy.split(":", 2); pol = OpenpiPolicy(cfgname, ck, a.seed) + else: + raise ValueError(a.policy) + extra_ck = dict(kv.split("=", 1) for kv in a.rsm_ckpt_extra) + modes = ["greedy"] + (["idql", "permuted:idql"] if a.idql_ckpt else []) + (["rsm", "permuted:rsm"] if a.rsm_ckpt else []) \ + + [f"rsm@{n}" for n in extra_ck] + # RSM state features: the cache's z, z-scored and clipped exactly as the trainer does (data.py). + zfeat = mu = sd = zclip = ep_from = None + if a.rsm_ckpt: + cache = Path(a.rsm_cache) + zfeat = np.load(cache / "z.f16.npy", mmap_mode="r") + # the #261 real cells were trained on [z | proprio] (the checkpoint says 1546-d = 1536 + 10), so the + # state is the cache's z concatenated with the cache's proprio, z-scored with feat_stats over both. + pfeat = np.load(cache / "proprio.f32.npy", mmap_mode="r") + st = np.load(cache / "feat_stats.npz"); m = np.load(cache / "meta.npz", allow_pickle=True) + d = zfeat.shape[1] + pfeat.shape[1] + mu, sd = st["mu"][:d].astype(np.float32), st["sd"][:d].astype(np.float32) + zclip = float(st["z_clip"]) if "z_clip" in st else 10.0 + ep_from = {int(e): int(v) for e, v in enumerate(m["ep_from"])} + print(f"[ol] rsm feats z{zfeat.shape} + proprio{pfeat.shape} -> d_in {d} z_clip {zclip} from {cache}", flush=True) + scorers = {m: Scorer(m, lo, hi, idql_ckpt=a.idql_ckpt, rsm_ckpt=a.rsm_ckpt, seed=a.seed, + rsm_backend=a.rsm_backend, rsm_mode=a.rsm_mode, rsm_depth=a.rsm_depth, + rsm_beta=a.rsm_beta, rsm_gamma=a.rsm_gamma, rsm_particles=a.rsm_particles, rsm_flow_steps=a.rsm_flow_steps, rsm_hop_ckpt=a.rsm_hop_ckpt, + rsm_score_kind=a.rsm_score_kind, rsm_temperature=a.rsm_temperature, + rsm_dim=(d if zfeat is not None else 1546)) for m in modes if not m.startswith("rsm@")} + # the extra reward-head variants: same class, same read-out knobs, different checkpoint. Scorer parses its + # own mode string, so it is constructed as a plain "rsm" and only the dict key carries the variant name. + for _n, _p in extra_ck.items(): + scorers[f"rsm@{_n}"] = Scorer("rsm", lo, hi, idql_ckpt=None, rsm_ckpt=_p, seed=a.seed, + rsm_backend=a.rsm_backend, rsm_mode=a.rsm_mode, rsm_depth=a.rsm_depth, + rsm_beta=a.rsm_beta, rsm_gamma=a.rsm_gamma, rsm_particles=a.rsm_particles, rsm_flow_steps=a.rsm_flow_steps, rsm_hop_ckpt=a.rsm_hop_ckpt, + rsm_score_kind=a.rsm_score_kind, rsm_temperature=a.rsm_temperature, + rsm_dim=(d if zfeat is not None else 1546)) + # --baselines: goal-blind plausibility columns on the SAME candidates. Appended AFTER the model + # columns and excluded from the per-episode RNG enumeration below (see BASE_MODES there), so every + # pre-existing column reproduces BIT-IDENTICALLY against a run without this flag -- which is what makes + # this one change per measurement rather than a re-seed of the whole screen. + BASE_MODES = [s for s in (x.strip() for x in a.baselines.split(",")) if s] + BASE_SET = set(BASE_MODES) | {"permuted:" + m for m in BASE_MODES} + if BASE_MODES: + unknown = [m for m in BASE_MODES if m not in ("pose", "bc")] + if unknown: + raise ValueError(f"--baselines: only pose/bc are wired here, got {unknown}") + if not a.rsm_ckpt: + raise ValueError("--baselines needs --rsm-ckpt: BaselineScorer hosts on the rsm backend") + from logged_action_rank import BaselineScorer + _host = scorers["rsm"].rsm # the RSMScorer, i.e. the SAME loaded MLPBackend + _host_bc = _host + if "bc" in BASE_MODES and a.baseline_hop_ckpt != a.rsm_hop_ckpt: + # second backend, gauss hop head, SAME successor checkpoint. See --baseline-hop-ckpt. + _host_bc = Scorer("rsm", lo, hi, idql_ckpt=None, rsm_ckpt=a.rsm_ckpt, seed=a.seed, + rsm_backend=a.rsm_backend, rsm_mode=a.rsm_mode, rsm_depth=a.rsm_depth, + rsm_beta=a.rsm_beta, rsm_gamma=a.rsm_gamma, rsm_particles=a.rsm_particles, rsm_flow_steps=a.rsm_flow_steps, + rsm_hop_ckpt=a.baseline_hop_ckpt, rsm_score_kind=a.rsm_score_kind, + rsm_temperature=a.rsm_temperature, + rsm_dim=(d if zfeat is not None else 1546)).rsm + print(f"[ol] bc baseline on its own gauss-hop host: {a.baseline_hop_ckpt}", flush=True) + for _bm in BASE_MODES: + for _pm in ("", "permuted:"): + scorers[_pm + _bm] = BaselineScorer(_pm + _bm, _host_bc if _bm == "bc" else _host, + seed=a.seed) + modes.append(_pm + _bm) + print(f"[ol] baselines={BASE_MODES} (+permuted) hosted on the rsm backend", flush=True) + print(f"[ol] policy={a.policy} scorers={modes} N={a.n_cand} horizon={a.horizon} stride={a.stride}", flush=True) + + EF = None + if a.edge_test: + from edge_field import (load_frames, stack, fit_fields, unit, ang_deg, edges_from, + ON_ROUTE, FAILURE, BRANCH_STATES) + eh = a.edge_horizon or a.horizon + _states = tuple(int(x) for x in a.edge_states.split(",") if x.strip()) or tuple(BRANCH_STATES) + if _states != tuple(BRANCH_STATES): + print(f"[edge] anchoring on states {_states} only (of {BRANCH_STATES})", flush=True) + if a.edge_entry_window: + print(f"[edge] anchors restricted to <= {a.edge_entry_window} frames past state ENTRY", flush=True) + _mm = a.edge_min_move_mm / 1000.0 + _rec = load_frames(horizon=eh, hdf5=a.hdf5, split=a.split) + _tr = stack(_rec, "train") + _fields, _counts = fit_fields(_tr, k=a.edge_knn, min_move_m=_mm) + EF = dict(fields=_fields, counts=_counts, eh=eh, mm=_mm, unit=unit, ang_deg=ang_deg, + ON_ROUTE=ON_ROUTE, FAILURE=FAILURE, + avail={s_: sorted(edges_from(_fields, s_)) for s_ in BRANCH_STATES}) + print(f"[edge] fields {sorted(_fields)} edge_horizon={eh} " + f"avail={ {k2: [f'{u}->{v}' for u, v in v2] for k2, v2 in EF['avail'].items()} }", flush=True) + edge_parts = out / "edge_parts"; edge_parts.mkdir(exist_ok=True) + edge_rec = [] # one dict per anchor + + def save_edge_part(ep_, recs): + """one npz per episode, so a sharded screen (--ep-shard, forced by the 1-GPU ban) and a + resumed one reduce to the SAME summary: edge_report.py merges these.""" + meta = [{k2: v2 for k2, v2 in r.items() + if k2 not in ("cls", "onroute", "cand_mag_mm", "scores", + "cand_disp_mm", "logged_disp_mm", "ee_xyz_mm")} for r in recs] + d = {"__meta__": np.frombuffer(json.dumps(meta).encode(), np.uint8)} + if recs: + d["cls"] = np.stack([r["cls"] for r in recs]) + d["onroute"] = np.stack([r["onroute"] for r in recs]) + d["cand_mag_mm"] = np.stack([r["cand_mag_mm"] for r in recs]) + # gen_q#278 (owner 2026-09-23 12:30Z): the FIGURE needs the raw 3-vectors, not the class + # labels -- "for every anchor give a 3D direction projected to image". Base frame, mm. + d["cand_disp_mm"] = np.stack([r["cand_disp_mm"] for r in recs]) # [n_anchor,N,3] + d["logged_disp_mm"] = np.stack([r["logged_disp_mm"] for r in recs]) # [n_anchor,3] + d["ee_xyz_mm"] = np.stack([r["ee_xyz_mm"] for r in recs]) # [n_anchor,3] + for m_ in modes: + if recs[0]["scores"].get(m_) is not None: + d["score_" + _k(m_)] = np.stack([r["scores"][m_] for r in recs]).astype(np.float32) + tmp = edge_parts / f"ep{ep_:06d}.tmp.npz" + np.savez_compressed(tmp, **d); tmp.rename(edge_parts / f"ep{ep_:06d}.npz") + + def anchor_frames(P, ef_arr, T, ep_excl=None): + """indices i of admissible anchors in this episode (support from every edge leaving the state, + and the fields at that position separated by >= --edge-min-sep-deg). + + ep_excl: FT_EVAL guard 1. The edge fields are fitted on the TRAIN split, so anchoring on a + train episode (--ep-ids) would let that episode's own frames define the field that labels its + own candidates -- the GROUND TRUTH would be self-confirming. Passing the anchor's episode id + drops its frames from both the support count and the field direction. For a VALID anchor this + is a no-op (the field holds no valid frames), so every held-out row already measured is + bit-identical.""" + keep = [] + ent = {} + r = a.edge_anchor_radius_mm / 1000.0 + for s_ in _states: + av = EF["avail"][s_] + if len(av) < 2: + continue + idx = np.array([i for i in range(0, T - eh) if ef_arr[i] == s_], int) + if not len(idx): + continue + ent[s_] = int(idx[0]) # ENTRY frame of this episode into state s_ + if a.edge_entry_window: + idx = idx[idx - idx[0] <= a.edge_entry_window] + if not len(idx): + continue + p = P[idx] + ok = np.ones(len(idx), bool) + for e in av: + F = _fields[e] + nb = F.tree.query_ball_point(p, r) + if ep_excl is None: + cnt = np.array([len(x) for x in nb]) + else: + cnt = np.array([int((F.ep[np.asarray(x, int)] != ep_excl).sum()) if len(x) else 0 + for x in nb]) + ok &= cnt >= a.edge_anchor_min_support + if ok.any(): + _xe = None if ep_excl is None else np.full(int(ok.sum()), ep_excl, int) + Fv = {e: _fields[e](p[ok], exclude_ep=_xe) for e in av} + sep = np.ones(int(ok.sum()), bool) + for i1 in range(len(av)): + for j1 in range(i1 + 1, len(av)): + sep &= ang_deg(Fv[av[i1]], Fv[av[j1]]) >= a.edge_min_sep_deg + sel = idx[ok][sep] + keep.extend((int(i), s_) for i in sel) + keep.sort() + st = a.edge_anchor_stride or a.stride + keep = keep[::st] + if a.edge_max_anchors_per_ep: + keep = keep[: a.edge_max_anchors_per_ep] + return keep, ent + + need_frames = kind == "openpi" + if need_frames: + import av # noqa: F401 (fail fast if the video decoder is missing) + + def decode_mp4(path): + import av + with av.open(str(path)) as c: + st = c.streams.video[0]; st.thread_type = "AUTO" + return np.stack([fr.to_ndarray(format="rgb24") for fr in c.decode(st)]) + + _want = "train" if (a.edge_test and a.edge_train_anchors) else "valid" + if a.ep_ids: + _raw = open(a.ep_ids[1:]).read() if a.ep_ids.startswith("@") else a.ep_ids + _want_ids = sorted({int(x) for x in _raw.replace(",", " ").split()}) + _all = {int(k) for k in json.load(open(a.split))["episodes"]} + _miss = [e for e in _want_ids if e not in _all] + if _miss: raise SystemExit(f"--ep-ids: {len(_miss)} ids not in the corpus: {_miss[:10]}") + eps = _want_ids + _nv = sum(1 for e in eps if json.load(open(a.split))["episodes"][str(e)]["split"] == "valid") + print(f"[ol] --ep-ids: {len(eps)} explicit episodes ({_nv} valid, {len(eps)-_nv} TRAIN) -- " + f"this is NOT a held-out screen", flush=True) + else: + eps = sorted(int(k) for k, v in json.load(open(a.split))["episodes"].items() if v["split"] == _want) + if a.max_eps: eps = eps[:a.max_eps] + if a.ep_shard: + # NB: do NOT name these _i/_k -- `_k` is the npz-key helper defined above in this same scope, and + # rebinding it made save_part() die with "'int' object is not callable" (job 1870319, all 4 shards). + _shard_i, _shard_n = (int(x) for x in a.ep_shard.split("/")) + if not 0 <= _shard_i < _shard_n: + raise SystemExit(f"--ep-shard {a.ep_shard}: need 0 <= I < K") + eps = eps[_shard_i::_shard_n] + print(f"[ol] shard {_shard_i}/{_shard_n}: {len(eps)} of the held-out episodes -> {eps}", flush=True) + INJ = None + if a.inject_logged: + # stage -> {route: [(episode, t, chunk[H,10])]}, every episode of the corpus (the anchor's own is + # excluded at draw time). Raw action units, the same as the proposer's output. + INJ = {} + with h5py.File(a.hdf5, "r") as _fi: + for _dk in _fi["data"]: # NOT _k: that is the npz-key helper (see note above) + _g = _fi["data"][_dk]; _r = str(_g.attrs.get("path", "")); _e = int(_dk.split("_")[1]) + if _r not in ("2->3->4", "0->2->6"): + continue + _A = (_g["actions_raw"] if "actions_raw" in _g else _g["actions"])[()].astype(np.float32) + _st = _g["annot"]["edge_from"][()].astype(int) + for _t in range(0, len(_A) - a.horizon, a.inject_stride): + _ch0 = _A[_t:_t + a.horizon].copy() + # the action is an ABSOLUTE end-effector target pose (job 1881603), so the chunk's + # displacement is its last minus its first -- the quantity --inject-mag-match matches on. + _mg = float(np.linalg.norm(_ch0[-1, :3] - _ch0[0, :3])) + INJ.setdefault(int(_st[_t]), {}).setdefault(_r, []).append((_e, _t, _ch0, _mg)) + print("[inject] pool " + " ".join( + f"S{s_}:{ {r_: len(v_) for r_, v_ in d_.items()} }" for s_, d_ in sorted(INJ.items())), flush=True) + if a.inject_mag_match > 0: + print(f"[inject] MAGNITUDE-MATCHED draw, tol x{a.inject_mag_match:g} around the anchor's own " + f"chunk displacement; anchors whose pool empties are padded and dropped offline", + flush=True) + inj_match = {"goal": [], "fail": []} # per anchor: (kept pool entries, total) under --inject-mag-match + + rows = {m: [] for m in modes + ["oracle"]}; spreads = []; per_ep = [] + ranks = {m: [] for m in modes + ["oracle"]}; dump_scores: dict[str, list] = {}; dump_err: list = [] + with h5py.File(a.hdf5, "r") as f: + for ep in eps: + if not a.no_resume and a.edge_test and (out / "edge_parts" / f"ep{ep:06d}.npz").exists(): + # the edge screen runs at N=128 over hundreds of anchors, i.e. hours; a preemption that + # lost every finished episode would make the measurement unaffordable. Both parts are + # written together at the end of an episode, so both are resumed together or neither is. + got = load_part(ep, modes + ["oracle"]) + if got is not None: + from edge_report import load_dir as _ld # same decoder as the shard merge + _one = [r for r in _ld(out) if int(r["episode"]) == ep] + meta, r_, k_, sp_, err_, sc_ = got + for m in r_: rows[m].extend(r_[m]) + for m in k_: ranks[m].extend(k_[m]) + spreads.extend(sp_); dump_err.extend(err_); per_ep.append(meta) + for m, v in sc_.items(): dump_scores.setdefault(m, []).extend(v) + edge_rec.extend(_one) + print(f"[edge] ep {ep} RESUMED from edge_parts/ anchors={len(_one)}", flush=True) + continue + if not a.no_resume and not a.edge_test: + got = load_part(ep, modes + ["oracle"]) + if got is not None: + meta, r_, k_, sp_, err_, sc_ = got + for m in r_: rows[m].extend(r_[m]) + for m in k_: ranks[m].extend(k_[m]) + spreads.extend(sp_); dump_err.extend(err_); per_ep.append(meta) + for m, v in sc_.items(): dump_scores.setdefault(m, []).extend(v) + print(f"[ol] ep {ep} RESUMED from parts/ n={meta['n_decisions']}", flush=True) + continue + # Per-episode RNG. The proposer's noise (OpenpiPolicy.rng / RandomPolicy.rng) and the permuted + # control's shuffle used to be drawn from one sequential stream, so an episode's candidates + # depended on how many episodes had run before it -- a resumed screen then produced different + # (equally valid, but not comparable) draws. Seeding per episode makes every episode independent + # and a resumed screen identical to an uninterrupted one (test_screen_resume.sh). + _sseed = a.seed if a.scorer_seed is None else a.scorer_seed + if hasattr(pol, "rng"): pol.rng = np.random.default_rng([a.seed, ep]) + # The enumeration order fixes each scorer's stream, so it must not shift when a column is + # ADDED. --baselines columns are therefore sorted to the END rather than into the middle + # ('bc' < 'idql', 'permuted:bc' < 'permuted:idql' would have re-seeded rsm/idql and silently + # made every previously measured number a non-replicate. + _ord = sorted(m for m in scorers if m not in BASE_SET) + sorted(m for m in scorers if m in BASE_SET) + for _i, _m in enumerate(_ord): + if hasattr(scorers[_m], "rng"): scorers[_m].rng = np.random.default_rng([_sseed, ep, 1000 + _i]) + g = f["data"][f"demo_{ep}"] + S = g["obs"]["ee_state"][()].astype(np.float32) + A = (g["actions_raw"] if "actions_raw" in g else g["actions"])[()].astype(np.float32) + im = {"global": g["obs"]["agentview_image"], "wrist": g["obs"]["robot0_eye_in_hand_image"]} + T = len(S); ep_rows = {m: [] for m in modes + ["oracle"]} + ep_rank = {m: [] for m in modes + ["oracle"]} + ep_spread: list = []; ep_err: list = []; ep_scores: dict[str, list] = {} + if hasattr(pol, "hist"): pol.hist = [] + To = int(getattr(pol, "To", 1)) + hi_g = hi_w = None + if need_frames: + vr = Path(a.lerobot_root) / "videos/chunk-000" + hi_g = decode_mp4(vr / f"observation.images.global/episode_{ep:06d}.mp4") + hi_w = decode_mp4(vr / f"observation.images.wrist/episode_{ep:06d}.mp4") + assert len(hi_g) == T and len(hi_w) == T, (ep, len(hi_g), len(hi_w), T) + mk_obs = lambda t: {"state": S[t], "grip_thresh": grip_thresh, + "images84": {c: im[c][t] for c in im}, + "images": ({"global": hi_g[t], "wrist": hi_w[t]} if need_frames else None)} + grid = list(range(0, T - a.horizon, a.stride)) + ep_anchor_state = {} + if a.edge_test: + _P = g["obs"]["robot0_eef_pos"][()].astype(np.float64) + _ef = g["annot"]["edge_from"][()].astype(int) + _et = g["annot"]["edge_to"][()].astype(int) + _anch, ep_entry = anchor_frames(_P, _ef, T, ep_excl=(int(ep) if a.ep_ids else None)) + grid = [i for i, _s in _anch] + ep_anchor_state = {i: _s for i, _s in _anch} + print(f"[edge] ep {ep} anchors {len(grid)} of {T} frames " + f"(states {sorted(set(ep_anchor_state.values()))})", flush=True) + for i in grid: + obs = mk_obs(i) + # the actor's To-frame history must be the TRUE preceding frames (as in training and in + # rise_replay_eval.py), not the previous decision 25 frames back -- see RobomimicPolicy._obs_batch + obs["history"] = [mk_obs(max(0, i - k)) for k in range(To - 1, 0, -1)] + if zfeat is not None: + gi = ep_from[ep] + i + z = np.concatenate([np.asarray(zfeat[gi], np.float32), np.asarray(pfeat[gi], np.float32)]) + obs["rsm_feat"] = np.clip((z - mu) / sd, -zclip, zclip) + # RAW (un-z-scored) proprio: the `pose` baseline compares a candidate's first ABSOLUTE + # commanded pose with where the arm actually is, so it must be in metres, not sigmas. + obs["proprio_raw"] = np.asarray(pfeat[gi], np.float32) + cands = pol.candidates(obs, a.n_cand, a.horizon) + if a.cand_shrink != 1.0: + # Scale the cloud about its own centroid. Done BEFORE the injection block so the + # injected logged chunks (--inject-logged) are never rescaled: they are real data, + # not proposer draws. The centroid is the candidates' own mean, NOT the ground + # truth, so this cannot leak the target into the candidate set. + _c = np.asarray(cands, np.float32) + _m = _c.mean(0, keepdims=True) + cands = (_m + float(a.cand_shrink) * (_c - _m)).astype(np.float32) + gt = A[i:i + a.horizon] + inj_names = [] + if INJ is not None: + # index 0..N-1 stay the proposer's draws so every existing read-out is unchanged; + # the injected chunks are appended in a FIXED order and recorded by name. + s_inj = int(ep_anchor_state.get(i, -1)) if a.edge_test else int(-1) + pool = INJ.get(s_inj, {}) + extra, names = [], [] + if len(gt) == a.horizon: + extra.append(gt.astype(np.float32)); names.append("own") + _rng_i = np.random.default_rng([a.seed, ep, i, 77]) + # magnitude reference = the anchor's OWN logged chunk, which is by construction + # exchangeable with the proposer's draws (both start at the current pose). + _mg_own = (float(np.linalg.norm(gt[-1, :3] - gt[0, :3])) + if len(gt) == a.horizon else 0.0) + for _lbl, _route in (("goal", "2->3->4"), ("fail", "0->2->6")): + cand_list = [c for c in pool.get(_route, []) if c[0] != ep] + if a.inject_mag_match > 0 and _mg_own > 0: + _tol = float(a.inject_mag_match) + _kept = [c for c in cand_list + if _mg_own / _tol <= c[3] <= _mg_own * _tol] + inj_match[_lbl].append((len(_kept), len(cand_list))) + cand_list = _kept # empty -> the slot is padded and dropped offline + if cand_list: + _e2, _t2, _ch, _mg2 = cand_list[int(_rng_i.integers(len(cand_list)))] + _ch = _ch.astype(np.float32).copy() + if a.inject_rebase and len(gt) == a.horizon: + # absolute-pose convention: shift so the injected chunk STARTS where the + # anchor's own first commanded action does. Shape/direction survive. + _ch[:, :3] += (gt[0, :3] - _ch[0, :3])[None, :] + extra.append(_ch); names.append(_lbl) + else: + # the candidate COUNT must not vary between anchors: save_edge_part np.stacks + # the per-anchor arrays, so a 130-candidate S0 anchor beside a 131-candidate S2 + # one would raise. At S0 the goal route 2->3->4 has no frames at all (it starts + # at state 2), so that slot is padded with a DUPLICATE of `own` and named + # `pad_`; the offline analysis drops every `pad_*` index. + extra.append(gt.astype(np.float32)); names.append("pad_" + _lbl) + if extra: + cands = np.concatenate([np.asarray(cands, np.float32), + np.stack(extra).astype(np.float32)], 0) + inj_names = names + err_first = 100.0 * np.linalg.norm(cands[:, 0, :3] - gt[0, :3], axis=-1) # [N] cm + err_chunk = 100.0 * np.linalg.norm(cands[..., :3] - gt[None, :, :3], axis=-1).mean(1) + ep_spread.append(float(100 * np.linalg.norm(cands[:, 0, :3] - cands[:, 0, :3].mean(0), axis=1).mean())) + n = len(cands) + last_scores = {} + for m in modes: + idx, sc = scorers[m].pick(cands, obs) + last_scores[m] = sc + ep_rows[m].append((float(err_first[idx]), float(err_chunk[idx]))) + # where the pick lands in the ORACLE's ordering of this decision's candidates + ep_rank[m].append(float((err_first > err_first[idx]).sum()) / max(n - 1, 1)) + if sc is not None: + ep_scores.setdefault(m, []).append(np.asarray(sc, np.float32)) + j = int(np.argmin(err_first)); ep_rows["oracle"].append((float(err_first[j]), float(err_chunk[j]))) + ep_rank["oracle"].append(1.0) + ep_err.append(err_first.astype(np.float32)) + if a.edge_test: + s_ = ep_anchor_state[i] + av = EF["avail"][s_] + p_now = _P[i] + disp = cands[:, EF["eh"] - 1, :3] - p_now[None, :] # [N,3] metres + mag = np.linalg.norm(disp, axis=1) + _xe1 = np.array([int(ep)]) if a.ep_ids else None + Fq = np.stack([EF["fields"][e](p_now[None, :], exclude_ep=_xe1)[0] + for e in av], 0) # [E,3] + cos = EF["unit"](disp) @ Fq.T # [N,E] + cls = cos.argmax(1).astype(np.int8) + cls[mag < EF["mm"]] = -1 # a candidate that does not move + onroute = np.array([(av[c] in EF["ON_ROUTE"]) if c >= 0 else False for c in cls], bool) + true_e = (int(_ef[i]), int(_et[i])) + rec_e = {"episode": int(ep), "frame": int(i), "state": int(s_), + "frames_past_entry": int(i) - int(ep_entry.get(s_, 0)), + "avail": [f"{u}->{v}" for u, v in av], + "true_edge": f"{true_e[0]}->{true_e[1]}", + "true_is_failure": bool(true_e in EF["FAILURE"]), + "n_cand": int(n), "n_proposer": int(n - len(inj_names)), + "inject": list(inj_names), "cls": cls, "onroute": onroute, + "inject_rebase": bool(a.inject_rebase), + "cand_mag_mm": (1000.0 * mag).astype(np.float32), + "cand_disp_mm": (1000.0 * disp).astype(np.float32), + "logged_disp_mm": (1000.0 * ( + gt[min(EF["eh"], len(gt)) - 1, :3] - p_now)).astype(np.float32), + "ee_xyz_mm": (1000.0 * p_now).astype(np.float32), + "disp_spread_mm": float(1000.0 * np.linalg.norm( + disp - disp.mean(0, keepdims=True), axis=1).mean()), + "scores": {}} + for m in modes: + sc_m = last_scores.get(m) + rec_e["scores"][m] = (None if sc_m is None else np.asarray(sc_m, np.float64)) + edge_rec.append(rec_e) + for m in ep_rows: rows[m].extend(ep_rows[m]) + for m in ep_rank: ranks[m].extend(ep_rank[m]) + spreads.extend(ep_spread); dump_err.extend(ep_err) + for m, v in ep_scores.items(): dump_scores.setdefault(m, []).extend(v) + meta = {"episode": ep, "path": str(g.attrs["path"]), "n_decisions": len(ep_rows["greedy"]), + **{m: float(np.mean([r[0] for r in ep_rows[m]])) for m in ep_rows}} + per_ep.append(meta) + save_part(ep, meta, ep_rows, ep_rank, ep_spread, ep_err, ep_scores) + if a.edge_test: + save_edge_part(ep, [r for r in edge_rec if r["episode"] == ep]) + print(f"[ol] ep {ep} {g.attrs['path']} n={len(ep_rows['greedy'])} " + + " ".join(f"{m}={np.mean([r[0] for r in ep_rows[m]]):.2f}" for m in ep_rows) + + f" {time.time()-t0:.0f}s", flush=True) + + if a.edge_test: + from edge_field import summarise_anchors + edge_sum = summarise_anchors(edge_rec, modes, seed=a.seed) + edge_sum["config"] = { + "policy": a.policy, "tag": a.tag, "rsm_ckpt": a.rsm_ckpt, "idql_ckpt": a.idql_ckpt, + "rsm_mode": a.rsm_mode, "rsm_depth": a.rsm_depth, "rsm_beta": a.rsm_beta, "rsm_gamma": a.rsm_gamma, + "rsm_particles": a.rsm_particles, "rsm_flow_steps": a.rsm_flow_steps, "rsm_score_kind": a.rsm_score_kind, + "rsm_temperature": a.rsm_temperature, "n_cand": a.n_cand, "horizon": a.horizon, "cand_shrink": a.cand_shrink, + "edge_horizon": EF["eh"], "edge_knn": a.edge_knn, "edge_min_move_mm": a.edge_min_move_mm, + "edge_min_sep_deg": a.edge_min_sep_deg, + "edge_anchor_radius_mm": a.edge_anchor_radius_mm, + "edge_anchor_min_support": a.edge_anchor_min_support, + "edge_anchor_stride": a.edge_anchor_stride or a.stride, + "edge_entry_window": a.edge_entry_window, + "edge_states": list(_states), + "split": ("train" if a.edge_train_anchors else "valid"), + "ep_shard": a.ep_shard, "episodes": eps, "seed": a.seed, "scorer_seed": (a.seed if a.scorer_seed is None else a.scorer_seed), + "ep_ids": a.ep_ids, "held_out": not bool(a.ep_ids), + "edge_field_validate": "status/real/EDGE_FIELD_VALIDATE_h%d.json" % EF["eh"]} + # hop accounting of the chain read-out (rsm_scorer.chain_hop_acc), reported beside every number + for _m, _s in scorers.items(): + _acc = getattr(getattr(_s, "rsm", None), "chain_hop_acc", None) + if _acc: + edge_sum.setdefault("hop_accounting", {})[_m] = { + k2: (float(v2) if isinstance(v2, (int, float)) else v2) for k2, v2 in _acc.items()} + json.dump(edge_sum, open(out / "edge_test.json", "w"), indent=1) + print("[edge] wrote", out / "edge_test.json", flush=True) + for _s, _d in edge_sum["states"].items(): + print(f"[edge] {_s} anchors={_d['n_anchors']} (contrastive {_d['n_anchors_contrastive']}, " + f"failure-edge {_d['n_anchors_failure_edge']}) coverage={_d['coverage']:.3f} " + f"spread={_d['cand_disp_spread_mm']:.1f} mm", flush=True) + for _m, _v in _d["scorers"].items(): + _r = _v["onroute_rank_pct"] + _dg = _v.get("delta_vs_greedy", {}) + print(f"[edge] {_m:<16} rank_pct {_r['mean']:.3f} [{_r['lo']:.3f},{_r['hi']:.3f}] n={_r['n']}" + f" d_vs_greedy {_dg.get('mean', float('nan')):+.3f}" + f" [{_dg.get('lo', float('nan')):+.3f},{_dg.get('hi', float('nan')):+.3f}]" + f" ties@max {_v['ties_at_max_mean']:.1f}" + f" flip {_d['flip'][_m]['rate_covered_anchors']:.3f}" + f" (n={_d['flip'][_m]['n_covered']})", flush=True) + + base = np.array([r[0] for r in rows["greedy"]]) + summary = {"policy": a.policy, "tag": a.tag, "rsm_ckpt": a.rsm_ckpt, "rsm_hop_ckpt": a.rsm_hop_ckpt, + "rsm_score_kind": a.rsm_score_kind, "rsm_temperature": a.rsm_temperature, + "rsm_mode": a.rsm_mode, + "rsm_depth": a.rsm_depth, "rsm_beta": a.rsm_beta, "rsm_gamma": a.rsm_gamma, "rsm_particles": a.rsm_particles, "rsm_flow_steps": a.rsm_flow_steps, + "rsm_ckpt_extra": extra_ck, + "n_cand": a.n_cand, "horizon": a.horizon, "stride": a.stride, "cand_shrink": a.cand_shrink, + "n_episodes": len(eps), "n_decisions": len(base), "open_loop": True, "valid_for_results": True, + "candidate_spread_xyz_cm": float(np.mean(spreads)), "per_episode": per_ep, "scorers": {}} + for m in rows: + f1 = np.array([r[0] for r in rows[m]]); fc = np.array([r[1] for r in rows[m]]) + rk = np.array(ranks[m]) + summary["scorers"][m] = {"first_mean_cm": float(f1.mean()), "first_median_cm": float(np.median(f1)), + "first_p90_cm": float(np.percentile(f1, 90)), "chunk_mean_cm": float(fc.mean()), + "win_rate_vs_greedy": float((f1 < base).mean()), + "delta_vs_greedy_cm": float(f1.mean() - base.mean()), + "oracle_rank_pct_mean": float(rk.mean()), "oracle_rank_pct_median": float(np.median(rk)), + "oracle_rank_pct_p10": float(np.percentile(rk, 10)), + "oracle_rank_pct_top10_frac": float((rk >= 0.9).mean()), + "oracle_rank_pct_bottom10_frac": float((rk <= 0.1).mean())} + json.dump(summary, open(out / "scorer_openloop.json", "w"), indent=1) + np.savez_compressed(out / "scores.npz", err_first=np.stack(dump_err) if dump_err else np.zeros((0, 0), np.float32), + **{f"score_{m.replace(':','_')}": np.stack(v) for m, v in dump_scores.items()}) + if a.inject_mag_match > 0: + for _lbl in ("goal", "fail"): + _v = inj_match[_lbl] + if not _v: + print(f"[inject] {_lbl}: NO anchor reached the magnitude-matched draw", flush=True) + continue + _kept = np.array([x[0] for x in _v], float); _tot = np.array([x[1] for x in _v], float) + print("[inject] %s: pool kept %.1f of %.0f entries per anchor (%.3f), anchors with an empty " + "pool %.3f of %d" % (_lbl, _kept.mean(), _tot.mean(), + float((_kept / np.maximum(_tot, 1)).mean()), + float((_kept == 0).mean()), len(_v)), flush=True) + print("[ol] candidate spread %.2f cm over %d decisions" % (summary["candidate_spread_xyz_cm"], len(base))) + for m, v in summary["scorers"].items(): + print("[ol] %-14s first %5.2f cm (med %5.2f p90 %5.2f) chunk %5.2f cm win-vs-greedy %.3f delta %+.2f cm " + "rank_pct mean %.3f med %.3f p10 %.3f top10 %.3f bot10 %.3f" + % (m, v["first_mean_cm"], v["first_median_cm"], v["first_p90_cm"], v["chunk_mean_cm"], + v["win_rate_vs_greedy"], v["delta_vs_greedy_cm"], v["oracle_rank_pct_mean"], + v["oracle_rank_pct_median"], v["oracle_rank_pct_p10"], v["oracle_rank_pct_top10_frac"], + v["oracle_rank_pct_bottom10_frac"]), flush=True) + + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/real/screen_reproducibility.py b/rsm_rise/scripts/real/screen_reproducibility.py new file mode 100644 index 0000000000000000000000000000000000000000..a7f768e5d2b0ce6687d1e0f554fa9d69083ae2e0 --- /dev/null +++ b/rsm_rise/scripts/real/screen_reproducibility.py @@ -0,0 +1,119 @@ +#!/usr/bin/env python +"""How reproducible is the #271 open-loop screen across an independent candidate draw? + +Run 5 of this stream had to redo the screen after the stale-checkpoint fix, which left TWO complete +runs of the same protocol -- `RW271_*` and `RW271b_*` -- with the same 705 decisions per proposer +seed and (for every head except B_s1/v0lit*) the same weights. Run 7 added a THIRD, `RW271c_*`, +when the literal-v0 control finished training: it is a replicate of `RW271b` with no excluded head +at all (same weights everywhere, only the candidate draw differs), so it is the cleanest estimate +of the noise floor we have. The candidate sets are NOT the same across runs: the proposer is +re-sampled, so any two runs are an honest replicate of the whole measurement, not just of the +bootstrap over decisions. + +That replicate is the only estimate we have of the screen's real noise floor, and it is the number +that decides how large an effect the screen can resolve. It is reported two ways: + * on the raw `oracle_rank_pct` level, and + * on the paired delta against the permuted control -- the quantity the screen actually quotes. +If pairing worked, the second should be much smaller than the first. + +Every available pair of runs is reported under `pairs`; the top level carries the PRIMARY pair (the +two most recent complete runs, i.e. the one with the fewest excluded heads), because that is what +the PDF / CHECKPOINTS.md quote. Override with RW_REPRO_TAGS="RW271b,RW271c". + +Writes status/real/SCREEN_REPRODUCIBILITY.json. +""" +from __future__ import annotations +import itertools +import json +import os +from pathlib import Path +import numpy as np + +ROOT = Path("/proj/dmfexp/zwhong/rsm_rise") +ST = ROOT / "status/real" +TAGS = tuple(t.strip() for t in (os.environ.get("RW_REPRO_TAGS") or "RW271,RW271b,RW271c").split(",") if t.strip()) +SEEDS = {"s0": "s0_e2000", "s1": "s1_e2500"} +CONTROL = "permuted_rsm" +# heads whose WEIGHTS differ between RW271 and every later run (run 5's stale-checkpoint bug): excluded +# from any pair that involves RW271, because for them those runs are not a replicate of the same thing. +# RW271b vs RW271c share weights for every head, so nothing is excluded there. +CHANGED = {"rsm@ft_B_s1", "rsm@ft_v0lit", "rsm@ft_v0lit_s1"} +STALE_TAG = "RW271" + + +def npz_path(tag: str, suffix: str) -> Path: + return ST / f"openloop_{tag}_S0Aidql_{suffix}_d1_T25" / "scores.npz" + + +def levels(path: Path) -> dict[str, float]: + z = np.load(path) + err = z["err_first"] + order = np.argsort(np.argsort(err, axis=1), axis=1) + D, N = err.shape + out = {} + for k in z.files: + if not k.startswith("score_"): + continue + pick = np.argmax(z[k], axis=1) + out[k[6:]] = float((1.0 - order[np.arange(D), pick] / (N - 1)).mean()) + return out + + +def pair_stats(ta: str, tb: str) -> dict: + """The replicate statistic for one pair of screen runs.""" + drop = CHANGED if STALE_TAG in (ta, tb) else set() + res = {"tags": [ta, tb], "excluded_weights_changed": sorted(drop), "seeds": {}} + for seed, suffix in SEEDS.items(): + pa, pb = npz_path(ta, suffix), npz_path(tb, suffix) + if not (pa.exists() and pb.exists()): + print(f"[repro] {ta}|{tb} SKIP {seed}: missing {[str(p) for p in (pa, pb) if not p.exists()]}") + continue + a, b = levels(pa), levels(pb) + keys = sorted((set(a) & set(b)) - drop - {CONTROL}) + raw = np.array([b[k] - a[k] for k in keys]) + dlt = np.array([(b[k] - b[CONTROL]) - (a[k] - a[CONTROL]) for k in keys]) + res["seeds"][seed] = { + "n_heads": len(keys), + "control_level": {ta: a[CONTROL], tb: b[CONTROL]}, + "raw": {"mean": float(raw.mean()), "rms": float(np.sqrt((raw ** 2).mean())), + "max_abs": float(np.abs(raw).max())}, + "paired_delta": {"mean": float(dlt.mean()), "rms": float(np.sqrt((dlt ** 2).mean())), + "max_abs": float(np.abs(dlt).max())}, + "per_head": {k: {"raw_a": a[k], "raw_b": b[k], + "delta_a": a[k] - a[CONTROL], "delta_b": b[k] - b[CONTROL]} + for k in keys}, + } + r, d = res["seeds"][seed]["raw"], res["seeds"][seed]["paired_delta"] + print(f"[repro] {ta}|{tb} {seed}: {len(keys)} heads, control {a[CONTROL]:.4f} -> {b[CONTROL]:.4f}") + print(" raw level rms %.4f max|.| %.4f" % (r["rms"], r["max_abs"])) + print(" paired delta rms %.4f max|.| %.4f" % (d["rms"], d["max_abs"])) + res["noise_floor_paired_delta_rms"] = max( + (v["paired_delta"]["rms"] for v in res["seeds"].values()), default=float("nan")) + return res + + +def main(): + have = [t for t in TAGS if all(npz_path(t, s).exists() for s in SEEDS.values())] + print(f"[repro] complete screen runs on disk: {have or 'none'}") + if len(have) < 2: + print("[repro] need two complete runs; nothing written") + return + pairs = {f"{a}|{b}": pair_stats(a, b) for a, b in itertools.combinations(have, 2)} + # PRIMARY = the two most recent complete runs: the pair with the fewest excluded heads. + pa, pb = have[-2], have[-1] + res = dict(pairs[f"{pa}|{pb}"]) + res["available_tags"] = have + res["primary_pair"] = [pa, pb] + res["pairs"] = {k: {kk: vv for kk, vv in v.items() if kk != "pairs"} for k, v in pairs.items()} + print(f"[repro] PRIMARY pair {pa}|{pb}: noise floor on the quoted paired delta: " + f"rms {res['noise_floor_paired_delta_rms']:.4f} " + f"(the screen cannot resolve head differences smaller than this)") + for k, v in pairs.items(): + print(f"[repro] pair {k}: noise floor rms {v['noise_floor_paired_delta_rms']:.4f} " + f"({len(v['excluded_weights_changed'])} heads excluded)") + (ST / "SCREEN_REPRODUCIBILITY.json").write_text(json.dumps(res, indent=1) + "\n") + print(f"[repro] wrote {ST/'SCREEN_REPRODUCIBILITY.json'}") + + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/real/seddGwNRb b/rsm_rise/scripts/real/seddGwNRb new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/rsm_rise/scripts/real/seed_aggregate_t45.py b/rsm_rise/scripts/real/seed_aggregate_t45.py new file mode 100644 index 0000000000000000000000000000000000000000..2f2f9ceb4c055e41ca3ae17c0d1db93fc831ea08 --- /dev/null +++ b/rsm_rise/scripts/real/seed_aggregate_t45.py @@ -0,0 +1,364 @@ +#!/usr/bin/env python +"""AUG_SUCC (gen_q#279) run 18: score the three REGISTERED PREDICTIONS against the +JUNC_feat_t45_c0p5_s{0..4} seed replicates, in one pass, the moment they land. + +Predictions on the record (written before pack 1887312 returned): + run 15 -- 5-seed MEAN GATE in [0.45, 0.62]; >=2 of the 4 NEW seeds clear 0.5; all 4 healthy + (qwin > 0.7 and Ffail > 0.85). Falsifier: >=3 of 4 below 0.45 or inverted (qwin<0.5). + run 16 -- PAIRED DELTA vs baseline positive for ALL 5 seeds, 5-seed mean in [0.20, 0.42]; + the CELL MEAN clears 0.5 in AT MOST 3 of 5. Falsifier: any seed with delta <= 0. + run 17 -- frac(goal rank pct > 0.5) above 0.5 in >=4 of 5 seeds, 5-seed mean >= 0.62, and + uniformity (KS) rejected at p<0.05 in >=3 of 5. + Falsifier: if >=3 seeds ACCEPT uniformity, the t45 effect is a single-seed fluke. + +Statistics, all episode-clustered over the 5 anchor episodes (the only honest cluster for 37 +anchors in 5 episodes): + * gate = mean rank percentile of candidate 0 (the goal-bound chunk) among the other 31; + * frac>0.5, the cluster-robust test of "the model went uninformative" -- under that null the + percentiles are Uniform[0,1] and this fraction is 0.5 exactly, but unlike the mean it is not + dragged by a few deeply-buried anchors (run 17's finding); + * KS vs Uniform[0,1] (anti-conservative here: 37 anchors sit in only 5 episodes -- reported as a + companion to frac>0.5, never on its own); + * own-chunk rank percentile, the plausibility-competence control; + * paired delta vs baseline, ONLY when the candidate sets are verified identical (see below). + +CANDIDATE PAIRING IS VERIFIED, NOT ASSUMED. Run 16 reported a paired delta; run 17 argued the +baseline and JUNC cells were scored on different distractor draws and so cannot be paired. This +script decides it per-cell from data: scores_bc and scores_pose are DETERMINISTIC given the +candidate set (a fixed chunk's BC log-likelihood / pose-continuity does not depend on the RSM +checkpoint), so bit-identity of those columns proves the candidates match. scores_knn is +particle-based and stochastic -- run 17 had to retract a probe built on it -- so it is never used +here. If the check fails the paired delta is reported as null and only the unpaired contrast is +printed. +""" +import argparse, json, os +import numpy as np +from scipy import stats + +ROOT = "/proj/dmfexp/zwhong/rsm_rise" +RK = f"{ROOT}/status/real/rankctrl" +RUNS = f"{ROOT}/runs/real_cooking_v5/rsm" + + +def rank_pct(S, col=0): + tgt = S[:, col] + oth = np.delete(S, col, axis=1) + return ((oth < tgt[:, None]).sum(1) + 0.5 * (oth == tgt[:, None]).sum(1)) / oth.shape[1] + + +def cboot(eps, vals, n=20000, seed=0, stat=np.mean): + """episode-clustered bootstrap: resample the 5 episodes with replacement.""" + rng = np.random.default_rng(seed) + ue = np.unique(eps) + groups = [vals[eps == e] for e in ue] + out = np.empty(n) + for b in range(n): + idx = rng.integers(0, len(groups), len(groups)) + out[b] = stat(np.concatenate([groups[i] for i in idx])) + return float(stat(vals)), float(np.std(out)), out + + +def hist(cell): + p = f"{RUNS}/{cell}/history.json" + if not os.path.exists(p): + return {} + h = json.load(open(p)) + return h[-1] if isinstance(h, list) and h else {} + + +def arm_top1(cell, arm, suf="val31"): + for nm in (f"{cell}__{arm}{suf}", f"{cell}__{arm}31"): + p = f"{RK}/{nm}/logged_action_rank.json" + if os.path.exists(p) and os.path.getsize(p): + d = json.load(open(p)) + return d["by"].get("rsm|S2", {}).get("top1_tie", float("nan")) + return float("nan") + + +def cands_match(za, zb): + """deterministic-column proof that two cells saw the SAME candidate set.""" + ok, seen = True, [] + for k in ("scores_bc", "scores_pose"): + if k in za.keys() and k in zb.keys(): + A, B = np.asarray(za[k]), np.asarray(zb[k]) + if A.shape != B.shape or not np.allclose(A, B): + ok = False + seen.append(k) + return (ok and bool(seen)), seen + + +def ties_at_max(S): + """fraction of anchors whose top score is attained by more than one candidate.""" + mx = S.max(1, keepdims=True) + return float(((S == mx).sum(1) > 1).mean()) + + +def score_cv(S): + """mean over anchors of std/|mean| across the candidate set -- a collapsed score field + (all candidates scored alike) makes every rank number meaningless, so it is reported + beside every rank, per Task 3.""" + mu = np.abs(S.mean(1)) + sd = S.std(1) + return float(np.mean(sd / np.maximum(mu, 1e-12))) + + +def pooled_over_seeds(per_seed, bz): + """THE METHOD-LEVEL ESTIMAND, which no per-seed row answers. + + Each per-seed row asks "did THIS training run acquire goal-direction?" and carries only the + anchor-episode variance (5 clusters). The question the stream is actually asked -- does the + t45 augmentation, as a method, give the successor goal-direction -- needs the SEED to be a + unit of variance too, because run 13 measured an across-seed |dgate| scatter of 0.099 that + appears in NONE of the per-seed SEs. + + Two estimates, reported together because they bound the answer: + * seed-level: mean of the 5 per-seed gates, SE = std/sqrt(5). Treats the anchor set as + fixed (it is: the same 37 anchors) and the seed as the only random draw. + * two-way bootstrap: resample the 5 anchor EPISODES with replacement AND the 5 SEEDS with + replacement, recomputing the statistic on the crossed resample. This is the only SE here + that carries both variance components, so it is the one to quote. + Pooling requires the seeds to have been scored on IDENTICAL candidates; that is proved from + the deterministic scores_bc/scores_pose columns, exactly as the paired delta is, and pooling + is refused otherwise rather than silently averaging incomparable rows. + """ + out = {"n_seeds": len(per_seed), "seeds": [d["seed"] for d in per_seed]} + if len(per_seed) < 2: + out["pooled"] = None + out["note"] = "fewer than 2 seeds present; nothing to pool" + return out + ref = per_seed[0] + ok = True + bad = [] + for d in per_seed[1:]: + if not np.array_equal(d["ep"], ref["ep"]): + ok = False; bad.append((d["cell"], "ep")) + continue + m, seen = cands_match(d["z"], ref["z"]) + if not (m and seen): + ok = False; bad.append((d["cell"], "cands")) + out["cands_aligned_across_seeds"] = bool(ok) + out["misaligned"] = bad + print("\n=== POOLED ACROSS SEEDS (method-level) ===") + if not ok: + print("[pooled] REFUSED: seeds were not scored on identical candidates: %s" % bad) + out["pooled"] = None + return out + ep = ref["ep"] + M = np.stack([d["gv"] for d in per_seed], axis=1) # (n_anchors, n_seeds) + per_anchor = M.mean(1) + gates = M.mean(0) + seed_mean = float(gates.mean()) + seed_se = float(gates.std(ddof=1) / np.sqrt(len(gates))) + fr = (M > 0.5).mean(0) + fr_mean = float(fr.mean()) + fr_se = float(fr.std(ddof=1) / np.sqrt(len(fr))) + + def twoway(stat, n=20000, seed=0): + rng = np.random.default_rng(seed) + ue = np.unique(ep) + groups = [np.where(ep == e)[0] for e in ue] + vals = np.empty(n) + for b in range(n): + gi = rng.integers(0, len(groups), len(groups)) + ri = np.concatenate([groups[i] for i in gi]) + si = rng.integers(0, M.shape[1], M.shape[1]) + vals[b] = stat(M[np.ix_(ri, si)]) + return float(np.std(vals)), vals + + g_point = float(M.mean()) + g_se, _ = twoway(lambda A: A.mean()) + f_point = float((M > 0.5).mean()) + f_se, fdist = twoway(lambda A: (A > 0.5).mean()) + out.update(seed_mean_gate=seed_mean, seed_se_gate=seed_se, + seed_mean_frac=fr_mean, seed_se_frac=fr_se, + twoway_gate=g_point, twoway_gate_se=g_se, + twoway_frac=f_point, twoway_frac_se=f_se, + twoway_frac_sigma=(f_point - 0.5) / f_se if f_se > 0 else float("nan"), + twoway_frac_p_le_half=float((fdist <= 0.5).mean()), + per_seed_gates=[float(x) for x in gates], + per_seed_fracs=[float(x) for x in fr]) + print(f"[pooled] seed-level gate {seed_mean:.4f} +-{seed_se:.4f} (n={len(gates)} seeds) " + f"frac>0.5 {fr_mean:.3f} +-{fr_se:.3f}") + print(f"[pooled] two-way gate {g_point:.4f} +-{g_se:.4f} " + f"frac>0.5 {f_point:.3f} +-{f_se:.3f} " + f"({out['twoway_frac_sigma']:.2f} sigma, boot p(frac<=0.5)={out['twoway_frac_p_le_half']:.4f})") + + # per-anchor seed-average: averaging out training noise, does the AUGMENTATION rank the goal + # chunk above the median failure chunk on a majority of anchors? + am, asd, _ = cboot(ep, per_anchor) + afm, afs, _ = cboot(ep, (per_anchor > 0.5).astype(float)) + out.update(anchor_avg_gate=am, anchor_avg_gate_se=asd, + anchor_avg_frac=afm, anchor_avg_frac_se=afs, + anchor_avg_n_above=int((per_anchor > 0.5).sum()), n_anchors=int(len(per_anchor))) + print(f"[pooled] seed-averaged per anchor: gate {am:.4f} +-{asd:.4f} " + f"frac>0.5 {afm:.3f} +-{afs:.3f} ({out['anchor_avg_n_above']}/{out['n_anchors']} anchors)") + + if bz is not None and np.array_equal(bz["ep"], ep): + m, seen = cands_match(ref["z"], bz) + out["baseline_paired"] = bool(m and seen) + if m and seen: + B = rank_pct(bz["scores_rsm"], 0) + D = M - B[:, None] + d_point = float(D.mean()) + rng = np.random.default_rng(1) + ue = np.unique(ep) + groups = [np.where(ep == e)[0] for e in ue] + vals = np.empty(20000) + for b in range(20000): + gi = rng.integers(0, len(groups), len(groups)) + ri = np.concatenate([groups[i] for i in gi]) + si = rng.integers(0, D.shape[1], D.shape[1]) + vals[b] = D[np.ix_(ri, si)].mean() + d_se = float(np.std(vals)) + out.update(twoway_paired_delta=d_point, twoway_paired_se=d_se, + twoway_paired_p_le_0=float((vals <= 0).mean())) + print(f"[pooled] two-way paired delta vs baseline {d_point:+.4f} +-{d_se:.4f} " + f"boot p(delta<=0)={out['twoway_paired_p_le_0']:.4f}") + else: + print("[pooled] baseline not candidate-paired to the seeds; paired delta withheld") + return out + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--base-cell", default="JUNC_feat_t45_c0p5") + ap.add_argument("--seeds", nargs="+", type=int, default=[0, 1, 2, 3, 4]) + ap.add_argument("--suffix", default="val31") + ap.add_argument("--baseline", default="BASEALIGN__Rval31", + help="un-augmented reference; BASEALIGN__Rval31 is the scorer-list-matched one") + ap.add_argument("--out", default=f"{ROOT}/status/real/augsucc/t45_seed_aggregate.json") + a = ap.parse_args() + + bz = None + bp = f"{RK}/{a.baseline}/per_anchor.npz" + if os.path.exists(bp): + bz = np.load(bp, allow_pickle=True) + gb = rank_pct(bz["scores_rsm"], 0) + epb = bz["ep"] + bm, bs, _ = cboot(epb, gb) + bf, bfs, _ = cboot(epb, (gb > 0.5).astype(float)) + print(f"[baseline {a.baseline}] gate {bm:.4f} +-{bs:.4f} frac>0.5 {bf:.3f} +-{bfs:.3f}") + + rows, missing, per_seed = [], [], [] + for s in a.seeds: + cell = f"{a.base_cell}_s{s}" + p = f"{RK}/{cell}__R{a.suffix}/per_anchor.npz" + if not os.path.exists(p): + missing.append(cell); continue + z = np.load(p, allow_pickle=True) + S, ep = z["scores_rsm"], z["ep"] + gv, ov = rank_pct(S, 0), rank_pct(S, 1) + gm, gs, _ = cboot(ep, gv) + fm, fs, _ = cboot(ep, (gv > 0.5).astype(float)) + om, _, _ = cboot(ep, ov) + ks = stats.kstest(gv, "uniform") + hh = hist(cell) + # Task 3 companions: the zero-parameter baselines ON THE SAME ANCHORS AND CANDIDATES, + # plus ties-at-max and score CV beside every rank number. + pose_m = bc_m = None + dpose_m = dpose_s = dbc_m = dbc_s = None + if "scores_pose" in z.keys(): + pv = rank_pct(np.asarray(z["scores_pose"]), 0) + pose_m, _, _ = cboot(ep, pv) + dpose_m, dpose_s, _ = cboot(ep, gv - pv) + if "scores_bc" in z.keys(): + bv = rank_pct(np.asarray(z["scores_bc"]), 0) + bc_m, _, _ = cboot(ep, bv) + dbc_m, dbc_s, _ = cboot(ep, gv - bv) + r = dict(cell=cell, seed=s, n=int(S.shape[0]), n_eps=int(len(np.unique(ep))), + gate=gm, gate_se=gs, frac_gt_half=fm, frac_se=fs, + frac_sigma=(fm - 0.5) / fs if fs > 0 else float("nan"), + ks_p=float(ks.pvalue), own_rank_pct=om, + qwin=hh.get("q_action_winrate", float("nan")), + aug_frac=hh.get("aug_frac", hh.get("aug_frac_batch", float("nan"))), + step=hh.get("step", float("nan")), + minmse=hh.get("minmse_val", float("nan")), + staymse=hh.get("staymse_val", float("nan")), + ffail=arm_top1(cell, "Ffail", a.suffix), fgoal=arm_top1(cell, "Fgoal", a.suffix), + pose_gate=pose_m, bc_gate=bc_m, + d_vs_pose=dpose_m, d_vs_pose_se=dpose_s, + d_vs_bc=dbc_m, d_vs_bc_se=dbc_s, + ties_at_max=ties_at_max(S), score_cv=score_cv(S), + paired_delta=None, paired_se=None, cands_paired=False) + if bz is not None and np.array_equal(ep, bz["ep"]): + okm, seen = cands_match(z, bz) + r["cands_paired"] = okm + r["cands_probe"] = seen + if okm: + d = gv - rank_pct(bz["scores_rsm"], 0) + dm, ds, _ = cboot(ep, d) + r["paired_delta"], r["paired_se"] = dm, ds + rows.append(r) + per_seed.append(dict(seed=s, gv=gv, ep=ep, z=z, cell=cell)) + + hdr = (f"{'cell':30s} {'gate':>7s} {'+-SE':>6s} {'frac>.5':>8s} {'+-SE':>6s} {'sigma':>6s} " + f"{'KSp':>7s} {'own':>6s} {'qwin':>6s} {'Ffail':>6s} {'Fgoal':>6s} {'pairD':>7s} " + f"{'minmse':>7s} {'step':>7s}") + print(hdr); print("-" * len(hdr)) + def f(x, n=4): + return "n/a" if x is None or x != x else f"{x:.{n}f}" + for r in rows: + print(f"{r['cell']:30s} {f(r['gate']):>7s} {f(r['gate_se']):>6s} {f(r['frac_gt_half'],3):>8s} " + f"{f(r['frac_se'],3):>6s} {f(r['frac_sigma'],2):>6s} {f(r['ks_p'],4):>7s} " + f"{f(r['own_rank_pct'],3):>6s} {f(r['qwin'],3):>6s} {f(r['ffail'],3):>6s} " + f"{f(r['fgoal'],3):>6s} {f(r['paired_delta'],3):>7s} {f(r['minmse']):>7s} {str(r['step']):>7s}") + # Task 3 mandates these beside every rank number, so they print unconditionally. + hdr2 = (f"{'cell':30s} {'pose':>7s} {'rsm-pose':>9s} {'+-SE':>6s} {'bc':>7s} {'rsm-bc':>8s} " + f"{'+-SE':>6s} {'tiesmax':>8s} {'scoreCV':>8s} {'staymse':>8s} {'paired?':>8s}") + print(); print(hdr2); print("-" * len(hdr2)) + for r in rows: + print(f"{r['cell']:30s} {f(r['pose_gate'],3):>7s} {f(r['d_vs_pose'],4):>9s} " + f"{f(r['d_vs_pose_se'],4):>6s} {f(r['bc_gate'],3):>7s} {f(r['d_vs_bc'],4):>8s} " + f"{f(r['d_vs_bc_se'],4):>6s} {f(r['ties_at_max'],3):>8s} {f(r['score_cv'],3):>8s} " + f"{f(r['staymse']):>8s} {str(r['cands_paired']):>8s}") + if missing: + print("\n[MISSING, not yet gated] %s" % ", ".join(missing)) + + # ---- score the registered predictions ------------------------------------------------- + verdicts = {} + if rows: + gates = np.array([r["gate"] for r in rows]) + fracs = np.array([r["frac_gt_half"] for r in rows]) + ksps = np.array([r["ks_p"] for r in rows]) + new = [r for r in rows if r["seed"] != 0] + ngates = np.array([r["gate"] for r in new]) if new else np.array([]) + healthy = [r for r in new if r["qwin"] > 0.7 and r["ffail"] > 0.85] + verdicts["run15"] = { + "n_seeds": len(rows), "mean_gate": float(gates.mean()), + "mean_gate_in_0.45_0.62": bool(0.45 <= gates.mean() <= 0.62), + "new_seeds_clearing_0.5": int((ngates > 0.5).sum()), "new_seeds": len(new), + "healthy_new_seeds": len(healthy), + "falsified": bool(len(new) and (ngates < 0.45).sum() >= 3), + } + pd_ = [r["paired_delta"] for r in rows if r["paired_delta"] is not None] + verdicts["run16"] = { + "n_paired": len(pd_), + "mean_paired_delta": float(np.mean(pd_)) if pd_ else None, + "all_positive": bool(pd_ and all(x > 0 for x in pd_)), + "mean_in_0.20_0.42": bool(pd_ and 0.20 <= float(np.mean(pd_)) <= 0.42), + "cell_means_clearing_0.5": int((gates > 0.5).sum()), + "at_most_3_of_5_clear": bool((gates > 0.5).sum() <= 3), + "falsified": bool(pd_ and any(x <= 0 for x in pd_)), + } + verdicts["run17"] = { + "seeds_frac_above_half": int((fracs > 0.5).sum()), "n_seeds": len(rows), + "mean_frac": float(fracs.mean()), "mean_frac_ge_0.62": bool(fracs.mean() >= 0.62), + "ks_rejected": int((ksps < 0.05).sum()), + "falsified": bool((ksps >= 0.05).sum() >= 3), + } + print("\n=== REGISTERED PREDICTIONS ===") + for k, v in verdicts.items(): + print(f"[{k}] {json.dumps(v)}") + print("\nNOTE: a prediction is only SCORED when all 5 seeds are present; with fewer, these") + print("counts are partial and must be reported as such.") + + pooled = pooled_over_seeds(per_seed, bz) + + os.makedirs(os.path.dirname(a.out), exist_ok=True) + json.dump({"rows": rows, "missing": missing, "baseline": a.baseline, + "verdicts": verdicts, "pooled": pooled}, open(a.out, "w"), indent=1) + print(f"\n[out] {a.out}") + + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/real/seed_pair_contrast.py b/rsm_rise/scripts/real/seed_pair_contrast.py new file mode 100644 index 0000000000000000000000000000000000000000..e71e82fd26b46606e098dce34102de03bfe26bdb --- /dev/null +++ b/rsm_rise/scripts/real/seed_pair_contrast.py @@ -0,0 +1,78 @@ +#!/usr/bin/env python3 +"""AUG_SUCC (gen_q#279) run 12 -- the within-hyperparameter control. + +Run 11 established Spearman(qwin, goalRank) = -0.811 across cells, but that pools cells that differ in +threshold, mode and dose, so "qwin explains the gate" was still confounded with "threshold explains the +gate". Seed pairs remove the confound completely: for a matched (mode, threshold) the threshold, the +dose and the trainer are IDENTICAL and only the seed differs. Where the two seeds land in different +qwin attractors, any gate difference is attributable to the attractor and to nothing else. + +Reads only the two gate tables + each run's history.json. No compute. +""" +import json, os, math, re, collections + +ROOT = "/proj/dmfexp/zwhong/rsm_rise" +ST = f"{ROOT}/status/real/augsucc" +RUNS = f"{ROOT}/runs/real_cooking_v5/rsm" + + +def qwin(cell): + p = f"{RUNS}/{cell}/history.json" + if not os.path.exists(p): + return float("nan") + h = json.load(open(p)) + h = h[-1] if isinstance(h, list) else h + return h.get("q_action_winrate", float("nan")) + + +rows = {} +for f in ("gate_table.json", "junc_gate_30k.json"): + p = f"{ST}/{f}" + if not os.path.exists(p): + continue + for r in json.load(open(p)): + rows.setdefault(r["cell"], r) + +pairs = collections.defaultdict(dict) +for cell in rows: + m = re.match(r"^(AUG_(?:contrastive|invariant)_t[0-9p]+)_s(\d)$", cell) + if m: + pairs[m.group(1)][int(m.group(2))] = cell + +def f(x, n=3): + return "n/a" if x is None or (isinstance(x, float) and x != x) else f"{x:.{n}f}" + +hdr = (f"{'base cell (mode,threshold)':28s} | {'s0 qwin':>7s} {'s0 gate':>7s} {'s0 own':>6s} " + f"| {'s1 qwin':>7s} {'s1 gate':>7s} {'s1 own':>6s} | {'|dqwin|':>7s} {'|dgate|':>7s} {'attractor':>10s}") +print(hdr); print("-" * len(hdr)) +split, same = [], [] +for base in sorted(pairs): + p = pairs[base] + if 0 not in p or 1 not in p: + continue + q0, q1 = qwin(p[0]), qwin(p[1]) + g0, g1 = rows[p[0]].get("goal_rank"), rows[p[1]].get("goal_rank") + o0, o1 = rows[p[0]].get("own_top1"), rows[p[1]].get("own_top1") + # attractor label: inverted (<0.3), mixed, ignoring (>0.7) + lab = lambda q: "INV" if q < 0.3 else ("MIX" if q < 0.7 else "IGN") + tag = f"{lab(q0)}/{lab(q1)}" + dq = abs(q0 - q1) if q0 == q0 and q1 == q1 else float("nan") + dg = abs(g0 - g1) if isinstance(g0, float) and isinstance(g1, float) and g0 == g0 and g1 == g1 else float("nan") + print(f"{base:28s} | {f(q0):>7s} {f(g0):>7s} {f(o0):>6s} | {f(q1):>7s} {f(g1):>7s} {f(o1):>6s} " + f"| {f(dq):>7s} {f(dg):>7s} {tag:>10s}") + (split if lab(q0) != lab(q1) else same).append((base, dq, dg, tag)) + +def summ(name, lst): + ds = [d for _, _, d, _ in lst if d == d] + print(f"\n{name}: n={len(lst)}, with gate on both seeds n={len(ds)}" + + (f", mean |dgate| = {sum(ds)/len(ds):.3f}, max {max(ds):.3f}" if ds else "")) + for b, dq, dg, tag in lst: + print(f" {b:28s} {tag:10s} |dqwin|={f(dq)} |dgate|={f(dg)}") + +summ("SAME-attractor seed pairs", same) +summ("SPLIT-attractor seed pairs (the control)", split) +print("\nThreshold and dose are held EXACTLY fixed inside each row. If |dgate| is small for") +print("same-attractor pairs and large for split-attractor pairs, the attractor -- not the") +print("augmentation threshold -- is what the gate number reads.") +json.dump({"same": same, "split": split}, open(f"{ST}/seed_pair_contrast.json", "w"), indent=1) +print(f"\n[out] {ST}/seed_pair_contrast.json") diff --git a/rsm_rise/scripts/real/seedwidth_table.py b/rsm_rise/scripts/real/seedwidth_table.py new file mode 100644 index 0000000000000000000000000000000000000000..529d0379394bd8df841051b58a09c707a8f49bd5 --- /dev/null +++ b/rsm_rise/scripts/real/seedwidth_table.py @@ -0,0 +1,77 @@ +#!/usr/bin/env python3 +"""SUCC_DEBUG run 40: score H89 S0-S4 from drift4_*.json (pure json arithmetic).""" +import json, os +O = "/proj/dmfexp/zwhong/rsm_rise/status/real/succdebug" +def get(tag, pre="drift4_", beta=0.99, h="16"): + f = f"{O}/{pre}{tag}.json" + if not os.path.exists(f): return None + d = json.load(open(f)) + for r in d["rows"]: + if abs(r["beta"]-beta) < 1e-9: + return {"W": d["flow_width"], "m": r["model"][h], "l": r["logged"][h], + "i": r["iso"][h], "s": r["stay"][h], "rows": d["rows"]} + return None + +print("== S0 REPRODUCTION drift4_R_M vs drift3_R_M (bar 1e-6) + admissibility ==") +bad=[] +for b in (0.95,0.97,0.99): + for h in ("1","2","4","8","16"): + a=get("R_M",beta=b,h=h); c=get("R_M",pre="drift3_",beta=b,h=h) + if a is None or c is None: continue + for k in ("spread_ratio","cos_disp","disp_mean"): + if abs(a["m"][k]-c["m"][k])>1e-6: bad.append(f"{k} b{b} h{h}: {a['m'][k]} vs {c['m'][k]}") +print(" repro misses:", bad if bad else "none -- identical to 1e-6 on all 15 rows x 3 stats") +bad2=[] +for t in ("R_M","R_M_s1","R_W1280","R_W1280_s1","R_XL","R_XL_s1","R_W3072","R_W3072_s1","R_L40","R_W1792","R_RW_v3"): + for b in (0.95,0.99): + for h in ("1","4","16"): + r=get(t,beta=b,h=h) + if r is None: continue + if abs(r["s"]["spread_ratio"]-1)>1e-6 or abs(r["s"]["disp_mean"])>1e-9: bad2.append(f"STAY {t} b{b} h{h}") + if abs(r["i"]["cos_disp"])>0.05: bad2.append(f"ISOcos {t} b{b} h{h}={r['i']['cos_disp']:+.4f}") +print(" admissibility misses:", bad2 if bad2 else "none") + +PAIRS=[("R_M","R_M_s1"),("R_W1280","R_W1280_s1"),("R_XL","R_XL_s1"),("R_W3072","R_W3072_s1")] +print("\n== TABLE b0.99 h16: seed pairs, with brackets ==") +hdr=f"{'ckpt':12s} {'W':>5s} | {'spread':>7s} {'cos':>7s} {'disp':>7s} {'q90/q10':>7s} {'sat':>5s} || {'L_spread':>8s} {'L_cos':>6s} {'L_sat':>5s} | {'STAY_sat':>8s} {'I_spread':>8s}" +print(hdr); print("-"*len(hdr)) +allc=[t for p in PAIRS for t in p]+["R_L40","R_W1792","R_RW_v3"] +for t in allc: + r=get(t) + if r is None: print(f"{t:12s} (missing)"); continue + m,l,i,s=r["m"],r["l"],r["i"],r["s"] + print(f"{t:12s} {r['W']:5d} | {m['spread_ratio']:7.4f} {m['cos_disp']:+7.4f} {m['disp_mean']:7.4f} " + f"{m['disp_q90_q10']:7.2f} {m.get('sat_frac',float('nan')):5.3f} || {l['spread_ratio']:8.4f} " + f"{l['cos_disp']:+6.4f} {l.get('sat_frac',float('nan')):5.3f} | {s.get('sat_frac',float('nan')):8.3f} {i['spread_ratio']:8.4f}") + +print("\n== S1/S2/S3: width effect vs training-seed effect (spread_ratio, b0.99, h16) ==") +s0={}; s1={} +for a,b in PAIRS: + ra,rb=get(a),get(b) + if ra is None or rb is None: print(f" pair {a}/{b}: MISSING"); continue + s0[ra["W"]]=ra["m"]["spread_ratio"]; s1[rb["W"]]=rb["m"]["spread_ratio"] +for t in ("R_L40","R_W1792"): + r=get(t) + if r: s0[r["W"]]=r["m"]["spread_ratio"] +if s0: + R=max(s0.values())-min(s0.values()) + print(f" seed-0 width ladder: "+" ".join(f"W{w} {s0[w]:.4f}" for w in sorted(s0))+f" RANGE R = {R:.4f}") + if s1: + print(f" seed-1 ladder: "+" ".join(f"W{w} {s1[w]:.4f}" for w in sorted(s1))) + gaps=sorted(abs(s0[w]-s1[w]) for w in s1) + g=(gaps[len(gaps)//2] if len(gaps)%2 else 0.5*(gaps[len(gaps)//2-1]+gaps[len(gaps)//2])) + print(" per-width seed gaps: "+" ".join(f"W{w} {abs(s0[w]-s1[w]):.4f}" for w in sorted(s1))) + print(f" S1/S2: median gap g = {g:.4f}; 0.25R = {0.25*R:.4f}; 0.5R = {0.5*R:.4f} -> ", + "UNDERPOWERED (seed >= half the width effect)" if g>=0.5*R else + ("WIDTH EFFECT REAL (every gap < 0.25R)" if all(x<0.25*R for x in gaps) else "AMBIGUOUS MIDDLE")) + o0=[w for w in sorted(s1, key=lambda w: s0[w])]; o1=[w for w in sorted(s1, key=lambda w: s1[w])] + print(f" S3 ordering by spread: seed0 {o0} seed1 {o1} -> {'SAME' if o0==o1 else 'DIFFERENT -- ordering is not a property of width'}") + +print("\n== S4 is the runaway just the feature clip? (b0.99, h16) ==") +for t in allc: + r=get(t) + if r is None: continue + m,l,s=r["m"],r["l"],r["s"] + v="void (anchors already saturated)" if s.get("sat_frac",0)>0.02 else ( + "HIT (pinned to the clip box)" if (m.get("sat_frac",0)>=0.20 and l.get("sat_frac",0)<=0.02) else "MISS") + print(f" {t:12s} W{r['W']:5d} MODEL sat {m.get('sat_frac',float('nan')):.3f} | LOGGED {l.get('sat_frac',float('nan')):.3f} | STAY {s.get('sat_frac',float('nan')):.3f} | ISO {r['i'].get('sat_frac',float('nan')):.3f} -> {v}") diff --git a/rsm_rise/scripts/real/selfcont_altnc_run30.sh b/rsm_rise/scripts/real/selfcont_altnc_run30.sh new file mode 100644 index 0000000000000000000000000000000000000000..f542dac3d352ec004dc2ebbf65dc7cbfa02d28bf --- /dev/null +++ b/rsm_rise/scripts/real/selfcont_altnc_run30.sh @@ -0,0 +1,53 @@ +#!/usr/bin/env bash +# run 30: the two controls that stand behind this run's page fix. +# 1. the alternation negative controls (six cases, both directions) +# 2. a REPLAY of run 29's MEASURED walk output (LSF 1907640, b6d0421) against the EDITED page, +# with block markers renumbered for the one output block the edit inserts. The executed +# commands are byte-identical between the two pages, so the replay is a real measurement of +# the page edit against real output -- it is NOT a substitute for the fresh walk, which runs +# separately against the pushed head. +set -uo pipefail +RSM_RISE=/proj/dmfexp/zwhong/rsm_rise +PAGE=/proj/dmfexp/zwhong/projs/rsm_real/QUICKSTART.md +SRCLOG=/proj/dmfexp/zwhong/scratch_selfcontained/qswalk29c/walk.log +T0=$(date +%s) +echo "########## ALTNC run30 host=$(hostname) job=${LSB_JOBID:-none} $(date -u)" + +echo "===== 1. alternation negative controls" +python3 "$RSM_RISE/scripts/real/selfcont_qswalk_altnc.py"; NC=$? +echo "altnc rc=$NC" + +echo "===== 2. runner parity: did the page edit change any EXECUTED command?" +TD=$(mktemp -d) +git -C /proj/dmfexp/zwhong/projs/rsm_real show b6d0421:QUICKSTART.md > "$TD/old.md" +python3 "$RSM_RISE/scripts/real/selfcont_qswalk.py" emit "$TD/old.md" "$TD/o" >/dev/null +python3 "$RSM_RISE/scripts/real/selfcont_qswalk.py" emit "$PAGE" "$TD/n" >/dev/null +for f in "$TD/o" "$TD/n"; do + grep -v "__QSWALK_BEGIN\|__QSWALK_END\|QSWALK blocks=" "$f/qswalk_runner.sh" > "$f/cmds"; done +if diff "$TD/o/cmds" "$TD/n/cmds" >/dev/null; then + echo "RUNNER PARITY: PASS -- executed commands byte-identical to b6d0421; only markers moved"; RP=0 +else + echo "RUNNER PARITY: FAIL -- the page edit changed an executed command:"; diff "$TD/o/cmds" "$TD/n/cmds"; RP=1 +fi + +echo "===== 3. replay run 29's measured walk output against the edited page" +if [ ! -f "$SRCLOG" ]; then + echo "REPLAY: NON-RESULT -- $SRCLOG is gone (scratch reaped); the fresh walk is the only evidence"; RV=2 +else + python3 - "$SRCLOG" "$TD/replay.log" <<'PY' +import re, sys +from pathlib import Path +m = {"9": "10", "11": "12", "12": "13", "14": "15"} # old page index -> new, from the emit tables +src = Path(sys.argv[1]).read_text(errors="replace") +out = re.sub(r"(__QSWALK_(?:BEGIN|END) block=)(\d+)", lambda mo: mo.group(1) + m.get(mo.group(2), mo.group(2)), src) +Path(sys.argv[2]).write_text(out) +print("renumbered %d block markers" % len(re.findall(r"__QSWALK_BEGIN", out))) +PY + python3 "$RSM_RISE/scripts/real/selfcont_qswalk.py" verdict "$PAGE" "$TD/replay.log"; RV=$? + echo "replay verdict rc=$RV" +fi +rm -rf "$TD" + +RC=0; [ "$NC" = 0 ] || RC=1; [ "$RP" = 0 ] || RC=1; [ "$RV" = 0 ] || RC=1 +echo "########## ALTNC VERDICT: $([ $RC = 0 ] && echo PASS || echo FAIL) altnc=$NC parity=$RP replay=$RV $(( $(date +%s) - T0 ))s" +exit $RC diff --git a/rsm_rise/scripts/real/selfcont_checkenv_openpi.sh b/rsm_rise/scripts/real/selfcont_checkenv_openpi.sh new file mode 100644 index 0000000000000000000000000000000000000000..f4a70ea9d22931f64f0e043552e43a30c0e9af89 --- /dev/null +++ b/rsm_rise/scripts/real/selfcont_checkenv_openpi.sh @@ -0,0 +1,30 @@ +#!/usr/bin/env bash +# Exercise the NEW check_env.py branches that only exist when openpi imports: +# * the TrainConfig names are BUILT via get_config(), not matched as strings in config.py +# * the new "builds with the training split ABSENT" line (rsm_real#5 item 1 regression guard) +# Runs in run6's uv venv, whose openpi tree now carries the FIXED patch (LSF 1887528 section B). +set -uo pipefail +SCRATCH=${SCRATCH:-/proj/dmfexp/zwhong/scratch_selfcontained/run6} +STAGE=${STAGE:-/proj/dmfexp/zwhong/scratch_selfcontained/stage_run9/rsm_real} +REPO="$SCRATCH/rsm_real"; OPI="$REPO/third_party/openpi"; PY="$OPI/.venv/bin/python" +hdr() { printf '\n\n########## %s ##########\n' "$*"; } +hdr "host=$(hostname) job=${LSB_JOBID:-none} $(date -u)" +unset RISE_ROOT PYTHONPATH HF_TOKEN HUGGING_FACE_HUB_TOKEN HF_HUB_OFFLINE +export PYTHONNOUSERSITE=1 JAX_PLATFORMS=cpu PATH="$OPI/.venv/bin:$PATH" TORCH_HOME="$SCRATCH/.torchhome" +export CKPTS="$SCRATCH/ckpts_hfpin" +[ -x "$PY" ] || { echo "no venv at $PY"; exit 1; } +cp "$STAGE/scripts/check_env.py" "$REPO/scripts/check_env.py" +cp "$STAGE/rise_stack/openpi/verify_inference_no_split.py" "$REPO/rise_stack/openpi/verify_inference_no_split.py" +cd "$REPO" +echo "openpi tree state (should be the FIXED patch):" +git -C "$OPI" status --porcelain | grep -v '^?? .venv' +grep -n "episodes_required_from" "$OPI/src/openpi/training/config.py" | head -3 + +hdr "A new check_env.py in the openpi interpreter" +"$PY" scripts/check_env.py 2>&1 +echo "A rc=$?" + +hdr "B the shipped verify script, from the repo, exactly as the docs tell a reader to run it" +"$PY" rise_stack/openpi/verify_inference_no_split.py 2>&1 | tail -20 +echo "B rc=${PIPESTATUS[0]}" +hdr "DONE $(date -u)" diff --git a/rsm_rise/scripts/real/selfcont_cipytest_run35.sh b/rsm_rise/scripts/real/selfcont_cipytest_run35.sh new file mode 100644 index 0000000000000000000000000000000000000000..4e7a757a96a391a378e157bcb7582cbf91a923a4 --- /dev/null +++ b/rsm_rise/scripts/real/selfcont_cipytest_run35.sh @@ -0,0 +1,111 @@ +#!/usr/bin/env bash +# SELFCONTAINED run 35 -- run the hardware-free CI job's OWN pytest list against the working tree. +# +# Why. Run 34 pushed 74a9293 after a gate whose pytest step ran ONE file +# (tests/test_rise_stack_rerun_out_dir.py, 25 tests, green). The change also altered the exception +# `reserve_out` raises, and tests/test_deployment_models.py -- a file the gate never opened -- still +# asserted the old one. CI went red on a push this gate had called clean. So: the list of files is +# EXTRACTED from .github/workflows/deployment.yml at run time, never retyped, and the run is a +# NON-RESULT rather than a pass if the interpreter cannot import what the tests need. +set -uo pipefail +REPO=${REPO:-/proj/dmfexp/zwhong/projs/rsm_real} +S=${S:-/proj/dmfexp/zwhong/scratch_selfcontained/cipytest35} +PY=${PY:-/proj/dmfexp/zwhong/rsm_rise/venv_rsm/bin/python} +rm -rf "$S"; mkdir -p "$S" +exec > >(tee "$S/cipytest.log") 2>&1 +echo "CIPYTEST host=$(hostname) job=${LSB_JOBID:-none} $(date -u)" +echo "repo=$REPO head=$(git -C "$REPO" rev-parse --short HEAD) py=$PY" + +# The list, from the workflow's bytes. A parse that found nothing must be a NON-RESULT: an empty +# list makes `pytest` collect the whole tree or nothing at all, and either would be read as a result. +mapfile -t FILES < <(python3 - "$REPO/.github/workflows/deployment.yml" <<'PYX' +import re, sys +text = open(sys.argv[1]).read() +jobs = re.split(r"^ (?=[A-Za-z0-9_-]+:\s*$)", text, flags=re.M) +body = [j for j in jobs if j.startswith("hardware-free:")] +if len(body) != 1: + raise SystemExit("EXPECTED exactly one hardware-free job, found %d" % len(body)) +if "pytest" not in body[0]: + raise SystemExit("the hardware-free job does not invoke pytest") +for f in re.findall(r"tests/[A-Za-z0-9_]+\.py", body[0]): + print(f) +PYX +) +echo "extracted ${#FILES[@]} test files from the hardware-free job" +if [ "${#FILES[@]}" -lt 14 ]; then + echo "CIPYTEST VERDICT: NON-RESULT -- extracted ${#FILES[@]} files (floor 14); the workflow's shape changed" + exit 2 +fi +printf ' %s\n' "${FILES[@]}" +for f in "${FILES[@]}"; do + [ -f "$REPO/$f" ] || { echo "CIPYTEST VERDICT: NON-RESULT -- the workflow names $f and it is not in the tree"; exit 2; } +done + +# The interpreter. `venv_rsm` has torch and pytest but not hydra/omegaconf (LSF 1910688 reported +# exactly that, as a NON-RESULT rather than a red suite), so by default this builds a venv from the +# workflow's OWN install lines -- extracted, not retyped, for the same reason as the file list -- and +# caches it across runs. CIVENV= reuses one; PY= skips the build and takes the caller's. +cd "$REPO" || exit 2 +CIVENV=${CIVENV:-/proj/dmfexp/zwhong/scratch_selfcontained/civenv35} +if [ -z "${PY_GIVEN:-}" ]; then + mapfile -t PIPCMDS < <(python3 - "$REPO/.github/workflows/deployment.yml" <<'PYP' +import re, sys +text = open(sys.argv[1]).read() +jobs = re.split(r"^ (?=[A-Za-z0-9_-]+:\s*$)", text, flags=re.M) +body = [j for j in jobs if j.startswith("hardware-free:")][0] +cmds = [l.strip() for l in body.splitlines() if l.strip().startswith("python -m pip install")] +if not cmds: + raise SystemExit("no pip install lines in the hardware-free job") +for c in cmds: + print(c) +PYP +) + echo "extracted ${#PIPCMDS[@]} pip install line(s) from the hardware-free job:" + printf ' %s\n' "${PIPCMDS[@]}" + [ "${#PIPCMDS[@]}" -ge 3 ] || { echo "CIPYTEST VERDICT: NON-RESULT -- ${#PIPCMDS[@]} pip lines (floor 3)"; exit 2; } + if [ ! -x "$CIVENV/bin/python" ]; then + echo "building $CIVENV (first run only)" + python3 -m venv "$CIVENV" || { echo "CIPYTEST VERDICT: NON-RESULT -- could not create $CIVENV"; exit 2; } + "$CIVENV/bin/python" -m pip install -q -U pip >/dev/null 2>&1 + for c in "${PIPCMDS[@]}"; do + echo " + $c" + # `python` -> this venv's interpreter; everything else is the workflow's own words. + ( export PIP_DISABLE_PIP_VERSION_CHECK=1; eval "${c/#python/$CIVENV/bin/python}" ) 2>&1 | tail -4 + rc=${PIPESTATUS[0]} + if [ "$rc" != 0 ]; then + echo "CIPYTEST VERDICT: NON-RESULT -- a pip line from the workflow failed (rc=$rc); no network?" + rm -rf "$CIVENV"; exit 2 + fi + done + else + echo "reusing $CIVENV" + fi + PY="$CIVENV/bin/python" +fi +echo "interpreter in use: $PY" +"$PY" - <<'PYDEP' || { echo "CIPYTEST VERDICT: NON-RESULT -- $PY cannot import the suite's dependencies (above)"; exit 2; } +import importlib, sys +need = ["pytest", "numpy", "torch", "hydra", "omegaconf", "yaml", "h5py", "cv2"] +bad = [] +for m in need: + try: + importlib.import_module(m) + except Exception as e: + bad.append("%s: %s" % (m, e)) +print("interpreter:", sys.version.split()[0]) +for m in need: + print(" %-12s %s" % (m, "no" if any(b.startswith(m + ":") for b in bad) else "yes")) +if bad: + print("MISSING:"); [print(" " + b) for b in bad] + raise SystemExit(1) +PYDEP + +echo; echo "=== pytest, the workflow's list, the workflow's flags ===" +PYTHONDONTWRITEBYTECODE=1 OMP_NUM_THREADS=1 OPENBLAS_NUM_THREADS=1 \ + "$PY" -m pytest -q -p no:cacheprovider "${FILES[@]}" 2>&1 | tail -60 +RC=${PIPESTATUS[0]} +echo "pytest rc=$RC" +echo +if [ "$RC" = 0 ]; then echo "=== CIPYTEST VERDICT: PASS rc=0"; exit 0; fi +if [ "$RC" = 5 ]; then echo "=== CIPYTEST VERDICT: NON-RESULT rc=2 (pytest collected nothing)"; exit 2; fi +echo "=== CIPYTEST VERDICT: FAIL rc=1 (pytest rc=$RC)"; exit 1 diff --git a/rsm_rise/scripts/real/selfcont_clean_venv.sh b/rsm_rise/scripts/real/selfcont_clean_venv.sh new file mode 100644 index 0000000000000000000000000000000000000000..8cb8ad04acbbff34fa32e4757ae524be2acf9159 --- /dev/null +++ b/rsm_rise/scripts/real/selfcont_clean_venv.sh @@ -0,0 +1,595 @@ +#!/usr/bin/env bash +# The REAL clean-clone test: a fresh venv (so robomimic is genuinely absent), the repo from SRC, +# and QUICKSTART.md followed line by line. LSF payload. Writes only under $SCRATCH. +set -uo pipefail +SCRATCH=${SCRATCH:-/proj/dmfexp/zwhong/scratch_selfcontained/run2} +SRC_MODE=${SRC_MODE:-worktree} # worktree | github | walk +# WALK_TREE: a repo the PAGE WALK already built (clone + .venv + checkpoints/). Set it and +# STEP 1/2/3 REUSE that tree instead of cloning, pip-installing and re-downloading -- so the +# merged gate (walk + gate-only steps) pays the ~6 GB pip and the 3 checkpoints ONCE. +# Everything the walk does NOT do -- 1b parity, 7/7b which-scorer, 8 RISE_ROOT, 9 leak scan, +# 10 module provenance -- still runs here, from this one copy of the code, not a second one. +WALK_TREE=${WALK_TREE:-} +# The walk's own log, required (and CHECKED) by the verdict whenever WALK_TREE is set. +WALK_LOG=${WALK_LOG:-} +export WALK_TREE WALK_LOG +BRANCH=${BRANCH:-rise-stack-scaffold} +BASEPY=${BASEPY:-/proj/dmfexp/zwhong/rsm_rise/env/bin/python} +RSM_RISE=/proj/dmfexp/zwhong/rsm_rise + +_T0=$(date +%s); _TPREV=$_T0; _PREVNAME=""; _DURS="" +# Every step is stamped and timed: QUICKSTART.md quotes wall times ('under five minutes', +# 'one decision measured N s') and until now the log only had a start and an end timestamp, +# so those claims could not be checked against a run. +# The elapsed time printed under a header belonged to the step that just ENDED, and that was +# misread once into a committed timing table (a 4 s clone was quoted as a 4 s pip install whose +# real cost was 75 s). So the duration is now printed on its own line, BEFORE the next header, +# labelled with the step it belongs to, and collected into the [ledger] line at DONE. +hdr() { + # two statements on purpose: `local a=$(..) b=$((a-1))` declares both names before assigning, + # so the arithmetic sees an unset local and `set -u` kills the run (LSF 1890171). + local now d + now=$(date +%s); d=$((now-_TPREV)) + if [ -n "$_PREVNAME" ]; then + printf '\n[t] step %s FINISHED, took %ds\n' "$_PREVNAME" "$d" + _DURS="$_DURS{\"step\":\"$_PREVNAME\",\"secs\":$d}," + fi + printf '\n\n########## %s ##########\n[t] +%ds since start\n' "$*" "$((now-_T0))" + _TPREV=$now; _PREVNAME=$(printf '%s' "$*" | awk '{print $1" "$2}') +} +hdr "host=$(hostname) job=${LSB_JOBID:-none} src_mode=$SRC_MODE $(date -u)" + +# $SCRATCH is wiped, so a WALK_TREE inside it would be deleted by the run that means to read it. +case "${WALK_TREE:-}" in "$SCRATCH"|"$SCRATCH"/*) + echo "GATE VERDICT: NON-RESULT -- WALK_TREE=$WALK_TREE is inside SCRATCH=$SCRATCH, which this" + echo "script wipes; point them at different directories."; exit 2;; esac +rm -rf "$SCRATCH"; mkdir -p "$SCRATCH" +# HF_TOKEN is exported cluster-wide here and is STALE: an invalid token turns the public mirror's +# 200 into a 401, which the hf CLI reports as "not found". A clean machine has no HF_TOKEN. +unset RISE_ROOT PYTHONPATH RSM_LIBERO_DIR RSM_CKPT PI05 OPENPI_DATA_HOME HF_LEROBOT_HOME CKPTS +unset HF_TOKEN HUGGING_FACE_HUB_TOKEN HF_HUB_OFFLINE +export PYTHONNOUSERSITE=1 GIT_TERMINAL_PROMPT=0 +export PIP_CACHE_DIR="$SCRATCH/.pipcache" +export TORCH_HOME="$SCRATCH/.torchhome" +# NO RISE_DINO_HUB_DIR export, deliberately, since 2026-09-24 (run 28). +# +# LSF 1889983 found `rise_stack.run`/`check` loading the DINOv2 *source* from +# /proj/dmfexp/zwhong/rsm_rise/cache/torch/hub/... -- the shipped value of dino_hub_dir: in +# rise_stack/configs/baselines.yaml -- and the repair was to export RISE_DINO_HUB_DIR into $SCRATCH. +# That fixed the GATE and not the file the reader gets: LSF 1905498 found the same 24 `dinov2.*` +# modules coming from the research tree in a process without the override. A gate that sets a variable +# QUICKSTART.md never mentions is not testing the reader's path, so the override is gone and +# `dino_hub_dir:` now ships as null. With null, rise_stack/scorers.py resolves +# $TORCH_HOME/hub/facebookresearch_dinov2_main -- which, with TORCH_HOME=$SCRATCH/.torchhome above, is +# byte-for-byte the path this line used to export, downloaded from github on first use. +# If a future tree reintroduces a research-tree default, STEP 10 must go red. Do not re-add this. + +# RSM_LIBERO_DIR is exported to a path that does not exist, deliberately. +# +# Until 2026-09-24 the vendored scorer defaulted it to /proj/dmfexp/zwhong/rsm_rise/code/gen_q/ +# rsm_libero and `_rsm_modules()` imported `model`, `train_rsm`, `is_ope` and `data` from there. This +# gate UNSET the variable, which on THIS cluster silently selected that default -- so every green run +# measured a scorer that raises `ModuleNotFoundError: No module named 'model'` anywhere else +# (LSF 1905498). Unsetting can no longer distinguish "used the vendored copy" from "found the cluster +# tree"; an invalid value can, because the only way past it is the vendored copy. +export RSM_LIBERO_DIR=/nonexistent-rsm-libero-a-clean-machine-has-no-cluster-tree +# Everything from here is teed, so the leak scan at DONE can read the whole run back. +GATELOG="$SCRATCH/gate.log" +exec > >(tee "$GATELOG") 2>&1 + +hdr "STEP 1 get the repo" +cd "$SCRATCH" +if [ -n "$WALK_TREE" ]; then + # The tree the page walk built by running QUICKSTART.md's own commands. Nothing is copied: the + # gate-only steps below must look at the SAME bytes the walk executed, and a copy would let the + # two disagree without anything saying so. + [ -d "$WALK_TREE/.git" ] || { echo "GATE VERDICT: NON-RESULT -- WALK_TREE=$WALK_TREE is not a clone"; exit 2; } + [ -x "$WALK_TREE/.venv/bin/python" ] || { echo "GATE VERDICT: NON-RESULT -- WALK_TREE has no .venv; the walk did not reach QUICKSTART step 2"; exit 2; } + ln -sfn "$WALK_TREE" rsm_real + echo "REUSING the page walk's tree: $WALK_TREE" +elif [ "$SRC_MODE" = github ]; then + git -c credential.helper= -c credential.https://github.com.helper= -c credential.helper=store \ + clone --branch "$BRANCH" https://github.com/jmarangola/rsm_real.git rsm_real 2>&1 \ + | sed -E 's#://[^@]*@#://@#' + [ -d rsm_real/.git ] || { echo "CLONE FAILED"; exit 1; } +elif [ "$SRC_MODE" = stage ]; then + # pre-commit validation of THIS stream's changes only: $STAGE_SRC is a local clone of the branch + # HEAD with just our edited files copied over it, so another stream's uncommitted work in the + # shared checkout cannot leak into the run. + rsync -a --exclude '__pycache__' --exclude 'runs/' --exclude 'outputs/' \ + --exclude 'third_party/' --exclude 'checkpoints/' --exclude '.venv' \ + "${STAGE_SRC:?set STAGE_SRC}/" rsm_real/ +else + # pre-commit validation: the working tree verbatim, minus everything git would not ship + rsync -a --exclude '.git' --exclude '__pycache__' --exclude 'runs/' --exclude 'outputs/' \ + --exclude 'third_party/' --exclude 'checkpoints/' --exclude '.venv' \ + /proj/dmfexp/zwhong/projs/rsm_real/ rsm_real/ +fi +REPO="$SCRATCH/rsm_real"; cd "$REPO"; export REPO +echo "repo at $REPO $(git rev-parse HEAD 2>/dev/null || echo '(rsync copy, no git)')" + +hdr "STEP 1b does this gate still run the commands QUICKSTART.md tells the reader to run?" +# Every STEP below carries a RETYPED copy of a QUICKSTART command, with comments that say +# "exactly as QUICKSTART.md now says" and "(VERBATIM)". Nothing enforced either word: rename a +# flag, rename a checkpoint, move a fixture or add a step in the document and this gate keeps +# running the OLD command and keeps printing 0.2826, while the reader who pastes the NEW file gets +# a traceback. A check that quietly stops checking the thing it names -- inside this stream's own +# primary check. So the two sides are parsed and compared by command signature BEFORE anything is +# installed; drift is a gate FAILURE, and "the extractor found nothing" is rc=2, a NON-RESULT. +# It runs here and not before STEP 1 because QUICKSTART.md is the CLONE's copy, not the tree's. +python3 "$RSM_RISE/scripts/real/selfcont_quickstart_parity.py" "$REPO" "$0" 2>&1 | tail -40 +_PARITY=${PIPESTATUS[0]} +echo "quickstart parity rc=$_PARITY" +if [ "$_PARITY" -ne 0 ]; then + # Aborting here rather than letting the STEP 9 verdict table catch it, for one reason: if the + # run continues it reaches STEP 5 and prints `score of chosen 0.2826` into a log whose commands + # are KNOWN not to be the document's, and this project's recorded failure mode is exactly a + # plausible number grepped out of a log that had already failed (run 23: `VENDORED COPY LOADED: + # False` next to `step7 rc=0`). Nothing below this line runs, so no score can be quoted from it. + # The verdict SENTINEL is printed here so the one string every reader and monitor greps still + # exists, and says FAIL -- this is the only path in this script that prints it outside STEP 9. + echo "GATE VERDICT: FAIL -- STEP 1b quickstart parity (rc=$_PARITY): the commands this gate runs" + echo "are not the commands QUICKSTART.md tells the reader to run. Nothing below STEP 1b was run," + echo "so this log contains no score and no verdict about the repo. Fix the drift named above." + exit 1 +fi + +hdr "STEP 2 QUICKSTART 2 -- venv + requirements" +REQ=requirements/rise-stack-replay.txt +if [ -n "$WALK_TREE" ]; then + # Built by the walk from the page's own block, already measured there. Re-creating it would be a + # second, retyped answer to "what does QUICKSTART step 2 install" -- the drift STEP 1b exists to + # catch. The two assertions that make this a test and not an assumption still run below: the venv + # must be usable, and robomimic must be absent from it. + echo "reusing the walk's venv at $REPO/.venv (QUICKSTART step 2 ran in the walk phase)" + source .venv/bin/activate + python -V + # DELIBERATELY no `pip rc=0` line. This gate did not run pip, and an rc line is how the verdict + # table below learns a step passed -- printing a green number for a command nobody ran here is + # this stream's recorded failure mode with the label filed off. In WALK_TREE mode the `pip` row + # is REPLACED, not satisfied: the verdict requires the WALK's own PASS out of $WALK_LOG. + echo "pip NOT RUN HERE -- QUICKSTART step 2 was executed by the walk phase; see $WALK_LOG" +else +"$BASEPY" -m venv .venv || exit 1 +source .venv/bin/activate +python -V +# QUICKSTART step 2 is now the TRACKED requirements file and nothing else -- no setup_env.sh, no +# network to github. The coupling it used to have (setup_env.sh GENERATED the list) dies on the +# six-way merge, because PR #10 replaces setup_env.sh whole-file with a uv builder that never writes +# requirements-rise-stack.txt. Measured: LSF 1891696. +[ -f "$REQ" ] || { echo "MISSING $REQ -- QUICKSTART step 2 cannot be followed"; exit 1; } +echo "--- $REQ (tracked) ---"; cat "$REQ" +# Run 14: LSF 1893267 sat 18 minutes inside this step on p1-r23-n1 with 119 MB RSS, 68 s of CPU and +# zero filesystem writes -- pip stalled on a socket read with its default 15 s timeout and 5 silent +# retries, after torch was already unpacked. A gate that can hang forever on one bad node reports +# nothing, so bound it: a failure here must LOOK like a failure instead of like a slow node. +export PIP_DEFAULT_TIMEOUT=${PIP_DEFAULT_TIMEOUT:-20} PIP_RETRIES=${PIP_RETRIES:-10} +pip install --quiet --upgrade pip 2>&1 | tail -3 +timeout "${PIP_STEP_TIMEOUT:-900}" pip install --quiet -r "$REQ" 2>&1 | tail -15 +_PIP_RC=${PIPESTATUS[0]} +# `echo "pip rc=$?"` stood here and WAS correct -- line 4 sets `pipefail`, so `pip | tail` carries +# pip's failure out of the pipeline. It stops being correct the moment any statement sits between the +# pipeline and the `$?`, which the _PIP_RC assignment above now does, so read PIPESTATUS explicitly +# rather than leaving a line whose correctness depends on nothing ever being inserted above it. +# 124 means the wall clock fired. +# The rc line carries NOTHING but the label and the number: the verdict's parser anchors on +# `^\s*(label) rc=(-?\d+)\s*$`, and run 14's first attempt appended an explanatory parenthesis here +# and got `FAIL pip: no rc line in the log -- the step did not run` (LSF 1893934). The guard caught it, +# which is the point, but the comment belongs above the line and not inside it. +# rc=124 means the ${PIP_STEP_TIMEOUT:-900}s wall clock fired, i.e. a stalled mirror, not a defect. +echo "pip rc=$_PIP_RC" +fi +# setup_env.sh is still a shipped path, so it is still exercised -- just no longer ON the quickstart +# path. It must reproduce the tracked list byte for byte, or the two can drift apart silently. +# SETUP_ENV_PARITY=skip is for the MERGED-TREE gate only: after the six-way merge, PR #10's +# uv-based setup_env.sh replaces ours whole-file, so "our script reproduces the tracked list" is +# not a property of that tree and asserting it would fail for a reason that is not a defect. +# The point of the run-11 fix is exactly that QUICKSTART no longer needs either script. +if [ "${SETUP_ENV_PARITY:-required}" = required ]; then + bash scripts/setup_env.sh 2>&1 | tail -20 + if cmp -s requirements-rise-stack.txt "$REQ"; then + echo "requirements-rise-stack.txt == $REQ" + echo "setup_env parity rc=0" + else + echo "setup_env.sh and $REQ have DRIFTED:"; diff "$REQ" requirements-rise-stack.txt | head -20 + echo "setup_env parity rc=1" + fi +else + echo "setup_env parity NOT ASSERTED (SETUP_ENV_PARITY=${SETUP_ENV_PARITY})" + echo " scripts/setup_env.sh in this tree: $(wc -l < scripts/setup_env.sh) lines, sha1 $(sha1sum scripts/setup_env.sh | cut -c1-12)" +fi +python - <<'PY' +import importlib.util as u +for m in ("numpy","h5py","yaml","cv2","torch","torchvision","av","huggingface_hub","jax","openpi","robomimic"): + print(f" {m:18s} {'yes' if u.find_spec(m) else 'NO'}") +PY +python -c " +import importlib.util as u, sys +assert u.find_spec('robomimic') is None, 'robomimic IS importable -- this is NOT a clean test' +print('CLEAN: robomimic is not importable in this venv')" + +hdr "STEP 3 QUICKSTART 3 -- hf download" +export CKPTS=$REPO/checkpoints +# One invocation PER FILE, exactly as QUICKSTART.md now says. The old combined form +# (repeated --include) fetches only the LAST pattern on huggingface_hub < 1.0 and exits 0; +# with setup_env.sh now pinning huggingface_hub>=0.34,<1.0 (openpi's transformers needs <1.0), +# the combined form would silently download 1 of 3. Verified both ways by LSF 1886546. +for f in successor_rsm_real_RM_s0_100k.pt successor_rsm_real_feat_stats.json \ + hop_head_rsm_real_gauss_r1.pt; do + if [ -n "$WALK_TREE" ] && [ -s "$CKPTS/$f" ]; then + # The walk ran the page's own `hf download` block into this same tree. Re-downloading would be + # a retyped second copy of that command; the completeness assertion below is what makes the + # reuse a check rather than an assumption, and it runs either way. + # Same rule as pip: no `hf rc=` line for a download this gate did not perform. What IS + # asserted here is the file, by the completeness check below, which runs on both paths. + echo " reused from the walk: $f ($(stat -c%s "$CKPTS/$f") bytes)" + continue + fi + hf download rli14/rsm_cooking_v5_checkpoints --local-dir "$CKPTS" --include "$f" 2>&1 | tail -2 + echo " hf rc=$? for $f" +done +echo "--- all three must be here ---"; ls -la "$CKPTS" 2>&1 | tail -6 +python - <<'PY2' +import os, sys +ck = os.environ["CKPTS"] +missing = [f for f in ("successor_rsm_real_RM_s0_100k.pt", "successor_rsm_real_feat_stats.json", + "hop_head_rsm_real_gauss_r1.pt") if not os.path.isfile(os.path.join(ck, f))] +print("PARTIAL DOWNLOAD:", missing) if missing else print("all 3 checkpoint files present") +sys.exit(1 if missing else 0) +PY2 +echo "download completeness rc=$?" + +hdr "STEP 4 QUICKSTART 4 -- python scripts/check_env.py (VERBATIM)" +python scripts/check_env.py 2>&1 +echo "checkenv rc=$?" + +hdr "STEP 4b QUICKSTART 4b -- rise_stack.check, synthetic obs, no dataset" +python -m rise_stack.check --policy random --scorer rsm \ + --rsm-ckpt "$CKPTS/successor_rsm_real_RM_s0_100k.pt" \ + --rsm-feat-stats "$CKPTS/successor_rsm_real_feat_stats.json" \ + --rsm-hop-ckpt "$CKPTS/hop_head_rsm_real_gauss_r1.pt" \ + --n-cand 8 --repeat 1 2>&1 | tail -30 +echo "step4b rc=${PIPESTATUS[0]}" + +hdr "STEP 5 QUICKSTART 5 -- one scored decision" +# T5 exists because of LSF 1909642. In `SRC_MODE=walk` the gate runs in the tree the PAGE WALK +# already used, so `runs/quickstart` is already populated when this step starts. Before +# `--overwrite` the run died on the reservation; its traceback went into `tail -40`, whose rc is 0, +# and the `$?` after the reader snippet measured the SNIPPET -- so the step printed the WALK's +# 0.2826 next to `step5 rc=0`. Three fixes, each of which alone would have caught it: +# * `--overwrite` (matching the page), so the run can happen at all in an already-used tree; +# * ${PIPESTATUS[0]}, so the step's rc is the RUN's rc and not tail's; +# * the snippet refuses a rollout.json older than T5, so no earlier file can be read as this run's. +T5=$(date +%s) +set -x +python -m rise_stack.run --policy random --scorer rsm --env replay \ + --hdf5 rise_stack/fixtures/replay_cooking_v5_ep7.hdf5 \ + --split rise_stack/fixtures/split.json \ + --video-root rise_stack/fixtures \ + --rsm-ckpt "$CKPTS/successor_rsm_real_RM_s0_100k.pt" \ + --rsm-feat-stats "$CKPTS/successor_rsm_real_feat_stats.json" \ + --rsm-hop-ckpt "$CKPTS/hop_head_rsm_real_gauss_r1.pt" \ + --episodes 1 --n-cand 8 --horizon 8 --max-decisions 1 \ + --out runs/quickstart --overwrite 2>&1 | tail -40 +set +x +RUN5=${PIPESTATUS[0]} +echo "--- the QUICKSTART reader snippet ---" +python - "$T5" <<'QSREAD' +import json, os, sys +t5 = float(sys.argv[1]) +f = "runs/quickstart/rollout.json" +if not os.path.exists(f): + raise SystemExit(f"{f} does not exist -- the run wrote nothing, so there is no score to read") +age = os.path.getmtime(f) - t5 +if age < 0: + raise SystemExit(f"{f} is {-age:.0f}s OLDER than this step; it belongs to an earlier run and " + "reading it here would report that run's numbers as this one's") +d = json.load(open(f)) +r = d["runs"][0]["trace"][0] +print("scorer ", d["scorer"]) +print("candidates ", d["n_cand"]) +print("chose candidate ", r["chosen"], "of", d["n_cand"]) +print("score of chosen %.4f (mean %.4f, sd %.4f)" % (r["score_chosen"], r["score_mean"], r["score_std"])) +print("scoring took %.0f ms" % r["score_ms"]) +print("rollout.json written %.0fs into this step" % age) +QSREAD +SNIP5=$? +if [ "$RUN5" != 0 ]; then STEP5=$RUN5; else STEP5=$SNIP5; fi +# The rc line the verdict parser reads is `